Open History to see the last commit
1import type { ConfirmDialogOptions, ContextMenuItem, LocalApi } from "@t3tools/contracts";
2
3import { requestConfirmDialog } from "./confirmDialog";
4import { 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 },
45 persistence: {
46 getClientSettings: async () => {
47 if (window.desktopBridge) {
48 return window.desktopBridge.getClientSettings();
49 }
50 return readBrowserClientSettings();
51 },
52 setClientSettings: async (settings) => {
53 if (window.desktopBridge) {
54 return window.desktopBridge.setClientSettings(settings);
55 }
56 writeBrowserClientSettings(settings);
57 },
58 },
59 };
60}
61
62export function createLocalApi(): LocalApi {
63 return createBrowserLocalApi();
64}
65
66export function readLocalApi(): LocalApi | undefined {
67 if (typeof window === "undefined") return undefined;
68 if (cachedApi) return cachedApi;
69
70 cachedApi = createLocalApi();
71 return cachedApi;
72}
73
74export function ensureLocalApi(): LocalApi {
75 const api = readLocalApi();
76 if (!api) {
77 throw new Error("Local API not found");
78 }
79 return api;
80}
81
82export async function __resetLocalApiForTests() {
83 cachedApi = undefined;
84 const { __resetClientSettingsPersistenceForTests } = await import("./hooks/useSettings");
85 __resetClientSettingsPersistenceForTests();
86 resetRequestLatencyStateForTests();
87}