diff --git a/packages/studio/src/components/OpenInDesktopButton.dom.test.tsx b/packages/studio/src/components/OpenInDesktopButton.dom.test.tsx index 5a0e2fdf38d..d7ef72fa704 100644 --- a/packages/studio/src/components/OpenInDesktopButton.dom.test.tsx +++ b/packages/studio/src/components/OpenInDesktopButton.dom.test.tsx @@ -1,8 +1,9 @@ // @vitest-environment happy-dom /** - * "Install the desktop app": shown where the preview server has the app or its download to offer. With the app ready a - * press opens the project in it; otherwise it opens the guide card (download, install, open). + * "Make editing easier" / "Open in desktop app": shown where the preview server has the app or its download to offer. + * With the app ready a press opens the project in it; otherwise in the header it shows the glowing aurora pill and + * 5-scene Desktop card (with install detection while open). */ import React, { act } from "react"; import { createRoot, type Root } from "react-dom/client"; @@ -11,7 +12,9 @@ import { afterEach, beforeEach, expect, it, vi } from "vitest"; (globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true; const showToast = vi.fn(); -vi.mock("../contexts/StudioContext", () => ({ useStudioShellContext: () => ({ showToast }) })); +vi.mock("../contexts/StudioContext", () => ({ + useStudioShellContext: () => ({ showToast, renderQueue: { jobs: [] } }), +})); const track = vi.fn(); vi.mock("../utils/studioTelemetry", () => ({ trackStudioEvent: track })); const FOLDER = "/work/launch-teaser"; @@ -24,6 +27,7 @@ vi.mock("../utils/clipboard", () => ({ })); const { OpenInDesktopButton } = await import("./OpenInDesktopButton"); +const { resetDesktopCardStore } = await import("./desktop-card/desktopCardStore"); const { resolveTabId } = await import("../telemetry/tabId"); const tagged = (url: string) => { const withId = new URL(url); @@ -63,10 +67,19 @@ async function mount(placement?: "storyboard"): Promise { const button = () => document.querySelector('[data-testid="header-open-in-desktop"]'); +const showcaseCard = () => document.querySelector('[data-testid="desktop-app-card"]'); +const showcaseCta = () => + document.querySelector('[data-testid="desktop-app-card-cta"]'); +const guide = () => document.querySelector('[data-testid="desktop-guide"]'); +const stepState = (n: number) => + guide()?.querySelector(`[data-step="${n}"]`)?.dataset.state ?? null; +const cardButton = (text: string) => + [...(guide()?.querySelectorAll("button") ?? [])].find((b) => b.textContent === text) ?? null; let reveal: (() => void) | null = null; beforeEach(() => { + resetDesktopCardStore(); showToast.mockReset(); track.mockReset(); reveal = null; @@ -87,16 +100,36 @@ beforeEach(() => { const events = (name: string) => track.mock.calls.filter(([event]) => event === name).map(([, props]) => props); const MAC = { os: "darwin", app_installed: true, download_available: true, placement: "header" }; +const noApp = { os: "darwin", app_installed: false, download_available: true, placement: "header" }; +const routeBody = (over: Record = {}) => ({ + ...noApp, + available: true, + handoff: false, + downloadUrl: DOWNLOAD, + installed: false, + ...over, +}); afterEach(() => { vi.unstubAllGlobals(); - if (!mounted) return; - const { root, host } = mounted; - mounted = null; - act(() => root.unmount()); - host.remove(); + if (mounted) { + const { root, host } = mounted; + mounted = null; + act(() => root.unmount()); + host.remove(); + } + resetDesktopCardStore(); }); +async function withFakeTimers(body: () => Promise) { + vi.useFakeTimers({ toFake: ["setInterval", "clearInterval", "setTimeout", "clearTimeout"] }); + try { + await body(); + } finally { + vi.useRealTimers(); + } +} + it("stays hidden where the server has no hand-off (the desktop's own Studio)", async () => { serve(null); await mount(); @@ -125,36 +158,11 @@ it("opens the project in an installed app that has no download (FreeBSD)", async expect(posts).toBe(1); }); -/** Runs `body` with the poll and slow-download timers under test control. */ -async function withFakeTimers(body: () => Promise) { - vi.useFakeTimers({ toFake: ["setInterval", "clearInterval", "setTimeout", "clearTimeout"] }); - try { - await body(); - } finally { - vi.useRealTimers(); - } -} - -const guide = () => document.querySelector('[data-testid="desktop-guide"]'); -const stepState = (n: number) => - guide()?.querySelector(`[data-step="${n}"]`)?.dataset.state ?? null; -const cardButton = (text: string) => - [...(guide()?.querySelectorAll("button") ?? [])].find((b) => b.textContent === text) ?? null; -const noApp = { os: "darwin", app_installed: false, download_available: true, placement: "header" }; -const routeBody = (over: Record = {}) => ({ - ...noApp, - available: true, - handoff: false, - downloadUrl: DOWNLOAD, - installed: false, - ...over, -}); - -it("reads 'Install the desktop app' beside Framey, and 'Open in desktop app' once the app takes projects", async () => { +it("reads 'Make editing easier' when not installed, and 'Open in desktop app' once the app takes projects", async () => { serve(Response.json(routeBody())); await mount(); - expect(button()!.textContent).toBe("Install the desktop app"); - expect(button()!.querySelector("svg .hf-framey-eye")).not.toBeNull(); + expect(button()!.getAttribute("aria-label")).toBe("Make editing easier"); + expect(button()!.className).toContain("hf-trim"); act(() => mounted!.root.unmount()); mounted = null; @@ -163,47 +171,48 @@ it("reads 'Install the desktop app' beside Framey, and 'Open in desktop app' onc expect(button()!.textContent).toBe("Open in desktop app"); }); -it("without the app, a press opens the guide at step 1 and hands nothing over", async () => { +it("without the app, a press opens the 5-scene Desktop card and hands nothing over", async () => { serve(Response.json(routeBody()), { opened: true }); await mount(); + expect(showcaseCard()!.dataset.open).toBe("false"); await act(async () => button()!.click()); - expect(guide()).not.toBeNull(); - expect([stepState(1), stepState(2), stepState(3)]).toEqual(["now", "todo", "todo"]); - expect(cardButton("Open in desktop app")!.disabled).toBe(true); + expect(showcaseCard()!.dataset.open).toBe("true"); + expect(showcaseCta()!.textContent).toBe("Download free for Mac"); + expect(document.querySelectorAll('[data-testid="desktop-app-card-segs"] button')).toHaveLength(5); expect(posts).toBe(0); - expect(events("desktop_cta_guide")).toEqual([{ step: "opened", ...noApp }]); + expect(events("desktop_cta_guide")).toEqual([{ step: "opened", ...noApp, source: "header" }]); }); -it("step 1 opens the tagged download in a new tab, then the button says what is left", async () => { +it("card CTA opens the tagged download in a new tab and switches to 'Download started'", async () => { const opened: string[] = []; const tab = { opener: {} as unknown }; vi.stubGlobal("open", (url: string) => (opened.push(url), tab)); serve(Response.json(routeBody())); await mount(); await act(async () => button()!.click()); - await act(async () => cardButton("Download for Mac")!.click()); + await act(async () => showcaseCta()!.click()); expect(opened).toEqual([tagged(DOWNLOAD)]); expect(tab.opener).toBeNull(); - expect([stepState(1), stepState(2)]).toEqual(["done", "now"]); - expect(guide()!.textContent).toContain("Looking for the app…"); - expect(button()!.textContent).toBe("Finish installing2 of 3"); - expect(events("desktop_cta_outcome")).toEqual([{ outcome: "sent_to_download", ...noApp }]); + expect(showcaseCta()!.textContent).toBe("Download started"); + expect(events("desktop_cta_outcome")).toEqual([ + { outcome: "sent_to_download", ...noApp, source: "header" }, + ]); expect(events("desktop_cta_guide").map((e) => (e as { step: string }).step)).toEqual([ "opened", "download_opened", ]); }); -it("names the download when the browser blocks the new tab, and leaves step 1 to do", async () => { +it("names the download when the browser blocks the new tab and leaves the CTA label intact", async () => { vi.stubGlobal("open", () => null); serve(Response.json(routeBody())); await mount(); await act(async () => button()!.click()); - await act(async () => cardButton("Download for Mac")!.click()); + await act(async () => showcaseCta()!.click()); expect(showToast).toHaveBeenCalledWith(`Get the HyperFrames desktop app at ${DOWNLOAD}`, "info"); - expect(stepState(1)).toBe("now"); + expect(showcaseCta()!.textContent).toBe("Download free for Mac"); expect(events("desktop_cta_outcome")).toEqual([ - { outcome: "failed", reason: "download_tab_blocked", ...noApp }, + { outcome: "failed", reason: "download_tab_blocked", ...noApp, source: "header" }, ]); }); @@ -226,7 +235,7 @@ it("finds the install only from the preview server, asking only while the card i expect(gets).toBe(1); await act(async () => button()!.click()); - await act(async () => cardButton("Download for Mac")!.click()); + await act(async () => showcaseCta()!.click()); await act(async () => vi.advanceTimersByTime(2000)); const asked = gets; expect(asked).toBeGreaterThan(1); @@ -236,10 +245,7 @@ it("finds the install only from the preview server, asking only while the card i answer = routeBody({ handoff: true, installed: true }); await act(async () => vi.advanceTimersByTime(2000)); - expect([stepState(2), stepState(3)]).toEqual(["done", "now"]); - expect(cardButton("Open in desktop app")!.disabled).toBe(false); expect(button()!.textContent).toBe("Open in desktop app"); - expect(guide()!.querySelector('svg[data-mood="found"]')).not.toBeNull(); const detected = events("desktop_cta_guide").filter( (e) => (e as { step: string }).step === "install_detected", ); @@ -272,16 +278,16 @@ it("records the install once per page, even when the app goes and comes back", ( await act(async () => button()!.click()); answer = routeBody({ handoff: true, installed: true }); await act(async () => vi.advanceTimersByTime(2000)); - expect(stepState(2)).toBe("done"); + expect(button()!.textContent).toBe("Open in desktop app"); - // The app is removed: the hand-off finds it gone, and the server stops reporting it. + // The app is removed: hand-off finds it gone and reopens the showcase card. answer = routeBody(); - await act(async () => cardButton("Open in desktop app")!.click()); - expect(stepState(2)).toBe("todo"); - // Installed again: the card finds it a second time. + await act(async () => button()!.click()); + expect(showcaseCard()!.dataset.open).toBe("true"); + // Installed again: detected without double-counting install_detected. answer = routeBody({ handoff: true, installed: true }); await act(async () => vi.advanceTimersByTime(2000)); - expect(stepState(2)).toBe("done"); + expect(button()!.textContent).toBe("Open in desktop app"); const detected = events("desktop_cta_guide").filter( (e) => (e as { step: string }).step === "install_detected", @@ -301,7 +307,7 @@ it("stops asking the preview server when the card closes", () => await act(async () => vi.advanceTimersByTime(4000)); expect(gets).toBeGreaterThan(2); await act(async () => button()!.click()); - expect(guide()).toBeNull(); + expect(showcaseCard()!.dataset.open).toBe("false"); const closedAt = gets; await act(async () => vi.advanceTimersByTime(10_000)); expect(gets).toBe(closedAt); @@ -353,7 +359,7 @@ it("a failed hand-off opens the card at step 3 with the folder to copy and Try a expect(posts).toBe(2); }); -it("a hand-off that finds the app gone goes back to the download step", async () => { +it("a hand-off that finds the app gone falls back to the Make editing easier pill and opens the card", async () => { serve(Response.json(routeBody({ handoff: true, installed: true })), { opened: false, reason: "not-installed", @@ -361,8 +367,8 @@ it("a hand-off that finds the app gone goes back to the download step", async () }); await mount(); await act(async () => button()!.click()); - expect([stepState(1), stepState(3)]).toEqual(["now", "todo"]); - expect(button()!.textContent).toBe("Install the desktop app"); + expect(button()!.getAttribute("aria-label")).toBe("Make editing easier"); + expect(showcaseCard()!.dataset.open).toBe("true"); }); it("where the app is installed but cannot take a project (Linux), step 3 shows the folder to drop in", async () => { @@ -387,7 +393,7 @@ it("where the app is installed but cannot take a project (Linux), step 3 shows t expect(posts).toBe(0); }); -it("on Windows, step 1 names the Windows download and opens it tagged", async () => { +it("on Windows, the card names 'Download free for Windows' and opens it tagged", async () => { const opened: string[] = []; vi.stubGlobal("open", (url: string) => (opened.push(url), { opener: {} })); serve( @@ -402,7 +408,8 @@ it("on Windows, step 1 names the Windows download and opens it tagged", async () await mount(); expect(button()).not.toBeNull(); await act(async () => button()!.click()); - await act(async () => cardButton("Download for Windows")!.click()); + expect(showcaseCta()!.textContent).toBe("Download free for Windows"); + await act(async () => showcaseCta()!.click()); expect(opened).toEqual([tagged(`${DOWNLOAD}?os=windows`)]); expect(events("desktop_cta_eligibility")).toEqual([ { @@ -581,9 +588,14 @@ it("records the download press as sent to the download, never as an install", as ); await mount(); await act(async () => button()!.click()); - await act(async () => cardButton("Download for Linux")!.click()); - expect(events("toolbar_action")).toEqual([{ action: "get_desktop_app", ...linux }]); - expect(events("desktop_cta_outcome")).toEqual([{ outcome: "sent_to_download", ...linux }]); + expect(showcaseCta()!.textContent).toBe("Download free for Linux"); + await act(async () => showcaseCta()!.click()); + expect(events("toolbar_action")).toEqual([ + { action: "get_desktop_app", ...linux, source: "header" }, + ]); + expect(events("desktop_cta_outcome")).toEqual([ + { outcome: "sent_to_download", ...linux, source: "header" }, + ]); const sent = JSON.stringify(track.mock.calls); expect(sent).not.toMatch(/"(outcome|step)":"[a-z_]*install/); expect(sent).not.toContain("/"); diff --git a/packages/studio/src/components/OpenInDesktopButton.tsx b/packages/studio/src/components/OpenInDesktopButton.tsx index 52e7040409a..8ce540245be 100644 --- a/packages/studio/src/components/OpenInDesktopButton.tsx +++ b/packages/studio/src/components/OpenInDesktopButton.tsx @@ -1,9 +1,22 @@ import { useCallback, useEffect, useRef, useState } from "react"; import { useStudioShellContext } from "../contexts/StudioContext"; import { useFileManagerContextOptional } from "../contexts/FileManagerContext"; +import { usePlayerStore } from "../player"; import { resolveTabId } from "../telemetry/tabId"; import { studioApiFetch } from "../utils/studioApiFetch"; import { trackStudioEvent } from "../utils/studioTelemetry"; +import { DesktopAppCard } from "./desktop-card/DesktopAppCard"; +import { DesktopInstallPill } from "./desktop-card/DesktopInstallPill"; +import { + canShowDesktopUpsell, + closeDesktopCard, + launchDesktopDownload, + maybeAutoOpenDesktopCard, + openDesktopCard, + resolveDownloadOs, + setDesktopCardRoute, + useDesktopCardStore, +} from "./desktop-card/desktopCardStore"; import { GuideCard, Swap, @@ -18,36 +31,22 @@ import { FrameyGlyph } from "./FrameyGlyph"; import { Button, Popover, cn } from "./ui"; // "Install the desktop app": the preview server (`/api/open-in-desktop`) says whether to show it, whether the app is -// here and whether it takes the project. With the app ready a press opens the project in it; otherwise the press -// opens a card where Framey walks through download, install and open. +// here and whether it takes the project. With the app ready a press opens the project in it; otherwise in the header +// it renders the glowing "Make editing easier" pill and 5-scene Desktop card (with once-a-week auto-open after +// watching or exporting). const ROUTE = "/api/open-in-desktop"; -/** How far the pupils travel towards the pointer, in the glyph's own units. */ const GAZE = 2.2; -/** Long enough for the flight to finish before the label comes back. */ const OPENING_MS = 1600; -/** While the card is open and the app is not here yet, how often to ask the preview server again. */ const POLL_MS = 2000; -/** After this long without the app turning up, the card asks whether the download finished. */ const SLOW_MS = 60_000; type OpenResult = { opened: true } | { opened: false; reason: string; downloadUrl: string }; - type Eligibility = "open_in_app" | "download" | "no_app_for_platform"; - -/** Every Guide step change, for the funnel: never a download counted as an install. */ type GuideStep = "opened" | "closed" | "download_opened" | "install_detected"; -/** The download, tagged with this page's telemetry `tab_id` so a later install can be matched to the press. */ -const withCta = (url: string): string => { - const tagged = new URL(url); - tagged.searchParams.set("hf_cta", resolveTabId()); - return tagged.toString(); -}; - const eligibilityOf = (route: DesktopRoute): Eligibility => route.handoff ? "open_in_app" : route.downloadUrl ? "download" : "no_app_for_platform"; -/** The preview server's answer, or null when there is none (the desktop's own Studio, or no server). */ async function readRoute(placement: DesktopCtaPlacement): Promise { const res = await studioApiFetch(ROUTE); if (!res.ok) return null; @@ -72,7 +71,6 @@ async function readRoute(placement: DesktopCtaPlacement): Promise(null); useEffect(() => { @@ -84,17 +82,32 @@ function useDesktopRoute(placement: DesktopCtaPlacement) { eligibility: eligibilityOf(answered), ...answered.context, }); - if (answered.handoff || answered.downloadUrl) setRoute(answered); + if (answered.handoff || answered.downloadUrl) { + setRoute(answered); + if (placement === "header") setDesktopCardRoute(answered); + } else if (placement === "header") { + setDesktopCardRoute(null); + } }) .catch(() => {}); return () => { live = false; + if (placement === "header") { + closeDesktopCard(); + setDesktopCardRoute(null); + } }; }, [placement]); - return [route, setRoute] as const; + const updateRoute = useCallback( + (next: DesktopRoute) => { + setRoute(next); + if (placement === "header") setDesktopCardRoute(next); + }, + [placement], + ); + return [route, updateRoute] as const; } -/** One impression per page, once the button is on screen. */ function useImpression(anchor: React.RefObject, route: DesktopRoute | null) { const shown = route !== null; const routeRef = useRef(route); @@ -120,7 +133,6 @@ function useImpression(anchor: React.RefObject, route: Deskt }, [anchor, shown]); } -/** Framey looks at the pointer: one listener, one write per frame, no re-render. */ function useGaze( anchor: React.RefObject, eye: React.RefObject, @@ -146,7 +158,6 @@ function useGaze( }, [anchor, eye]); } -/** While the card is open and the app is not here, ask the preview server again; stops on close or once found. */ function useInstallWatch( watching: boolean, placement: DesktopCtaPlacement, @@ -168,15 +179,94 @@ function useInstallWatch( }, [watching, placement, onAnswer]); } +function didPlaybackReachEnd( + wasPlaying: boolean, + prevTime: number, + next: { isPlaying: boolean; currentTime: number; duration: number }, +): boolean { + if (!wasPlaying || next.duration <= 0) return false; + if (!next.isPlaying) return Math.max(next.currentTime, prevTime) >= next.duration - 0.15; + return next.duration > 1 && prevTime >= next.duration - 0.25 && next.currentTime < 0.25; +} + +function completedRenderIds(rawJobs: unknown): Set { + const jobs = (rawJobs ?? []) as ReadonlyArray<{ id?: string; status?: string }>; + const ids = new Set(); + for (const job of jobs) { + if (job.status === "complete" && typeof job.id === "string") ids.add(job.id); + } + return ids; +} + +function hasUnseenId(next: Set, known: Set): boolean { + for (const id of next) { + if (!known.has(id)) return true; + } + return false; +} + +/** Auto-open the Desktop card (at most once a week) when playback finishes or an export completes. */ +function useAutoOpenTriggers(enabled: boolean): void { + const shell = useStudioShellContext(); + const rawJobs = shell.renderQueue?.jobs; + const knownCompleted = useRef | null>(null); + + useEffect(() => { + if (!enabled) return; + let wasPlaying = usePlayerStore.getState().isPlaying; + let prevTime = usePlayerStore.getState().currentTime; + return usePlayerStore.subscribe((next) => { + const reachedEnd = didPlaybackReachEnd(wasPlaying, prevTime, next); + wasPlaying = next.isPlaying; + prevTime = next.currentTime; + if (reachedEnd) maybeAutoOpenDesktopCard("auto_watch"); + }); + }, [enabled]); + + useEffect(() => { + const completedIds = completedRenderIds(rawJobs); + const prev = knownCompleted.current; + knownCompleted.current = completedIds; + if (enabled && prev !== null && hasUnseenId(completedIds, prev)) { + maybeAutoOpenDesktopCard("auto_export"); + } + }, [enabled, rawJobs]); +} + +function useShowcaseOpenTelemetry( + active: boolean, + route: DesktopRoute | null, + open: boolean, + source: string, +): void { + const prevOpen = useRef(false); + useEffect(() => { + if (!active || !route) { + if (prevOpen.current && route) { + trackStudioEvent("desktop_cta_guide", { step: "closed", ...route.context, source }); + } + prevOpen.current = false; + return; + } + if (open === prevOpen.current) return; + prevOpen.current = open; + trackStudioEvent("desktop_cta_guide", { + step: open ? "opened" : "closed", + ...route.context, + source, + }); + }, [active, route, open, source]); +} + const LOOK = "hf-framey-trigger gap-1.5 border border-accent/40 bg-accent/10 pl-1 font-semibold text-text-0 enabled:hover:bg-accent/20 hover:bg-accent/20"; const LOOK_FAILED = "border-danger/45 bg-danger/8 text-danger-ink enabled:hover:bg-danger/14"; -/** The guide's state and the two actions that move it: the download and the hand-off. */ function useGuide( route: DesktopRoute | null, setRoute: (route: DesktopRoute) => void, placement: DesktopCtaPlacement, + showcaseOpen: boolean, ) { const { showToast } = useStudioShellContext(); const [cardOpen, setCardOpen] = useState(false); @@ -186,7 +276,6 @@ function useGuide( const [slow, setSlow] = useState(false); const [arrived, setArrived] = useState(false); const installed = route?.context.app_installed === true; - // The funnel counts one install per page, even if the app is removed and found again. const installCounted = useRef(false); const onAnswer = useCallback( @@ -200,7 +289,7 @@ function useGuide( }, [setRoute], ); - useInstallWatch(cardOpen && route !== null && !installed, placement, onAnswer); + useInstallWatch((cardOpen || showcaseOpen) && route !== null && !installed, placement, onAnswer); useEffect(() => { if (!downloaded || installed) return; @@ -227,18 +316,7 @@ function useGuide( }; const download = () => { - if (!route.downloadUrl) return; - trackStudioEvent("toolbar_action", { action: "get_desktop_app", ...context }); - const tab = window.open(withCta(route.downloadUrl), "_blank"); - if (!tab) { - showToast(`Get the HyperFrames desktop app at ${route.downloadUrl}`, "info"); - outcome("failed", "download_tab_blocked"); - return; - } - tab.opener = null; - setDownloaded(true); - outcome("sent_to_download"); - guideStep("download_opened"); + if (launchDesktopDownload(route, undefined, showToast)) setDownloaded(true); }; const landed = async (result: OpenResult) => { @@ -250,10 +328,15 @@ function useGuide( return; } outcome("failed", result.reason); - // The app is gone: back to the download. Anything else: say so where the person is, with a way through. - if (result.reason === "not-installed") + if (result.reason === "not-installed") { setRoute({ ...route, handoff: false, context: { ...context, app_installed: false } }); - else setFailed(true); + if (placement === "header") { + openDesktopCard(0, "header"); + return; + } + } else { + setFailed(true); + } showCard(true); }; @@ -281,30 +364,72 @@ function useGuide( }; const progress: Progress = { route, opening, failed, downloaded, slow, arrived }; - return { progress, cardOpen, showCard, download, open }; + return { progress, cardOpen, showCard, download, open, guideStep }; } -export function OpenInDesktopButton({ - placement = "header", +function HeaderShowcaseTrigger({ + placement, + route, + triggerRef, }: { - placement?: DesktopCtaPlacement; -} = {}) { - const projectDir = useFileManagerContextOptional()?.projectDir ?? null; - const [route, setRoute] = useDesktopRoute(placement); - const trigger = useRef(null); - const eye = useRef(null); - useGaze(trigger, eye); - useImpression(trigger, route); - const guide = useGuide(route, setRoute, placement); - if (!guide) return null; - const { progress, cardOpen, showCard, download, open } = guide; + placement: DesktopCtaPlacement; + route: DesktopRoute; + triggerRef: React.RefObject; +}) { + const { showToast } = useStudioShellContext(); + const store = useDesktopCardStore(); + const { key: osKey, label: osLabel } = resolveDownloadOs(route.context.os); + + return ( + <> + (store.open ? closeDesktopCard() : openDesktopCard(0, "header"))} + /> + launchDesktopDownload(route, store.source, showToast)} + onClose={closeDesktopCard} + /> + + ); +} + +function GuidePopoverTrigger({ + placement, + projectDir, + triggerRef, + eyeRef, + progress, + cardOpen, + showCard, + download, + open, +}: { + placement: DesktopCtaPlacement; + projectDir: string | null; + triggerRef: React.RefObject; + eyeRef: React.RefObject; + progress: Progress; + cardOpen: boolean; + showCard: (next: boolean) => void; + download: () => void; + open: () => Promise; +}) { const label = labelOf(progress); const waiting = isWaiting(progress); return ( { if (next && progress.route.handoff && !progress.failed) return void open(); showCard(next); @@ -315,7 +440,7 @@ export function OpenInDesktopButton({ className="w-[360px] overflow-hidden p-0" trigger={ + + ); +} diff --git a/packages/studio/src/components/desktop-card/DesktopAppCard.tsx b/packages/studio/src/components/desktop-card/DesktopAppCard.tsx new file mode 100644 index 00000000000..af28cc7a8a4 --- /dev/null +++ b/packages/studio/src/components/desktop-card/DesktopAppCard.tsx @@ -0,0 +1,264 @@ +import { useEffect, useRef, useState } from "react"; +import { createPortal } from "react-dom"; +import { PlatformMark, resolveDesktopCardAgent } from "./agentBrands"; +import { createCardChoreography, type CardChoreographyController } from "./cardChoreography"; +import { CARD_W, createEmptyStageElements, SECTIONS } from "./cardStageTypes"; +import { DesktopAppCardStage } from "./DesktopAppCardStage"; +import type { DesktopCardSceneIndex } from "./desktopCardStore"; + +export interface DesktopAppCardProps { + open: boolean; + initialScene: DesktopCardSceneIndex; + openSeq: number; + anchorRef: React.RefObject; + osKey: "mac" | "win" | "linux"; + osLabel: string; + downloaded: boolean; + onDownload: () => void; + onClose: () => void; +} + +function useCardAnchorPosition( + open: boolean, + anchorRef: React.RefObject, + openSeq: number, +) { + const [pos, setPos] = useState<{ left: number; top: number; originX: number }>({ + left: 16, + top: 44, + originX: CARD_W - 80, + }); + + useEffect(() => { + if (!open) return; + const place = () => { + const vw = window.innerWidth || 1440; + const anchor = anchorRef.current?.getBoundingClientRect(); + if (anchor && anchor.width > 0) { + const left = Math.max(8, Math.min(vw - CARD_W - 8, anchor.right - CARD_W)); + const top = Math.max(8, anchor.bottom + 7); + setPos({ left, top, originX: anchor.left + anchor.width / 2 - left }); + } else { + setPos({ left: Math.max(8, vw - CARD_W - 16), top: 44, originX: CARD_W - 80 }); + } + }; + place(); + window.addEventListener("resize", place); + return () => window.removeEventListener("resize", place); + }, [open, anchorRef, openSeq]); + + return pos; +} + +function useCardDismiss( + open: boolean, + cardRef: React.RefObject, + anchorRef: React.RefObject, + onClose: () => void, +) { + useEffect(() => { + const cardEl = cardRef.current; + if (!cardEl) return; + if (open) cardEl.removeAttribute("inert"); + else cardEl.setAttribute("inert", ""); + }, [cardRef, open]); + + useEffect(() => { + if (!open) return; + const onPointerDown = (event: PointerEvent) => { + const target = event.target as Node | null; + if (!target || cardRef.current?.contains(target) || anchorRef.current?.contains(target)) { + return; + } + onClose(); + }; + const onKeyDown = (event: KeyboardEvent) => { + if (event.key === "Escape") onClose(); + }; + document.addEventListener("pointerdown", onPointerDown, true); + window.addEventListener("keydown", onKeyDown); + return () => { + document.removeEventListener("pointerdown", onPointerDown, true); + window.removeEventListener("keydown", onKeyDown); + }; + }, [open, cardRef, anchorRef, onClose]); +} + +function useCardChoreography(params: { + open: boolean; + initialScene: DesktopCardSceneIndex; + openSeq: number; + agentHeadline: string; + cardRef: React.RefObject; + stageRef: React.RefObject>; + lineBoxRef: React.RefObject; + segFillRefs: React.RefObject<(HTMLElement | null)[]>; +}) { + const { open, initialScene, openSeq, agentHeadline, cardRef, stageRef, lineBoxRef, segFillRefs } = + params; + const controllerRef = useRef(null); + + useEffect(() => { + const cardEl = cardRef.current; + if (!cardEl || openSeq === 0) return; + const ctrl = createCardChoreography({ + cardEl, + stage: stageRef.current, + lineBox: lineBoxRef.current, + segBars: segFillRefs.current, + agentHeadline, + }); + controllerRef.current = ctrl; + if (!ctrl) return; + if (open) ctrl.jump(initialScene); + else ctrl.stop(); + return () => { + controllerRef.current = null; + ctrl.stop(); + }; + }, [open, initialScene, openSeq, agentHeadline, cardRef, stageRef, lineBoxRef, segFillRefs]); + + return controllerRef; +} + +function DesktopAppCardStageSlot({ + openSeq, + agentLogo, + stageRef, + onDownload, +}: { + openSeq: number; + agentLogo: ReturnType["logo"]; + stageRef: React.RefObject>; + onDownload: () => void; +}) { + if (openSeq === 0) return