fix(studio): close multi-selection review gaps

This commit is contained in:
Miguel Angel Simon Sierra
2026-08-09 19:10:57 -04:00
parent d94c70c2c5
commit 32769f75fe
18 changed files with 369 additions and 176 deletions
+1 -2
View File
@@ -94,7 +94,6 @@ export function StudioApp() {
const setTimelineSelectionSet = usePlayerStore((s) => s.setSelectedElementIds);
const timelineDuration = usePlayerStore((s) => s.duration);
const isPlaying = usePlayerStore((s) => s.isPlaying);
const isMasterView = !activeCompPath || activeCompPath === "index.html";
const effectiveTimelineDuration = useMemo(() => {
const maxEnd =
timelineElements.length > 0
@@ -271,12 +270,12 @@ export function StudioApp() {
const domEditSession = useDomEditSession({
projectId,
activeCompPath,
isMasterView,
compIdToSrc,
captionEditMode,
compositionLoading,
previewIframeRef,
timelineElements,
getTimelineSelectionSet: () => usePlayerStore.getState().selectedElementIds,
setSelectedTimelineElementId,
setTimelineSelectionSet,
setRightCollapsed: panelLayout.setRightCollapsed,
@@ -281,7 +281,9 @@ describe("DomEditOverlay", () => {
const host = document.createElement("div");
document.body.append(host);
const root = createRoot(host);
const iframeRef = { current: document.createElement("iframe") as HTMLIFrameElement | null };
const iframeRef: { current: HTMLIFrameElement | null } = {
current: document.createElement("iframe"),
};
const onCanvasMouseDown = vi.fn();
const onMarqueeSelect = vi.fn();
@@ -326,6 +328,44 @@ describe("DomEditOverlay", () => {
host.remove();
});
it("starts a marquee from outside the composition frame", async () => {
const restoreRect = stubViewportRect();
const originalPointerCapture = HTMLDivElement.prototype.setPointerCapture;
const setPointerCapture = vi.fn();
HTMLDivElement.prototype.setPointerCapture = setPointerCapture;
const host = document.createElement("div");
document.body.append(host);
const root = createRoot(host);
const iframeRef: { current: HTMLIFrameElement | null } = {
current: document.createElement("iframe"),
};
act(() => {
root.render(
React.createElement(DomEditOverlay, {
...createOverlayProps({
iframeRef,
selection: null,
hoverSelection: null,
onSelectionChange: () => {},
}),
onMarqueeSelect: vi.fn(),
}),
);
});
await flushOverlayRaf();
// Negative x is outside the 0..800 composition frame but still reaches the
// overlay in a real pointer event when the user starts in the grey margin.
dispatchOverlayPointerDown(getOverlay(host), -40, 100);
expect(setPointerCapture).toHaveBeenCalledTimes(1);
act(() => root.unmount());
HTMLDivElement.prototype.setPointerCapture = originalPointerCapture;
restoreRect();
host.remove();
});
it("does not start a drag from a stale hover target on canvas pointer-down", () => {
const host = document.createElement("div");
document.body.append(host);
@@ -178,6 +178,7 @@ describe("orientedOverlayRect — rotation gate (perf fix, V15 18a/18b)", () =>
* parent got an upright box.
*/
const SCALE_1_2_MATRIX = "matrix(1.2, 0, 0, 1.2, 0, 0)";
const MIRROR_X_MATRIX = "matrix(-1, 0, 0, 1, 0, 0)";
it("sizes the box by the accumulated transform, not the element's own", () => {
const { overlayEl, iframe, el } = buildHarness();
@@ -206,6 +207,24 @@ describe("orientedOverlayRect — rotation gate (perf fix, V15 18a/18b)", () =>
expect(rect!.angle).toBeCloseTo(30, 3);
});
it("does not misread a mirrored ancestor as a 180-degree rotation", () => {
const { overlayEl, iframe, el } = buildHarness();
el.parentElement!.style.transform = MIRROR_X_MATRIX;
const rect = orientedOverlayRect(overlayEl, iframe, el);
expect(rect?.angle ?? 0).toBe(0);
});
it("stops transform composition at the composition root", () => {
const { overlayEl, iframe, el } = buildHarness();
iframe.contentDocument!.body.style.transform = ROTATE_30DEG_MATRIX;
const rect = orientedOverlayRect(overlayEl, iframe, el);
expect(rect?.angle ?? 0).toBe(0);
});
it("preserves an ordinary element's rotation through the group-aware entry point", () => {
const { overlayEl, iframe, el } = buildHarness();
el.style.transform = ROTATE_30DEG_MATRIX;
@@ -150,9 +150,11 @@ function readElementTransformSnapshot(
let matrix = new DOMMatrixCtor();
for (let node: HTMLElement | null = element; node; node = node.parentElement) {
const transform = node === element ? cs.transform : win.getComputedStyle(node).transform;
if (!transform || transform === "none") continue;
// An ancestor applies outside, so it multiplies on the left.
matrix = new DOMMatrixCtor(transform).multiply(matrix);
if (transform && transform !== "none") {
// An ancestor applies outside, so it multiplies on the left.
matrix = new DOMMatrixCtor(transform).multiply(matrix);
}
if (node.hasAttribute("data-composition-id")) break;
}
return { matrix, cs };
} catch {
@@ -169,7 +171,16 @@ function readElementTransformSnapshot(
function rotationDegreesFromMatrix(matrix: DOMMatrix): number {
const a = Number.isFinite(matrix.a) ? matrix.a : 1;
const b = Number.isFinite(matrix.b) ? matrix.b : 0;
const deg = (Math.atan2(b, a) * 180) / Math.PI;
const c = Number.isFinite(matrix.c) ? matrix.c : 0;
const d = Number.isFinite(matrix.d) ? matrix.d : 1;
const fromX = (Math.atan2(b, a) * 180) / Math.PI;
const determinant = a * d - b * c;
// A reflection makes one basis direction read 180° away from the authored
// rotation. For cursor/handle orientation those directions are equivalent;
// choose the representative nearest zero instead of drawing a pure mirror's
// rotate handle on the opposite side of the element.
const fromY = (Math.atan2(-c, d) * 180) / Math.PI;
const deg = determinant < 0 && Math.abs(fromY) < Math.abs(fromX) ? fromY : fromX;
return Number.isFinite(deg) ? deg : 0;
}
@@ -26,6 +26,7 @@ export function createGroupDragMover(
setDraftGroupOverlayItems: (items: GroupOverlayItem[]) => void,
) {
let lastGroupPositions: Record<string, string> = {};
let lastGesture: GroupGestureState | null = null;
/** Snap the group's delta to nearby edges, publishing the guides drawn for it. */
// fallow-ignore-next-line complexity
@@ -36,7 +37,10 @@ export function createGroupDragMover(
) => {
const sc = groupG.snapContext;
if (!sc?.snapEnabled || sc.targets.length === 0) return proposed;
if (!snapEngagedForTravel(proposed.dx, proposed.dy)) return proposed;
if (!snapEngagedForTravel(proposed.dx, proposed.dy)) {
opts.snapGuidesRef.current = null;
return proposed;
}
const groupBounds = resolveDomEditGroupOverlayRect(groupG.originItems.map((i) => i.rect));
if (!groupBounds) return proposed;
const allTargets = sc.compositionTarget ? [...sc.targets, sc.compositionTarget] : sc.targets;
@@ -67,6 +71,10 @@ export function createGroupDragMover(
/** One frame of a group drag: snap the delta, redraw the boxes, move every member. */
const moveGroupDrag = (groupG: GroupGestureState, e: React.PointerEvent<HTMLDivElement>) => {
if (groupG !== lastGesture) {
lastGesture = groupG;
lastGroupPositions = {};
}
const { dx, dy } = snapGroupDelta(groupG, e, {
dx: e.clientX - groupG.startX,
dy: e.clientY - groupG.startY,
@@ -1,31 +0,0 @@
import { describe, expect, it } from "vitest";
import { rectsOverlap } from "../../utils/marqueeGeometry";
/**
* An element dragged past the edge of the frame sits out in the grey, and the
* rubber band refused to START there — it only began inside the composition
* rect, so the one gesture that could reach those elements could not be begun
* near them, leaving the timeline as the only way to select something plainly
* visible on screen.
*
* The collection half never had that limit: it compares rects in overlay space
* and never clipped to the frame, so a band drawn out in the grey has always
* been able to find what it covers. This pins that, including the negative
* coordinates an off-canvas element actually has.
*/
describe("marquee reaches elements outside the composition", () => {
const offCanvas = { left: -180, top: 40, width: 90, height: 40 };
it("covers an element sitting left of the frame", () => {
expect(rectsOverlap({ left: -220, top: 10, width: 160, height: 120 }, offCanvas)).toBe(true);
});
it("covers one sitting above the frame", () => {
const above = { left: 60, top: -140, width: 80, height: 50 };
expect(rectsOverlap({ left: 20, top: -200, width: 200, height: 120 }, above)).toBe(true);
});
it("does not claim one the band misses", () => {
expect(rectsOverlap({ left: 400, top: 400, width: 50, height: 50 }, offCanvas)).toBe(false);
});
});
@@ -5,6 +5,7 @@ import { logSelect } from "../utils/selectDebug";
interface TimelineMirrorDeps {
timelineElements: TimelineElement[];
getTimelineSelectionSet: () => ReadonlySet<string>;
setSelectedTimelineElementId: (id: string | null, options?: SelectElementOptions) => void;
setTimelineSelectionSet: (ids: Set<string>) => void;
}
@@ -27,7 +28,12 @@ export function announceTimelineSelection(
group: DomEditSelection[],
primary: DomEditSelection | null,
): void {
const { timelineElements, setSelectedTimelineElementId, setTimelineSelectionSet } = deps;
const {
timelineElements,
getTimelineSelectionSet,
setSelectedTimelineElementId,
setTimelineSelectionSet,
} = deps;
if (!primary) {
setTimelineSelectionSet(new Set());
setSelectedTimelineElementId(null);
@@ -51,10 +57,11 @@ export function announceTimelineSelection(
anchor,
anchorPublished: anchor != null && members.includes(anchor),
});
// Only a real multi-selection publishes members. A single selection keeps the
// older contract on purpose: anchoring with preserveSet holds a live set the
// element already belongs to (a late async primary must not collapse a group)
// and collapses otherwise, which is what a fresh click means.
if (group.length > 1) setTimelineSelectionSet(new Set(members));
// A late async primary that already belongs to the live set must preserve the
// group. A fresh single click does not belong to it, so publish the singleton
// first; otherwise `preserveSet` clears the set and sync wipes the canvas.
if (group.length > 1 || !anchor || !getTimelineSelectionSet().has(anchor)) {
setTimelineSelectionSet(new Set(members));
}
setSelectedTimelineElementId(anchor, { preserveSet: true });
}
@@ -60,6 +60,46 @@ const capturedOnReorderShadow: { fn: ((targets: string[]) => void) | undefined }
const domEditSelectionRef: { current: DomEditSelection | null } = { current: null };
const gsapCommitMutation = Object.assign(vi.fn(), { batch: vi.fn() });
function createSessionParams(
overrides: Partial<UseDomEditSessionParams> = {},
): UseDomEditSessionParams {
return {
projectId: "proj-1",
activeCompPath: "index.html",
compIdToSrc: new Map(),
captionEditMode: false,
compositionLoading: false,
previewIframeRef: { current: null },
timelineElements: [],
getTimelineSelectionSet: () => new Set(),
setSelectedTimelineElementId: vi.fn(),
setTimelineSelectionSet: vi.fn(),
setRightCollapsed: vi.fn(),
setRightPanelTab: vi.fn(),
showToast: vi.fn(),
refreshPreviewDocumentVersion: vi.fn(),
queueDomEditSave: async <T,>(save: () => Promise<T>) => save(),
readProjectFile: async () => "",
writeProjectFile: async () => {},
updateEditingFileContent: vi.fn(),
domEditSaveTimestampRef: { current: 0 },
editHistory: { recordEdit: async () => {} },
fileTree: [],
importedFontAssetsRef: { current: [] },
projectDir: null,
projectIdRef: { current: "proj-1" },
previewIframe: null,
refreshKey: 0,
previewDocumentVersion: 0,
rightPanelTab: "design",
applyStudioManualEditsToPreviewRef: { current: async () => {} },
syncPreviewHistoryHotkey: vi.fn(),
reloadPreview: vi.fn(),
setRefreshKey: vi.fn(),
...overrides,
};
}
vi.mock("../utils/sdkResolverShadow", () => ({
runResolverShadow: vi.fn(),
recordResolverParity: (...args: unknown[]) => recordResolverParity(...args),
@@ -220,44 +260,16 @@ describe("onReorderShadow source filter", () => {
const sdkSession = {} as unknown as Composition;
function Probe() {
const params: UseDomEditSessionParams = {
projectId: "proj-1",
activeCompPath: "index.html",
isMasterView: false,
compIdToSrc: new Map(),
captionEditMode: false,
compositionLoading: false,
previewIframeRef: { current: null },
timelineElements: [],
setSelectedTimelineElementId: vi.fn(),
setTimelineSelectionSet: vi.fn(),
setRightCollapsed: vi.fn(),
setRightPanelTab: vi.fn(),
showToast: vi.fn(),
refreshPreviewDocumentVersion: vi.fn(),
const params = createSessionParams({
queueDomEditSave: vi.fn(async <T,>(save: () => Promise<T>) => save()) as <T>(
save: () => Promise<T>,
) => Promise<T>,
readProjectFile,
writeProjectFile: vi.fn(async () => {}),
updateEditingFileContent: vi.fn(),
domEditSaveTimestampRef: { current: 0 },
editHistory: { recordEdit: vi.fn(async () => {}) },
fileTree: [],
importedFontAssetsRef: { current: [] },
projectDir: null,
projectIdRef: { current: "proj-1" },
previewIframe: null,
refreshKey: 0,
previewDocumentVersion: 0,
rightPanelTab: "design",
applyStudioManualEditsToPreviewRef: { current: async () => {} },
syncPreviewHistoryHotkey: vi.fn(),
reloadPreview: vi.fn(),
setRefreshKey: vi.fn(),
sdkSession,
forceReloadSdkSession: vi.fn(),
};
});
useDomEditSession(params);
return null;
}
@@ -319,40 +331,7 @@ describe("bulk segment ease commits", () => {
| undefined;
function Probe() {
const params: UseDomEditSessionParams = {
projectId: "proj-1",
activeCompPath: "index.html",
isMasterView: false,
compIdToSrc: new Map(),
captionEditMode: false,
compositionLoading: false,
previewIframeRef: { current: null },
timelineElements: [],
setSelectedTimelineElementId: vi.fn(),
setTimelineSelectionSet: vi.fn(),
setRightCollapsed: vi.fn(),
setRightPanelTab: vi.fn(),
showToast: vi.fn(),
refreshPreviewDocumentVersion: vi.fn(),
queueDomEditSave: async <T,>(save: () => Promise<T>) => save(),
readProjectFile: async () => "",
writeProjectFile: async () => {},
updateEditingFileContent: vi.fn(),
domEditSaveTimestampRef: { current: 0 },
editHistory: { recordEdit: async () => {} },
fileTree: [],
importedFontAssetsRef: { current: [] },
projectDir: null,
projectIdRef: { current: "proj-1" },
previewIframe: null,
refreshKey: 0,
previewDocumentVersion: 0,
rightPanelTab: "design",
applyStudioManualEditsToPreviewRef: { current: async () => {} },
syncPreviewHistoryHotkey: vi.fn(),
reloadPreview: vi.fn(),
setRefreshKey: vi.fn(),
};
const params = createSessionParams();
updateSegmentEase = useDomEditSession(params).handleUpdateSegmentEase;
return null;
}
@@ -31,12 +31,12 @@ interface RecordEditInput {
export interface UseDomEditSessionParams {
projectId: string | null;
activeCompPath: string | null;
isMasterView: boolean;
compIdToSrc: Map<string, string>;
captionEditMode: boolean;
compositionLoading: boolean;
previewIframeRef: React.MutableRefObject<HTMLIFrameElement | null>;
timelineElements: TimelineElement[];
getTimelineSelectionSet: () => ReadonlySet<string>;
setSelectedTimelineElementId: (id: string | null, options?: SelectElementOptions) => void;
setTimelineSelectionSet: (ids: Set<string>) => void;
setRightCollapsed: (collapsed: boolean) => void;
@@ -74,12 +74,12 @@ export interface UseDomEditSessionParams {
export function useDomEditSession({
projectId,
activeCompPath,
isMasterView,
compIdToSrc,
captionEditMode,
compositionLoading,
previewIframeRef,
timelineElements,
getTimelineSelectionSet,
setSelectedTimelineElementId,
setTimelineSelectionSet,
setRightCollapsed,
@@ -111,6 +111,7 @@ export function useDomEditSession({
publishSdkSession,
forceReloadSdkSession,
}: UseDomEditSessionParams) {
const isMasterView = !activeCompPath || activeCompPath === "index.html";
void _setRefreshKey;
const {
domEditSelection,
@@ -139,6 +140,7 @@ export function useDomEditSession({
captionEditMode,
previewIframeRef,
timelineElements,
getTimelineSelectionSet,
setSelectedTimelineElementId,
setTimelineSelectionSet,
setRightCollapsed,
@@ -47,6 +47,7 @@ function renderHarness(
captionEditMode: false,
previewIframeRef: { current: null },
timelineElements: options.timelineElements ?? [],
getTimelineSelectionSet: () => new Set(),
setSelectedTimelineElementId: timeline.setSelectedTimelineElementId,
setTimelineSelectionSet: timeline.setTimelineSelectionSet,
setRightCollapsed: vi.fn(),
+14 -2
View File
@@ -45,6 +45,7 @@ export interface UseDomSelectionParams {
captionEditMode: boolean;
previewIframeRef: React.MutableRefObject<HTMLIFrameElement | null>;
timelineElements: TimelineElement[];
getTimelineSelectionSet: () => ReadonlySet<string>;
setSelectedTimelineElementId: (id: string | null, options?: SelectElementOptions) => void;
/** Publishes a whole multi-selection to the timeline; the anchor is set separately. */
setTimelineSelectionSet: (ids: Set<string>) => void;
@@ -109,6 +110,7 @@ export function useDomSelection({
captionEditMode,
previewIframeRef,
timelineElements,
getTimelineSelectionSet,
setSelectedTimelineElementId,
setTimelineSelectionSet,
setRightCollapsed,
@@ -149,11 +151,21 @@ export function useDomSelection({
const announceTimelineSelection = useCallback(
(group: DomEditSelection[], primary: DomEditSelection | null) =>
announceSelectionToTimeline(
{ timelineElements, setSelectedTimelineElementId, setTimelineSelectionSet },
{
timelineElements,
getTimelineSelectionSet,
setSelectedTimelineElementId,
setTimelineSelectionSet,
},
group,
primary,
),
[setSelectedTimelineElementId, setTimelineSelectionSet, timelineElements],
[
getTimelineSelectionSet,
setSelectedTimelineElementId,
setTimelineSelectionSet,
timelineElements,
],
);
const applyDomSelection = useCallback(
@@ -67,6 +67,7 @@ function renderHarness(props: HarnessProps) {
captionEditMode: false,
previewIframeRef: { current: props.iframe },
timelineElements: props.timelineElements,
getTimelineSelectionSet: () => usePlayerStore.getState().selectedElementIds,
setSelectedTimelineElementId: props.setSelectedTimelineElementId ?? vi.fn(),
setTimelineSelectionSet:
props.setTimelineSelectionSet ?? usePlayerStore.getState().setSelectedElementIds,
@@ -239,7 +240,7 @@ describe("useDomSelection — marquee multi-select survives the late async prima
iframe.remove();
});
it("collapses the set when a late primary-set targets a non-member (fresh click)", async () => {
it("collapses the set to a fresh single-click target instead of publishing an empty set", async () => {
const iframe = document.createElement("iframe");
document.body.append(iframe);
const doc = iframe.contentDocument!;
@@ -271,7 +272,7 @@ describe("useDomSelection — marquee multi-select survives the late async prima
await pending;
});
expect(usePlayerStore.getState().selectedElementIds.size).toBe(0);
expect([...usePlayerStore.getState().selectedElementIds]).toEqual(["d"]);
expect(usePlayerStore.getState().selectedElementId).toBe("d");
harness.cleanup();
iframe.remove();
+78 -22
View File
@@ -91,6 +91,69 @@ function replaceHash(nextHash: string) {
window.history.replaceState(null, "", nextHash);
}
interface ResolveUrlSelectionsParams {
doc: Document;
primaryElement: HTMLElement;
selection: StudioUrlSelectionState;
group: StudioUrlSelectionTarget[];
activeCompPath: string | null;
isCurrent: () => boolean;
buildDomSelection: UseStudioUrlStateParams["buildDomSelectionFromTarget"];
}
function findUrlSelectionElement(
doc: Document,
target: StudioUrlSelectionTarget,
fallbackSourceFile: string,
activeCompPath: string | null,
): HTMLElement | null {
return findElementForSelection(
doc,
{
sourceFile: target.sourceFile ?? fallbackSourceFile,
id: target.id,
selector: target.selector,
selectorIndex: target.selectorIndex,
},
activeCompPath,
);
}
async function buildOptionalDomSelection(
element: HTMLElement | null,
buildDomSelection: UseStudioUrlStateParams["buildDomSelectionFromTarget"],
): Promise<DomEditSelection | null> {
if (!element) return null;
return buildDomSelection(element, { preferClipAncestor: false });
}
async function resolveUrlSelections({
doc,
primaryElement,
selection,
group,
activeCompPath,
isCurrent,
buildDomSelection,
}: ResolveUrlSelectionsParams): Promise<DomEditSelection[] | null> {
const primary = await buildDomSelection(primaryElement, { preferClipAncestor: false });
if (!isCurrent()) return null;
if (!primary) return [];
const members = [primary];
for (const member of group) {
const element = findUrlSelectionElement(
doc,
member,
selection.sourceFile ?? "",
activeCompPath,
);
const resolved = await buildOptionalDomSelection(element, buildDomSelection);
if (!isCurrent()) return null;
if (resolved) members.push(resolved);
}
return members;
}
export function useStudioUrlState({
projectId,
activeCompPath,
@@ -120,6 +183,7 @@ export function useStudioUrlState({
const [selectionHydrated, setSelectionHydrated] = useState(initialState.selection == null);
const pendingSelectionRef = useRef(initialState.selection);
const stableTimeRef = useRef<number | null>(initialState.currentTime);
const selectionApplySeqRef = useRef(0);
const buildUrlState = useCallback(
(): StudioUrlState => ({
@@ -141,6 +205,7 @@ export function useStudioUrlState({
// a missing element or null selection clears the selection and returns true.
const applyUrlSelection = useCallback(
(selection: StudioUrlSelectionState | null): boolean => {
const applySeq = ++selectionApplySeqRef.current;
if (!selection) {
applyDomSelection(null, { revealPanel: false });
return true;
@@ -167,31 +232,22 @@ export function useStudioUrlState({
return true;
}
const group = selection.group ?? [];
void (async () => {
const primary = await buildDomSelectionFromTarget(element, { preferClipAncestor: false });
void resolveUrlSelections({
doc,
primaryElement: element,
selection,
group,
activeCompPath,
isCurrent: () => applySeq === selectionApplySeqRef.current,
buildDomSelection: buildDomSelectionFromTarget,
}).then((members) => {
if (!members) return;
const primary = members[0];
if (!primary) return applyDomSelection(null, { revealPanel: false });
if (group.length === 0) return applyDomSelection(primary, { revealPanel: false });
// Restore the whole multi-selection, primary first so it stays the anchor.
// Members whose element is gone are dropped rather than failing the rest.
const members = [primary];
for (const member of group) {
const memberEl = findElementForSelection(
doc,
{
sourceFile: member.sourceFile ?? selection.sourceFile ?? "",
id: member.id,
selector: member.selector,
selectorIndex: member.selectorIndex,
},
activeCompPath,
);
const resolved = memberEl
? await buildDomSelectionFromTarget(memberEl, { preferClipAncestor: false })
: null;
if (resolved) members.push(resolved);
}
// Missing group members are dropped without failing the rest.
applyMarqueeSelection(members, false);
})();
});
return true;
},
[
+23 -8
View File
@@ -13,8 +13,10 @@ let moveN = 0;
/** Per-pointermove logging, throttled: the first move then every 8th. */
export function logDragMove(data: Record<string, unknown>): void {
moveN += 1;
if (moveN % 8 === 1) logDrag("move", { n: moveN, ...data });
logDrag("move", () => {
moveN += 1;
return moveN % 8 === 1 ? { n: moveN, ...data } : null;
});
}
export function resetDragMoveLog(): void {
@@ -74,10 +76,23 @@ export function logDragSettle(
stage: string,
elements: Array<{ key: string; element: HTMLElement }>,
): void {
logDrag(stage, { at: readDragPositions(elements) });
const win = elements[0]?.element.ownerDocument.defaultView;
if (!win) return;
win.setTimeout(() => logDrag(`${stage}+120ms`, { at: readDragPositions(elements) }), 120);
win.setTimeout(() => logDrag(`${stage}+400ms`, { at: readDragPositions(elements) }), 400);
win.setTimeout(() => logDrag(`${stage}+900ms`, { at: readDragPositions(elements) }), 900);
logDrag(stage, () => {
const at = readDragPositions(elements);
const win = elements[0]?.element.ownerDocument.defaultView;
if (win) {
win.setTimeout(
() => logDrag(`${stage}+120ms`, () => ({ at: readDragPositions(elements) })),
120,
);
win.setTimeout(
() => logDrag(`${stage}+400ms`, () => ({ at: readDragPositions(elements) })),
400,
);
win.setTimeout(
() => logDrag(`${stage}+900ms`, () => ({ at: readDragPositions(elements) })),
900,
);
}
return { at };
});
}
+20 -30
View File
@@ -1,33 +1,18 @@
// Resize/gesture diagnostics — grep [hf-resize]. Off by default; opt in per
// session with `localStorage.setItem("hf-resize-debug", "1")` (then reload).
// Granular per-move/per-gesture tracing that complements the always-on
// [hf-commit] transaction telemetry in gestureTransaction.ts.
// Granular per-move/per-gesture tracing for resize investigation.
import { makeStudioDebugLogger } from "./studioDebug";
export const logResize = makeStudioDebugLogger("resize");
let moveN = 0;
let enabled: boolean | null = null;
function isEnabled(): boolean {
if (enabled === null) {
try {
enabled = localStorage.getItem("hf-resize-debug") === "1";
} catch {
enabled = false;
}
}
return enabled;
}
export function logResize(stage: string, data: Record<string, unknown>): void {
if (!isEnabled()) return;
console.log(
`[hf-resize] ${JSON.stringify({ stage, t: Math.round(performance.now()), ...data })}`,
);
}
/** Per-pointermove logging, throttled: first move then every 8th. */
export function logResizeMove(data: Record<string, unknown>): void {
if (!isEnabled()) return;
moveN += 1;
if (moveN % 8 === 1) logResize("move", { n: moveN, ...data });
logResize("move", () => {
moveN += 1;
return moveN % 8 === 1 ? { n: moveN, ...data } : null;
});
}
export function resetResizeMoveLog(): void {
@@ -36,11 +21,10 @@ export function resetResizeMoveLog(): void {
/** Snapshot the element's live geometry now and again after 200ms (jump detector). */
export function logResizeSettle(el: HTMLElement, tag: string): void {
if (!isEnabled()) return;
const snap = (phase: string) => {
const snapshot = (phase: string) => {
const r = el.getBoundingClientRect();
const cs = el.ownerDocument.defaultView?.getComputedStyle(el);
logResize("settle", {
return {
tag,
phase,
rect: { x: r.x, y: r.y, w: r.width, h: r.height },
@@ -48,8 +32,14 @@ export function logResizeSettle(el: HTMLElement, tag: string): void {
cssH: cs?.height,
transform: cs?.transform,
inlineStyle: el.getAttribute("style"),
});
};
};
snap("t0");
setTimeout(() => snap("t200"), 200);
logResize("settle", () => {
const current = snapshot("t0");
el.ownerDocument.defaultView?.setTimeout(
() => logResize("settle", () => snapshot("t200")),
200,
);
return current;
});
}
@@ -0,0 +1,32 @@
// @vitest-environment happy-dom
import { beforeEach, describe, expect, it, vi } from "vitest";
import { makeStudioDebugLogger } from "./studioDebug";
describe("makeStudioDebugLogger", () => {
beforeEach(() => {
localStorage.clear();
vi.restoreAllMocks();
});
it("does no console work while its channel is disabled", () => {
const log = vi.spyOn(console, "log").mockImplementation(() => undefined);
const buildDetails = vi.fn(() => ({ expensive: true }));
makeStudioDebugLogger("commit")("persisted", buildDetails);
expect(buildDetails).not.toHaveBeenCalled();
expect(log).not.toHaveBeenCalled();
});
it("logs only after its exact channel is enabled", () => {
localStorage.setItem("hf-commit-debug", "1");
const log = vi.spyOn(console, "log").mockImplementation(() => undefined);
makeStudioDebugLogger("commit")("persisted", { mutations: 2 });
expect(log).toHaveBeenCalledOnce();
expect(log.mock.calls[0]?.[0]).toContain('[hf-commit] {"stage":"persisted"');
expect(log.mock.calls[0]?.[0]).toContain('"mutations":2');
});
});
+3 -1
View File
@@ -1,12 +1,13 @@
// Opt-in diagnostic channels — one per question worth tracing, all off by
// default. Turn one on for the session with `localStorage.setItem("hf-<name>-debug",
// "1")` and reload, then grep the console for `[hf-<name>]`.
// Live channels: reload, select, drag, resize.
//
// These exist because the interesting failures here are decisions, not crashes:
// a preview that reloads when it should not, a shift-click that selects nothing.
// Nothing is thrown and nothing is logged by default, so without a trace of the
// decision the only way to find the cause is to guess.
type DebugDetails = Record<string, unknown> | (() => Record<string, unknown>);
type DebugDetails = Record<string, unknown> | (() => Record<string, unknown> | null);
type DebugLogger = (stage: string, data?: DebugDetails) => void;
export function makeStudioDebugLogger(name: string): DebugLogger {
@@ -21,6 +22,7 @@ export function makeStudioDebugLogger(name: string): DebugLogger {
}
if (!enabled) return;
const details = typeof data === "function" ? data() : data;
if (!details) return;
console.log(
`[hf-${name}] ${JSON.stringify({ stage, t: Math.round(performance.now()), ...details })}`,
);
@@ -222,6 +222,56 @@ describe("studio url state", () => {
harness.unmount();
});
it("does not let an older async URL selection overwrite a newer hash", async () => {
const previewDoc = document.implementation.createHTMLDocument("preview");
const firstElement = previewDoc.createElement("div");
firstElement.id = "first";
const secondElement = previewDoc.createElement("div");
secondElement.id = "second";
previewDoc.body.append(firstElement, secondElement);
const first = { element: firstElement, id: "first", sourceFile: "index.html" };
const second = { element: secondElement, id: "second", sourceFile: "index.html" };
let resolveFirst = (_selection: typeof first) => undefined;
const firstResolution = new Promise<typeof first>((resolve) => {
resolveFirst = resolve;
});
const applyDomSelection = vi.fn();
const harness = renderStudioUrlStateHarness({
previewIframeRef: { current: previewIframeFor(previewDoc) },
applyDomSelection,
buildDomSelectionFromTarget: (target) =>
target === firstElement ? firstResolution : Promise.resolve(second),
initialState: {
activeCompPath: null,
currentTime: null,
rightPanelTab: null,
rightCollapsed: null,
timelineVisible: null,
selection: null,
},
});
act(() => {
window.history.replaceState(null, "", "#project/demo?v=1&selId=first");
window.dispatchEvent(new HashChangeEvent("hashchange"));
window.history.replaceState(null, "", "#project/demo?v=1&selId=second");
window.dispatchEvent(new HashChangeEvent("hashchange"));
});
await act(async () => {
await Promise.resolve();
});
expect(applyDomSelection).toHaveBeenCalled();
expect(applyDomSelection.mock.calls.every(([selection]) => selection === second)).toBe(true);
const appliedBeforeOlderResolution = applyDomSelection.mock.calls.length;
await act(async () => {
resolveFirst(first);
await firstResolution;
});
expect(applyDomSelection).toHaveBeenCalledTimes(appliedBeforeOlderResolution);
harness.unmount();
});
it("builds a project hash with persisted studio state", () => {
expect(
buildStudioHash("demo", {