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
152 changes: 82 additions & 70 deletions packages/studio/src/components/OpenInDesktopButton.dom.test.tsx
Original file line number Diff line number Diff line change
@@ -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";
Expand All @@ -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";
Expand All @@ -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);
Expand Down Expand Up @@ -63,10 +67,19 @@ async function mount(placement?: "storyboard"): Promise<HTMLElement> {

const button = () =>
document.querySelector<HTMLButtonElement>('[data-testid="header-open-in-desktop"]');
const showcaseCard = () => document.querySelector<HTMLElement>('[data-testid="desktop-app-card"]');
const showcaseCta = () =>
document.querySelector<HTMLButtonElement>('[data-testid="desktop-app-card-cta"]');
const guide = () => document.querySelector<HTMLElement>('[data-testid="desktop-guide"]');
const stepState = (n: number) =>
guide()?.querySelector<HTMLElement>(`[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;
Expand All @@ -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<string, unknown> = {}) => ({
...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<void>) {
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();
Expand Down Expand Up @@ -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<void>) {
vi.useFakeTimers({ toFake: ["setInterval", "clearInterval", "setTimeout", "clearTimeout"] });
try {
await body();
} finally {
vi.useRealTimers();
}
}

const guide = () => document.querySelector<HTMLElement>('[data-testid="desktop-guide"]');
const stepState = (n: number) =>
guide()?.querySelector<HTMLElement>(`[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<string, unknown> = {}) => ({
...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;

Expand All @@ -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" },
]);
});

Expand All @@ -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);
Expand All @@ -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",
);
Expand Down Expand Up @@ -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",
Expand All @@ -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);
Expand Down Expand Up @@ -353,16 +359,16 @@ 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",
downloadUrl: DOWNLOAD,
});
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 () => {
Expand All @@ -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(
Expand All @@ -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([
{
Expand Down Expand Up @@ -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("/");
Expand Down
Loading
Loading