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