Skip to content

Commit

Permalink
refactor: simplify props, improve updates
Browse files Browse the repository at this point in the history
  • Loading branch information
bn-l committed Nov 30, 2024
1 parent 29cb8e2 commit 09b7239
Show file tree
Hide file tree
Showing 5 changed files with 173 additions and 24 deletions.
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,9 @@
"publish-ci": "tsx scripts/publish-ci.ts",
"format": "prettier --write .",
"lint": "prettier --check . && eslint .",
"prebumpp": "npm run tsx scripts/updateInitialGridOptionsSet.ts",
"test:unit": "vitest",
"run:file": "node",
"run:file": "tsx",
"test": "npm run test:unit -- --run && npm run test:e2e",
"test:e2e": "playwright test"
},
Expand Down
49 changes: 49 additions & 0 deletions scripts/updateInitialGridOptionsSet.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { readFile, writeFile } from "node:fs/promises";
import { resolve } from "node:path";

async function updateInitialGridOptions() {
try {
// Read the propertyKeys.d.ts file
const filePath = resolve(
"node_modules/@ag-grid-community/core/dist/types/src/propertyKeys.d.ts",
);
const content = await readFile(filePath, "utf-8");

// Extract INITIAL_GRID_OPTION_KEYS object using regex
const match = content.match(/INITIAL_GRID_OPTION_KEYS:\s*{([^}]*)}/);
if (!match) {
console.error(
"Could not find INITIAL_GRID_OPTION_KEYS in the file",
);
return;
}

// Extract the keys from the object
const keysString = match[1];
const keys = keysString
.split("\n")
.map((line) => line.trim())
.filter((line) => line.length > 0)
.map((line) => line.replace(":", " ").split(" ")[0].trim());

// Generate the new content for initialGridOptionsSet.ts
const newContent = `// A list of grid options to exclude from the update
export default new Set([
${keys.map((key) => `"${key}"`).join(",\n ")}
]);
`;

// Write the updated content
await writeFile(
"src/lib/initialGridOptionsSet.ts",
newContent,
"utf-8",
);
console.log("Successfully updated initialGridOptionsSet.ts");
} catch (error) {
console.error("Error updating initial grid options:", error);
}
}

