From 0f8d10eb912bd254e28b53dd7b9a2db3c7f5fcf6 Mon Sep 17 00:00:00 2001 From: Ajay Ghanwat Date: Sat, 5 Sep 2026 16:28:11 +0530 Subject: [PATCH] Support explicit empty slot drop zones in shared editor --- packages/block-editor/package.json | 2 +- packages/block-editor/src/runtime.ts | 10 ++++++ packages/block-editor/test/runtime.test.ts | 31 ++++++++++++++++-- packages/dnd/package.json | 2 +- packages/dnd/src/manager.ts | 23 +++++++++++--- packages/dnd/src/types.ts | 8 +++++ packages/dnd/test/manager-lifecycle.test.ts | 35 +++++++++++++++++++-- 7 files changed, 100 insertions(+), 11 deletions(-) diff --git a/packages/block-editor/package.json b/packages/block-editor/package.json index 6b3824c1..fe223019 100644 --- a/packages/block-editor/package.json +++ b/packages/block-editor/package.json @@ -1,6 +1,6 @@ { "name": "@wrnexus/block-editor", - "version": "0.1.4", + "version": "0.1.5", "type": "module", "description": "Hydrated accessible editor runtime for WRNexus block documents.", "exports": { diff --git a/packages/block-editor/src/runtime.ts b/packages/block-editor/src/runtime.ts index cdf83cb4..0c59b744 100644 --- a/packages/block-editor/src/runtime.ts +++ b/packages/block-editor/src/runtime.ts @@ -107,6 +107,16 @@ export function mountBlockEditor(root: HTMLElement, options: MountEditorOptions) }); }, }); + for (const element of root.querySelectorAll("[data-block-slot-target][data-block-parent]")) { + const parentId = element.dataset.blockParent!; + const slot = element.dataset.blockSlotTarget!; + const hasChildren = [...root.querySelectorAll("[data-block-id][data-block-parent][data-block-slot]")] + .some(child => child.dataset.blockParent === parentId && child.dataset.blockSlot === slot); + if (hasChildren) continue; + const group = JSON.stringify([parentId, slot]); + groups.set(group, { parentId, slot }); + cleanups.push(manager.registerDropZone({ id: `wrn-slot:${group}`, group, index: 0, element })); + } for (const element of root.querySelectorAll( "[data-block-id][data-block-parent][data-block-slot]", )) { diff --git a/packages/block-editor/test/runtime.test.ts b/packages/block-editor/test/runtime.test.ts index 4721bfd0..94ca6ec1 100644 --- a/packages/block-editor/test/runtime.test.ts +++ b/packages/block-editor/test/runtime.test.ts @@ -1,7 +1,7 @@ import { expect, test } from "bun:test"; import { readFileSync } from "node:fs"; import { Window } from "happy-dom"; -import type { DndManagerOptions, SortableRegistration } from "@wrnexus/dnd"; +import type { DndManagerOptions, SortableRegistration, DropZoneRegistration } from "@wrnexus/dnd"; import type { MountedEditor, MountEditorOptions } from "../src/runtime.ts"; const code = new Bun.Transpiler({ loader: "ts" }) @@ -19,13 +19,18 @@ function fixture(onMove: MountEditorOptions["onMove"] = () => false) { const backends: Array<{ options: DndManagerOptions; registrations: SortableRegistration[]; + zones: DropZoneRegistration[]; destroyed: number; }> = []; const mount = new Function("createDndManager", code + ";return mountBlockEditor;")( (options: DndManagerOptions) => { - const backend = { options, registrations: [] as SortableRegistration[], destroyed: 0 }; + const backend = { options, registrations: [] as SortableRegistration[], zones: [] as DropZoneRegistration[], destroyed: 0 }; backends.push(backend); return { + registerDropZone: (registration: DropZoneRegistration) => { + backend.zones.push(registration); + return () => {}; + }, registerSortable: (registration: SortableRegistration) => { backend.registrations.push(registration); return () => {}; @@ -66,6 +71,28 @@ test("cancelled optimistic moves restore original DOM nodes across containers", f.editor.destroy(); }); +test("empty named slot targets produce validated editor move intents and refresh away when populated", async () => { + const moves: unknown[] = []; + const f = fixture(intent => { moves.push(intent); return true; }); + const target = f.document.createElement("div"); + target.dataset.blockParent = "parent:empty"; + target.dataset.blockSlotTarget = "content:empty"; + f.root.append(target); + f.editor.refresh(); + const backend = f.backends.at(-1)!; + expect(backend.zones).toHaveLength(1); + const zone = backend.zones[0]!; + expect(backend.options.accept!(["a"], { group: zone.group, index: 0 })).toBe(true); + await backend.options.onMoveIntent({ ids: ["a"], from: [], to: { group: zone.group, index: 0 } }); + expect(moves).toEqual([{ nodeIds: ["a"], to: { parentId: "parent:empty", slot: "content:empty", index: 0 } }]); + const child = f.root.querySelector('[data-block-id="a"]')! as any; + child.dataset.blockParent = "parent:empty"; child.dataset.blockSlot = "content:empty"; + target.append(child); + f.editor.refresh(); + expect(f.backends.at(-1)!.zones).toHaveLength(0); + f.editor.destroy(); +}); + test("slot and parent identifiers containing colons round-trip without collisions", async () => { const moves: unknown[] = []; const f = fixture((intent) => { diff --git a/packages/dnd/package.json b/packages/dnd/package.json index 5f4db0bd..beefae78 100644 --- a/packages/dnd/package.json +++ b/packages/dnd/package.json @@ -1,6 +1,6 @@ { "name": "@wrnexus/dnd", - "version": "0.1.2", + "version": "0.1.3", "type": "module", "description": "Stable accessible drag-and-drop primitives for WRNexus.", "exports": { diff --git a/packages/dnd/src/manager.ts b/packages/dnd/src/manager.ts index de0e6ce8..7aacbec5 100644 --- a/packages/dnd/src/manager.ts +++ b/packages/dnd/src/manager.ts @@ -1,4 +1,4 @@ -import { DragDropManager } from "@dnd-kit/dom"; +import { DragDropManager, Droppable } from "@dnd-kit/dom"; import { Sortable } from "@dnd-kit/dom/sortable"; import type { DndManager, @@ -19,6 +19,7 @@ export function createDndManager(options: DndManagerOptions): DndManager { } >(); const manager = new DragDropManager(); + const zones = new Map(); let activeIds: Array = []; let generation = 0; let destroyed = false; @@ -39,7 +40,7 @@ export function createDndManager(options: DndManagerOptions): DndManager { const target = event.operation.target as (typeof event.operation.target & { group?: string | number; index?: number }) | null; if (!target) return; - const destination = { group: target.group ?? "default", index: target.index ?? 0 }; + const destination = zones.get(target.id)?.location ?? { group: target.group ?? "default", index: target.index ?? 0 }; if (options.accept && !options.accept(activeIds, destination)) { event.preventDefault(); options.announce?.({ type: "invalid", ids: activeIds, location: destination }); @@ -70,7 +71,7 @@ export function createDndManager(options: DndManagerOptions): DndManager { index: source.initialIndex ?? source.index ?? 0, }, ], - to: { group: source.group ?? "default", index: source.index ?? 0 }, + to: { ...(event.operation.target ? zones.get(event.operation.target.id)?.location : undefined) ?? { group: source.group ?? "default", index: source.index ?? 0 } }, }; // A pending commit must not own the next gesture's selection or lifecycle. activeIds = []; @@ -96,9 +97,21 @@ export function createDndManager(options: DndManagerOptions): DndManager { }); return { + registerDropZone(registration) { + if (destroyed) throw new Error("Cannot register a drop zone after manager destruction."); + if (entries.has(registration.id) || zones.has(registration.id)) throw new Error(`Duplicate draggable or drop zone id ${String(registration.id)}.`); + if (!Number.isSafeInteger(registration.index) || registration.index < 0) throw new Error("Drop zone index must be a non-negative safe integer."); + const droppable = new Droppable({ id: registration.id, element: registration.element, accept: registration.accepts, disabled: registration.disabled }, manager); + zones.set(registration.id, { droppable, location: { group: registration.group, index: registration.index } }); + return () => { + if (zones.get(registration.id)?.droppable !== droppable) return; + droppable.destroy(); + zones.delete(registration.id); + }; + }, registerSortable(registration) { if (destroyed) throw new Error("Cannot register a sortable after manager destruction."); - if (entries.has(registration.id)) + if (entries.has(registration.id) || zones.has(registration.id)) throw new Error(`Duplicate sortable id ${String(registration.id)}.`); const sortable = new Sortable( { @@ -134,6 +147,8 @@ export function createDndManager(options: DndManagerOptions): DndManager { activeIds = []; for (const entry of entries.values()) entry.sortable.destroy(); entries.clear(); + for (const zone of zones.values()) zone.droppable.destroy(); + zones.clear(); manager.destroy(); }, }; diff --git a/packages/dnd/src/types.ts b/packages/dnd/src/types.ts index 420be5b0..3a0be4d8 100644 --- a/packages/dnd/src/types.ts +++ b/packages/dnd/src/types.ts @@ -40,6 +40,14 @@ export interface DndManagerOptions { } export interface DndManager { + registerDropZone(registration: DropZoneRegistration): () => void; registerSortable(registration: SortableRegistration): () => void; destroy(): void; } + +export interface DropZoneRegistration extends SortableLocation { + id: DndId; + element: HTMLElement; + accepts?: DndId[]; + disabled?: boolean; +} diff --git a/packages/dnd/test/manager-lifecycle.test.ts b/packages/dnd/test/manager-lifecycle.test.ts index 82349999..36bdcd9e 100644 --- a/packages/dnd/test/manager-lifecycle.test.ts +++ b/packages/dnd/test/manager-lifecycle.test.ts @@ -36,8 +36,9 @@ function fixture(overrides: Partial = {}) { const create = new Function( "DragDropManager", "Sortable", + "Droppable", compiled + ";return createDndManager;", - )(Backend, Sortable); + )(Backend, Sortable, Sortable); const manager: DndManager = create({ onMoveIntent: () => true, announce: (event: DndAnnouncement) => announcements.push(event), @@ -54,8 +55,8 @@ function fixture(overrides: Partial = {}) { announcements, instances, start: (id: string) => listeners.dragstart!(event(id)), - end: (id: string) => listeners.dragend!(event(id)), - over: (target: { group: string; index: number }) => { + end: (id: string, target?: { id: string }) => listeners.dragend!({ ...event(id), operation: { ...event(id).operation, target } }), + over: (target: { id?: string; group?: string; index?: number }) => { let prevented = false; listeners.dragover!({ ...event("first"), @@ -93,6 +94,34 @@ test("late drop resolution cannot clear or announce a newer gesture", async () = ]); }); +test("empty drop zones use explicit locations for acceptance and commit", async () => { + const commits: unknown[] = []; + const f = fixture({ accept: (_ids, to) => to.group === "empty", onMoveIntent: intent => { commits.push(intent.to); } }); + const registration = { id: "zone", group: "empty", index: 0, element: {} as HTMLElement }; + const cleanup = f.manager.registerDropZone(registration); + f.start("block"); + expect(f.over({ id: "zone" })).toBe(false); + expect(f.announcements.at(-1)?.location).toEqual({ group: "empty", index: 0 }); + await f.end("block", { id: "zone" }); + expect(commits).toEqual([{ group: "empty", index: 0 }]); + expect(() => f.manager.registerSortable(registration)).toThrow("Duplicate"); + cleanup(); + f.manager.registerDropZone(registration); + cleanup(); + expect(() => f.manager.registerDropZone(registration)).toThrow("Duplicate"); + f.manager.destroy(); f.manager.destroy(); + expect(f.instances.map(instance => instance.destroyed)).toEqual([1, 1]); + expect(() => f.manager.registerDropZone(registration)).toThrow("destruction"); +}); + +test("invalid drop zone indices are rejected before backend registration", () => { + const f = fixture(); + for (const index of [-1, 0.5, Infinity, Number.MAX_SAFE_INTEGER + 1]) { + expect(() => f.manager.registerDropZone({ id: "zone", group: "empty", index, element: {} as HTMLElement })).toThrow("index"); + } + expect(f.instances).toEqual([]); +}); + test("hover acceptance checks the proposed target instead of the source's old group", () => { const f = fixture({ accept: (_ids, to) => to.group === "allowed" }); f.start("first");