diff --git a/packages/core/src/runtime/editingAgent.test.ts b/packages/core/src/runtime/editingAgent.test.ts index ec0bb19fd1..5b36eb780e 100644 --- a/packages/core/src/runtime/editingAgent.test.ts +++ b/packages/core/src/runtime/editingAgent.test.ts @@ -200,6 +200,7 @@ describe("installEditingAgent", () => { "max-z-index", "crop-lift", "edit-element", + "stacking-family", "gsap-set", "patch-tweens", "soft-reload", diff --git a/packages/core/src/runtime/editingAgent.ts b/packages/core/src/runtime/editingAgent.ts index 8fc08480df..9736c41c05 100644 --- a/packages/core/src/runtime/editingAgent.ts +++ b/packages/core/src/runtime/editingAgent.ts @@ -39,6 +39,7 @@ import { gestureStart } from "./editingGestureStart"; import { gsapSnapshot } from "./editing/gsapSnapshot"; import { motionPathHome } from "./editing/motionPathHome"; import { cropLift } from "./editing/cropLift"; +import { stackingFamily } from "./editingLayers"; import { gsapSet } from "./editing/gsapSet"; import { patchTweens } from "./editing/patchTween"; import { softReload } from "./editing/softReload"; @@ -224,6 +225,7 @@ const HANDLERS: Handlers = { "max-z-index": () => maxZIndex(), "crop-lift": cropLift, "edit-element": editElement, + "stacking-family": stackingFamily, "gsap-set": gsapSet, "patch-tweens": patchTweens, "soft-reload": softReload, diff --git a/packages/core/src/runtime/editingLayers.test.ts b/packages/core/src/runtime/editingLayers.test.ts index 27f35c09dc..c0bbf58173 100644 --- a/packages/core/src/runtime/editingLayers.test.ts +++ b/packages/core/src/runtime/editingLayers.test.ts @@ -1,7 +1,7 @@ import { afterEach, describe, expect, it } from "vitest"; import { MAX_QUERY_MATCHES } from "./editingElement"; -import { elementForHandle } from "./editingHandles"; -import { layersOf } from "./editingLayers"; +import { elementForHandle, handleFor } from "./editingHandles"; +import { layersOf, stackingFamily } from "./editingLayers"; afterEach(() => { document.body.innerHTML = ""; @@ -76,3 +76,35 @@ describe("layers", () => { expect(layersOf("0123456789abcdef:1")).toMatchObject({ layers: [], missingGroup: true }); }); }); + +describe("stacking-family", () => { + const family = (id: string) => + stackingFamily({ handle: handleFor(document.getElementById(id)!) }); + + it("answers an element's painting siblings in DOM order with their z-index, hidden ones too", () => { + document.body.innerHTML = `
+
+ + +
`; + const reply = family("back"); + expect(reply.locked).toBe(false); + expect( + reply.family!.map(({ handle, zIndex }) => [elementForHandle(handle)!.id, zIndex]), + ).toEqual([ + ["back", 1], + ["gone", 5], + ["front", 2], + ]); + }); + + it("says when a locked clip holds the element", () => { + document.body.innerHTML = `
`; + expect(family("a").locked).toBe(true); + }); + + it("answers no family for a family past the cap", () => { + document.body.innerHTML = `
${"
".repeat(MAX_QUERY_MATCHES)}
`; + expect(family("last").family).toBeNull(); + }); +}); diff --git a/packages/core/src/runtime/editingLayers.ts b/packages/core/src/runtime/editingLayers.ts index 8ab7bb9a8f..3a20905827 100644 --- a/packages/core/src/runtime/editingLayers.ts +++ b/packages/core/src/runtime/editingLayers.ts @@ -3,6 +3,7 @@ import { isRichTextFormattingTag } from "../utils/richTextSanitize"; import { isClipHiddenByRuntime } from "../studioPreviewMark"; import { MAX_QUERY_MATCHES, type EditingElementHandle } from "./editingElement"; import { elementForHandle, handleFor } from "./editingHandles"; +import type { EditingParams, EditingResult } from "./editingPort"; import { isDomLayerElement } from "./editingTargets"; import { isElementNode } from "./domRealm"; @@ -113,3 +114,43 @@ export function layersOf( })), }; } + +/** + * Tags that never paint, so they take no z slot in a stacking family: audio (the qa-clean audio + * element), script/style/link/meta, and template/noscript, whose markup a renumber must not touch. + */ +export const NON_PAINTING_TAGS = new Set([ + "AUDIO", + "SCRIPT", + "STYLE", + "LINK", + "META", + "TEMPLATE", + "NOSCRIPT", +]); + +export interface EditingStackingSibling { + handle: EditingElementHandle; + zIndex: number; +} + +export function stackingFamily({ + handle, +}: EditingParams<"stacking-family">): EditingResult<"stacking-family"> { + const element = elementForHandle(handle); + const parent = element?.parentElement; + if (!element || !parent) return { family: null, locked: false }; + const siblings = Array.from(parent.children).filter( + (child) => child === element || (isElementNode(child) && !NON_PAINTING_TAGS.has(child.tagName)), + ); + return { + family: + siblings.length > MAX_QUERY_MATCHES + ? null + : siblings.map((child) => ({ + handle: handleFor(child), + zIndex: elementZIndex(child as HTMLElement), + })), + locked: !!element.closest("[data-timeline-locked]"), + }; +} diff --git a/packages/core/src/runtime/editingPort.test.ts b/packages/core/src/runtime/editingPort.test.ts index eba361e5cd..0120fa6a37 100644 --- a/packages/core/src/runtime/editingPort.test.ts +++ b/packages/core/src/runtime/editingPort.test.ts @@ -103,6 +103,7 @@ describe("createEditingPortClient", () => { "max-z-index", "crop-lift", "edit-element", + "stacking-family", "gsap-set", "patch-tweens", "soft-reload", diff --git a/packages/core/src/runtime/editingPort.ts b/packages/core/src/runtime/editingPort.ts index 5d66027615..32efc6a1bd 100644 --- a/packages/core/src/runtime/editingPort.ts +++ b/packages/core/src/runtime/editingPort.ts @@ -28,6 +28,7 @@ import type { EditingElementBox, EditingElementGeometry } from "./editingGeometr import type { EditingGestureStart } from "./editingGestureStart"; import type { GsapSnapshot } from "./editing/gsapSnapshot"; import type { MotionPathFrameHome } from "./editing/motionPathHome"; +import type { EditingLayer, EditingStackingSibling } from "./editingLayers"; import { parseGsapSet, type GsapSetParams } from "./editing/gsapSet"; import { parsePatchTweens, type PatchTweensParams } from "./editing/patchTween"; import { @@ -35,7 +36,6 @@ import { type SoftReloadParams, type SoftReloadResult, } from "./editing/softReload"; -import type { EditingLayer } from "./editingLayers"; import type { RuntimeTimelineMessage } from "./types"; import { wallClearTimeout, wallSetTimeout } from "./wallClock"; import { parseCombo } from "../keyCombo"; @@ -137,9 +137,11 @@ export { export { elementZIndex, hasOnlyFormattingChildren, + NON_PAINTING_TAGS, isCompositionHost, layerKindOf, type EditingLayer, + type EditingStackingSibling, type LayerKind, } from "./editingLayers"; export { @@ -187,6 +189,7 @@ export const EDITING_REQUEST_KINDS = [ "max-z-index", "crop-lift", "edit-element", + "stacking-family", "gsap-set", "patch-tweens", "soft-reload", @@ -325,6 +328,10 @@ export interface EditingRequests { result: { lifted: boolean; clipPath: string | null }; }; "edit-element": { params: EditElementParams; result: EditElementResult }; + "stacking-family": { + params: { handle: EditingElementHandle }; + result: { family: EditingStackingSibling[] | null; locked: boolean }; + }; "gsap-set": { params: GsapSetParams; result: { applied: boolean } }; "patch-tweens": { params: PatchTweensParams; result: { patched: boolean } }; "soft-reload": { params: SoftReloadParams; result: { result: SoftReloadResult } }; @@ -537,6 +544,8 @@ const PARAM_PARSERS: { ? { handle: params.handle, lift: params.lift } : null, "edit-element": parseEditElement, + "stacking-family": (params) => + hasKeys(params, "handle") && isHandle(params.handle) ? { handle: params.handle } : null, "gsap-set": parseGsapSet, "patch-tweens": parsePatchTweens, "soft-reload": parseSoftReload, diff --git a/packages/studio/src/components/editor/LayersPanel.opaque.test.ts b/packages/studio/src/components/editor/LayersPanel.opaque.test.ts index 949bc17563..8d13587369 100644 --- a/packages/studio/src/components/editor/LayersPanel.opaque.test.ts +++ b/packages/studio/src/components/editor/LayersPanel.opaque.test.ts @@ -5,8 +5,9 @@ import { createRoot } from "react-dom/client"; import { afterEach, expect, it, vi } from "vitest"; import { installReactActEnvironment } from "../../hooks/domSelectionTestHarness"; import { usePreviewIframeStore } from "../../player/store/previewIframeStore"; -import type { DomEditSelection } from "./domEditing"; import { LayersPanel } from "./LayersPanel"; +import type { LayerReorderEvent } from "./useLayerDrag"; +import type { DomEditLayerItem, DomEditSelection } from "./domEditing"; import { announcePreviewDocumentLoaded } from "../../player/sceneSwap"; import { describePreviewElements, queryPreviewElements } from "../../player/lib/previewElements"; import { standInFor } from "./previewSelection"; @@ -22,7 +23,29 @@ const mocks = vi.hoisted(() => ({ // While set, a layers read waits on it after the frame answers. hold: null as Promise | null, answered: 0, + showToast: vi.fn(), + commitZ: vi.fn(async () => ({ durable: true })), + onReorder: null as ((event: LayerReorderEvent) => void) | null, + sorted: [] as DomEditLayerItem[], })); +vi.mock("./layersPanelSort", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + sortLayersByZIndex: (layers: DomEditLayerItem[]) => + (mocks.sorted = actual.sortLayersByZIndex(layers)), + }; +}); +vi.mock("./useLayerDrag", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + useLayerDrag: (options: Parameters[0]) => { + mocks.onReorder = options.onReorder; + return actual.useLayerDrag(options); + }, + }; +}); vi.mock("../../player/lib/previewElements", async (importOriginal) => { const actual = await importOriginal(); return { @@ -39,7 +62,7 @@ vi.mock("../../contexts/StudioContext", () => ({ useStudioShellContextOptional: () => ({ previewIframeRef: mocks.previewIframeRef, activeCompPath: "index.html", - showToast: vi.fn(), + showToast: mocks.showToast, }), useStudioPlaybackContextOptional: () => ({ refreshKey: 0, @@ -54,7 +77,7 @@ vi.mock("../../contexts/DomEditContext", () => ({ activeGroupElement: mocks.activeGroupElement, applyDomSelection: mocks.applyDomSelection, updateDomEditHoverSelection: vi.fn(), - handleDomZIndexReorderCommit: vi.fn(), + handleDomZIndexReorderCommit: mocks.commitZ, setActiveGroupElement: mocks.setActiveGroupElement, }), })); @@ -68,6 +91,7 @@ afterEach(() => { mocks.activeGroupElement = null; mocks.hold = null; mocks.answered = 0; + mocks.sorted = []; vi.clearAllMocks(); usePreviewIframeStore.setState({ iframe: null }); document.body.innerHTML = ""; @@ -93,7 +117,7 @@ it("lists an opaque frame's layers, selects a row, and drills into a group row", expect(named("Title").querySelector("[data-layer-kind]")!.getAttribute("data-layer-kind")).toBe( "text", ); - expect(named("pair").title).toBe("This layer can't be reordered"); + expect(named("pair").title).toBe("Double-click to enter group"); const hostIcon = named("Intro").querySelector("[data-layer-kind]")!; expect(hostIcon.className).toContain("bg-on"); @@ -149,3 +173,48 @@ it("reads the layers once more when a refresh lands while a read is in flight", act(() => release()); await vi.waitFor(() => expect(rows()).toEqual(["Late", "Card"])); }); + +/** The panel's rows once listed, and a drop of `label` to the top of its siblings. */ +async function sealedStack(markup: string) { + document.body.innerHTML = `
${markup}
`; + const iframe = sealedPreviewFrame().iframe; + renderPanel(iframe); + await vi.waitFor(() => expect(mocks.sorted.length).toBeGreaterThan(1)); + return (label: string) => { + const depth = mocks.sorted.find((layer) => layer.id === label)!.depth; + const siblingLayers = mocks.sorted.filter((layer) => layer.depth === depth); + const fromIndex = siblingLayers.findIndex((layer) => layer.id === label); + act(() => mocks.onReorder!({ siblingLayers, fromIndex, toIndex: 0 })); + }; +} + +it("restacks a sealed layer dragged to the top, saving its z-index through its stand-in", async () => { + const drop = await sealedStack( + `
+
`, + ); + drop("back"); + await vi.waitFor(() => expect(mocks.commitZ).toHaveBeenCalledOnce()); + const [entries, , source] = mocks.commitZ.mock.calls[0]! as unknown as [ + Array<{ element: HTMLElement; zIndex: number; id?: string }>, + string, + string, + ]; + expect(source).toBe("layer-drag"); + expect(entries).toEqual([expect.objectContaining({ id: "back", zIndex: 3 })]); + expect(entries[0]!.element.isConnected).toBe(false); +}); + +it("refuses to restack a sealed layer inside a locked clip, and saves nothing", async () => { + const drop = await sealedStack( + `
+
+
+
`, + ); + drop("back"); + await vi.waitFor(() => + expect(mocks.showToast).toHaveBeenCalledWith("This layer can't be reordered", "info"), + ); + expect(mocks.commitZ).not.toHaveBeenCalled(); +}); diff --git a/packages/studio/src/components/editor/LayersPanel.tsx b/packages/studio/src/components/editor/LayersPanel.tsx index 6c3841e30e..d7f8572015 100644 --- a/packages/studio/src/components/editor/LayersPanel.tsx +++ b/packages/studio/src/components/editor/LayersPanel.tsx @@ -41,8 +41,12 @@ import { useLayerReorderTimelineMirror } from "../nle/useCanvasZOrderTimelineMir import { runZLaneGesture } from "../nle/zLaneGesture"; import { useLayerRevealOverride } from "./useLayerRevealOverride"; import { previewFrameOpaque } from "../../player/lib/previewChannel"; -import { describePreviewElements } from "../../player/lib/previewElements"; -import { collectPreviewLayerItems, layerDataAttribute } from "./previewLayers"; +import { describePreviewElements, editPreviewElement } from "../../player/lib/previewElements"; +import { + collectPreviewLayerItems, + layerDataAttribute, + previewStackingFamily, +} from "./previewLayers"; import { resolvePreviewSelection, selectionDataAttribute } from "./previewSelection"; // Rows this panel renders before it stops. A display budget, not a document limit. @@ -330,22 +334,17 @@ export const LayersPanel = memo(function LayersPanel({ host }: { host?: LayersPa }, []); // fallow-ignore-next-line complexity - const handleReorder = useCallback( - (event: LayerReorderEvent) => { - const { siblingLayers, fromIndex, toIndex } = event; - const reordered = [...siblingLayers]; - const [moved] = reordered.splice(fromIndex, 1); - reordered.splice(toIndex, 0, moved); - - // Panel order is top-first (sortLayersByZIndex: z desc, later-DOM-first), - // so the desired RENDER order (bottom→top) is the reverse. The minimal - // resolver (shared with the canvas z-menu) then writes one between-z - // value when a strict gap exists, band-safe renumber otherwise — instead - // of the old computeReorderZValues stamp of every sibling. - const desiredBottomToTop = [...reordered].reverse(); + const commitReorder = useCallback( + ( + siblingLayers: DomEditLayerItem[], + moved: DomEditLayerItem, + desiredBottomToTop: DomEditLayerItem[], + family?: NonNullable>>, + ) => { const patches = resolveZOrderReposition( moved.element, desiredBottomToTop.map((l) => l.element), + family?.entries, ); if (!patches || patches.length === 0) return; // paint order unchanged @@ -365,26 +364,28 @@ export const LayersPanel = memo(function LayersPanel({ host }: { host?: LayersPa // node, exactly like the canvas menu's siblingZIndexEntry. Un-targetable // nodes get a live-only style write (reverts on reload). const layer = layerByElement.get(patch.element); - const id = layer?.id ?? (patch.element.id || undefined); - const selector = layer?.selector ?? buildStableSelector(patch.element); + const sealed = family?.identities.get(patch.element); + const id = layer?.id ?? (sealed ? sealed.id : patch.element.id || undefined); + const selector = + layer?.selector ?? (sealed ? sealed.selector : buildStableSelector(patch.element)); if (!id && !selector) { - patch.element.style.zIndex = String(patch.zIndex); + const zIndex = String(patch.zIndex); + const iframe = previewIframeRef.current; + if (!sealed) patch.element.style.zIndex = zIndex; + else if (iframe) + editPreviewElement(iframe, sealed.handle, { styles: [["z-index", zIndex]] }); continue; } - const sourceFile = layer?.sourceFile ?? moved.sourceFile; + const sourceFile = layer?.sourceFile ?? sealed?.sourceFile ?? moved.sourceFile; + const selectorIndex = layer?.selectorIndex ?? sealed?.selectorIndex; entries.push({ element: patch.element, zIndex: patch.zIndex, id, selector, - selectorIndex: layer?.selectorIndex, + selectorIndex, sourceFile, - key: deriveTimelineStoreKey({ - domId: id, - selector, - selectorIndex: layer?.selectorIndex, - sourceFile, - }), + key: deriveTimelineStoreKey({ domId: id, selector, selectorIndex, sourceFile }), }); } if (entries.length === 0) return; @@ -418,7 +419,25 @@ export const LayersPanel = memo(function LayersPanel({ host }: { host?: LayersPa mirrorLayerReorderToTimeline({ selectionKey: movedKey, desiredOrderKeys, coalesceKey }), }).catch(() => undefined); }, - [handleDomZIndexReorderCommit, mirrorLayerReorderToTimeline], + [handleDomZIndexReorderCommit, mirrorLayerReorderToTimeline, previewIframeRef], + ); + + const handleReorder = useCallback( + (event: LayerReorderEvent) => { + const { siblingLayers, fromIndex, toIndex } = event; + const reordered = [...siblingLayers]; + const [moved] = reordered.splice(fromIndex, 1); + reordered.splice(toIndex, 0, moved); + // Panel order is top-first (z desc, later-DOM-first): render order is its reverse. + const desiredBottomToTop = [...reordered].reverse(); + const iframe = previewIframeRef.current; + if (!moved.preview || !iframe) return commitReorder(siblingLayers, moved, desiredBottomToTop); + void previewStackingFamily(iframe, moved.preview.handle, activeCompPath).then((family) => { + if (family?.locked) return showToast("This layer can't be reordered", "info"); + if (family) commitReorder(siblingLayers, moved, desiredBottomToTop, family); + }); + }, + [commitReorder, previewIframeRef, activeCompPath, showToast], ); const selectedKey = domEditSelection ? getDomEditLayerKey(domEditSelection) : null; @@ -492,7 +511,7 @@ export const LayersPanel = memo(function LayersPanel({ host }: { host?: LayersPa const KindIcon = KIND_ICON[kind]; const kindName = kind[0].toUpperCase() + kind.slice(1); const hint = draggable - ? layer.element.hasAttribute("data-hf-group") + ? layerDataAttribute(layer, "data-hf-group") !== null ? "Double-click to enter group" : undefined : "This layer can't be reordered"; diff --git a/packages/studio/src/components/editor/canvasContextMenuZOrder.ts b/packages/studio/src/components/editor/canvasContextMenuZOrder.ts index a1c753a0d9..95a56f3d80 100644 --- a/packages/studio/src/components/editor/canvasContextMenuZOrder.ts +++ b/packages/studio/src/components/editor/canvasContextMenuZOrder.ts @@ -42,6 +42,7 @@ */ import { COLOR_GRADING_SOURCE_HIDDEN_ATTR } from "@hyperframes/core/color-grading"; +import { NON_PAINTING_TAGS } from "@hyperframes/core/runtime/editing-port"; import { readLayerRevealPriorZ } from "../../player/lib/timelineElementHelpers"; export type ZOrderAction = "bring-forward" | "send-backward" | "bring-to-front" | "send-to-back"; @@ -94,7 +95,7 @@ export function isElementVisibleForZOrder(el: HTMLElement): boolean { } } -interface RenderEntry { +export interface RenderEntry { element: HTMLElement; zIndex: number; /** Position within the shared parent's children (DOM document order). */ @@ -129,25 +130,6 @@ function isElementNode(node: Node): node is HTMLElement { return node.nodeType === 1; } -/** - * Tags that never paint pixels and so must be excluded from z-order siblings. - * `