Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

mediaActions.test.ts

180 lines6.1 KB

1import {
2 AuthFilesystemReadScope,
3 EnvironmentId,
4 ThreadId,
5 type AuthSessionState,
6} from "@t3tools/contracts";
7import { AsyncResult } from "effect/reactivity";
8import { beforeEach, expect, it, vi } from "vite-plus/test";
9​
10const state = vi.hoisted(() => ({
11 sessions: new Map<string, Pick<AuthSessionState, "authenticated" | "scopes">>(),
12 refresh: vi.fn(),
13 download: vi.fn(),
14 shareLocal: vi.fn(),
15 shareDraft: vi.fn(),
16 navigate: vi.fn(),
17 copy: vi.fn(),
18}));
19​
20vi.mock("react", () => ({
21 useEffect: () => {},
22 useRef: <A>(current: A) => ({ current }),
23 useState: <A>(initial: A) => [initial, () => {}],
24}));
25vi.mock("react-native", () => ({ Alert: { alert: vi.fn() } }));
26vi.mock("@react-navigation/native", () => ({
27 useNavigation: () => ({ navigate: state.navigate }),
28}));
29vi.mock("./markdownLinks", () => ({
30 normalizeNativeMarkdownUrl: (uri: string) => uri,
31}));
32vi.mock("../state/assets", () => ({
33 useRefreshAssetUrl: (environmentId: string, resource: unknown) => () =>
34 state.refresh(environmentId, resource),
35}));
36vi.mock("../state/session", () => ({
37 environmentSession: { sessionStateAtom: (environmentId: string) => environmentId },
38}));
39vi.mock("../state/query", () => ({
40 useEnvironmentQuery: (environmentId: string) => ({
41 data: state.sessions.get(environmentId) ?? null,
42 error: null,
43 }),
44}));
45vi.mock("../state/atom-registry", () => ({
46 appAtomRegistry: {
47 get: (environmentId: string) => {
48 const session = state.sessions.get(environmentId);
49 return session === undefined ? AsyncResult.initial() : AsyncResult.success(session);
50 },
51 },
52}));
53vi.mock("./attachmentDownload", () => ({
54 downloadAndShareAttachment: state.download,
55 shareLocalAttachment: state.shareLocal,
56}));
57vi.mock("./copyTextWithHaptic", () => ({ copyTextWithHaptic: state.copy }));
58vi.mock("./localAttachmentPreview", () => ({
59 loadLocalAttachmentPreview: async () => ({ share: state.shareDraft, dispose: vi.fn() }),
60}));
61​
62import { useMediaActions } from "../state/mediaActions";
63import type { MediaActionsSource } from "./mediaActionsSource";
64​
65const environmentId = EnvironmentId.make("media-environment");
66const otherEnvironmentId = EnvironmentId.make("other-environment");
67const threadId = ThreadId.make("media-thread");
68const granted: Pick<AuthSessionState, "authenticated" | "scopes"> = {
69 authenticated: true,
70 scopes: [AuthFilesystemReadScope],
71};
72const denied: Pick<AuthSessionState, "authenticated" | "scopes"> = {
73 authenticated: true,
74 scopes: [],
75};
76​
77function hostSource(_tag: "workspace-file" | "media-file" = "media-file"): MediaActionsSource {
78 return {
79 environmentId,
80 threadId,
81 resource: { _tag, threadId, path: "/repo/image.png" },
82 reference: { kind: "file", path: "/repo/image.png", relativePath: "image.png" },
83 name: "image.png",
84 mimeType: "image/png",
85 };
87​
88beforeEach(() => {
89 state.sessions.clear();
90 state.sessions.set(environmentId, denied);
91 state.refresh.mockReset().mockResolvedValue("https://host.test/image.png");
92 state.download.mockReset().mockResolvedValue(undefined);
93 state.shareLocal.mockReset().mockResolvedValue(undefined);
94 state.shareDraft.mockReset().mockResolvedValue(undefined);
95 state.navigate.mockReset();
96 state.copy.mockReset();
97});
98​
99it.each(["workspace-file", "media-file"] as const)(
100 "blocks denied %s sharing and file opening while preserving path copying",
101 async (_tag) => {
102 const media = useMediaActions(hostSource(_tag));
103 await media.share();
104 media.actions.find(({ id }) => id === "open-file")!.run();
105 media.actions.find(({ id }) => id === "copy-full-path")!.run();
106​
107 expect(state.refresh).not.toHaveBeenCalled();
108 expect(state.download).not.toHaveBeenCalled();
109 expect(state.navigate).not.toHaveBeenCalled();
110 expect(state.copy).toHaveBeenCalledWith("/repo/image.png");
111 expect(media.actions.find(({ id }) => id === "save")?.disabled).toBe(true);
112 expect(media.actions.find(({ id }) => id === "open-file")?.disabled).toBe(true);
113 },
114);
115​
116it("rechecks a retained menu action after revocation", async () => {
117 state.sessions.set(environmentId, granted);
118 const media = useMediaActions(hostSource());
119 state.sessions.set(environmentId, denied);
120​
121 await media.share();
122 media.actions.find(({ id }) => id === "open-file")!.run();
123​
124 expect(state.refresh).not.toHaveBeenCalled();
125 expect(state.navigate).not.toHaveBeenCalled();
126});
127​
128it("reenables sharing after gaining access while preserving a retained callback", async () => {
129 const media = useMediaActions(hostSource());
130 state.sessions.set(environmentId, granted);
131​
132 await media.share();
133​
134 expect(state.download).toHaveBeenCalledOnce();
135 expect(useMediaActions(hostSource()).actions.find(({ id }) => id === "save")?.disabled).toBe(
136 false,
137 );
138});
139​
140it.each([false, true])("uses the media environment's grant (allowed: %s)", async (allowed) => {
141 state.sessions.set(environmentId, allowed ? granted : denied);
142 state.sessions.set(otherEnvironmentId, allowed ? denied : granted);
143​
144 await useMediaActions(hostSource()).share();
145​
146 expect(state.refresh).toHaveBeenCalledTimes(allowed ? 1 : 0);
147 expect(state.download).toHaveBeenCalledTimes(allowed ? 1 : 0);
148});
149​
150it("stops before downloading if access is revoked while the URL is refreshed", async () => {
151 state.sessions.set(environmentId, granted);
152 state.refresh.mockImplementation(async () => {
153 state.sessions.set(environmentId, denied);
154 return "https://host.test/image.png";
155 });
156​
157 await useMediaActions(hostSource()).share();
158​
159 expect(state.refresh).toHaveBeenCalledOnce();
160 expect(state.download).not.toHaveBeenCalled();
161});
162​
163it("lets an unresolved grant be authorized by an explicit server request", async () => {
164 state.sessions.delete(environmentId);
165​
166 await useMediaActions(hostSource()).share();
167​
168 expect(state.refresh).toHaveBeenCalledOnce();
169 expect(state.download).toHaveBeenCalledOnce();
170});
171​
172it.each(["https://cdn.test/image.png", "file:///device/image.png"])(
173 "shares direct media without a host grant: %s",
174 async (uri) => {
175 await useMediaActions({ uri, name: "image.png", mimeType: "image/png" }).share();
176​
177 expect(state.refresh).not.toHaveBeenCalled();
178 expect(uri.startsWith("file:") ? state.shareLocal : state.download).toHaveBeenCalledOnce();
179 },
180);