Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(grid): optimize and simplify code logic #226

Merged
merged 1 commit into from
Jan 7, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
refactor(grid): optimize code logic
  • Loading branch information
minlovehua committed Jan 7, 2025
commit def47d6256307c67e0edd4a00af22cb9d7473541
9 changes: 3 additions & 6 deletions packages/grid/src/core/types/ai-table.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export interface AITable {
fields: WritableSignal<AITableFields>;
context?: RendererContext;
selection: WritableSignal<AITableSelection>;
matchedCells: WritableSignal<string[]>; // [`${recordId}:${fieldId}`]
keywordsMatchedCells: WritableSignal<Set<string>>; // [`${recordId}:${fieldId}`]
recordsMap: Signal<{ [key: string]: AITableRecord }>;
fieldsMap: Signal<{ [key: string]: AITableField }>;
recordsWillHidden: WritableSignal<string[]>;
Expand Down Expand Up @@ -48,11 +48,8 @@ export const AITable = {
isCellVisible(aiTable: AITable, cell: AIRecordFieldIdPath): boolean {
const visibleRowIndexMap = aiTable.context!.visibleRowsIndexMap();
const visibleColumnIndexMap = aiTable.context!.visibleColumnsMap();
let isVisible = false;
if (Array.isArray(cell) && !!cell.length) {
const [recordId, fieldId] = cell;
isVisible = visibleRowIndexMap!.has(recordId) && visibleColumnIndexMap.has(fieldId);
}
const [recordId, fieldId] = cell || [];
const isVisible = visibleRowIndexMap!.has(recordId) && visibleColumnIndexMap.has(fieldId);
return isVisible;
},
getCellIndex(aiTable: AITable, cell: AIRecordFieldIdPath): { rowIndex: number; columnIndex: number } | null {
Expand Down
2 changes: 1 addition & 1 deletion packages/grid/src/core/utils/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export function createAITable(records: WritableSignal<AITableRecords>, fields: W
selectedCells: new Set(),
activeCell: null
}),
matchedCells: signal([]),
keywordsMatchedCells: signal(new Set()),
recordsMap: computed(() => {
return records().reduce(
(object, item) => {
Expand Down
3 changes: 0 additions & 3 deletions packages/grid/src/grid-base.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ import { AI_TABLE_GRID_FIELD_SERVICE_MAP, AITableGridFieldService } from './serv
import { AITableGridSelectionService } from './services/selection.service';
import { AIFieldConfig, AITableFieldMenuItem, AITableContextMenuItem, AITableReferences } from './types';
import { AITableFieldPropertyEditor } from './components';
import { AITableGridMatchCellService } from './services/match-cell.service';

@Component({
selector: 'ai-table-grid-base',
Expand Down Expand Up @@ -102,7 +101,6 @@ export class AITableGridBase implements OnInit {
protected aiTableGridFieldService = inject(AITableGridFieldService);
protected aiTableGridEventService = inject(AITableGridEventService);
protected aiTableGridSelectionService = inject(AITableGridSelectionService);
protected aiTableGridMatchCellService = inject(AITableGridMatchCellService);

ngOnInit(): void {
this.initAITable();
Expand All @@ -120,7 +118,6 @@ export class AITableGridBase implements OnInit {
initService() {
this.aiTableGridEventService.initialize(this.aiTable, this.aiFieldConfig()?.fieldRenderers);
this.aiTableGridSelectionService.initialize(this.aiTable);
this.aiTableGridMatchCellService.initialize(this.aiTable);
this.aiTableGridEventService.registerEvents(this.elementRef.nativeElement);
this.aiTableGridFieldService.initAIFieldConfig(this.aiFieldConfig());
this.aiTable.references.set(this.aiReferences());
Expand Down
30 changes: 22 additions & 8 deletions packages/grid/src/grid.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,8 @@ import { AITableGridEventService } from './services/event.service';
import { AITableGridFieldService } from './services/field.service';
import { AITableGridSelectionService } from './services/selection.service';
import { AITableMouseDownType, AITableRendererConfig, ScrollActionOptions } from './types';
import { buildGridLinearRows, getColumnIndicesMap, getDetailByTargetName, handleMouseStyle, isWindows } from './utils';
import { buildGridLinearRows, getColumnIndicesMap, getDetailByTargetName, handleMouseStyle, isCellMatchKeywords, isWindows } from './utils';
import { getMousePosition } from './utils/position';
import { AITableGridMatchCellService } from './services/match-cell.service';

@Component({
selector: 'ai-table-grid',
Expand All @@ -54,7 +53,7 @@ import { AITableGridMatchCellService } from './services/match-cell.service';
class: 'ai-table-grid'
},
imports: [AITableRenderer],
providers: [AITableGridEventService, AITableGridFieldService, AITableGridSelectionService, AITableGridMatchCellService]
providers: [AITableGridEventService, AITableGridFieldService, AITableGridSelectionService]
})
export class AITableGrid extends AITableGridBase implements OnInit, OnDestroy {
private viewContainerRef = inject(ViewContainerRef);
Expand Down Expand Up @@ -154,7 +153,7 @@ export class AITableGrid extends AITableGridBase implements OnInit, OnDestroy {
});
effect(
() => {
this.aiTableGridMatchCellService.findMatchedCells(this.aiKeywords()!, this.aiReferences());
this.setKeywordsMatchedCells();
},
{ allowSignalWrites: true }
);
Expand All @@ -180,6 +179,24 @@ export class AITableGrid extends AITableGridBase implements OnInit, OnDestroy {
});
}

private setKeywordsMatchedCells() {
const keywords = this.aiKeywords();
let matchedCells = new Set<string>();

if (keywords) {
const references = this.aiReferences();
this.aiTable.records().forEach((record) => {
this.aiTable.fields().forEach((field) => {
if (isCellMatchKeywords(this.aiTable, field, record._id, keywords, references)) {
matchedCells.add(`${record._id}:${field._id}`);
}
});
});
}

this.aiTable.keywordsMatchedCells.set(matchedCells);
}

stageMousemove(e: KoEventObject<MouseEvent>) {
if (this.timer) {
cancelAnimationFrame(this.timer);
Expand Down Expand Up @@ -433,10 +450,7 @@ export class AITableGrid extends AITableGridBase implements OnInit, OnDestroy {
(e) =>
e.target instanceof Element &&
!this.containerElement().contains(e.target) &&
!(
e.target.closest(AI_TABLE_PREVENT_CLEAR_SELECTION_CLASS) &&
AITable.getActiveRecordIds(this.aiTable).length > 0
)
!e.target.closest(AI_TABLE_PREVENT_CLEAR_SELECTION_CLASS)
),
takeUntilDestroyed(this.destroyRef)
)
Expand Down
60 changes: 17 additions & 43 deletions packages/grid/src/renderer/creations/create-cells.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,17 +145,17 @@ const getCellBackground = (cell: AIRecordFieldIdPath, isHover: boolean, targetNa
const [recordId, fieldId] = cell;
let background = colors.white;

const _isHoverRecord = isHoverRecord(isHover, targetName);
const _isSelectedRecord = isSelectedRecord(recordId, aiTable);
const _isSelectedField = isSelectedField(fieldId, aiTable);
const _isSiblingActiveCell = isSiblingActiveCell(cell, aiTable);
const _isSiblingCell = isSiblingCell(cell, aiTable);
const _isActiveCell = isActiveCell(cell, aiTable);
const _isSelectedCell = isSelectedCell(cell, aiTable);
const _isMatchedCell = isMatchedCell(cell, aiTable);
const _isHoverRecord = isHoverRecord(isHover, targetName);
const _isKeywordsMatchedCell = isKeywordsMatchedCell(cell, aiTable);

if (_isMatchedCell) {
if (_isKeywordsMatchedCell) {
background = colors.itemMatchBgColor;
} else if (_isSelectedRecord || _isSelectedField || _isSiblingActiveCell || (_isSelectedCell && !_isActiveCell)) {
} else if (_isSelectedRecord || _isSelectedField || _isSiblingCell || (_isSelectedCell && !_isActiveCell)) {
background = colors.itemActiveBgColor;
} else if (_isHoverRecord && !_isActiveCell) {
background = colors.gray80;
Expand All @@ -165,59 +165,33 @@ const getCellBackground = (cell: AIRecordFieldIdPath, isHover: boolean, targetNa
};

const isActiveCell = (cell: AIRecordFieldIdPath, aiTable: AITable): boolean => {
let isActive = false;
const activeCell = AITable.getActiveCell(aiTable);
if (Array.isArray(activeCell) && !!activeCell.length) {
const [activeCellRecordId, activeCellFieldId] = activeCell;
const [recordId, fieldId] = cell;
if (recordId === activeCellRecordId && fieldId === activeCellFieldId) {
isActive = true;
}
}
return isActive;
const [recordId, fieldId] = cell;
const [activeRecordId, activeFieldId] = AITable.getActiveCell(aiTable) || [];
return recordId === activeRecordId && fieldId === activeFieldId;
};

const isSiblingActiveCell = (cell: AIRecordFieldIdPath, aiTable: AITable): boolean => {
let isSiblingCell = false;
const activeCell = AITable.getActiveCell(aiTable);
if (Array.isArray(activeCell) && !!activeCell.length) {
const [recordId, fieldId] = cell;
const [activeCellRecordId, activeCellFieldId] = activeCell;
const selectedCells = aiTable.selection().selectedCells;
isSiblingCell =
selectedCells.size === 1 &&
selectedCells.has(`${activeCellRecordId}:${activeCellFieldId}`) &&
recordId === activeCellRecordId &&
fieldId !== activeCellFieldId;
}
return isSiblingCell;
const isSiblingCell = (cell: AIRecordFieldIdPath, aiTable: AITable): boolean => {
const [recordId, fieldId] = cell;
const [activeRecordId, activeFieldId] = AITable.getActiveCell(aiTable) || [];
return AITable.getActiveRecordIds(aiTable).length === 1 && recordId === activeRecordId && fieldId !== activeFieldId;
};

const isMatchedCell = (cell: AIRecordFieldIdPath, aiTable: AITable): boolean => {
const isKeywordsMatchedCell = (cell: AIRecordFieldIdPath, aiTable: AITable): boolean => {
const [recordId, fieldId] = cell;
let matchedCellsMap: { [key: string]: boolean } = {};
aiTable.matchedCells().forEach((key) => {
matchedCellsMap[key] = true;
});
const isMatchedCell = matchedCellsMap[`${recordId}:${fieldId}`];
return isMatchedCell;
return aiTable.keywordsMatchedCells().has(`${recordId}:${fieldId}`);
};

const isSelectedCell = (cell: AIRecordFieldIdPath, aiTable: AITable): boolean => {
const [recordId, fieldId] = cell;
const selectedCells = aiTable.selection().selectedCells;
const isSelectedCell = selectedCells.has(`${recordId}:${fieldId}`);
return isSelectedCell;
return aiTable.selection().selectedCells.has(`${recordId}:${fieldId}`);
};

const isSelectedField = (fieldId: string, aiTable: AITable): boolean => {
const selectedFields = aiTable.selection().selectedFields;
return selectedFields.has(fieldId);
return aiTable.selection().selectedFields.has(fieldId);
};

const isSelectedRecord = (recordId: string, aiTable: AITable): boolean => {
const selectedRecords = aiTable.selection().selectedRecords;
return selectedRecords.has(recordId);
return aiTable.selection().selectedRecords.has(recordId);
};

const isHoverRecord = (isHover: boolean, targetName: string): boolean => {
Expand Down
1 change: 0 additions & 1 deletion packages/grid/src/services/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
export * from './event.service';
export * from './field.service';
export * from './selection.service';
export * from './match-cell.service';
46 changes: 0 additions & 46 deletions packages/grid/src/services/match-cell.service.ts

This file was deleted.

27 changes: 10 additions & 17 deletions packages/grid/src/services/selection.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,35 +80,28 @@ export class AITableGridSelectionService {

selectCells(startCell: AIRecordFieldIdPath, endCell?: AIRecordFieldIdPath) {
const [startRecordId, startFieldId] = startCell;

if (
!this.aiTable.context!.visibleRowsIndexMap().has(startRecordId) ||
!this.aiTable.context!.visibleColumnsMap().has(startFieldId)
) {
return;
}

const records = this.aiTable.records();
const fields = this.aiTable.fields();
const selectedCells = new Set<string>();
if (!endCell || !endCell.length) {

if (!endCell) {
selectedCells.add(`${startRecordId}:${startFieldId}`);
} else {
const [endRecordId, endFieldId] = endCell;
const startRowIndex = this.aiTable.context!.visibleRowsIndexMap().get(startRecordId)!;
const endRowIndex = this.aiTable.context!.visibleRowsIndexMap().get(endRecordId)!;
const startColIndex = this.aiTable.context!.visibleColumnsMap().get(startFieldId)!;
const endColIndex = this.aiTable.context!.visibleColumnsMap().get(endFieldId)!;

const startRowIndex = records.findIndex((record) => record._id === startRecordId);
const endRowIndex = records.findIndex((record) => record._id === endRecordId);
const startColIndex = fields.findIndex((field) => field._id === startFieldId);
const endColIndex = fields.findIndex((field) => field._id === endFieldId);

const minRowIndex = Math.min(startRowIndex, endRowIndex);
const maxRowIndex = Math.max(startRowIndex, endRowIndex);
const minColIndex = Math.min(startColIndex, endColIndex);
const maxColIndex = Math.max(startColIndex, endColIndex);

const rows = this.aiTable.context!.linearRows();
const fields = AITable.getVisibleFields(this.aiTable);

for (let i = minRowIndex; i <= maxRowIndex; i++) {
for (let j = minColIndex; j <= maxColIndex; j++) {
selectedCells.add(`${rows[i]._id}:${fields[j]._id}`);
selectedCells.add(`${records[i]._id}:${fields[j]._id}`);
}
}
}
Expand Down
1 change: 1 addition & 0 deletions packages/grid/src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,4 @@ export * from './text-measure';
export * from './visible-range';
export * from './field/model';
export * from './field/operate';
export * from './match-keywords';
18 changes: 18 additions & 0 deletions packages/grid/src/utils/match-keywords.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { AITable, AITableField, AITableQueries } from '../core';
import { AITableReferences } from '../types';
import { transformCellValue } from './cell';
import { ViewOperationMap } from './field/model';

export const isCellMatchKeywords = (
aiTable: AITable,
field: AITableField,
recordId: string,
keywords: string,
references: AITableReferences
) => {
const cellValue = AITableQueries.getFieldValue(aiTable, [recordId, field._id]);
const transformValue = transformCellValue(aiTable, field, cellValue);
const fieldMethod = ViewOperationMap[field.type];
let cellFullText: string[] = fieldMethod.cellFullText(transformValue, field, references);
return keywords && cellFullText.length && cellFullText.some((text) => text.toLowerCase().includes(keywords.toLowerCase()));
};
Loading