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

localApi.ts

92 lines2.9 KB

1import type { ConfirmDialogOptions, ContextMenuItem, LocalApi } from "@t3tools/contracts";
2​
3import { isWebUrl } from "./browser/webUrl";
4import { requestConfirmDialog } from "./confirmDialog";
5import { dismissContextMenu, showContextMenuFallback } from "./contextMenuFallback";
6import { readBrowserClientSettings, writeBrowserClientSettings } from "./clientPersistenceStorage";
7​
8let cachedApi: LocalApi | undefined;
9​
10export function createLocalApi(): 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 if (!isWebUrl(url)) throw new Error("Unable to open link.");
32 window.open(url, "_blank", "noopener,noreferrer");
33 },
34 openSystemSettings: async (pane) => {
35 if (!window.desktopBridge) {
36 throw new Error("Unable to open System Settings.");
37 }
38 const opened = await window.desktopBridge.openSystemSettings(pane);
39 if (!opened) {
40 throw new Error("Unable to open System Settings.");
41 }
42 },
43 },
44 contextMenu: {
45 show: async <T extends string>(
46 items: readonly ContextMenuItem<T>[],
47 position?: { x: number; y: number },
48 ): Promise<T | null> => {
49 if (window.desktopBridge) {
50 return window.desktopBridge.showContextMenu(items, position) as Promise<T | null>;
51 }
52 return showContextMenuFallback(items, position);
53 },
54 // Unlike native menus, the DOM fallback needs dismissal when underlying state disappears.
55 close: async () => {
56 if (!window.desktopBridge) {
57 dismissContextMenu();
58 }
59 },
60 },
61 persistence: {
62 getClientSettings: async () => {
63 if (window.desktopBridge) {
64 return window.desktopBridge.getClientSettings();
65 }
66 return readBrowserClientSettings();
67 },
68 setClientSettings: async (settings) => {
69 if (window.desktopBridge) {
70 return window.desktopBridge.setClientSettings(settings);
71 }
72 writeBrowserClientSettings(settings);
73 },
74 },
75 };
77​
78export function readLocalApi(): LocalApi | undefined {
79 if (typeof window === "undefined") return undefined;
80 if (cachedApi) return cachedApi;
81​
82 cachedApi = createLocalApi();
83 return cachedApi;
85​
86export function ensureLocalApi(): LocalApi {
87 const api = readLocalApi();
88 if (!api) {
89 throw new Error("Local API not found");
90 }
91 return api;