Files
Homarr/src/components/Dashboard/Wrappers/gridstack/init-gridstack.ts

71 lines
2.2 KiB
TypeScript
Raw Normal View History

2022-12-04 17:36:30 +01:00
import { GridStack, GridStackNode } from 'fily-publish-gridstack';
import { MutableRefObject, RefObject } from 'react';
import { AppType } from '../../../../types/app';
import { IWidget } from '../../../../widgets/widgets';
2022-12-04 17:36:30 +01:00
export const initializeGridstack = (
areaType: 'wrapper' | 'category' | 'sidebar',
wrapperRef: RefObject<HTMLDivElement>,
gridRef: MutableRefObject<GridStack | undefined>,
itemRefs: MutableRefObject<Record<string, RefObject<HTMLDivElement>>>,
areaId: string,
items: AppType[],
widgets: IWidget<string, any>[],
2022-12-04 17:36:30 +01:00
isEditMode: boolean,
events: {
onChange: (changedNode: GridStackNode) => void;
onAdd: (addedNode: GridStackNode) => void;
}
) => {
if (!wrapperRef.current) return;
// calculates the currently available count of columns
const columnCount = areaType === 'sidebar' ? 4 : 12;
2022-12-04 17:36:30 +01:00
const minRow = areaType !== 'sidebar' ? 1 : Math.floor(wrapperRef.current.offsetHeight / 64);
// initialize gridstack
2022-12-22 11:45:48 +09:00
const newGrid = gridRef;
newGrid.current = GridStack.init(
2022-12-04 17:36:30 +01:00
{
column: columnCount,
margin: 10,
cellHeight: 64,
float: true,
alwaysShowResizeHandle: 'mobile',
acceptWidgets: true,
disableOneColumnMode: true,
staticGrid: !isEditMode,
minRow,
},
// selector of the gridstack item (it's eather category or wrapper)
`.grid-stack-${areaType}[data-${areaType}='${areaId}']`
);
2022-12-22 11:45:48 +09:00
const grid = newGrid.current;
2022-12-04 17:36:30 +01:00
// Add listener for moving items around in a wrapper
grid.on('change', (_, el) => {
const nodes = el as GridStackNode[];
const firstNode = nodes.at(0);
if (!firstNode) return;
events.onChange(firstNode);
});
// Add listener for moving items in config from one wrapper to another
grid.on('added', (_, el) => {
const nodes = el as GridStackNode[];
const firstNode = nodes.at(0);
if (!firstNode) return;
events.onAdd(firstNode);
});
2022-12-04 17:36:30 +01:00
grid.batchUpdate();
grid.removeAll(false);
items.forEach(
({ id }) =>
itemRefs.current[id] && grid.makeWidget(itemRefs.current[id].current as HTMLDivElement)
);
widgets.forEach(
({ id }) =>
itemRefs.current[id] && grid.makeWidget(itemRefs.current[id].current as HTMLDivElement)
2022-12-04 17:36:30 +01:00
);
grid.batchUpdate(false);
};