The VS Code of video editing, built for agents.
TypeScript
Refactor LayerContext and NodeLayer components to simplify drag-and-drop functionality
konstantin-paulus16bb65bbccc6
diff --git a/apps/web/src/components/timeline/layers/context.tsx b/apps/web/src/components/timeline/layers/context.tsxindex 83e017d7..33b6de10 100644--- a/apps/web/src/components/timeline/layers/context.tsx+++ b/apps/web/src/components/timeline/layers/context.tsx@@ -8,28 +8,18 @@ import { assert } from "@/utils";import type { Entity } from "koota";-export type DropPosition = 'above' | 'below' | 'inside';--export type LayerDragState = {- target: Entity;- position: DropPosition;-};-type LayerContextValue = {/** The row whose height is being dragged, if any. */resized: Signal<Entity | null>;- /** Where the rows being dragged would land, if they were dropped now. */- dragState: Signal<LayerDragState | null>;}const LayerContext = createContext<LayerContextValue>();export function LayerContextProvider(props: { children: JSX.Element }) {const resized = createSignal<Entity | null>(null);- const dragState = createSignal<LayerDragState | null>(null);return (- <LayerContext.Provider value={{ resized, dragState }}>+ <LayerContext.Provider value={{ resized }}>{props.children}</LayerContext.Provider>);diff --git a/apps/web/src/components/timeline/layers/node.tsx b/apps/web/src/components/timeline/layers/node.tsxindex 859f3fa3..c568bcc5 100644--- a/apps/web/src/components/timeline/layers/node.tsx+++ b/apps/web/src/components/timeline/layers/node.tsx@@ -40,16 +40,12 @@ import { useEditor } from '@/engine/hooks';import { DEFAULT_CLIP_HEIGHT, MAX_CLIP_HEIGHT, MIN_CLIP_HEIGHT } from '@/engine/timeline';import { NESTED_INDENT_PX } from './config';import { useLayerContext } from './context';-import { dropSelection, findDropTarget } from './reparent';import { setRowHover } from './hover';-import type { Entity, World } from 'koota';+import type { World } from 'koota';import type { TimelineNode } from '@diffusionstudio/runtime';import type { LayerRowProps } from './layer';-/** How far the pointer must move before a press on a row becomes a drag. */-const DRAG_THRESHOLD_PX = 4;-export function NodeLayer(props: LayerRowProps) {const world = useWorld();const editor = useEditor();@@ -67,7 +63,6 @@ export function NodeLayer(props: LayerRowProps) {const controlsVisible = createMemo(() => hovering() || muted() || soloed() || hidden());const [resized, setResized] = useLayerContext().resized;- const [dragState, setDragState] = useLayerContext().dragState;const [editing, setEditing] = createSignal(false);let originalName = '';@@ -76,11 +71,6 @@ export function NodeLayer(props: LayerRowProps) {const name = createMemo(() => nameTrait()?.value ?? 'Layer');const icon = createMemo(() => getLayerIcon(world, props.layer));- const dropPosition = createMemo(() => {- const state = dragState();- return state?.target === entity() ? state.position : null;- });-const toggleMuted = (e?: Event) => {e?.stopPropagation();editor.editProperty(entity(), 'muted', !muted());@@ -109,40 +99,12 @@ export function NodeLayer(props: LayerRowProps) {if (!wasSoloed) entity().add(Soloed);};- /**- * A press selects, and becomes a drag if it travels far enough. Selecting- * first means the drag carries whatever the press selected, so dragging an- * unselected row moves that row and dragging a selected one moves the whole- * selection.- */+ /** A press on a row selects it, shift-clicking to extend the selection. */const handleRowPointerDown = (e: PointerEvent) => {if (e.button !== 0 || resized() !== null) return;if ((e.target as HTMLElement | null)?.closest('button')) return;editor.select(entity(), { extend: e.shiftKey });-- const startX = e.clientX;- const startY = e.clientY;- let dragging = false;-- const onMove = (event: PointerEvent) => {- dragging ||= Math.abs(event.clientX - startX) > DRAG_THRESHOLD_PX- || Math.abs(event.clientY - startY) > DRAG_THRESHOLD_PX;-- if (dragging) setDragState(findDropTarget(event));- };-- const onUp = (event: PointerEvent) => {- document.removeEventListener('pointermove', onMove);- document.removeEventListener('pointerup', onUp);- if (!dragging) return;-- dropSelection(world, findDropTarget(event));- setDragState(null);- };-- document.addEventListener('pointermove', onMove);- document.addEventListener('pointerup', onUp);};let resizeStartY = 0;@@ -236,11 +198,7 @@ export function NodeLayer(props: LayerRowProps) {}}style={{ height: height() + 'px' }}>- <div- data-layer-row- ref={(el) => registerRow(el, entity())}- class="w-full pl-0.5 pr-2 flex items-center justify-between h-full"- >+ <div class="w-full pl-0.5 pr-2 flex items-center justify-between h-full"><divdata-layer-labelclass="flex-1 min-w-0 overflow-hidden"@@ -352,7 +310,6 @@ export function NodeLayer(props: LayerRowProps) {{/* Drag the bottom edge to make the row taller. */}<divclass="absolute bottom-0 left-0 right-0 h-[3px] cursor-ns-resize translate-y-0.5 z-20 group/resize"- classList={{ 'hidden': dragState() !== null }}onPointerDown={handleResizeStart}><div@@ -360,17 +317,6 @@ export function NodeLayer(props: LayerRowProps) {classList={{ 'bg-primary': resized() === entity() }}/></div>-- {/* Where a drop would land. */}- <Show when={dropPosition() === 'above'}>- <div class="pointer-events-none absolute top-0 left-0 right-0 h-[2px] bg-primary z-30" />- </Show>- <Show when={dropPosition() === 'below'}>- <div class="pointer-events-none absolute bottom-0 left-0 right-0 h-[2px] bg-primary z-30" />- </Show>- <Show when={dropPosition() === 'inside'}>- <div class="pointer-events-none absolute inset-0 ring-2 ring-inset ring-primary z-30" />- </Show></ContextMenuTrigger><ContextMenuPortal><ContextMenuContent class="w-[160px]">@@ -394,25 +340,6 @@ export function NodeLayer(props: LayerRowProps) {)}-/**- * Which entity a row's element stands for. A drop is found by hit-testing the- * DOM (`elementFromPoint`), which hands back an element and nothing else, so- * the entity is kept beside it — an id in a data attribute would have to be- * turned back into an entity, and koota hands out ids again once they are- * free. Marked on the row's own content rather than the context-menu trigger- * around it, so this does not rest on that forwarding a ref; the two have the- * same box either way.- */-const ROW_ENTITIES = new WeakMap<HTMLElement, Entity>();--function registerRow(element: HTMLElement, entity: Entity): void {- ROW_ENTITIES.set(element, entity);-}--export function getRowEntity(element: HTMLElement): Entity | undefined {- return ROW_ENTITIES.get(element);-}-function getLayerIcon(world: World, layer: TimelineNode) {const entity = layer.entity;diff --git a/apps/web/src/components/timeline/layers/reparent.ts b/apps/web/src/components/timeline/layers/reparent.tsdeleted file mode 100644index 865ed476..00000000--- a/apps/web/src/components/timeline/layers/reparent.ts+++ /dev/null@@ -1,157 +0,0 @@-/* This Source Code Form is subject to the terms of the Mozilla Public- * License, v. 2.0. If a copy of the MPL was not distributed with this- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */--/**- * Dragging rows onto other rows. Where a drop lands is worked out from the- * DOM — the rows are what the pointer is actually over — and the move itself- * is a reparent through the editor, so the elements move in the file.- *- * Order comes out of the file too: a parent's children are drawn in the order- * they are written, so moving an element in front of another is the whole of- * reordering. Nothing here has to renumber anything.- */--import {- Expanded,- Geometry,- Group,- Selected,- buildTimelineLayers,- getActiveEntity,- getEntityChildren,- getEntityTree,- getParentEntity,- isGroup,-} from '@diffusionstudio/runtime';-import { Or } from 'koota';--import { getDocumentEditor } from '@/engine/editor';-import { getRowEntity } from './node';--import type { Entity, World } from 'koota';-import type { TimelineNode } from '@diffusionstudio/runtime';-import type { DropPosition, LayerDragState } from './context';--/**- * The row under the pointer and which part of it, or null over anything else.- * A row already being dragged is not a target: dropping a thing next to- * itself means nothing.- */-export function findDropTarget(event: PointerEvent): LayerDragState | null {- const element = document.elementFromPoint(event.clientX, event.clientY) as HTMLElement | null;- const row = element?.closest<HTMLElement>('[data-layer-row]');- if (!row) return null;-- const target = getRowEntity(row);- if (!target?.isAlive() || target.has(Selected)) return null;-- const rect = row.getBoundingClientRect();- const offset = event.clientY - rect.top;-- // A group can be dropped into as well as beside, so it gives up its middle- // to that. Everything else is one edge or the other.- let position: DropPosition;- if (isGroup(target)) {- if (offset < rect.height * 0.25) position = 'above';- else if (offset > rect.height * 0.75) position = 'below';- else position = 'inside';- } else {- position = offset < rect.height * 0.5 ? 'above' : 'below';- }-- // Below one row is above the next, and 'above' is the only one the drop- // itself can express (it anchors on the row it goes in front of). The last- // row has no next, so it keeps its 'below'.- if (position === 'below') {- const next = nextDroppableRow(row);- if (next) return { target: next, position: 'above' };- }-- return { target, position };-}--/** The first row after `row` that is not itself being dragged. */-function nextDroppableRow(row: HTMLElement): Entity | undefined {- const rows = [...document.querySelectorAll<HTMLElement>('[data-layer-row]')];-- for (const candidate of rows.slice(rows.indexOf(row) + 1)) {- const entity = getRowEntity(candidate);- if (entity?.isAlive() && !entity.has(Selected)) return entity;- }-- return undefined;-}--/**- * Moves the selection to where the drag ended: inside the target, or in front- * of it among its siblings. Only the tops of the selected subtrees move —- * a selected node under another selected node travels with it.- */-export function dropSelection(world: World, drop: LayerDragState | null): void {- if (!drop) return;-- const editor = getDocumentEditor(world);- const { target, position } = drop;-- const parent = position === 'inside' ? target : getParentEntity(target);- if (!parent) return;-- const selection = new Set(world.query(Selected, Or(Geometry, Group)));- // Top to bottom as the column shows them, so what they were relative to- // each other survives the move. The query's own order means nothing.- const moving = columnOrder(world).filter((entity) => {- if (!selection.has(entity)) return false;- for (let ancestor = getParentEntity(entity); ancestor; ancestor = getParentEntity(ancestor)) {- if (selection.has(ancestor)) return false;- }- return true;- });- if (moving.length === 0) return;-- // Into its own subtree is not a move, it is a loop.- for (const entity of moving) {- if (getEntityTree(world, entity).includes(parent)) return;- }-- // Dropped into a collapsed group, the rows would land out of sight.- if (position === 'inside' && !parent.has(Expanded)) {- editor.editProperty(parent, 'expanded', true);- }-- // The column reads bottom-up: the last child of an element is drawn on top- // of its siblings, so it is the topmost row. Dropping *above* a row- // therefore means going *after* it in the file, which is in front of- // whatever was written next — and the rows go in bottom one first, so each- // lands in front of the one before it and their order comes out as it was.- const anchor = position === 'inside' ? undefined : nextSibling(world, parent, target);-- for (const entity of [...moving].reverse()) {- editor.reparent(entity, parent, anchor);- }-}--/** Every clip row of the scene on show, top to bottom as the column has them. */-function columnOrder(world: World): Entity[] {- const scene = getActiveEntity(world);- if (scene === null) return [];-- const ordered: Entity[] = [];-- const walk = (nodes: TimelineNode[]): void => {- for (const node of nodes) {- if (node.kind === 'geometry') ordered.push(node.entity);- walk(node.children);- }- };-- walk(buildTimelineLayers(world, scene));-- return ordered;-}--/** The element written after `entity` among `parent`'s children, if any. */-function nextSibling(world: World, parent: Entity, entity: Entity): Entity | undefined {- const siblings = getEntityChildren(world, parent);- return siblings[siblings.indexOf(entity) + 1];-}