From d94c70c2c532fd9c72bd747d592b5b841bc035b8 Mon Sep 17 00:00:00 2001 From: Miguel Angel Simon Sierra Date: Sun, 9 Aug 2026 12:50:00 -0400 Subject: [PATCH] fix(studio): preserve selector groups in share URLs --- .../studio/src/hooks/useStudioUrlState.ts | 60 +++++++++--- .../studio/src/utils/studioUrlState.test.ts | 93 +++++++++++++++++-- packages/studio/src/utils/studioUrlState.ts | 64 ++++++++++--- 3 files changed, 184 insertions(+), 33 deletions(-) diff --git a/packages/studio/src/hooks/useStudioUrlState.ts b/packages/studio/src/hooks/useStudioUrlState.ts index 263182676c..2b8d02e0d0 100644 --- a/packages/studio/src/hooks/useStudioUrlState.ts +++ b/packages/studio/src/hooks/useStudioUrlState.ts @@ -7,6 +7,7 @@ import { buildStudioHash, parseStudioUrlStateFromHash, type StudioUrlSelectionState, + type StudioUrlSelectionTarget, type StudioUrlState, } from "../utils/studioUrlState"; @@ -40,6 +41,25 @@ interface UseStudioUrlStateParams { initialState: StudioUrlState; } +function toPersistedTarget(selection: DomEditSelection): StudioUrlSelectionTarget | null { + if (!selection.id && !selection.selector) return null; + return { + sourceFile: selection.sourceFile || undefined, + id: selection.id || undefined, + selector: selection.selector || undefined, + selectorIndex: selection.selectorIndex ?? undefined, + }; +} + +function selectionTargetKey(selection: StudioUrlSelectionTarget): string { + return [ + selection.sourceFile ?? "", + selection.id ?? "", + selection.selector ?? "", + selection.selectorIndex ?? "", + ].join("|"); +} + function toPersistedSelection( selection: DomEditSelection | null, // Optional: a caller that only ever has one selection has nothing to add, and @@ -47,18 +67,21 @@ function toPersistedSelection( group: DomEditSelection[] = [], ): StudioUrlSelectionState | null { if (!selection) return null; - if (!selection.id && !selection.selector) return null; - // The primary is already carried by selId; the rest ride along so the link + const primary = toPersistedTarget(selection); + if (!primary) return null; + // The primary is already carried by the top-level fields; the rest ride along so the link // reopens the same multi-selection instead of a single element. - const groupIds = group - .filter((member) => member.id && member.id !== selection.id) - .map((member) => member.id as string); + const primaryKey = selectionTargetKey(primary); + const members = new Map(); + for (const member of group) { + const target = toPersistedTarget(member); + if (!target) continue; + const key = selectionTargetKey(target); + if (key !== primaryKey) members.set(key, target); + } return { - sourceFile: selection.sourceFile || undefined, - id: selection.id || undefined, - selector: selection.selector || undefined, - selectorIndex: selection.selectorIndex ?? undefined, - groupIds: groupIds.length > 0 ? groupIds : undefined, + ...primary, + group: members.size > 0 ? [...members.values()] : undefined, }; } @@ -143,16 +166,25 @@ export function useStudioUrlState({ applyDomSelection(null, { revealPanel: false }); return true; } - const groupIds = selection.groupIds ?? []; + const group = selection.group ?? []; void (async () => { const primary = await buildDomSelectionFromTarget(element, { preferClipAncestor: false }); if (!primary) return applyDomSelection(null, { revealPanel: false }); - if (groupIds.length === 0) return applyDomSelection(primary, { 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 memberId of groupIds) { - const memberEl = doc.getElementById(memberId); + 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; diff --git a/packages/studio/src/utils/studioUrlState.test.ts b/packages/studio/src/utils/studioUrlState.test.ts index 22246970a9..e23ec3c287 100644 --- a/packages/studio/src/utils/studioUrlState.test.ts +++ b/packages/studio/src/utils/studioUrlState.test.ts @@ -81,6 +81,7 @@ function renderStudioUrlStateHarness( applyMarqueeSelection: () => {}, buildDomSelectionFromTarget: () => Promise.resolve(null), applyDomSelection: () => {}, + setRightPanelTab: () => {}, initialState: { activeCompPath: null, currentTime: 4.2, @@ -118,6 +119,12 @@ function StudioUrlStateHarness(props: Parameters[0]) { return null; } +function previewIframeFor(contentDocument: Document): HTMLIFrameElement { + const iframe = document.createElement("iframe"); + Object.defineProperty(iframe, "contentDocument", { value: contentDocument }); + return iframe; +} + describe("studio url state", () => { it("parses persisted studio state from project hash", () => { const state = parseStudioUrlStateFromHash( @@ -134,7 +141,7 @@ describe("studio url state", () => { id: "hero", selector: undefined, selectorIndex: undefined, - groupIds: undefined, + group: undefined, }); }); @@ -153,17 +160,66 @@ describe("studio url state", () => { selection: { sourceFile: "index.html", id: "chip", - groupIds: ["card", "dot-b"], + group: [ + { sourceFile: "index.html", id: "card" }, + { sourceFile: "index.html", selector: ".dot", selectorIndex: 1 }, + ], }, }); - expect(hash).toContain("selGroup=card%2Cdot-b"); - expect(parseStudioUrlStateFromHash(hash).selection?.groupIds).toEqual(["card", "dot-b"]); + expect(parseStudioUrlStateFromHash(hash).selection?.group).toEqual([ + { sourceFile: "index.html", id: "card" }, + { sourceFile: "index.html", selector: ".dot", selectorIndex: 1 }, + ]); }); it("reads a single selection as having no group", () => { const hash = parseStudioUrlStateFromHash("#project/demo?v=1&selFile=index.html&selId=hero"); - expect(hash.selection?.groupIds).toBeUndefined(); + expect(hash.selection?.group).toBeUndefined(); + }); + + it("restores selector-based multi-selection members from the hash", async () => { + const previewDoc = document.implementation.createHTMLDocument("preview"); + const primaryElement = previewDoc.createElement("div"); + primaryElement.id = "hero"; + const memberElement = previewDoc.createElement("div"); + memberElement.className = "dot"; + previewDoc.body.append(primaryElement, memberElement); + const primary = { element: primaryElement, id: "hero", sourceFile: "index.html" }; + const member = { + element: memberElement, + selector: ".dot", + selectorIndex: 0, + sourceFile: "index.html", + }; + const applyMarqueeSelection = vi.fn(); + + const harness = renderStudioUrlStateHarness({ + previewIframeRef: { + current: previewIframeFor(previewDoc), + }, + applyMarqueeSelection, + buildDomSelectionFromTarget: (target) => + Promise.resolve(target === primaryElement ? primary : member), + initialState: { + activeCompPath: null, + currentTime: null, + rightPanelTab: null, + rightCollapsed: null, + timelineVisible: null, + selection: { + sourceFile: "index.html", + id: "hero", + group: [{ sourceFile: "index.html", selector: ".dot", selectorIndex: 0 }], + }, + }, + }); + + await act(async () => { + await Promise.resolve(); + }); + expect(applyMarqueeSelection).toHaveBeenCalledWith([primary, member], false); + harness.unmount(); }); it("builds a project hash with persisted studio state", () => { @@ -259,7 +315,7 @@ describe("studio url state", () => { const harness = renderStudioUrlStateHarness({ previewIframeRef: { - current: { contentDocument: previewDoc } as HTMLIFrameElement, + current: previewIframeFor(previewDoc), }, rightPanelTab: "design", rightCollapsed: false, @@ -310,6 +366,31 @@ describe("studio url state", () => { expect(window.location.hash).toContain("t=4.2"); expect(window.location.hash).toContain("selId=hero"); + const selectorMember = { + ...restoredSelection, + element: document.createElement("div"), + id: "", + selector: ".dot", + selectorIndex: 1, + label: "Dot", + }; + harness.rerender({ + currentTime: 4.2, + domEditSelection: restoredSelection, + domEditGroupSelections: [restoredSelection, selectorMember], + }); + act(() => { + vi.advanceTimersByTime(250); + }); + expect(parseStudioUrlStateFromHash(window.location.hash).selection?.group).toEqual([ + { + sourceFile: "index.html", + id: undefined, + selector: ".dot", + selectorIndex: 1, + }, + ]); + harness.unmount(); }); }); diff --git a/packages/studio/src/utils/studioUrlState.ts b/packages/studio/src/utils/studioUrlState.ts index 89624ec386..1dfe976f10 100644 --- a/packages/studio/src/utils/studioUrlState.ts +++ b/packages/studio/src/utils/studioUrlState.ts @@ -2,18 +2,21 @@ import type { RightPanelTab } from "./studioHelpers"; import { buildProjectHash, parseProjectHashRoute } from "./projectRouting"; import { roundTo3 } from "./rounding"; -export interface StudioUrlSelectionState { +export interface StudioUrlSelectionTarget { sourceFile?: string; id?: string; selector?: string; selectorIndex?: number; +} + +export interface StudioUrlSelectionState extends StudioUrlSelectionTarget { /** - * The other members of a multi-selection, by element id, primary excluded. + * The other members of a multi-selection, primary excluded. * A link to a bug in a group edit is only reproducible if it carries the group; * without this, opening the URL lands on one element and the report reads as * "works for me". */ - groupIds?: string[]; + group?: StudioUrlSelectionTarget[]; } export interface StudioUrlState { @@ -70,13 +73,48 @@ function parseTab(value: string | null): RightPanelTab | null { return VALID_TABS.includes(value as RightPanelTab) ? (value as RightPanelTab) : null; } -/** The other members of a multi-selection, dropping blanks a hand-edited URL leaves. */ -function parseGroupIds(value: string | null): string[] | undefined { - const ids = (value ?? "") - .split(",") - .map((id) => id.trim()) - .filter(Boolean); - return ids.length > 0 ? ids : undefined; +function optionalString(value: unknown): string | undefined { + return typeof value === "string" ? value : undefined; +} + +function normalizedIndex(value: unknown): number | undefined { + return typeof value === "number" && Number.isFinite(value) + ? Math.max(0, Math.floor(value)) + : undefined; +} + +function parseSelectionTarget(value: unknown): StudioUrlSelectionTarget | null { + if (!value || typeof value !== "object") return null; + const sourceFile = optionalString(Reflect.get(value, "sourceFile")); + const id = optionalString(Reflect.get(value, "id")); + const selector = optionalString(Reflect.get(value, "selector")); + if (!id && !selector) return null; + return { + sourceFile, + id, + selector, + selectorIndex: normalizedIndex(Reflect.get(value, "selectorIndex")), + }; +} + +/** The other members of a multi-selection, dropping invalid hand-edited entries. */ +function parseGroup(value: string | null): StudioUrlSelectionTarget[] | undefined { + if (!value) return undefined; + let parsed: unknown; + try { + parsed = JSON.parse(value); + } catch { + // Compatibility with links produced by the first id-only implementation. + const legacy = value + .split(",") + .map((id) => id.trim()) + .filter(Boolean) + .map((id) => ({ id })); + return legacy.length > 0 ? legacy : undefined; + } + if (!Array.isArray(parsed)) return undefined; + const targets = parsed.map(parseSelectionTarget).filter((target) => target !== null); + return targets.length > 0 ? targets : undefined; } function normalizeSelection(params: URLSearchParams): StudioUrlSelectionState | null { @@ -91,7 +129,7 @@ function normalizeSelection(params: URLSearchParams): StudioUrlSelectionState | id, selector, selectorIndex: selectorIndex != null ? Math.max(0, Math.floor(selectorIndex)) : undefined, - groupIds: parseGroupIds(params.get("selGroup")), + group: parseGroup(params.get("selGroup")), }; } @@ -146,8 +184,8 @@ export function buildStudioHash(projectId: string, state: StudioUrlState): strin if (typeof state.selection.selectorIndex === "number") { params.set("selIndex", String(Math.max(0, Math.floor(state.selection.selectorIndex)))); } - if (state.selection.groupIds?.length) { - params.set("selGroup", state.selection.groupIds.join(",")); + if (state.selection.group?.length) { + params.set("selGroup", JSON.stringify(state.selection.group)); } }