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