okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
e5476b0e1
main
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 > { 20return new Promise ( resolve => { 21current ?. resolve ( null ); 22current = { message, resolve :path => { current = null ; emit (); resolve ( path ); } }; 23emit (); 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 }> { 31try { return await api . post < T >( url , {}); } 32catch ( e ) { 33if ( ! isChooserUnavailable ( e )) throw e ; 34for (;;) { 35const typed = await askForFolderPath (( e as ApiError ). message ); 36if ( ! typed ) return { cancelled :true }; 37try { return await api . post < T >( url , { path :typed }); } 38catch ( again ) { 39// A path the host refuses ("That folder does not exist.") is shown and asked for again; anything else is a real failure. 40if ( ! ( again instanceof ApiError ) || again . status !== 400 ) throw again ; 41e = 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 { 49return / ^(localhost|127(\.\d{1,3}){3}|\[?::1\]?)$ / i . test ( hostname ); 50}