import type { FilePolicyReference, FilePickerPort, FileSelectionLimitReduction, FileSelectionOutcome, LocalFileRef, } from "../../application/ports/browser-file-storage/file.ts"; import type { BrowserDataResult } from "../../application/ports/browser-file-storage/shared.ts"; import { abortedResult, browserDataFailure, browserDataSuccess, mapBrowserDataException, } from "../browser-file-storage/result.ts"; import { BrowserFileVault, type SystemFileHandle, } from "./browser-file-vault.ts"; import { byteBucket, observeBrowserFile, type BrowserFileObserver, } from "./file-observer.ts"; import type { RegisteredFileSelectionPolicy } from "./file-policy.ts"; import { BrowserFilePolicyRegistry } from "./browser-file-policy-registry.ts"; import { createAbortableOperation } from "../platform/abortable-operation.ts"; type UserActivationState = Readonly<{ isActive: boolean }>; type PickerScheduler = Readonly<{ setTimeout(callback: () => void, delayMs: number): unknown; clearTimeout(handle: unknown): void; }>; type InputEventDependencies = Readonly<{ add( type: string, listener: EventListener, options?: AddEventListenerOptions, ): void; remove(type: string, listener: EventListener): void; getAttribute(name: string): string | null; activate(): void; }>; type WindowEventDependencies = Readonly<{ add(type: "focus", listener: EventListener): void; remove(type: "focus", listener: EventListener): void; }>; interface DisposableFilePicker extends FilePickerPort { dispose(): void; } /** * Focus can return before some engines dispatch the file input change event. * This grace keeps the fallback from misclassifying a real selection as a * dismissal. The native cancel event remains authoritative and immediate, and * once a picker has seen it the fallback is no longer installed. */ export const DEFAULT_NATIVE_PICKER_FOCUS_GRACE_MS = 1_000; export type NativeInputFilePickerOptions = Readonly<{ /** * A connected, labelled input owned by presentation. The adapter does not * create an inaccessible hidden control. */ input: HTMLInputElement; vault: BrowserFileVault; policies: BrowserFilePolicyRegistry; window?: Pick; userActivation?: UserActivationState; scheduler?: PickerScheduler; focusFallbackGraceMs?: number; /** @deprecated Use focusFallbackGraceMs. */ cancelFallbackDelayMs?: number; systemOpenPickerSupported?: boolean; systemSavePickerSupported?: boolean; observer?: BrowserFileObserver; }>; /** * Canonical cross-browser picker. select() must be called directly from the * input's labelled button/keyboard activation. */ export class NativeInputFilePicker implements DisposableFilePicker { readonly support; readonly #input: HTMLInputElement; readonly #captureFiles: BrowserFileVault["captureFiles"]; readonly #releaseFile: BrowserFileVault["release"]; readonly #resolveSelection: BrowserFilePolicyRegistry["resolveSelection"]; readonly #inputEvents: InputEventDependencies; readonly #windowEvents: WindowEventDependencies | undefined; readonly #userActivation: UserActivationState | undefined; readonly #scheduler: PickerScheduler; readonly #focusFallbackGraceMs: number; readonly #observer: BrowserFileObserver | undefined; #pending = false; #disposed = false; #abortPending: (() => void) | undefined; /** * Q-6.2-8. Once this engine has dispatched a native `cancel`, dismissal is * reported natively, so the focus heuristic would only turn a slow `change` * (a cloud provider still fetching the file) into a false dismissal. */ #nativeCancelObserved = false; constructor(options: NativeInputFilePickerOptions) { this.#input = options.input; this.#captureFiles = options.vault.captureFiles.bind(options.vault); this.#releaseFile = options.vault.release.bind(options.vault); this.#resolveSelection = options.policies.resolveSelection.bind(options.policies); const addInputEvent = options.input.addEventListener; const removeInputEvent = options.input.removeEventListener; const getInputAttribute = options.input.getAttribute; const click = options.input.click; if ( typeof addInputEvent !== "function" || typeof removeInputEvent !== "function" || typeof getInputAttribute !== "function" || typeof click !== "function" ) { throw new TypeError("Native file input API is invalid."); } this.#inputEvents = Object.freeze({ add: addInputEvent.bind(options.input), remove: removeInputEvent.bind(options.input), getAttribute: getInputAttribute.bind(options.input), // The baseline path intentionally uses click(). // showPicker() exists in multiple engines but is not a portable // automation/event-interception contract. Enhanced native picking is a // separate capability owned by EnhancedFilePicker. activate: click.bind(options.input), }); const windowHost = options.window ?? globalThis.window; if (windowHost) { const addWindowEvent = windowHost.addEventListener; const removeWindowEvent = windowHost.removeEventListener; if ( typeof addWindowEvent !== "function" || typeof removeWindowEvent !== "function" ) { throw new TypeError("Native picker window API is invalid."); } this.#windowEvents = Object.freeze({ add: addWindowEvent.bind(windowHost), remove: removeWindowEvent.bind(windowHost), }); } else { this.#windowEvents = undefined; } this.#userActivation = options.userActivation ?? globalThis.navigator?.userActivation; const scheduler = options.scheduler ?? ({ setTimeout: (callback: () => void, delayMs: number) => globalThis.setTimeout(callback, delayMs), clearTimeout: (handle: unknown) => globalThis.clearTimeout( handle as ReturnType, ), } satisfies PickerScheduler); if ( typeof scheduler.setTimeout !== "function" || typeof scheduler.clearTimeout !== "function" ) { throw new TypeError("Native picker scheduler is invalid."); } this.#scheduler = Object.freeze({ setTimeout: scheduler.setTimeout.bind(scheduler), clearTimeout: scheduler.clearTimeout.bind(scheduler), }); if ( options.focusFallbackGraceMs !== undefined && options.cancelFallbackDelayMs !== undefined && options.focusFallbackGraceMs !== options.cancelFallbackDelayMs ) { throw new TypeError("Native picker focus grace is ambiguous."); } this.#focusFallbackGraceMs = options.focusFallbackGraceMs ?? options.cancelFallbackDelayMs ?? DEFAULT_NATIVE_PICKER_FOCUS_GRACE_MS; this.#observer = options.observer; this.support = Object.freeze({ nativeInput: true as const, systemOpenPicker: options.systemOpenPickerSupported ?? false, systemSavePicker: options.systemSavePickerSupported ?? false, }); if ( !Number.isSafeInteger(this.#focusFallbackGraceMs) || this.#focusFallbackGraceMs < 0 ) { throw new TypeError("Native picker cancel fallback delay is invalid."); } } async select(input: { policy: FilePolicyReference; limits?: FileSelectionLimitReduction; signal?: AbortSignal; }): Promise> { let request: SelectionRequestSnapshot; try { request = snapshotSelectionRequest(input); } catch { return observeSelection( this.#observer, browserDataFailure("INVALID_INPUT", "FILE_SELECT"), ); } if (this.#disposed) { return observeSelection( this.#observer, browserDataFailure("UNAVAILABLE", "FILE_SELECT"), ); } const cancelled = abortedResult(request.signal, "FILE_SELECT"); if (cancelled) return observeSelection(this.#observer, cancelled); const resolvedPolicy = this.#resolveSelection( request.policy, request.limits, ); if (!resolvedPolicy.ok) { return observeSelection(this.#observer, resolvedPolicy); } const policy = resolvedPolicy.value; if ( !isUsableFileInput( this.#input, this.#inputEvents.getAttribute, ) ) { return observeSelection( this.#observer, browserDataFailure("INVALID_INPUT", "FILE_SELECT"), ); } if (this.#pending) { return observeSelection( this.#observer, browserDataFailure("BLOCKED", "FILE_SELECT"), ); } if (this.#userActivation && !this.#userActivation.isActive) { return observeSelection( this.#observer, browserDataFailure("PERMISSION_DENIED", "FILE_SELECT"), ); } this.#pending = true; try { const result = await new Promise>( (resolve) => { let settled = false; let focusTimer: unknown; const signal = request.signal; // The kernel operation owns the caller signal listener. const operation = createAbortableOperation({ signal }); const finish = ( outcome: BrowserDataResult, ): void => { if (settled) return; settled = true; this.#inputEvents.remove("change", onChange); this.#inputEvents.remove("cancel", onCancel); operation.close(); this.#windowEvents?.remove("focus", onWindowFocus); if (focusTimer !== undefined) { this.#scheduler.clearTimeout(focusTimer); } if (this.#abortPending === abortPending) { this.#abortPending = undefined; } resolve(outcome); }; const dismiss = (): void => finish( browserDataSuccess( Object.freeze({ kind: "DISMISSED" as const }), ), ); const onChange = (): void => { const files = this.#input.files; if (!files || files.length === 0) { dismiss(); return; } const captured = this.#captureFiles( files, policy, "NATIVE_INPUT", ); finish( captured.ok ? browserDataSuccess( Object.freeze({ kind: "SELECTED" as const, files: captured.value, }), ) : captured, ); }; const onCancel = (): void => { this.#nativeCancelObserved = true; dismiss(); }; const abortPending = (): void => finish(browserDataFailure("ABORTED", "FILE_SELECT")); const onWindowFocus = (): void => { if (settled || focusTimer !== undefined) return; focusTimer = this.#scheduler.setTimeout( () => { focusTimer = undefined; if (settled) return; // Some engines expose FileList before dispatching change. // Prefer the selected files over a synthetic dismissal. if ((this.#input.files?.length ?? 0) > 0) { onChange(); return; } dismiss(); }, this.#focusFallbackGraceMs, ); }; this.#inputEvents.add("change", onChange, { once: true }); this.#inputEvents.add("cancel", onCancel, { once: true }); // Settles only when the operation ends; after `finish` this is a no-op. void operation.race(new Promise(() => {})).then(abortPending); if (!this.#nativeCancelObserved) { this.#windowEvents?.add("focus", onWindowFocus); } this.#abortPending = abortPending; try { this.#input.accept = pickerAcceptValue(policy); this.#input.multiple = policy.multiple; // Allows the same file to produce a new change event. this.#input.value = ""; this.#inputEvents.activate(); } catch (error) { finish(mapBrowserDataException(error, "FILE_SELECT")); } }, ); return observeSelection(this.#observer, result); } catch (error) { return observeSelection( this.#observer, mapBrowserDataException(error, "FILE_SELECT"), ); } finally { this.#pending = false; } } release(ref: LocalFileRef): void { this.#releaseFile(ref); } dispose(): void { if (this.#disposed) return; this.#disposed = true; this.#abortPending?.(); try { this.#input.value = ""; } catch { // Some test doubles or constrained DOM hosts expose a readonly value. } } } export type SystemOpenPickerAcceptType = Readonly<{ description?: string; accept: Readonly>; }>; export type SystemOpenPickerOptions = Readonly<{ multiple: boolean; excludeAcceptAllOption: boolean; types: readonly SystemOpenPickerAcceptType[]; }>; export type SystemOpenPicker = ( options: SystemOpenPickerOptions, ) => Promise; export type EnhancedFilePickerOptions = Readonly<{ showOpenFilePicker: SystemOpenPicker; vault: BrowserFileVault; policies: BrowserFilePolicyRegistry; userActivation?: UserActivationState; systemSavePickerSupported?: boolean; observer?: BrowserFileObserver; }>; /** * Progressive enhancement. Failure never opens the native fallback in the * same activation; presentation may offer a baseline button for the next * explicit user action. */ export class EnhancedFilePicker implements DisposableFilePicker { readonly support; readonly #showOpenFilePicker: SystemOpenPicker; readonly #captureHandles: BrowserFileVault["captureHandles"]; readonly #releaseFile: BrowserFileVault["release"]; readonly #resolveSelection: BrowserFilePolicyRegistry["resolveSelection"]; readonly #userActivation: UserActivationState | undefined; readonly #observer: BrowserFileObserver | undefined; #pending = false; #disposed = false; #abortPending: (() => void) | undefined; constructor(options: EnhancedFilePickerOptions) { if (typeof options.showOpenFilePicker !== "function") { throw new TypeError("Enhanced file picker API is invalid."); } // Bound to undefined, not to options: `window.showOpenFilePicker` throws // "Illegal invocation" for any other receiver, and Web IDL maps an // undefined receiver to the global object. this.#showOpenFilePicker = options.showOpenFilePicker.bind(undefined); this.#captureHandles = options.vault.captureHandles.bind(options.vault); this.#releaseFile = options.vault.release.bind(options.vault); this.#resolveSelection = options.policies.resolveSelection.bind(options.policies); this.#userActivation = options.userActivation ?? globalThis.navigator?.userActivation; this.#observer = options.observer; this.support = Object.freeze({ nativeInput: true as const, systemOpenPicker: true, systemSavePicker: options.systemSavePickerSupported ?? false, }); } async select(input: { policy: FilePolicyReference; limits?: FileSelectionLimitReduction; signal?: AbortSignal; }): Promise> { let request: SelectionRequestSnapshot; try { request = snapshotSelectionRequest(input); } catch { return observeSelection( this.#observer, browserDataFailure("INVALID_INPUT", "FILE_SELECT"), ); } if (this.#disposed) { return observeSelection( this.#observer, browserDataFailure("UNAVAILABLE", "FILE_SELECT"), ); } const cancelled = abortedResult(request.signal, "FILE_SELECT"); if (cancelled) return observeSelection(this.#observer, cancelled); const resolvedPolicy = this.#resolveSelection( request.policy, request.limits, ); if (!resolvedPolicy.ok) { return observeSelection(this.#observer, resolvedPolicy); } const policy = resolvedPolicy.value; if (this.#pending) { return observeSelection( this.#observer, browserDataFailure("BLOCKED", "FILE_SELECT"), ); } if (this.#userActivation && !this.#userActivation.isActive) { return observeSelection( this.#observer, browserDataFailure("PERMISSION_DENIED", "FILE_SELECT"), ); } this.#pending = true; try { // This call intentionally happens before the first await. const picker = this.#showOpenFilePicker( systemPickerOptions(policy), ); const handles = await this.#awaitPickerOrDispose( picker, request.signal, ); const aborted = abortedResult(request.signal, "FILE_SELECT"); if (aborted) return observeSelection(this.#observer, aborted); if (handles.length === 0) { return observeSelection( this.#observer, browserDataSuccess( Object.freeze({ kind: "DISMISSED" as const }), ), ); } const captured = await this.#captureHandles( handles, policy, request.signal ?? new AbortController().signal, ); return observeSelection( this.#observer, captured.ok ? browserDataSuccess( Object.freeze({ kind: "SELECTED" as const, files: captured.value, }), ) : captured, ); } catch (error) { if (error instanceof PickerDisposedError) { return observeSelection( this.#observer, browserDataFailure("ABORTED", "FILE_SELECT"), ); } if (error instanceof DOMException && error.name === "AbortError") { const aborted = abortedResult(input.signal, "FILE_SELECT"); if (aborted) return observeSelection(this.#observer, aborted); return observeSelection( this.#observer, browserDataSuccess( Object.freeze({ kind: "DISMISSED" as const }), ), ); } return observeSelection( this.#observer, mapBrowserDataException(error, "FILE_SELECT"), ); } finally { this.#pending = false; } } release(ref: LocalFileRef): void { this.#releaseFile(ref); } dispose(): void { if (this.#disposed) return; this.#disposed = true; this.#abortPending?.(); } #awaitPickerOrDispose( picker: Promise, signal?: AbortSignal, ): Promise { if (signal?.aborted) { return Promise.reject( new DOMException("Picker aborted", "AbortError"), ); } const operation = createAbortableOperation({ signal }); const abortPending = (): void => operation.close(); this.#abortPending = abortPending; return operation.race(picker).then((outcome) => { if (this.#abortPending === abortPending) { this.#abortPending = undefined; } operation.close(); if (outcome.kind === "VALUE") return outcome.value; throw outcome.kind === "REJECTED" ? outcome.reason : outcome.terminal === "CALLER_ABORT" ? new DOMException("Picker aborted", "AbortError") : new PickerDisposedError(); }); } } /** One observation per terminal selection result, shared by both pickers. */ function observeSelection( observer: BrowserFileObserver | undefined, result: BrowserDataResult, ): BrowserDataResult { if (!result.ok) { observeBrowserFile(observer, { operation: "FILE_SELECT", outcome: "FAILED", failureCode: result.error.code, }); } else if (result.value.kind === "DISMISSED") { observeBrowserFile(observer, { operation: "FILE_SELECT", outcome: "DISMISSED", }); } else { const bytes = result.value.files.reduce( (total, file) => total + file.sizeBytes, 0, ); observeBrowserFile(observer, { operation: "FILE_SELECT", outcome: "SUCCESS", byteBucket: byteBucket(bytes), }); } return result; } function pickerAcceptValue( policy: RegisteredFileSelectionPolicy, ): string { return policy.accept .flatMap((rule) => [rule.mediaType, ...rule.extensions]) .join(","); } function systemPickerOptions( policy: RegisteredFileSelectionPolicy, ): SystemOpenPickerOptions { const types = policy.accept.map((rule) => Object.freeze({ accept: Object.freeze({ [rule.mediaType]: Object.freeze([...rule.extensions]), }), }), ); return Object.freeze({ multiple: policy.multiple, excludeAcceptAllOption: types.length > 0, types: Object.freeze(types), }); } type SelectionRequestSnapshot = Readonly<{ policy: FilePolicyReference; limits?: FileSelectionLimitReduction; signal?: AbortSignal; }>; function snapshotSelectionRequest(input: { policy: FilePolicyReference; limits?: FileSelectionLimitReduction; signal?: AbortSignal; }): SelectionRequestSnapshot { const policy = input.policy; const limits = input.limits; const signal = input.signal; return Object.freeze({ policy, ...(limits ? { limits: Object.freeze({ ...(limits.maxCount !== undefined ? { maxCount: limits.maxCount } : {}), ...(limits.maxFileBytes !== undefined ? { maxFileBytes: limits.maxFileBytes } : {}), ...(limits.maxTotalBytes !== undefined ? { maxTotalBytes: limits.maxTotalBytes } : {}), }), } : {}), ...(signal ? { signal } : {}), }); } function isUsableFileInput( input: HTMLInputElement, getAttribute: (name: string) => string | null, ): boolean { if (input.type !== "file" || !input.isConnected) return false; if ((input.labels?.length ?? 0) > 0) return true; return ( (getAttribute("aria-label")?.trim().length ?? 0) > 0 || (getAttribute("aria-labelledby")?.trim().length ?? 0) > 0 ); } class PickerDisposedError extends Error { constructor() { super("Picker runtime disposed"); this.name = "PickerDisposedError"; } }