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

localApi.ts

95 lines3.0 KB

1import type { ConfirmDialogOptions, ContextMenuItem, LocalApi } from "@t3tools/contracts";
2​
3import { requestConfirmDialog } from "./confirmDialog";
4import { dismissContextMenu, showContextMenuFallback } from "./contextMenuFallback";
5import { readBrowserClientSettings, writeBrowserClientSettings } from "./clientPersistenceStorage";
6import { resetRequestLatencyStateForTests } from "./rpc/requestLatencyState";
7​
8let cachedApi: LocalApi | undefined;
9​
10function createBrowserLocalApi(): LocalApi {
11 return {
12 dialogs: {
13 pickFolder: async (options) => {
14 if (!window.desktopBridge) return null;
15 return window.desktopBridge.pickFolder(options);
16 },
17 confirm: async (message, options?: ConfirmDialogOptions) => {
18 return requestConfirmDialog(message, options) ?? false;
19 },
20 },
21 shell: {
22 openExternal: async (url) => {
23 if (window.desktopBridge) {
24 const opened = await window.desktopBridge.openExternal(url);
25 if (!opened) {
26 throw new Error("Unable to open link.");
27 }
28 return;
29 }
30​
31 window.open(url, "_blank", "noopener,noreferrer");
32 },
33 },
34 contextMenu: {
35 show: async <T extends string>(
36 items: readonly ContextMenuItem<T>[],
37 position?: { x: number; y: number },
38 ): Promise<T | null> => {
39 if (window.desktopBridge) {
40 return window.desktopBridge.showContextMenu(items, position) as Promise<T | null>;
41 }
42 return showContextMenuFallback(items, position);
43 },
44 // A native desktop menu blocks keyboard input and closes on outside
45 // interaction, so nothing to do there; the DOM fallback needs an explicit
46 // dismiss when the state behind it goes away.
47 close: async () => {
48 if (!window.desktopBridge) {
49 dismissContextMenu();
50 }
51 },
52 },
53 persistence: {
54 getClientSettings: async () => {
55 if (window.desktopBridge) {
56 return window.desktopBridge.getClientSettings();
57 }
58 return readBrowserClientSettings();
59 },
60 setClientSettings: async (settings) => {
61 if (window.desktopBridge) {
62 return window.desktopBridge.setClientSettings(settings);
63 }
64 writeBrowserClientSettings(settings);
65 },
66 },
67 };
69​
70export function createLocalApi(): LocalApi {
71 return createBrowserLocalApi();
73​
74export function readLocalApi(): LocalApi | undefined {
75 if (typeof window === "undefined") return undefined;
76 if (cachedApi) return cachedApi;
77​
78 cachedApi = createLocalApi();
79 return cachedApi;
81​
82export function ensureLocalApi(): LocalApi {
83 const api = readLocalApi();
84 if (!api) {
85 throw new Error("Local API not found");
86 }
87 return api;
89​
90export async function __resetLocalApiForTests() {
91 cachedApi = undefined;
92 const { __resetClientSettingsPersistenceForTests } = await import("./hooks/useSettings");
93 __resetClientSettingsPersistenceForTests();
94 resetRequestLatencyStateForTests();