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

localApi.ts

96 lines3.0 KB

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 openSystemSettings: async (pane) => {
33 if (!window.desktopBridge?.openSystemSettings) {
34 throw new Error("Unable to open System Settings.");
35 }
36 const opened = await window.desktopBridge.openSystemSettings(pane);
37 if (!opened) {
38 throw new Error("Unable to open System Settings.");
39 }
40 },
41 },
42 contextMenu: {
43 show: async <T extends string>(
44 items: readonly ContextMenuItem<T>[],
45 position?: { x: number; y: number },
46 ): Promise<T | null> => {
47 if (window.desktopBridge) {
48 return window.desktopBridge.showContextMenu(items, position) as Promise<T | null>;
49 }
50 return showContextMenuFallback(items, position);
51 },
52 // A native desktop menu blocks keyboard input and closes on outside
53 // interaction, so nothing to do there; the DOM fallback needs an explicit
54 // dismiss when the state behind it goes away.
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 createLocalApi(): LocalApi {
79 return createBrowserLocalApi();
81​
82export function readLocalApi(): LocalApi | undefined {
83 if (typeof window === "undefined") return undefined;
84 if (cachedApi) return cachedApi;
85​
86 cachedApi = createLocalApi();
87 return cachedApi;
89​
90export function ensureLocalApi(): LocalApi {
91 const api = readLocalApi();
92 if (!api) {
93 throw new Error("Local API not found");
94 }
95 return api;