import { describe, it, expect, beforeEach, afterEach } from "vitest"; import { createRoot, type Root } from "react-dom/client"; import { act } from "react"; import { useState } from "react"; import type { GridHTMLElement, GridItemHTMLElement, GridStack as GridStackInstance } from "gridstack"; import type { GridStackWidget } from "gridstack"; import { GridStack } from "./src/gridstack"; import { useWidgetSerializer, useGridStackItem, useGridStack } from "./src/hooks"; function flush(): Promise { return new Promise((r) => { setTimeout(r, 0); }); } /** * Replicates the DOM/engine bookkeeping GS core does in the `drop` handler when an * item is dragged from one live grid into another (gridstack.ts `.on(this.el, 'drop', ...)`): * the item element is reused via `appendChild` (no `addRemoveCB` call) and the node object * is moved from one engine's node list to the other's. Used to reproduce cross-grid DnD * without driving the real pointer-based drag/drop implementation through jsdom. */ function simulateCrossGridDrop(from: GridStackInstance, to: GridStackInstance, el: GridItemHTMLElement) { const node = el.gridstackNode!; const f = from as unknown as { engine: { nodes: unknown[]; removedNodes: unknown[]; removeNodeFromLayoutCache(n: unknown): void }; _triggerRemoveEvent(): unknown; _triggerChangeEvent(): unknown }; const t = to as unknown as { engine: { nodes: unknown[]; addedNodes: unknown[] }; el: HTMLElement; _triggerAddEvent(): unknown; _triggerChangeEvent(): unknown }; f.engine.removeNodeFromLayoutCache(node); f.engine.nodes = f.engine.nodes.filter((n) => n !== node); f.engine.removedNodes.push(node); f._triggerRemoveEvent(); f._triggerChangeEvent(); node.grid = to; t.engine.nodes.push(node); t.el.appendChild(el); t.engine.addedNodes.push(node); t._triggerAddEvent(); t._triggerChangeEvent(); } function Num({ start }: { start: number }) { const [n] = useState(start); useWidgetSerializer({ serialize: () => ({ extra: n }) }); return {n}; } describe("GridStack React wrapper", () => { let container: HTMLDivElement; let root: Root; beforeEach(() => { container = document.createElement("div"); document.body.appendChild(container); root = createRoot(container); }); afterEach(() => { act(() => { root.unmount(); }); container.remove(); }); it("renders component mode into .grid-stack-item-content via portal", async () => { await act(async () => { root.render( ) => ( {String(p.label ?? "")} ), }} /> ); }); await act(flush); expect(document.querySelector("[data-testid=\"portal\"]")?.textContent).toBe( "hello" ); }); it("save() merges useWidgetSerializer into widget props", async () => { await act(async () => { root.render( ) => ( ), }} /> ); }); await act(flush); const gridEl = container.querySelector(".grid-stack") as GridHTMLElement; const g = gridEl?.gridstack; expect(g).toBeTruthy(); const saved = g!.save(true, false) as GridStackWidget[]; const w = saved.find((n) => String(n.id) === "c1"); expect(w?.props?.extra).toBe(7); }); it("supports two sibling grids", async () => { await act(async () => { root.render( <> ); }); await act(flush); expect(container.querySelectorAll(".grid-stack").length).toBe(2); }); it("keeps React host chrome outside the .grid-stack root (no overlap with items)", async () => { await act(async () => { root.render(
toolbar
); }); await act(flush); const chrome = container.querySelector("[data-testid=\"host-chrome\"]"); const stack = container.querySelector(".grid-stack"); expect(chrome).toBeTruthy(); expect(stack).toBeTruthy(); expect(stack?.contains(chrome)).toBe(false); }); it("unmount destroys without throwing", async () => { await act(async () => { root.render( ) => ( {String(p.t ?? "")} ), }} /> ); }); await act(flush); await act(async () => { root.render(
); }); await act(flush); expect(container.querySelector(".grid-stack")).toBeNull(); }); it("keeps component content rendered after cross-grid drag & drop (#3371)", async () => { const T = (p: Record) => ( {String(p.label ?? "")} ); await act(async () => { root.render( <> ); }); await act(flush); expect(document.querySelector("[data-testid=\"portal\"]")?.textContent).toBe("hello"); const [gridElA, gridElB] = Array.from( container.querySelectorAll(".grid-stack") ) as GridHTMLElement[]; const gridA = gridElA.gridstack!; const gridB = gridElB.gridstack!; const itemEl = gridElA.querySelector(".grid-stack-item") as GridItemHTMLElement; await act(async () => { simulateCrossGridDrop(gridA, gridB, itemEl); }); await act(flush); // The item's DOM element physically moved into grid B's container... expect(gridElB.contains(itemEl)).toBe(true); // ...and its React-rendered content must have followed, not been unmounted. expect(document.querySelector("[data-testid=\"portal\"]")?.textContent).toBe("hello"); }); it("#2976 renders a sidebar drag-in widget that has a component but no id", async () => { await act(async () => { root.render( ) => ( {String(p.label ?? "")} ), }} /> ); }); await act(flush); const gridEl = container.querySelector(".grid-stack") as GridHTMLElement; const g = gridEl?.gridstack as GridStackInstance; expect(g).toBeTruthy(); // What GS core does at the end of its `drop` handler for a sidebar item // (gridstack.ts: `el = this.addWidget(node)`): the spec comes straight from // GridStack.setupDragIn(..., widgets) so it has NO id of its own. await act(async () => { g.addWidget({ w: 2, h: 2, component: "Side", props: { label: "dropped" } } as GridStackWidget); }); await act(flush); expect( document.querySelector('[data-testid="dragin"]')?.textContent ).toBe("dropped"); // a second drop of the same spec must get its own portal, not collide with the first await act(async () => { g.addWidget({ w: 2, h: 2, component: "Side", props: { label: "again" } } as GridStackWidget); }); await act(flush); const both = Array.from(document.querySelectorAll('[data-testid="dragin"]')).map(e => e.textContent); expect(both.sort()).toEqual(["again", "dropped"]); // and the minted id round-trips through save() so layouts stay reloadable const saved = g.save(false) as GridStackWidget[]; expect(saved.length).toBe(2); expect(saved.every(w => !!w.id)).toBe(true); expect(new Set(saved.map(w => w.id)).size).toBe(2); }); it("#2974 re-renders item content after an interactive resize (change event)", async () => { function ShowH() { const { node } = useGridStackItem(); return {String(node?.h ?? "?")}; } await act(async () => { root.render( }} /> ); }); await act(flush); expect(document.querySelector('[data-testid="h"]')?.textContent).toBe("2"); const gridEl = container.querySelector(".grid-stack") as GridHTMLElement; const g = gridEl?.gridstack as GridStackInstance; // what an interactive resize leaves behind: the node is mutated in place and `change` fires. // (a programmatic grid.update() instead goes through updateCB -> requestUpdate, which did bump) const t = g as unknown as { _triggerChangeEvent(): unknown }; await act(async () => { g.engine.nodes[0].h = 5; g.engine.nodes[0]._dirty = true; t._triggerChangeEvent(); }); await act(flush); expect(document.querySelector('[data-testid="h"]')?.textContent).toBe("5"); }); it("#3459 keeps item content mounted when change fires while node.el is the drag placeholder", async () => { let mounts = 0; function Probe() { useState(() => { mounts++; return 0; }); return hi; } await act(async () => { root.render( }} /> ); }); await act(flush); expect(document.querySelector('[data-testid="probe"]')).not.toBeNull(); const g = (container.querySelector(".grid-stack") as GridHTMLElement).gridstack as GridStackInstance; const node = g.engine.nodes[0]; const realEl = node.el!; // what _onStartMoving leaves behind: node.el is the placeholder (no .grid-stack-item-content) node.el = g.placeholder; const t = g as unknown as { _triggerChangeEvent(): unknown }; await act(async () => { node.h = 3; node._dirty = true; t._triggerChangeEvent(); }); await act(flush); expect(document.querySelector('[data-testid="probe"]')).not.toBeNull(); expect(mounts).toBe(1); node.el = realEl; }); it("#2960 useGridStack().removeWidget takes an element, matching core's signature", async () => { let api: ReturnType | undefined; function Probe() { api = useGridStack(); return null; } await act(async () => { root.render( x }} > ); }); await act(flush); const gridEl = container.querySelector(".grid-stack") as GridHTMLElement; const g = gridEl?.gridstack as GridStackInstance; expect(g.engine.nodes.length).toBe(1); const el = g.engine.nodes[0].el as GridItemHTMLElement; await act(async () => { api!.removeWidget(el, true, true); }); await act(flush); expect(g.engine.nodes.length).toBe(0); expect(document.querySelector('[data-testid="keep"]')).toBeNull(); }); });