Open History to see the last commit
1import type { ContextMenuItem, LocalApi } from "@t3tools/contracts";
2
3import { resetRequestLatencyStateForTests } from "./rpc/requestLatencyState";
4import { showContextMenuFallback } from "./contextMenuFallback";
5import { readBrowserClientSettings, writeBrowserClientSettings } from "./clientPersistenceStorage";
6
7let cachedApi: LocalApi | undefined;
8
9function createBrowserLocalApi(): LocalApi {
10 return {
11 dialogs: {
12 pickFolder: async (options) => {
13 if (!window.desktopBridge) return null;
14 return window.desktopBridge.pickFolder(options);
15 },
16 confirm: async (message) => {
17 if (window.desktopBridge) {
18 return window.desktopBridge.confirm(message);
19 }
20 return window.confirm(message);
21 },
22 },
23 shell: {
24 openExternal: async (url) => {
25 if (window.desktopBridge) {
26 const opened = await window.desktopBridge.openExternal(url);
27 if (!opened) {
28 throw new Error("Unable to open link.");
29 }
30 return;
31 }
32
33 window.open(url, "_blank", "noopener,noreferrer");
34 },
35 },
36 contextMenu: {
37 show: async <T extends string>(
38 items: readonly ContextMenuItem<T>[],
39 position?: { x: number; y: number },
40 ): Promise<T | null> => {
41 if (window.desktopBridge) {
42 return window.desktopBridge.showContextMenu(items, position) as Promise<T | null>;
43 }
44 return showContextMenuFallback(items, position);
45 },
46 },
47 persistence: {
48 getClientSettings: async () => {
49 if (window.desktopBridge) {
50 return window.desktopBridge.getClientSettings();
51 }
52 return readBrowserClientSettings();
53 },
54 setClientSettings: async (settings) => {
55 if (window.desktopBridge) {
56 return window.desktopBridge.setClientSettings(settings);
57 }
58 writeBrowserClientSettings(settings);
59 },
60 },
61 };
62}
63
64export function createLocalApi(): LocalApi {
65 return createBrowserLocalApi();
66}
67
68export function readLocalApi(): LocalApi | undefined {
69 if (typeof window === "undefined") return undefined;
70 if (cachedApi) return cachedApi;
71
72 cachedApi = createLocalApi();
73 return cachedApi;
74}
75
76export function ensureLocalApi(): LocalApi {
77 const api = readLocalApi();
78 if (!api) {
79 throw new Error("Local API not found");
80 }
81 return api;
82}
83
84export async function __resetLocalApiForTests() {
85 cachedApi = undefined;
86 const { __resetClientSettingsPersistenceForTests } = await import("./hooks/useSettings");
87 __resetClientSettingsPersistenceForTests();
88 resetRequestLatencyStateForTests();
89}