Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import React, { act } from "react";
import { createRoot } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from "vitest";
import {
getAllPreviewTargetsFromPointer,
getPreviewTargetFromPointer,
Expand Down Expand Up @@ -160,11 +160,15 @@ describe("useDomSelection over an opaque frame's canvas", () => {
type Resolve = ReturnType<typeof useDomSelection>["resolveDomSelectionFromPreviewPoint"];
let interaction: ReturnType<typeof usePreviewInteraction> | null = null;
let menu: ReturnType<typeof useCanvasContextMenuState> | null = null;
function renderSelection(iframe: HTMLIFrameElement, wrapResolve = (resolve: Resolve) => resolve) {
function renderSelection(
iframe: HTMLIFrameElement,
wrapResolve = (resolve: Resolve) => resolve,
projectId: string | null = null,
) {
let hook: ReturnType<typeof useDomSelection> | null = null;
function Harness() {
hook = useDomSelection({
projectId: null,
projectId,
activeCompPath: "index.html",
isMasterView: true,
compIdToSrc: new Map(),
Expand Down Expand Up @@ -294,6 +298,41 @@ describe("useDomSelection over an opaque frame's canvas", () => {
expect(hook().activeGroupElement).toBe(group.element);
});

// fails without the fix: the clip click and useTimelineSelectionPreviewSync each built the selection, so the
// source was asked twice (one request of two targets same-origin, two requests opaque).
it.each([
["opaque", opaqueFrame],
["same-origin", liveFrame],
])(
"asks the source once when a clip click and the timeline's sync select the same clip (%s)",
async (_kind, frame) => {
const probed: unknown[] = [];
const fetch = vi.spyOn(globalThis, "fetch").mockImplementation(async (input, init) => {
if (!String(input).includes("/probe-elements/")) return new Response("{}");
const { targets } = JSON.parse(String(init?.body)) as { targets: unknown[] };
probed.push(...targets);
return new Response(JSON.stringify({ exists: targets.map(() => true) }));
});
onTestFinished(() => fetch.mockRestore());
const hook = renderSelection(frame(), undefined, "demo");
const clip = {
id: "title",
key: "index.html:title:0",
domId: "title",
selector: "#title",
} as unknown as TimelineElement;
const [, synced] = await act(() =>
Promise.all([
hook().handleTimelineElementSelect(clip),
hook().buildDomSelectionForTimelineElement(clip),
]),
);
expect(synced).toMatchObject({ id: "title", existsInSource: true });
expect(hook().domEditSelection).toMatchObject({ id: "title" });
expect(probed).toHaveLength(1);
},
);

it("selects a timeline clip the frame knows only by its clip id", async () => {
const hook = renderSelection(opaqueFrame());
const clip = (id: string) => ({ id, key: `index.html:${id}:0` }) as unknown as TimelineElement;
Expand Down
69 changes: 69 additions & 0 deletions packages/studio/src/hooks/timelineSelectionBuild.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import type { TimelineElement } from "../player";
import {
findElementForTimelineElement,
type DomEditSelection,
} from "../components/editor/domEditing";
import { findOpaqueTimelineElement } from "../components/editor/previewSelection";
import type { PreviewElement } from "../player/lib/previewElements";
import { reapplyPositionEditsAfterSeek } from "../components/editor/manualEdits";
import { holdScenesOf } from "../utils/sceneHold";
import type { ResolveDomSelectionOptions } from "./useDomSelectionTypes";

type TimelineSelectionBuild = (
element: TimelineElement,
iframe: HTMLIFrameElement | null,
) => Promise<DomEditSelection | null>;

type TargetSelectionBuild = (
target: HTMLElement | PreviewElement,
options: ResolveDomSelectionOptions,
iframe?: HTMLIFrameElement | null,
) => Promise<DomEditSelection | null>;

// fallow-ignore-next-line complexity
export async function buildTimelineSelection(
element: TimelineElement,
iframe: HTMLIFrameElement | null,
lookup: Parameters<typeof findElementForTimelineElement>[2],
buildFromTarget: TargetSelectionBuild,
): Promise<DomEditSelection | null> {
let doc: Document | null = null;
try {
doc = iframe?.contentDocument ?? null;
} catch {
return null;
}
if (!doc) {
await holdScenesOf(iframe, element);
const found = await findOpaqueTimelineElement(iframe, element, lookup);
return found ? buildFromTarget(found, { preferClipAncestor: false }, iframe) : null;
}

const held = holdScenesOf(iframe, element);
if (held) await held;
reapplyPositionEditsAfterSeek(doc);

const targetElement = findElementForTimelineElement(doc, element, lookup);
return targetElement ? buildFromTarget(targetElement, { preferClipAncestor: false }) : null;
}

export function sharingRunningBuilds(
build: TimelineSelectionBuild,
iframeRef: { current: HTMLIFrameElement | null },
): (element: TimelineElement) => Promise<DomEditSelection | null> {
const running = new Map<
string,
{ iframe: HTMLIFrameElement | null; built: Promise<DomEditSelection | null> }
>();
return (element) => {
const key = element.key ?? element.id;
const iframe = iframeRef.current;
const shared = running.get(key);
if (shared?.iframe === iframe) return shared.built;
const built = build(element, iframe).finally(() => {
if (running.get(key)?.built === built) running.delete(key);
});
running.set(key, { iframe, built });
return built;
};
}
51 changes: 15 additions & 36 deletions packages/studio/src/hooks/useDomSelection.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useState, useCallback, useRef, useEffect } from "react";
import { useState, useCallback, useMemo, useRef, useEffect } from "react";
import type { TimelineElement } from "../player";
import {
domEditSelectionsEqual,
Expand All @@ -8,13 +8,9 @@ import {
replaceDomEditGroupSelection,
seedDomEditGroupWithSelection,
} from "../utils/domEditHelpers";
import {
findElementForTimelineElement,
type DomEditSelection,
} from "../components/editor/domEditing";
import { type DomEditSelection } from "../components/editor/domEditing";
import {
elementWithin,
findOpaqueTimelineElement,
findPointerTarget,
findPointerTargets,
findSelectionElement,
Expand All @@ -28,6 +24,7 @@ import { useStudioTestHooks } from "./useStudioTestHooks";
import { logSelect } from "../utils/selectDebug";
import type { MarqueeSelectionMode } from "../utils/marqueeGeometry";
import { announceTimelineSelection as announceSelectionToTimeline } from "./domSelectionTimelineMirror";
import { buildTimelineSelection, sharingRunningBuilds } from "./timelineSelectionBuild";
import type {
ApplyDomSelectionOptions,
ResolveDomSelectionOptions,
Expand Down Expand Up @@ -319,36 +316,18 @@ export function useDomSelection({
setDomEditHoverSelection(selection);
}, []);

const buildDomSelectionForTimelineElement = useCallback(
// fallow-ignore-next-line complexity
async (element: TimelineElement): Promise<DomEditSelection | null> => {
const iframe = previewIframeRef.current;
const lookup = { activeCompositionPath: activeCompPath, compIdToSrc, isMasterView };
let doc: Document | null = null;
try {
doc = iframe?.contentDocument ?? null;
} catch {
return null;
}
if (!doc) {
await holdScenesOf(iframe, element);
const found = await findOpaqueTimelineElement(iframe, element, lookup);
return found
? buildDomSelectionFromTarget(found, { preferClipAncestor: false }, iframe)
: null;
}

const held = holdScenesOf(iframe, element);
if (held) await held;
reapplyPositionEditsAfterSeek(doc);

const targetElement = findElementForTimelineElement(doc, element, lookup);
return targetElement
? buildDomSelectionFromTarget(targetElement, {
preferClipAncestor: false,
})
: null;
},
const buildDomSelectionForTimelineElement = useMemo(
() =>
sharingRunningBuilds(
(element, iframe) =>
buildTimelineSelection(
element,
iframe,
{ activeCompositionPath: activeCompPath, compIdToSrc, isMasterView },
buildDomSelectionFromTarget,
),
previewIframeRef,
),
[activeCompPath, buildDomSelectionFromTarget, compIdToSrc, isMasterView, previewIframeRef],
);

Expand Down
Loading