Files
Homarr/src/components/Board/gridstack/init-gridstack.ts

76 lines
2.2 KiB
TypeScript
Raw Normal View History

import { GridItemHTMLElement, GridStack, GridStackNode } from 'fily-publish-gridstack';
2023-01-20 20:24:25 +01:00
import { MutableRefObject, RefObject } from 'react';
import { Item, Section } from '~/components/Board/context';
2022-12-04 17:36:30 +01:00
type InitializeGridstackProps = {
section: Section;
refs: {
wrapper: RefObject<HTMLDivElement>;
items: MutableRefObject<Record<string, RefObject<GridItemHTMLElement>>>;
gridstack: MutableRefObject<GridStack | undefined>;
};
isEditMode: boolean;
sectionColumnCount: number;
};
export const initializeGridstack = ({
section,
refs,
isEditMode,
sectionColumnCount,
}: InitializeGridstackProps) => {
if (!refs.wrapper.current) return;
2022-12-04 17:36:30 +01:00
// calculates the currently available count of columns
const columnCount = section.type === 'sidebar' ? 2 : sectionColumnCount;
const minRow =
section.type !== 'sidebar' ? 1 : Math.floor(refs.wrapper.current.offsetHeight / 128);
2022-12-04 17:36:30 +01:00
// initialize gridstack
const newGrid = refs.gridstack;
2022-12-22 11:45:48 +09:00
newGrid.current = GridStack.init(
2022-12-04 17:36:30 +01:00
{
column: columnCount,
margin: section.type === 'sidebar' ? 5 : 10,
2023-01-06 23:50:08 +01:00
cellHeight: 128,
2022-12-04 17:36:30 +01:00
float: true,
alwaysShowResizeHandle: 'mobile',
acceptWidgets: true,
disableOneColumnMode: true,
staticGrid: !isEditMode,
minRow,
2023-01-06 22:46:07 +01:00
animate: false,
2022-12-04 17:36:30 +01:00
},
// selector of the gridstack item (it's eather category or wrapper)
`.grid-stack-${section.type}[data-${section.type}='${section.id}']`
2022-12-04 17:36:30 +01:00
);
2022-12-22 11:45:48 +09:00
const grid = newGrid.current;
if (!grid) return;
2023-01-06 22:46:07 +01:00
// Must be used to update the column count after the initialization
2023-01-17 21:35:17 +01:00
grid.column(columnCount, 'none');
2022-12-04 17:36:30 +01:00
grid.batchUpdate();
grid.removeAll(false);
section.items.forEach((item) => {
const ref = refs.items.current[item.id]?.current;
setAttributesFromShape(ref, item);
ref && grid.makeWidget(ref);
2023-01-07 09:45:00 +01:00
});
2022-12-04 17:36:30 +01:00
grid.batchUpdate(false);
};
2023-01-06 23:50:08 +01:00
function setAttributesFromShape(ref: GridItemHTMLElement | null, item: Item) {
if (!item || !ref) return;
ref.setAttribute('gs-x', item.x.toString());
ref.setAttribute('gs-y', item.y.toString());
ref.setAttribute('gs-w', item.width.toString());
ref.setAttribute('gs-h', item.height.toString());
2023-01-06 23:50:08 +01:00
}
2023-01-07 23:25:13 +01:00
export type ItemWithUnknownLocation = {
2023-01-07 23:25:13 +01:00
x?: number;
y?: number;
w?: number;
h?: number;
type: 'app' | 'widget';
id: string;
};