okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-split-int (c157ea373) into f-split-qa1: my new strings renumbered after s3236 (s3237-s3255)e5476b0e1

main
2.5 KiB50 linesraw
1import { useSyncExternalStore } from 'react';
2import { ApiError, api } from './client';
3
4/**
5 * Picking a folder when the system has no working chooser (Linux without zenity, kdialog or a desktop portal, or one that fails).
6 * The host answers 501 with code `folder-chooser-unavailable` and a plain sentence; the app then asks for the path in a small dialog
7 * and sends it back as `{ path }`, which the host checks the same way as a picked folder. Closing the dialog is a cancel.
8 */
9export interface FolderPrompt { message: string; resolve: (path: string | null) => void }
10
11let current: FolderPrompt | null = null;
12const listeners = new Set<() => void>();
13const subscribe = (fn: () => void) => { listeners.add(fn); return () => { listeners.delete(fn); }; };
14const emit = () => listeners.forEach(fn => fn());
15
16export function useFolderPrompt() { return useSyncExternalStore(subscribe, () => current, () => null); }
17
18/** Ask for a folder path in words; resolves with the typed text, or null when the person cancels. */
19export function askForFolderPath(message: string): Promise<string | null> {
20  return new Promise(resolve => {
21    current?.resolve(null);
22    current = { message, resolve: path => { current = null; emit(); resolve(path); } };
23    emit();
24  });
25}
26
27export const isChooserUnavailable = (e: unknown) => e instanceof ApiError && (e.body as { code?: string } | undefined)?.code === 'folder-chooser-unavailable';
28
29/** POST to a host route that opens the system folder chooser; if there is none, ask for the path and POST it instead. */
30export async function postWithFolderFallback<T>(url: string): Promise<T | { cancelled: true }> {
31  try { return await api.post<T>(url, {}); }
32  catch (e) {
33    if (!isChooserUnavailable(e)) throw e;
34    for (;;) {
35      const typed = await askForFolderPath((e as ApiError).message);
36      if (!typed) return { cancelled: true };
37      try { return await api.post<T>(url, { path: typed }); }
38      catch (again) {
39        // A path the host refuses ("That folder does not exist.") is shown and asked for again; anything else is a real failure.
40        if (!(again instanceof ApiError) || again.status !== 400) throw again;
41        e = Object.assign(new ApiError(again.message, 501, { code: 'folder-chooser-unavailable' }));
42      }
43    }
44  }
45}
46
47/** Is this page open on the computer that runs Strata? A folder window opens on that computer's screen, so a page opened from another one cannot use it. */
48export function pageIsOnThisComputer(hostname: string): boolean {
49  return /^(localhost|127(\.\d{1,3}){3}|\[?::1\]?)$/i.test(hostname);
50}