updateInitialGridOptions();
34 changes: 17 additions & 17 deletions src/lib/AgGrid.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,12 @@
import { onMount } from "svelte";
import SvelteFrameworkOverrides from "./SvelteFrameworkOverrides.svelte";
import initialGridOptionsList from "./initialGridOptionsSet";
interface Props {
initialOptions: GridOptions<TData>;
updateOptions?: Omit<GridOptions<TData>, "getRowId">;
gridOptions: GridOptions<TData>;
/**
* Include a id property on row objects you pass to this or a getRowId() function
* to initialOptions.
* to initialOptions. Can set here or in gridOptions.
*/
rowData?: TData[];
modules?: Module[];
Expand All @@ -33,8 +32,7 @@
}
let {
initialOptions,
updateOptions,
gridOptions,
rowData,
modules,
gridClass,
Expand All @@ -50,31 +48,33 @@
frameworkOverrides: new SvelteFrameworkOverrides(),
};
// // Update on theme change
// $effect(() => {
// api?.setGridOption("theme", theme);
// });
$effect(() => {
// prettier-ignore
const updatedOptions: GridOptions<TData> = {};
for (const key in gridOptions) {
if (!initialGridOptionsList.has(key)) {
// @ts-expect-error
updatedOptions[key] = gridOptions[key];
}
}
api?.updateGridOptions(updatedOptions);
});
// Update grid on data change + init
$effect(() => {
api?.setGridOption("rowData", rowData);
// if (sizeColumnsToFit) api?.sizeColumnsToFit();
});
$effect(() => {
if (updateOptions) {
api?.updateGridOptions({ ...updateOptions });
}
});
$effect(() => {
if (quickFilterText !== undefined) {
api?.setGridOption("quickFilterText", quickFilterText);
}
});
onMount(() => {
api = createGrid(divContainerEl!, initialOptions, gridParams);
api = createGrid(divContainerEl!, gridOptions, gridParams);
if (sizeColumnsToFit) api.sizeColumnsToFit();
return () => {
Expand Down
88 changes: 88 additions & 0 deletions src/lib/initialGridOptionsSet.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
// A list of grid options to exclude from the update

export default new Set([
"enableBrowserTooltips",
"tooltipTrigger",
"tooltipMouseTrack",
"tooltipShowMode",
"tooltipInteraction",
"defaultColGroupDef",
"suppressAutoSize",
"skipHeaderOnAutoSize",
"autoSizeStrategy",
"components",
"stopEditingWhenCellsLoseFocus",
"undoRedoCellEditing",
"undoRedoCellEditingLimit",
"excelStyles",
"cacheQuickFilter",
"advancedFilterModel",
"customChartThemes",
"chartThemeOverrides",
"chartToolPanelsDef",
"loadingCellRendererSelector",
"localeText",
"keepDetailRows",
"keepDetailRowsCount",
"detailRowHeight",
"detailRowAutoHeight",
"tabIndex",
"valueCache",
"valueCacheNeverExpires",
"enableCellExpressions",
"suppressTouch",
"suppressAsyncEvents",
"suppressBrowserResizeObserver",
"suppressPropertyNamesCheck",
"debug",
"dragAndDropImageComponent",
"loadingOverlayComponent",
"suppressLoadingOverlay",
"noRowsOverlayComponent",
"paginationPageSizeSelector",
"paginateChildRows",
"pivotPanelShow",
"pivotSuppressAutoColumn",
"suppressExpandablePivotGroups",
"aggFuncs",
"suppressAggFuncInHeader",
"allowShowChangeAfterFilter",
"ensureDomOrder",
"enableRtl",
"suppressColumnVirtualisation",
"suppressMaxRenderedRowRestriction",
"suppressRowVirtualisation",
"rowDragText",
"suppressGroupMaintainValueType",
"groupLockGroupColumns",
"rowGroupPanelSuppressSort",
"suppressGroupRowsSticky",
"rowModelType",
"cacheOverflowSize",
"infiniteInitialRowCount",
"serverSideInitialRowCount",
"suppressServerSideInfiniteScroll",
"maxBlocksInCache",
"maxConcurrentDatasourceRequests",
"blockLoadDebounceMillis",
"serverSideOnlyRefreshFilteredGroups",
"serverSidePivotResultFieldSeparator",
"viewportRowModelPageSize",
"viewportRowModelBufferSize",
"debounceVerticalScrollbar",
"suppressAnimationFrame",
"suppressPreventDefaultOnMouseWheel",
"scrollbarWidth",
"icons",
"suppressRowTransform",
"gridId",
"enableGroupEdit",
"initialState",
"processUnpinnedColumns",
"createChartContainer",
"getLocaleText",
"getRowId",
"reactiveCustomComponents",
"columnMenu",
"suppressSetFilterByDefault"
]);
23 changes: 17 additions & 6 deletions src/routes/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
</div>
<div class="flex w-full justify-center">
<div class="m-10 w-3/4 max-w-[65rem]">
<AgGrid {initialOptions} {rowData} {modules} {quickFilterText} />
<AgGrid {gridOptions} {rowData} {modules} {quickFilterText} />
</div>
</div>
<!-- <button
Expand Down Expand Up @@ -74,7 +74,7 @@
);
// prettier-ignore
let initialOptions: GridOptions<PaymentRow> = $state< GridOptions<PaymentRow>>({
let gridOptions: GridOptions<PaymentRow> = $state< GridOptions<PaymentRow>>({
defaultColDef: {
enableCellChangeFlash: true,
suppressMovable: true,
Expand Down Expand Up @@ -109,13 +109,19 @@
},
},
{ field: "sentAt" },
{ field: "confirmedSent" },
{
field: "confirmedSent",
maxWidth: 100,
cellClass: "flex justify-center items-center"
},
],
// Important for reducing dom updates and improving performance
getRowId: (params) => params.data.id.toString(),
domLayout: "autoHeight",
theme: themeQuartz,
theme: themeQuartz.withParams({
accentColor: "#EE28ED",
}),
autoSizeStrategy: {
type: "fitCellContents"
},
Expand All @@ -124,14 +130,14 @@
// cellFlashDuration: 100,
// cellFadeDuration: 300,
pagination: true,
paginationPageSizeSelector: [10, 25, 50, 100],
paginationPageSize: 10,
// paginationAutoPageSize: true,
});
onMount(() => {
const interval = setInterval(() => {
// rowData.push(generatePaymentRow());
const indicesToUpdate = Array.from({ length: 50 }, () =>
Math.floor(Math.random() * rowData.length),
);
Expand Down Expand Up @@ -159,8 +165,13 @@
}
rowData[index] = updatedRow;
});
}, 1600);
gridOptions.theme = themeQuartz.withParams({
accentColor: `#${Math.floor(Math.random() * 16777215)
.toString(16)
.padStart(6, "0")}`,
});
}, 1600);
return () => clearInterval(interval);
});
Expand Down

0 comments on commit 09b7239

Please sign in to comment.