foldkit-primitives 0.8.0 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +32 -2
- package/dist/device/index.d.mts +66 -33
- package/dist/device/index.d.mts.map +1 -1
- package/dist/device/index.mjs +34 -34
- package/dist/device/index.mjs.map +1 -1
- package/dist/dom/index.d.mts +78 -18
- package/dist/dom/index.d.mts.map +1 -1
- package/dist/dom/index.mjs +56 -22
- package/dist/dom/index.mjs.map +1 -1
- package/dist/{editable-text-BbsPOATY.d.mts → editable-text-Dvm-Fuqs.d.mts} +65 -3
- package/dist/editable-text-Dvm-Fuqs.d.mts.map +1 -0
- package/dist/events/index.d.mts +52 -31
- package/dist/events/index.d.mts.map +1 -1
- package/dist/events/index.mjs +40 -28
- package/dist/events/index.mjs.map +1 -1
- package/dist/{follow-tab-stop-BDxyoUPQ.mjs → follow-tab-stop-Ci1tqAIW.mjs} +63 -61
- package/dist/follow-tab-stop-Ci1tqAIW.mjs.map +1 -0
- package/dist/{index-Cppf-lBx.d.mts → index-BC8kcar9.d.mts} +35 -16
- package/dist/index-BC8kcar9.d.mts.map +1 -0
- package/dist/index.d.mts +5 -5
- package/dist/index.mjs +5 -5
- package/dist/{input-modality-m6v7__Xs.mjs → input-modality-BXD383jg.mjs} +9 -9
- package/dist/input-modality-BXD383jg.mjs.map +1 -0
- package/dist/{input-modality-DGOhAknO.d.mts → input-modality-BY-bSrEc.d.mts} +9 -2
- package/dist/input-modality-BY-bSrEc.d.mts.map +1 -0
- package/dist/interaction/index.d.mts +118 -118
- package/dist/interaction/index.d.mts.map +1 -1
- package/dist/interaction/index.mjs +3 -3
- package/dist/interaction/index.mjs.map +1 -1
- package/dist/media/index.d.mts +24 -3
- package/dist/media/index.d.mts.map +1 -1
- package/dist/media/index.mjs +23 -13
- package/dist/media/index.mjs.map +1 -1
- package/dist/motion/index.d.mts +1 -1
- package/dist/motion/index.mjs +1 -2
- package/dist/{motion-DGGBZ0wt.mjs → motion-DmFDppRn.mjs} +20 -20
- package/dist/{motion-DGGBZ0wt.mjs.map → motion-DmFDppRn.mjs.map} +1 -1
- package/dist/net/index.d.mts +57 -19
- package/dist/net/index.d.mts.map +1 -1
- package/dist/net/index.mjs +31 -31
- package/dist/net/index.mjs.map +1 -1
- package/dist/observers/index.d.mts +25 -0
- package/dist/observers/index.d.mts.map +1 -1
- package/dist/observers/index.mjs +22 -22
- package/dist/observers/index.mjs.map +1 -1
- package/dist/state/index.d.mts +98 -44
- package/dist/state/index.d.mts.map +1 -1
- package/dist/state/index.mjs +39 -39
- package/dist/state/index.mjs.map +1 -1
- package/dist/time/index.d.mts +35 -5
- package/dist/time/index.d.mts.map +1 -1
- package/dist/time/index.mjs +20 -20
- package/dist/time/index.mjs.map +1 -1
- package/package.json +14 -14
- package/dist/editable-text-BbsPOATY.d.mts.map +0 -1
- package/dist/follow-tab-stop-BDxyoUPQ.mjs.map +0 -1
- package/dist/index-Cppf-lBx.d.mts.map +0 -1
- package/dist/input-modality-DGOhAknO.d.mts.map +0 -1
- package/dist/input-modality-m6v7__Xs.mjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["failMessage","failMessage","isDenied","failMessage"],"sources":["../../src/device/fullscreen.ts","../../src/device/geolocation.ts","../../src/device/media-devices.ts","../../src/device/media-stream.ts","../../src/device/permissions.ts"],"sourcesContent":["/**\n * Fullscreen as Commands plus an entry — not a bundle, because the document\n * owns the state: `document.fullscreenElement` is the fact, and the entry\n * reports it as `Changed`. Commands yield `Entered`/`Exited` on success and\n * `Failed` otherwise (rejected request, missing API), so `update` handles\n * both outcomes as Messages.\n */\nimport { Effect, Schema, Stream } from 'effect'\nimport type { Command } from 'foldkit/command'\nimport { defineMessageUnion } from 'foldkit/message'\n\nexport const FullscreenMessage = defineMessageUnion({\n Changed: { active: Schema.Boolean },\n Entered: {},\n Exited: {},\n Failed: { message: Schema.String },\n})\nexport type FullscreenMessage = typeof FullscreenMessage.Type\n\nconst failMessage = (error: unknown): string =>\n error instanceof Error ? error.message : String(error)\n\n/**\n * Requests fullscreen for an element. The capability is feature-checked on\n * the element itself (SVG and HTML elements both qualify), falling back to\n * the legacy `webkit` prefix; a platform with neither yields `Failed`\n * instead of throwing.\n */\nexport const enterFullscreen = (element: Element): Command<FullscreenMessage, never, never> => ({\n name: 'Fullscreen.enter',\n args: {},\n effect: Effect.matchEffect(\n Effect.tryPromise({\n try: () => {\n const requestable = element as unknown as {\n readonly requestFullscreen?: unknown\n readonly webkitRequestFullscreen?: unknown\n }\n const request = requestable.requestFullscreen ?? requestable.webkitRequestFullscreen\n if (typeof request !== 'function') {\n throw new Error('fullscreen is unavailable')\n }\n return (request as () => Promise<void>).call(element)\n },\n catch: (error: unknown) => error,\n }),\n {\n onFailure: error => Effect.succeed(FullscreenMessage.Failed({ message: failMessage(error) })),\n onSuccess: () => Effect.succeed(FullscreenMessage.Entered()),\n },\n ),\n})\n\n/** Leaves fullscreen, with the same legacy fallback. Without a document API it yields `Failed`, not a throw. */\nexport const exitFullscreen = (): Command<FullscreenMessage, never, never> => ({\n name: 'Fullscreen.exit',\n args: {},\n effect: Effect.matchEffect(\n Effect.tryPromise({\n try: () => {\n if (typeof document === 'undefined') {\n throw new Error('fullscreen is unavailable')\n }\n const api = document as unknown as {\n readonly exitFullscreen?: unknown\n readonly webkitExitFullscreen?: unknown\n }\n const exit = api.exitFullscreen ?? api.webkitExitFullscreen\n if (typeof exit !== 'function') {\n throw new Error('fullscreen is unavailable')\n }\n return (exit as () => Promise<void>).call(document)\n },\n catch: (error: unknown) => error,\n }),\n {\n onFailure: error => Effect.succeed(FullscreenMessage.Failed({ message: failMessage(error) })),\n onSuccess: () => Effect.succeed(FullscreenMessage.Exited()),\n },\n ),\n})\n\n/**\n * `Changed` whenever fullscreen state flips, starting with the current\n * answer. Without a document the stream is empty instead of throwing.\n */\nexport const fullscreenChanges = (): Stream.Stream<FullscreenMessage> => {\n if (typeof document === 'undefined' || typeof document.addEventListener !== 'function') {\n return Stream.empty\n }\n // Incomplete DOMs leave fullscreenElement undefined instead of null.\n const isActive = (): boolean =>\n document.fullscreenElement !== null && document.fullscreenElement !== undefined\n return Stream.concat(\n Stream.make(FullscreenMessage.Changed({ active: isActive() })),\n Stream.fromEventListener(document, 'fullscreenchange').pipe(\n Stream.map(() => FullscreenMessage.Changed({ active: isActive() })),\n ),\n )\n}\n","/**\n * Geolocation as a bundle: the device position in the Model, watched while\n * placed. Permission denial is its own status (actionable UI); transient\n * failures keep the last fix and note the error. No geolocation API yields\n * an empty stream instead of throwing.\n */\nimport { Effect, Queue, Schema, Stream } from 'effect'\nimport { defineMessageUnion } from 'foldkit/message'\nimport * as Subscription from 'foldkit/subscription'\nimport type * as Update from 'foldkit/update'\nimport { Bundle } from 'foldkit-bundle'\nimport { unlessSame } from '../internal.js'\n\nexport const Coordinates = Schema.Struct({\n latitude: Schema.Number,\n longitude: Schema.Number,\n accuracy: Schema.Number,\n})\nexport type Coordinates = typeof Coordinates.Type\n\nexport const GeolocationModel = Schema.Struct({\n status: Schema.Literals(['unknown', 'ready', 'denied']),\n coords: Schema.NullOr(Coordinates),\n lastError: Schema.NullOr(Schema.String),\n})\nexport type GeolocationModel = typeof GeolocationModel.Type\n\nexport const GeolocationMessage = defineMessageUnion({\n Located: {\n latitude: Schema.Number,\n longitude: Schema.Number,\n accuracy: Schema.Number,\n },\n Denied: {},\n Failed: { message: Schema.String },\n})\nexport type GeolocationMessage = typeof GeolocationMessage.Type\n\ntype PositionCallback = (position: {\n readonly coords: {\n readonly latitude: number\n readonly longitude: number\n readonly accuracy: number\n }\n}) => void\ntype ErrorCallback = (error: { readonly code: number; readonly message: string }) => void\n\nconst watchStream = (): Stream.Stream<GeolocationMessage> => {\n if (\n typeof navigator === 'undefined' ||\n typeof navigator.geolocation?.watchPosition !== 'function'\n ) {\n return Stream.empty\n }\n const geolocation = navigator.geolocation\n return Stream.unwrap(\n Effect.gen(function* () {\n const queue = yield* Queue.unbounded<GeolocationMessage>()\n const onLocated: PositionCallback = position => {\n Effect.runFork(\n Queue.offer(\n queue,\n GeolocationMessage.Located({\n latitude: position.coords.latitude,\n longitude: position.coords.longitude,\n accuracy: position.coords.accuracy,\n }),\n ),\n )\n }\n const onError: ErrorCallback = error => {\n Effect.runFork(\n Queue.offer(\n queue,\n error.code === 1\n ? GeolocationMessage.Denied()\n : GeolocationMessage.Failed({ message: error.message }),\n ),\n )\n }\n const watchId = geolocation.watchPosition(onLocated, onError)\n yield* Effect.addFinalizer(() => Effect.sync(() => geolocation.clearWatch(watchId)))\n return Stream.fromQueue(queue)\n }),\n )\n}\n\nexport const Geolocation = Bundle.make<\n 'Geolocation',\n GeolocationModel,\n GeolocationMessage,\n void,\n never,\n never,\n never,\n void,\n {},\n {}\n>('Geolocation', {\n Model: GeolocationModel,\n Message: GeolocationMessage,\n init: () => ({ model: { status: 'unknown', coords: null, lastError: null } }),\n update: (model, message) =>\n GeolocationMessage.match<\n Update.ReturnWithOutMessage<GeolocationModel, GeolocationMessage, never>\n >(message, {\n // A watch repeats a fix that has not moved.\n Located: ({ latitude, longitude, accuracy }) =>\n model.status === 'ready' &&\n model.coords !== null &&\n model.coords.latitude === latitude &&\n model.coords.longitude === longitude &&\n model.coords.accuracy === accuracy\n ? { model }\n : {\n model: {\n ...model,\n status: 'ready' as const,\n coords: { latitude, longitude, accuracy },\n },\n },\n Denied: () => ({ model: unlessSame(model, { ...model, status: 'denied' }) }),\n Failed: ({ message }) => ({ model: unlessSame(model, { ...model, lastError: message }) }),\n }),\n subscriptions: (): Subscription.Subscriptions<GeolocationModel, GeolocationMessage> =>\n Subscription.make<GeolocationModel, GeolocationMessage>()(() => ({\n watch: Subscription.persistent(watchStream()),\n })),\n})\n","/**\n * Media devices as a bundle factory: the enumerated device list in the\n * Model, scanned on placement and re-scanned on every `devicechange`.\n * Denial lands as `denied` while keeping the last list (actionable UI over\n * stale data, like Geolocation's last fix); any other failure keeps the\n * list and notes the error. No media-devices API yields an empty stream\n * and a `Failed` scan instead of throwing.\n */\nimport { Effect, Schema, Stream } from 'effect'\nimport { defineMessageUnion } from 'foldkit/message'\nimport * as Subscription from 'foldkit/subscription'\nimport type * as Update from 'foldkit/update'\nimport { Bundle } from 'foldkit-bundle'\nimport { unlessSame } from '../internal.js'\n\nexport const MediaDevice = Schema.Struct({\n deviceId: Schema.String,\n groupId: Schema.String,\n kind: Schema.Literals(['audioinput', 'audiooutput', 'videoinput']),\n label: Schema.String,\n})\nexport type MediaDevice = typeof MediaDevice.Type\n\nexport const MediaDevicesModel = Schema.Struct({\n status: Schema.Literals(['unknown', 'ready', 'denied']),\n devices: Schema.Array(MediaDevice),\n lastError: Schema.NullOr(Schema.String),\n})\nexport type MediaDevicesModel = typeof MediaDevicesModel.Type\n\nexport const MediaDevicesMessage = defineMessageUnion({\n Scan: {},\n DevicesChanged: {},\n Refreshed: { devices: Schema.Array(MediaDevice) },\n Denied: {},\n Failed: { message: Schema.String },\n})\nexport type MediaDevicesMessage = typeof MediaDevicesMessage.Type\n\nconst sameDevices = (a: ReadonlyArray<MediaDevice>, b: ReadonlyArray<MediaDevice>): boolean =>\n a.length === b.length &&\n a.every(\n (device, index) =>\n device.deviceId === b[index]!.deviceId &&\n device.groupId === b[index]!.groupId &&\n device.kind === b[index]!.kind &&\n device.label === b[index]!.label,\n )\n\n/** The slice of MediaDevices the bundle needs; satisfied by the platform object. */\nexport interface MediaDevicesHandle {\n enumerateDevices(): Promise<\n ReadonlyArray<{\n readonly deviceId: string\n readonly groupId: string\n readonly kind: string\n readonly label: string\n }>\n >\n addEventListener(type: string, listener: () => void): void\n removeEventListener(type: string, listener: () => void): void\n}\n\nconst failMessage = (error: unknown): string =>\n error instanceof Error ? error.message : String(error)\n\nconst isDenied = (error: unknown): boolean =>\n typeof (error as { readonly name?: unknown } | null)?.name === 'string' &&\n ['NotAllowedError', 'SecurityError'].includes((error as { readonly name: string }).name)\n\nexport const mediaDevices = <const Name extends string>(config: {\n readonly name: Name\n /** Read lazily so tests can substitute a double, like the SSE bundle. */\n readonly create?: ((navigator: Navigator) => MediaDevicesHandle | null) | undefined\n}) => {\n const handle = (): MediaDevicesHandle | null => {\n if (typeof navigator === 'undefined') return null\n if (config.create !== undefined) return config.create(navigator)\n const devices = navigator.mediaDevices as unknown as MediaDevicesHandle | undefined\n return devices ?? null\n }\n\n const scanEffect = Effect.matchEffect(\n Effect.tryPromise({\n try: async () => {\n const devices = handle()\n if (devices === null) throw new Error('media devices are unavailable')\n const listed = await devices.enumerateDevices()\n // The platform constrains kind to three values; anything else is a\n // boundary violation, so it fails the scan instead of entering the Model.\n return listed.map(item => {\n if (\n item.kind !== 'audioinput' &&\n item.kind !== 'audiooutput' &&\n item.kind !== 'videoinput'\n ) {\n throw new Error(`unknown device kind: ${item.kind}`)\n }\n // Guarded by the check above: only the three platform kinds reach here.\n return {\n deviceId: item.deviceId,\n groupId: item.groupId,\n kind: item.kind as MediaDevice['kind'],\n label: item.label,\n }\n })\n },\n catch: (error: unknown) => error,\n }),\n {\n onFailure: error =>\n Effect.succeed(\n isDenied(error)\n ? MediaDevicesMessage.Denied()\n : MediaDevicesMessage.Failed({ message: failMessage(error) }),\n ),\n onSuccess: devices =>\n Effect.succeed(MediaDevicesMessage.Refreshed({ devices: [...devices] })),\n },\n )\n\n const scan = () => ({ name: `${config.name}.scan`, effect: scanEffect })\n\n const changedStream = (): Stream.Stream<MediaDevicesMessage> => {\n const devices = handle()\n if (devices === null) return Stream.empty\n // The handle carries only the slice the bundle needs, not the full\n // EventTarget surface, so the listener attaches through a cast.\n return Stream.fromEventListener(devices as unknown as EventTarget, 'devicechange').pipe(\n Stream.map(() => MediaDevicesMessage.DevicesChanged()),\n )\n }\n\n return Bundle.make<Name, MediaDevicesModel, MediaDevicesMessage>(config.name, {\n Model: MediaDevicesModel,\n Message: MediaDevicesMessage,\n init: () => ({\n model: { status: 'unknown', devices: [], lastError: null },\n commands: [scan()],\n }),\n update: (model, message) =>\n MediaDevicesMessage.match<\n Update.ReturnWithOutMessage<MediaDevicesModel, MediaDevicesMessage, never>\n >(message, {\n Scan: () => ({ model, commands: [scan()] }),\n DevicesChanged: () => ({ model, commands: [scan()] }),\n // One plug-in fires several `devicechange`s, and each rescan finds the same list.\n Refreshed: ({ devices }) =>\n model.status === 'ready' && sameDevices(model.devices, devices)\n ? { model }\n : { model: { ...model, status: 'ready' as const, devices } },\n Denied: () => ({ model: unlessSame(model, { ...model, status: 'denied' }) }),\n Failed: ({ message }) => ({ model: unlessSame(model, { ...model, lastError: message }) }),\n }),\n subscriptions: (): Subscription.Subscriptions<MediaDevicesModel, MediaDevicesMessage> =>\n Subscription.make<MediaDevicesModel, MediaDevicesMessage>()(() => ({\n changes: Subscription.persistent(changedStream()),\n })),\n })\n}\n","/**\n * A camera/mic stream as a bundle factory: one live MediaStream held in a\n * Managed Resource while the Model asks for it. `Started` requests,\n * `Stopped` releases; denial parks at `denied` (actionable UI), any other\n * acquire failure parks at `idle` with the error noted — both clear\n * requirements, so a failing device never spins an acquire loop. Release\n * stops every track. No media-devices API fails the acquire instead of\n * throwing.\n */\nimport { Effect, Option, Schema } from 'effect'\nimport { defineMessageUnion } from 'foldkit/message'\nimport * as ManagedResource from 'foldkit/managedResource'\nimport type * as Update from 'foldkit/update'\nimport { Bundle } from 'foldkit-bundle'\nimport { unlessSame } from '../internal.js'\n\nexport const MediaStreamModel = Schema.Struct({\n status: Schema.Literals(['idle', 'requesting', 'live', 'denied']),\n lastError: Schema.NullOr(Schema.String),\n})\nexport type MediaStreamModel = typeof MediaStreamModel.Type\n\nexport const MediaStreamMessage = defineMessageUnion({\n Started: {},\n Stopped: {},\n Live: {},\n Ended: {},\n Denied: {},\n Failed: { message: Schema.String },\n})\nexport type MediaStreamMessage = typeof MediaStreamMessage.Type\n\n/** A single media track: stopped on release. */\nexport interface MediaTrackHandle {\n stop(): void\n}\n\n/** The live stream: its tracks stop on release. */\nexport interface MediaStreamHandle {\n getTracks(): ReadonlyArray<MediaTrackHandle>\n}\n\nexport interface MediaStreamConstraints {\n readonly audio: boolean\n readonly video: boolean\n}\n\n/** The live stream, for commands that attach it to an element. One assembly holds one. */\nexport const LiveStream = ManagedResource.tag<MediaStreamHandle>()('media-stream')\n\n/** The stream service a placed camera requires. */\nexport type LiveStreamService = ManagedResource.ServiceOf<typeof LiveStream>\n\ntype StreamResources = Readonly<{\n stream: ManagedResource.Entry<\n MediaStreamModel,\n MediaStreamMessage,\n Option.Option<MediaStreamConstraints>,\n MediaStreamHandle,\n LiveStreamService,\n () => MediaStreamMessage\n >\n}>\n\nconst failMessage = (error: unknown): string =>\n error instanceof Error ? error.message : String(error)\n\nconst isDenied = (error: unknown): boolean =>\n typeof (error as { readonly name?: unknown } | null)?.name === 'string' &&\n ['NotAllowedError', 'SecurityError'].includes((error as { readonly name: string }).name)\n\nexport const mediaStream = <const Name extends string>(config: {\n readonly name: Name\n /** Read lazily so tests can substitute a double, like the SSE bundle. */\n readonly request?:\n ((constraints: MediaStreamConstraints) => Promise<MediaStreamHandle>) | undefined\n}) => {\n const request = (constraints: MediaStreamConstraints): Promise<MediaStreamHandle> => {\n if (config.request !== undefined) return config.request(constraints)\n if (\n typeof navigator === 'undefined' ||\n typeof navigator.mediaDevices?.getUserMedia !== 'function'\n ) {\n return Promise.reject(new Error('media devices are unavailable'))\n }\n return navigator.mediaDevices.getUserMedia(constraints)\n }\n\n return Bundle.make(config.name, {\n Model: MediaStreamModel,\n Message: MediaStreamMessage,\n args: Schema.Struct({ audio: Schema.Boolean, video: Schema.Boolean }),\n init: () => ({ model: { status: 'idle' as const, lastError: null } }),\n update: (model, message) =>\n MediaStreamMessage.match<\n Update.ReturnWithOutMessage<MediaStreamModel, MediaStreamMessage, never>\n >(message, {\n // Starting a live stream would wait at `requesting` for an acquire\n // that never comes: the requirements are the same.\n Started: () =>\n model.status === 'requesting' || model.status === 'live'\n ? { model }\n : { model: { ...model, status: 'requesting' as const } },\n Stopped: () => ({ model: unlessSame(model, { ...model, status: 'idle' }) }),\n Live: () => ({ model: unlessSame(model, { ...model, status: 'live', lastError: null }) }),\n // Stopping releases the stream, whose release reports it ended.\n Ended: () => ({ model: unlessSame(model, { ...model, status: 'idle' }) }),\n Denied: () => ({ model: unlessSame(model, { ...model, status: 'denied' }) }),\n Failed: ({ message }) => ({\n model: unlessSame(model, { ...model, status: 'idle', lastError: message }),\n }),\n }),\n resources: args =>\n ManagedResource.make<MediaStreamModel, MediaStreamMessage>()(entry => ({\n stream: entry(\n Schema.Option(Schema.Struct({ audio: Schema.Boolean, video: Schema.Boolean })),\n {\n resource: LiveStream,\n modelToMaybeRequirements: model =>\n model.status === 'requesting' || model.status === 'live'\n ? Option.some({ audio: args.audio, video: args.video })\n : Option.none(),\n acquire: (constraints: MediaStreamConstraints) =>\n Effect.tryPromise({\n try: () => request(constraints),\n catch: (error: unknown) => error,\n }),\n onAcquired: () => MediaStreamMessage.Live(),\n onReleased: () => MediaStreamMessage.Ended(),\n onAcquireError: error =>\n isDenied(error)\n ? MediaStreamMessage.Denied()\n : MediaStreamMessage.Failed({ message: failMessage(error) }),\n release: stream =>\n Effect.sync(() => {\n for (const track of stream.getTracks()) track.stop()\n }),\n },\n ),\n })),\n })\n}\n","/**\n * Permission states as a bundle factory: queried on placement, kept current\n * by each status object's `onchange`. A resource holds the status objects\n * (they cannot live in the Model); its queue feeds the subscription, and\n * release detaches every handler. An unknown permission name fails the\n * acquire; an unknown state string fails it too — both become `Failed`,\n * never Model facts.\n */\nimport { Effect, Option, Queue, Schema, Stream } from 'effect'\nimport { defineMessageUnion } from 'foldkit/message'\nimport * as ManagedResource from 'foldkit/managedResource'\nimport * as Subscription from 'foldkit/subscription'\nimport type * as Update from 'foldkit/update'\nimport { Bundle } from 'foldkit-bundle'\nimport { unlessSame } from '../internal.js'\n\nexport const PermissionState = Schema.Literals(['granted', 'denied', 'prompt'])\nexport type PermissionState = typeof PermissionState.Type\n\nexport const PermissionsModel = Schema.Struct({\n states: Schema.Record(Schema.String, PermissionState),\n lastError: Schema.NullOr(Schema.String),\n})\nexport type PermissionsModel = typeof PermissionsModel.Type\n\nexport const PermissionsMessage = defineMessageUnion({\n Snapshot: { states: Schema.Record(Schema.String, PermissionState) },\n Changed: { name: Schema.String, state: PermissionState },\n Cleared: {},\n Failed: { message: Schema.String },\n})\nexport type PermissionsMessage = typeof PermissionsMessage.Type\n\n/** A queried permission status; `onchange` fires while watched. */\nexport interface PermissionStatusHandle {\n readonly state: string\n onchange: (() => void) | null\n}\n\n/** The slice of the Permissions API the bundle needs. */\nexport interface PermissionsHandle {\n query(descriptor: { readonly name: string }): Promise<PermissionStatusHandle>\n}\n\ninterface Acquired {\n readonly statuses: ReadonlyMap<string, PermissionStatusHandle>\n readonly snapshot: Readonly<Record<string, PermissionState>>\n readonly events: Queue.Queue<PermissionsMessage>\n}\n\n/** The watched statuses, for the changes subscription. One assembly holds one. */\nexport const Watch = ManagedResource.tag<Acquired>()('permissions')\n\n/** The watch service a placed Permissions bundle requires. */\nexport type WatchService = ManagedResource.ServiceOf<typeof Watch>\n\ntype WatchResources = Readonly<{\n watch: ManagedResource.Entry<\n PermissionsModel,\n PermissionsMessage,\n Option.Option<ReadonlyArray<string>>,\n Acquired,\n WatchService,\n (acquired: Acquired) => PermissionsMessage\n >\n}>\n\nconst failMessage = (error: unknown): string =>\n error instanceof Error ? error.message : String(error)\n\nconst readState = (state: string, name: string): PermissionState => {\n if (state !== 'granted' && state !== 'denied' && state !== 'prompt') {\n throw new Error(`unknown permission state for ${name}: ${state}`)\n }\n return state\n}\n\nexport const permissions = <const Name extends string>(config: {\n readonly name: Name\n /** Read lazily so tests can substitute a double, like the SSE bundle. */\n readonly create?: ((navigator: Navigator) => PermissionsHandle | null) | undefined\n}) => {\n const handle = (): PermissionsHandle | null => {\n if (typeof navigator === 'undefined') return null\n if (config.create !== undefined) return config.create(navigator)\n const api = navigator.permissions as unknown as PermissionsHandle | undefined\n return api ?? null\n }\n\n return Bundle.make<\n Name,\n PermissionsModel,\n PermissionsMessage,\n { readonly names: ReadonlyArray<string> },\n never,\n never,\n WatchService,\n void,\n WatchResources,\n {}\n >(config.name, {\n Model: PermissionsModel,\n Message: PermissionsMessage,\n args: Schema.Struct({ names: Schema.Array(Schema.String) }),\n init: () => ({ model: { states: {}, lastError: null } }),\n update: (model, message) =>\n PermissionsMessage.match<\n Update.ReturnWithOutMessage<PermissionsModel, PermissionsMessage, never>\n >(message, {\n Snapshot: ({ states }) => {\n const next = unlessSame(model.states, { ...states })\n return next === model.states ? { model } : { model: { ...model, states: next } }\n },\n Changed: ({ name, state }) =>\n Object.hasOwn(model.states, name) && model.states[name] === state\n ? { model }\n : { model: { ...model, states: { ...model.states, [name]: state } } },\n Cleared: () =>\n Object.keys(model.states).length === 0 ? { model } : { model: { ...model, states: {} } },\n Failed: ({ message }) => ({ model: unlessSame(model, { ...model, lastError: message }) }),\n }),\n resources: args => {\n const names = Option.some([...new Set(args.names)])\n return ManagedResource.make<PermissionsModel, PermissionsMessage>()(entry => ({\n watch: entry(Schema.Option(Schema.Array(Schema.String)), {\n resource: Watch,\n modelToMaybeRequirements: () => names,\n acquire: (names: ReadonlyArray<string>) =>\n Effect.gen(function* () {\n const api = handle()\n if (api === null) throw new Error('permissions are unavailable')\n const events = yield* Queue.unbounded<PermissionsMessage>()\n const statuses = new Map<string, PermissionStatusHandle>()\n // Offers run in arrival order; see the WebSocket bundle.\n let tail: Promise<void> = Promise.resolve()\n const offer = (message: PermissionsMessage) => {\n const run = () =>\n Effect.runPromise(Queue.offer(events, message)).then(\n () => undefined,\n () => undefined,\n )\n tail = tail.then(run, run)\n }\n // Two phases: query and validate everything first, so a later\n // name failing cannot abandon handlers attached to earlier ones.\n const queried: Array<readonly [string, PermissionStatusHandle, PermissionState]> = []\n for (const name of names) {\n const status = yield* Effect.tryPromise({\n try: () => api.query({ name }),\n catch: (error: unknown) => error,\n })\n queried.push([name, status, readState(status.state, name)] as const)\n }\n const snapshot: Record<string, PermissionState> = {}\n for (const [name, status, state] of queried) {\n status.onchange = () => {\n try {\n offer(\n PermissionsMessage.Changed({ name, state: readState(status.state, name) }),\n )\n } catch {\n // readState evaluates before offer runs, so a state the\n // schema rejects lands here instead of crashing the handler.\n offer(\n PermissionsMessage.Failed({\n message: `unknown permission state for ${name}`,\n }),\n )\n }\n }\n statuses.set(name, status)\n snapshot[name] = state\n }\n return { statuses, snapshot, events }\n }),\n // The snapshot is captured during acquire, so onAcquired cannot\n // throw re-reading a state that changed mid-acquire.\n onAcquired: ({ snapshot }) => PermissionsMessage.Snapshot({ states: { ...snapshot } }),\n onReleased: () => PermissionsMessage.Cleared(),\n onAcquireError: error => PermissionsMessage.Failed({ message: failMessage(error) }),\n release: ({ statuses, events }) =>\n Effect.asVoid(\n Effect.andThen(\n Effect.sync(() => {\n for (const status of statuses.values()) status.onchange = null\n }),\n Queue.shutdown(events),\n ),\n ),\n }),\n }))\n },\n subscriptions: (): Subscription.Subscriptions<\n PermissionsModel,\n PermissionsMessage,\n WatchService\n > =>\n Subscription.make<PermissionsModel, PermissionsMessage, WatchService>()(() => ({\n // No model gate: the queue outlives every state change, and release\n // ends the stream through teardown, not through dependencies.\n changes: Subscription.persistent(\n Stream.unwrap(\n Effect.matchEffect(Watch.get, {\n // Released between placement and attach: end quietly.\n onFailure: () => Effect.succeed(Stream.empty),\n onSuccess: ({ events }) => Effect.succeed(Stream.fromQueue(events)),\n }),\n ),\n ),\n })),\n })\n}\n"],"mappings":";;;;;;;;;;;;;;AAWA,MAAa,oBAAoB,mBAAmB;CAClD,SAAS,EAAE,QAAQ,OAAO,QAAQ;CAClC,SAAS,CAAC;CACV,QAAQ,CAAC;CACT,QAAQ,EAAE,SAAS,OAAO,OAAO;AACnC,CAAC;AAGD,MAAMA,iBAAe,UACnB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;;;;;;;AAQvD,MAAa,mBAAmB,aAAgE;CAC9F,MAAM;CACN,MAAM,CAAC;CACP,QAAQ,OAAO,YACb,OAAO,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;KACnB;KACA,OAAO;MAAE;MAAU;MAAU;KAAO;IACtC,CAAC;IAGH,aAAa,EAAE,eAAe,mBAAmB,SAAS,EAAE,QAAQ,EAAE,GAAG,SAAS,EAAE,CAAC;IACrF,kBAAkB,mBAAmB,QAAQ;IAC7C,iBAAgB,UAAS,mBAAmB,OAAO,EAAE,SAAS,YAAY,KAAK,EAAE,CAAC;IAClF,UAAU,EAAE,UAAU,aACpB,OAAO,OACL,OAAO,QACL,OAAO,WAAW;KAChB,KAAK,MAAM,UAAU,SAAS,OAAO,GAAG,OAAO,WAAW;IAC5D,CAAC,GACD,MAAM,SAAS,MAAM,CACvB,CACF;GACJ,CAAC,EACH,EAAE;EACJ;EACA,qBAKE,aAAa,KAAyD,CAAC,QAAQ,EAG7E,SAAS,aAAa,WACpB,OAAO,OACL,OAAO,YAAY,MAAM,KAAK;GAE5B,iBAAiB,OAAO,QAAQ,OAAO,KAAK;GAC5C,YAAY,EAAE,aAAa,OAAO,QAAQ,OAAO,UAAU,MAAM,CAAC;EACpE,CAAC,CACH,CACF,EACF,EAAE;CACN,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["failMessage","failMessage","isDenied","failMessage"],"sources":["../../src/device/fullscreen.ts","../../src/device/geolocation.ts","../../src/device/media-devices.ts","../../src/device/media-stream.ts","../../src/device/permissions.ts"],"sourcesContent":["/**\n * Fullscreen as Commands plus an entry — not a bundle, because the document\n * owns the state: `document.fullscreenElement` is the fact, and the entry\n * reports it as `Changed`. Commands yield `Entered`/`Exited` on success and\n * `Failed` otherwise (rejected request, missing API), so `update` handles\n * both outcomes as Messages.\n */\nimport { Effect, Schema, Stream } from 'effect'\nimport type { Command } from 'foldkit/command'\nimport { defineMessageUnion } from 'foldkit/message'\n\nexport const FullscreenMessage = defineMessageUnion({\n Changed: { active: Schema.Boolean },\n Entered: {},\n Exited: {},\n Failed: { message: Schema.String },\n})\nexport type FullscreenMessage = typeof FullscreenMessage.Type\n\nconst failMessage = (error: unknown): string =>\n error instanceof Error ? error.message : String(error)\n\n/**\n * Requests fullscreen for an element. The capability is feature-checked on\n * the element itself (SVG and HTML elements both qualify), falling back to\n * the legacy `webkit` prefix; a platform with neither yields `Failed`\n * instead of throwing.\n */\nexport const enterFullscreen = (element: Element): Command<FullscreenMessage, never, never> => ({\n name: 'Fullscreen.enter',\n args: {},\n effect: Effect.matchEffect(\n Effect.tryPromise({\n try: () => {\n const requestable = element as unknown as {\n readonly requestFullscreen?: unknown\n readonly webkitRequestFullscreen?: unknown\n }\n const request = requestable.requestFullscreen ?? requestable.webkitRequestFullscreen\n if (typeof request !== 'function') {\n throw new Error('fullscreen is unavailable')\n }\n return (request as () => Promise<void>).call(element)\n },\n catch: (error: unknown) => error,\n }),\n {\n onFailure: error => Effect.succeed(FullscreenMessage.Failed({ message: failMessage(error) })),\n onSuccess: () => Effect.succeed(FullscreenMessage.Entered()),\n },\n ),\n})\n\n/** Leaves fullscreen, with the same legacy fallback. Without a document API it yields `Failed`, not a throw. */\nexport const exitFullscreen = (): Command<FullscreenMessage, never, never> => ({\n name: 'Fullscreen.exit',\n args: {},\n effect: Effect.matchEffect(\n Effect.tryPromise({\n try: () => {\n if (typeof document === 'undefined') {\n throw new Error('fullscreen is unavailable')\n }\n const api = document as unknown as {\n readonly exitFullscreen?: unknown\n readonly webkitExitFullscreen?: unknown\n }\n const exit = api.exitFullscreen ?? api.webkitExitFullscreen\n if (typeof exit !== 'function') {\n throw new Error('fullscreen is unavailable')\n }\n return (exit as () => Promise<void>).call(document)\n },\n catch: (error: unknown) => error,\n }),\n {\n onFailure: error => Effect.succeed(FullscreenMessage.Failed({ message: failMessage(error) })),\n onSuccess: () => Effect.succeed(FullscreenMessage.Exited()),\n },\n ),\n})\n\n/**\n * `Changed` whenever fullscreen state flips, starting with the current\n * answer. Without a document the stream is empty instead of throwing.\n */\nexport const fullscreenChanges = (): Stream.Stream<FullscreenMessage> => {\n if (typeof document === 'undefined' || typeof document.addEventListener !== 'function') {\n return Stream.empty\n }\n // Incomplete DOMs leave fullscreenElement undefined instead of null.\n const isActive = (): boolean =>\n document.fullscreenElement !== null && document.fullscreenElement !== undefined\n return Stream.concat(\n Stream.make(FullscreenMessage.Changed({ active: isActive() })),\n Stream.fromEventListener(document, 'fullscreenchange').pipe(\n Stream.map(() => FullscreenMessage.Changed({ active: isActive() })),\n ),\n )\n}\n","import { Effect, Queue, Schema, Stream } from 'effect'\nimport { defineMessageUnion } from 'foldkit/message'\nimport * as Subscription from 'foldkit/subscription'\nimport type * as Update from 'foldkit/update'\nimport { Bundle } from 'foldkit-bundle'\nimport { unlessSame } from '../internal.js'\n\nexport const Coordinates = Schema.Struct({\n latitude: Schema.Number,\n longitude: Schema.Number,\n accuracy: Schema.Number,\n})\nexport type Coordinates = typeof Coordinates.Type\n\nexport const GeolocationModel = Schema.Struct({\n status: Schema.Literals(['unknown', 'ready', 'denied']),\n coords: Schema.NullOr(Coordinates),\n lastError: Schema.NullOr(Schema.String),\n})\nexport type GeolocationModel = typeof GeolocationModel.Type\n\nexport const GeolocationMessage = defineMessageUnion({\n Located: {\n latitude: Schema.Number,\n longitude: Schema.Number,\n accuracy: Schema.Number,\n },\n Denied: {},\n Failed: { message: Schema.String },\n})\nexport type GeolocationMessage = typeof GeolocationMessage.Type\n\ntype PositionCallback = (position: {\n readonly coords: {\n readonly latitude: number\n readonly longitude: number\n readonly accuracy: number\n }\n}) => void\ntype ErrorCallback = (error: { readonly code: number; readonly message: string }) => void\n\nconst watchStream = (): Stream.Stream<GeolocationMessage> => {\n if (\n typeof navigator === 'undefined' ||\n typeof navigator.geolocation?.watchPosition !== 'function'\n ) {\n return Stream.empty\n }\n const geolocation = navigator.geolocation\n return Stream.unwrap(\n Effect.gen(function* () {\n const queue = yield* Queue.unbounded<GeolocationMessage>()\n const onLocated: PositionCallback = position => {\n Effect.runFork(\n Queue.offer(\n queue,\n GeolocationMessage.Located({\n latitude: position.coords.latitude,\n longitude: position.coords.longitude,\n accuracy: position.coords.accuracy,\n }),\n ),\n )\n }\n const onError: ErrorCallback = error => {\n Effect.runFork(\n Queue.offer(\n queue,\n error.code === 1\n ? GeolocationMessage.Denied()\n : GeolocationMessage.Failed({ message: error.message }),\n ),\n )\n }\n const watchId = geolocation.watchPosition(onLocated, onError)\n yield* Effect.addFinalizer(() => Effect.sync(() => geolocation.clearWatch(watchId)))\n return Stream.fromQueue(queue)\n }),\n )\n}\n\n/**\n * Geolocation as a bundle: the device position in the Model, watched while\n * placed. Permission denial is its own status (actionable UI); transient\n * failures keep the last fix and note the error. No geolocation API yields\n * an empty stream instead of throwing.\n */\nexport const Geolocation = Bundle.make<\n 'Geolocation',\n GeolocationModel,\n GeolocationMessage,\n void,\n never,\n never,\n never,\n void,\n {},\n {}\n>('Geolocation', {\n Model: GeolocationModel,\n Message: GeolocationMessage,\n init: () => ({ model: { status: 'unknown', coords: null, lastError: null } }),\n update: (model, message) =>\n GeolocationMessage.match<\n Update.ReturnWithOutMessage<GeolocationModel, GeolocationMessage, never>\n >(message, {\n // A watch repeats a fix that has not moved.\n Located: ({ latitude, longitude, accuracy }) =>\n model.status === 'ready' &&\n model.coords !== null &&\n model.coords.latitude === latitude &&\n model.coords.longitude === longitude &&\n model.coords.accuracy === accuracy\n ? { model }\n : {\n model: {\n ...model,\n status: 'ready' as const,\n coords: { latitude, longitude, accuracy },\n },\n },\n Denied: () => ({ model: unlessSame(model, { ...model, status: 'denied' }) }),\n Failed: ({ message }) => ({ model: unlessSame(model, { ...model, lastError: message }) }),\n }),\n subscriptions: (): Subscription.Subscriptions<GeolocationModel, GeolocationMessage> =>\n Subscription.make<GeolocationModel, GeolocationMessage>()(() => ({\n watch: Subscription.persistentEntry(watchStream()),\n })),\n})\n","import { Effect, Schema, Stream } from 'effect'\nimport { defineMessageUnion } from 'foldkit/message'\nimport * as Subscription from 'foldkit/subscription'\nimport type * as Update from 'foldkit/update'\nimport { Bundle } from 'foldkit-bundle'\nimport { unlessSame } from '../internal.js'\n\nexport const MediaDevice = Schema.Struct({\n deviceId: Schema.String,\n groupId: Schema.String,\n kind: Schema.Literals(['audioinput', 'audiooutput', 'videoinput']),\n label: Schema.String,\n})\nexport type MediaDevice = typeof MediaDevice.Type\n\nexport const MediaDevicesModel = Schema.Struct({\n status: Schema.Literals(['unknown', 'ready', 'denied']),\n devices: Schema.Array(MediaDevice),\n lastError: Schema.NullOr(Schema.String),\n})\nexport type MediaDevicesModel = typeof MediaDevicesModel.Type\n\nexport const MediaDevicesMessage = defineMessageUnion({\n Scan: {},\n DevicesChanged: {},\n Refreshed: { devices: Schema.Array(MediaDevice) },\n Denied: {},\n Failed: { message: Schema.String },\n})\nexport type MediaDevicesMessage = typeof MediaDevicesMessage.Type\n\nconst sameDevices = (a: ReadonlyArray<MediaDevice>, b: ReadonlyArray<MediaDevice>): boolean =>\n a.length === b.length &&\n a.every(\n (device, index) =>\n device.deviceId === b[index]!.deviceId &&\n device.groupId === b[index]!.groupId &&\n device.kind === b[index]!.kind &&\n device.label === b[index]!.label,\n )\n\n/** The slice of MediaDevices the bundle needs; satisfied by the platform object. */\nexport interface MediaDevicesHandle {\n enumerateDevices(): Promise<\n ReadonlyArray<{\n readonly deviceId: string\n readonly groupId: string\n readonly kind: string\n readonly label: string\n }>\n >\n addEventListener(type: string, listener: () => void): void\n removeEventListener(type: string, listener: () => void): void\n}\n\nconst failMessage = (error: unknown): string =>\n error instanceof Error ? error.message : String(error)\n\nconst isDenied = (error: unknown): boolean =>\n typeof (error as { readonly name?: unknown } | null)?.name === 'string' &&\n ['NotAllowedError', 'SecurityError'].includes((error as { readonly name: string }).name)\n\n/**\n * Media devices as a bundle factory: the enumerated device list in the\n * Model, scanned on placement and re-scanned on every `devicechange`.\n * Denial lands as `denied` while keeping the last list (actionable UI over\n * stale data, like Geolocation's last fix); any other failure keeps the\n * list and notes the error. No media-devices API yields an empty stream\n * and a `Failed` scan instead of throwing.\n */\nexport const mediaDevices = <const Name extends string>(config: {\n readonly name: Name\n /** Read lazily so tests can substitute a double, like the SSE bundle. */\n readonly create?: ((navigator: Navigator) => MediaDevicesHandle | null) | undefined\n}) => {\n const handle = (): MediaDevicesHandle | null => {\n if (typeof navigator === 'undefined') return null\n if (config.create !== undefined) return config.create(navigator)\n const devices = navigator.mediaDevices as unknown as MediaDevicesHandle | undefined\n return devices ?? null\n }\n\n const scanEffect = Effect.matchEffect(\n Effect.tryPromise({\n try: async () => {\n const devices = handle()\n if (devices === null) throw new Error('media devices are unavailable')\n const listed = await devices.enumerateDevices()\n // The platform constrains kind to three values; anything else is a\n // boundary violation, so it fails the scan instead of entering the Model.\n return listed.map(item => {\n if (\n item.kind !== 'audioinput' &&\n item.kind !== 'audiooutput' &&\n item.kind !== 'videoinput'\n ) {\n throw new Error(`unknown device kind: ${item.kind}`)\n }\n // Guarded by the check above: only the three platform kinds reach here.\n return {\n deviceId: item.deviceId,\n groupId: item.groupId,\n kind: item.kind as MediaDevice['kind'],\n label: item.label,\n }\n })\n },\n catch: (error: unknown) => error,\n }),\n {\n onFailure: error =>\n Effect.succeed(\n isDenied(error)\n ? MediaDevicesMessage.Denied()\n : MediaDevicesMessage.Failed({ message: failMessage(error) }),\n ),\n onSuccess: devices =>\n Effect.succeed(MediaDevicesMessage.Refreshed({ devices: [...devices] })),\n },\n )\n\n const scan = () => ({ name: `${config.name}.scan`, effect: scanEffect })\n\n const changedStream = (): Stream.Stream<MediaDevicesMessage> => {\n const devices = handle()\n if (devices === null) return Stream.empty\n // The handle carries only the slice the bundle needs, not the full\n // EventTarget surface, so the listener attaches through a cast.\n return Stream.fromEventListener(devices as unknown as EventTarget, 'devicechange').pipe(\n Stream.map(() => MediaDevicesMessage.DevicesChanged()),\n )\n }\n\n return Bundle.make<Name, MediaDevicesModel, MediaDevicesMessage>(config.name, {\n Model: MediaDevicesModel,\n Message: MediaDevicesMessage,\n init: () => ({\n model: { status: 'unknown', devices: [], lastError: null },\n commands: [scan()],\n }),\n update: (model, message) =>\n MediaDevicesMessage.match<\n Update.ReturnWithOutMessage<MediaDevicesModel, MediaDevicesMessage, never>\n >(message, {\n Scan: () => ({ model, commands: [scan()] }),\n DevicesChanged: () => ({ model, commands: [scan()] }),\n // One plug-in fires several `devicechange`s, and each rescan finds the same list.\n Refreshed: ({ devices }) =>\n model.status === 'ready' && sameDevices(model.devices, devices)\n ? { model }\n : { model: { ...model, status: 'ready' as const, devices } },\n Denied: () => ({ model: unlessSame(model, { ...model, status: 'denied' }) }),\n Failed: ({ message }) => ({ model: unlessSame(model, { ...model, lastError: message }) }),\n }),\n subscriptions: (): Subscription.Subscriptions<MediaDevicesModel, MediaDevicesMessage> =>\n Subscription.make<MediaDevicesModel, MediaDevicesMessage>()(() => ({\n changes: Subscription.persistentEntry(changedStream()),\n })),\n })\n}\n","import { Effect, Option, Schema } from 'effect'\nimport { defineMessageUnion } from 'foldkit/message'\nimport * as ManagedResource from 'foldkit/managedResource'\nimport type * as Update from 'foldkit/update'\nimport { Bundle } from 'foldkit-bundle'\nimport { unlessSame } from '../internal.js'\n\nexport const MediaStreamModel = Schema.Struct({\n status: Schema.Literals(['idle', 'requesting', 'live', 'denied']),\n lastError: Schema.NullOr(Schema.String),\n})\nexport type MediaStreamModel = typeof MediaStreamModel.Type\n\nexport const MediaStreamMessage = defineMessageUnion({\n Started: {},\n Stopped: {},\n Live: {},\n Ended: {},\n Denied: {},\n Failed: { message: Schema.String },\n})\nexport type MediaStreamMessage = typeof MediaStreamMessage.Type\n\n/** A single media track: stopped on release. */\nexport interface MediaTrackHandle {\n stop(): void\n}\n\n/** The live stream: its tracks stop on release. */\nexport interface MediaStreamHandle {\n getTracks(): ReadonlyArray<MediaTrackHandle>\n}\n\n/** Which tracks `mediaStream` asks `getUserMedia` for. */\nexport interface MediaStreamConstraints {\n readonly audio: boolean\n readonly video: boolean\n}\n\n/** The live stream, for commands that attach it to an element. One assembly holds one. */\nexport const LiveStream = ManagedResource.tag<MediaStreamHandle>()('media-stream')\n\n/** The stream service a placed camera requires. */\nexport type LiveStreamService = ManagedResource.ServiceOf<typeof LiveStream>\n\ntype StreamResources = Readonly<{\n stream: ManagedResource.Entry<\n MediaStreamModel,\n MediaStreamMessage,\n Option.Option<MediaStreamConstraints>,\n MediaStreamHandle,\n LiveStreamService,\n () => MediaStreamMessage\n >\n}>\n\nconst failMessage = (error: unknown): string =>\n error instanceof Error ? error.message : String(error)\n\nconst isDenied = (error: unknown): boolean =>\n typeof (error as { readonly name?: unknown } | null)?.name === 'string' &&\n ['NotAllowedError', 'SecurityError'].includes((error as { readonly name: string }).name)\n\n/**\n * A camera/mic stream as a bundle factory: one live MediaStream held in a\n * Managed Resource while the Model asks for it. `Started` requests,\n * `Stopped` releases; denial parks at `denied` (actionable UI), any other\n * acquire failure parks at `idle` with the error noted — both clear\n * requirements, so a failing device never spins an acquire loop. Release\n * stops every track. No media-devices API fails the acquire instead of\n * throwing.\n */\nexport const mediaStream = <const Name extends string>(config: {\n readonly name: Name\n /** Read lazily so tests can substitute a double, like the SSE bundle. */\n readonly request?:\n ((constraints: MediaStreamConstraints) => Promise<MediaStreamHandle>) | undefined\n}) => {\n const request = (constraints: MediaStreamConstraints): Promise<MediaStreamHandle> => {\n if (config.request !== undefined) return config.request(constraints)\n if (\n typeof navigator === 'undefined' ||\n typeof navigator.mediaDevices?.getUserMedia !== 'function'\n ) {\n return Promise.reject(new Error('media devices are unavailable'))\n }\n return navigator.mediaDevices.getUserMedia(constraints)\n }\n\n return Bundle.make(config.name, {\n Model: MediaStreamModel,\n Message: MediaStreamMessage,\n args: Schema.Struct({ audio: Schema.Boolean, video: Schema.Boolean }),\n init: () => ({ model: { status: 'idle' as const, lastError: null } }),\n update: (model, message) =>\n MediaStreamMessage.match<\n Update.ReturnWithOutMessage<MediaStreamModel, MediaStreamMessage, never>\n >(message, {\n // Starting a live stream would wait at `requesting` for an acquire\n // that never comes: the requirements are the same.\n Started: () =>\n model.status === 'requesting' || model.status === 'live'\n ? { model }\n : { model: { ...model, status: 'requesting' as const } },\n Stopped: () => ({ model: unlessSame(model, { ...model, status: 'idle' }) }),\n Live: () => ({ model: unlessSame(model, { ...model, status: 'live', lastError: null }) }),\n // Stopping releases the stream, whose release reports it ended.\n Ended: () => ({ model: unlessSame(model, { ...model, status: 'idle' }) }),\n Denied: () => ({ model: unlessSame(model, { ...model, status: 'denied' }) }),\n Failed: ({ message }) => ({\n model: unlessSame(model, { ...model, status: 'idle', lastError: message }),\n }),\n }),\n resources: args =>\n ManagedResource.make<MediaStreamModel, MediaStreamMessage>()(entry => ({\n stream: entry(\n Schema.Option(Schema.Struct({ audio: Schema.Boolean, video: Schema.Boolean })),\n {\n resource: LiveStream,\n modelToMaybeRequirements: model =>\n model.status === 'requesting' || model.status === 'live'\n ? Option.some({ audio: args.audio, video: args.video })\n : Option.none(),\n acquire: (constraints: MediaStreamConstraints) =>\n Effect.tryPromise({\n try: () => request(constraints),\n catch: (error: unknown) => error,\n }),\n onAcquired: () => MediaStreamMessage.Live(),\n onReleased: () => MediaStreamMessage.Ended(),\n onAcquireError: error =>\n isDenied(error)\n ? MediaStreamMessage.Denied()\n : MediaStreamMessage.Failed({ message: failMessage(error) }),\n release: stream =>\n Effect.sync(() => {\n for (const track of stream.getTracks()) track.stop()\n }),\n },\n ),\n })),\n })\n}\n","import { Effect, Option, Queue, Schema, Stream } from 'effect'\nimport { defineMessageUnion } from 'foldkit/message'\nimport * as ManagedResource from 'foldkit/managedResource'\nimport * as Subscription from 'foldkit/subscription'\nimport type * as Update from 'foldkit/update'\nimport { Bundle } from 'foldkit-bundle'\nimport { unlessSame } from '../internal.js'\n\nexport const PermissionState = Schema.Literals(['granted', 'denied', 'prompt'])\nexport type PermissionState = typeof PermissionState.Type\n\nexport const PermissionsModel = Schema.Struct({\n states: Schema.Record(Schema.String, PermissionState),\n lastError: Schema.NullOr(Schema.String),\n})\nexport type PermissionsModel = typeof PermissionsModel.Type\n\nexport const PermissionsMessage = defineMessageUnion({\n Snapshot: { states: Schema.Record(Schema.String, PermissionState) },\n Changed: { name: Schema.String, state: PermissionState },\n Cleared: {},\n Failed: { message: Schema.String },\n})\nexport type PermissionsMessage = typeof PermissionsMessage.Type\n\n/** A queried permission status; `onchange` fires while watched. */\nexport interface PermissionStatusHandle {\n readonly state: string\n onchange: (() => void) | null\n}\n\n/** The slice of the Permissions API the bundle needs. */\nexport interface PermissionsHandle {\n query(descriptor: { readonly name: string }): Promise<PermissionStatusHandle>\n}\n\ninterface Acquired {\n readonly statuses: ReadonlyMap<string, PermissionStatusHandle>\n readonly snapshot: Readonly<Record<string, PermissionState>>\n readonly events: Queue.Queue<PermissionsMessage>\n}\n\n/** The watched statuses, for the changes subscription. One assembly holds one. */\nexport const Watch = ManagedResource.tag<Acquired>()('permissions')\n\n/** The watch service a placed Permissions bundle requires. */\nexport type WatchService = ManagedResource.ServiceOf<typeof Watch>\n\ntype WatchResources = Readonly<{\n watch: ManagedResource.Entry<\n PermissionsModel,\n PermissionsMessage,\n Option.Option<ReadonlyArray<string>>,\n Acquired,\n WatchService,\n (acquired: Acquired) => PermissionsMessage\n >\n}>\n\nconst failMessage = (error: unknown): string =>\n error instanceof Error ? error.message : String(error)\n\nconst readState = (state: string, name: string): PermissionState => {\n if (state !== 'granted' && state !== 'denied' && state !== 'prompt') {\n throw new Error(`unknown permission state for ${name}: ${state}`)\n }\n return state\n}\n\n/**\n * Permission states as a bundle factory: queried on placement, kept current\n * by each status object's `onchange`. A resource holds the status objects\n * (they cannot live in the Model); its queue feeds the subscription, and\n * release detaches every handler. An unknown permission name fails the\n * acquire; an unknown state string fails it too — both become `Failed`,\n * never Model facts.\n */\nexport const permissions = <const Name extends string>(config: {\n readonly name: Name\n /** Read lazily so tests can substitute a double, like the SSE bundle. */\n readonly create?: ((navigator: Navigator) => PermissionsHandle | null) | undefined\n}) => {\n const handle = (): PermissionsHandle | null => {\n if (typeof navigator === 'undefined') return null\n if (config.create !== undefined) return config.create(navigator)\n const api = navigator.permissions as unknown as PermissionsHandle | undefined\n return api ?? null\n }\n\n return Bundle.make<\n Name,\n PermissionsModel,\n PermissionsMessage,\n { readonly names: ReadonlyArray<string> },\n never,\n never,\n WatchService,\n void,\n WatchResources,\n {}\n >(config.name, {\n Model: PermissionsModel,\n Message: PermissionsMessage,\n args: Schema.Struct({ names: Schema.Array(Schema.String) }),\n init: () => ({ model: { states: {}, lastError: null } }),\n update: (model, message) =>\n PermissionsMessage.match<\n Update.ReturnWithOutMessage<PermissionsModel, PermissionsMessage, never>\n >(message, {\n Snapshot: ({ states }) => {\n const next = unlessSame(model.states, { ...states })\n return next === model.states ? { model } : { model: { ...model, states: next } }\n },\n Changed: ({ name, state }) =>\n Object.hasOwn(model.states, name) && model.states[name] === state\n ? { model }\n : { model: { ...model, states: { ...model.states, [name]: state } } },\n Cleared: () =>\n Object.keys(model.states).length === 0 ? { model } : { model: { ...model, states: {} } },\n Failed: ({ message }) => ({ model: unlessSame(model, { ...model, lastError: message }) }),\n }),\n resources: args => {\n const names = Option.some([...new Set(args.names)])\n return ManagedResource.make<PermissionsModel, PermissionsMessage>()(entry => ({\n watch: entry(Schema.Option(Schema.Array(Schema.String)), {\n resource: Watch,\n modelToMaybeRequirements: () => names,\n acquire: (names: ReadonlyArray<string>) =>\n Effect.gen(function* () {\n const api = handle()\n if (api === null) throw new Error('permissions are unavailable')\n const events = yield* Queue.unbounded<PermissionsMessage>()\n const statuses = new Map<string, PermissionStatusHandle>()\n // Offers run in arrival order; see the WebSocket bundle.\n let tail: Promise<void> = Promise.resolve()\n const offer = (message: PermissionsMessage) => {\n const run = () =>\n Effect.runPromise(Queue.offer(events, message)).then(\n () => undefined,\n () => undefined,\n )\n tail = tail.then(run, run)\n }\n // Two phases: query and validate everything first, so a later\n // name failing cannot abandon handlers attached to earlier ones.\n const queried: Array<readonly [string, PermissionStatusHandle, PermissionState]> = []\n for (const name of names) {\n const status = yield* Effect.tryPromise({\n try: () => api.query({ name }),\n catch: (error: unknown) => error,\n })\n queried.push([name, status, readState(status.state, name)] as const)\n }\n const snapshot: Record<string, PermissionState> = {}\n for (const [name, status, state] of queried) {\n status.onchange = () => {\n try {\n offer(\n PermissionsMessage.Changed({ name, state: readState(status.state, name) }),\n )\n } catch {\n // readState evaluates before offer runs, so a state the\n // schema rejects lands here instead of crashing the handler.\n offer(\n PermissionsMessage.Failed({\n message: `unknown permission state for ${name}`,\n }),\n )\n }\n }\n statuses.set(name, status)\n snapshot[name] = state\n }\n return { statuses, snapshot, events }\n }),\n // The snapshot is captured during acquire, so onAcquired cannot\n // throw re-reading a state that changed mid-acquire.\n onAcquired: ({ snapshot }) => PermissionsMessage.Snapshot({ states: { ...snapshot } }),\n onReleased: () => PermissionsMessage.Cleared(),\n onAcquireError: error => PermissionsMessage.Failed({ message: failMessage(error) }),\n release: ({ statuses, events }) =>\n Effect.asVoid(\n Effect.andThen(\n Effect.sync(() => {\n for (const status of statuses.values()) status.onchange = null\n }),\n Queue.shutdown(events),\n ),\n ),\n }),\n }))\n },\n subscriptions: (): Subscription.Subscriptions<\n PermissionsModel,\n PermissionsMessage,\n WatchService\n > =>\n Subscription.make<PermissionsModel, PermissionsMessage, WatchService>()(() => ({\n // No model gate: the queue outlives every state change, and release\n // ends the stream through teardown, not through dependencies.\n changes: Subscription.persistentEntry(\n Stream.unwrap(\n Effect.matchEffect(Watch.get, {\n // Released between placement and attach: end quietly.\n onFailure: () => Effect.succeed(Stream.empty),\n onSuccess: ({ events }) => Effect.succeed(Stream.fromQueue(events)),\n }),\n ),\n ),\n })),\n })\n}\n"],"mappings":";;;;;;;;;;;;;;AAWA,MAAa,oBAAoB,mBAAmB;CAClD,SAAS,EAAE,QAAQ,OAAO,QAAQ;CAClC,SAAS,CAAC;CACV,QAAQ,CAAC;CACT,QAAQ,EAAE,SAAS,OAAO,OAAO;AACnC,CAAC;AAGD,MAAMA,iBAAe,UACnB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;;;;;;;AAQvD,MAAa,mBAAmB,aAAgE;CAC9F,MAAM;CACN,MAAM,CAAC;CACP,QAAQ,OAAO,YACb,OA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S,QAAQ;KACnB;KACA,OAAO;MAAE;MAAU;MAAU;KAAO;IACtC,CAAC;IAGH,aAAa,EAAE,eAAe,mBAAmB,SAAS,EAAE,QAAQ,EAAE,GAAG,SAAS,EAAE,CAAC;IACrF,kBAAkB,mBAAmB,QAAQ;IAC7C,iBAAgB,UAAS,mBAAmB,OAAO,EAAE,SAAS,YAAY,KAAK,EAAE,CAAC;IAClF,UAAU,EAAE,UAAU,aACpB,OAAO,OACL,OAAO,QACL,OAAO,WAAW;KAChB,KAAK,MAAM,UAAU,SAAS,OAAO,GAAG,OAAO,WAAW;IAC5D,CAAC,GACD,MAAM,SAAS,MAAM,CACvB,CACF;GACJ,CAAC,EACH,EAAE;EACJ;EACA,qBAKE,aAAa,KAAyD,CAAC,QAAQ,EAG7E,SAAS,aAAa,gBACpB,OAAO,OACL,OAAO,YAAY,MAAM,KAAK;GAE5B,iBAAiB,OAAO,QAAQ,OAAO,KAAK;GAC5C,YAAY,EAAE,aAAa,OAAO,QAAQ,OAAO,UAAU,MAAM,CAAC;EACpE,CAAC,CACH,CACF,EACF,EAAE;CACN,CAAC;AACH"}
|
package/dist/dom/index.d.mts
CHANGED
|
@@ -1,10 +1,18 @@
|
|
|
1
|
-
import { A as ScrollLock, C as targetOf, D as MoveStarted, E as MoveEnded, M as tabbableWithin, O as Moved, S as Targets, T as Move, _ as boxOf, a as TextEdited, b as TargetHovered, c as DRAG_THRESHOLD, d as DragFact, f as DragPlace, g as PointerDrag, h as DraggedOver, i as TextCommitted, j as FocusScope, k as HideOutside, l as DragCancelled, m as DragZone, n as EditableText, o as TextFact, p as DragStarted, r as TextCancelled, s as textOf, t as EditAsked, u as DragDropped, v as zoneOf, w as Fact, x as TargetPressed, y as TargetFact } from "../editable-text-
|
|
1
|
+
import { A as ScrollLock, C as targetOf, D as MoveStarted, E as MoveEnded, M as tabbableWithin, O as Moved, S as Targets, T as Move, _ as boxOf, a as TextEdited, b as TargetHovered, c as DRAG_THRESHOLD, d as DragFact, f as DragPlace, g as PointerDrag, h as DraggedOver, i as TextCommitted, j as FocusScope, k as HideOutside, l as DragCancelled, m as DragZone, n as EditableText, o as TextFact, p as DragStarted, r as TextCancelled, s as textOf, t as EditAsked, u as DragDropped, v as zoneOf, w as Fact, x as TargetPressed, y as TargetFact } from "../editable-text-Dvm-Fuqs.mjs";
|
|
2
2
|
import { Schema, Stream } from "effect";
|
|
3
3
|
import * as Mount from "foldkit/mount";
|
|
4
|
+
import { Url } from "foldkit/url";
|
|
4
5
|
import { Command } from "foldkit/command";
|
|
5
6
|
//#region src/dom/autofocus.d.ts
|
|
6
7
|
export declare const Focused: Schema.TaggedStruct<"Focused", {}>;
|
|
7
8
|
export type Focused = typeof Focused.Type;
|
|
9
|
+
/**
|
|
10
|
+
* Autofocus as a Mount: focuses the element on insert, then emits `Focused`.
|
|
11
|
+
* The message means focus was requested — a non-focusable element or a
|
|
12
|
+
* hidden tab may decline, and the browser does not report that. Plain
|
|
13
|
+
* `focus()`, no scroll options: scroll behavior stays the application's
|
|
14
|
+
* choice.
|
|
15
|
+
*/
|
|
8
16
|
export declare const Autofocus: Mount.MountDefinitionNoArgs<"Autofocus", {
|
|
9
17
|
readonly _tag: "Focused";
|
|
10
18
|
}>;
|
|
@@ -13,16 +21,16 @@ export declare const Autofocus: Mount.MountDefinitionNoArgs<"Autofocus", {
|
|
|
13
21
|
export declare const ClipboardMessage: import("foldkit/message").MessageUnion<{
|
|
14
22
|
readonly Copied: {};
|
|
15
23
|
readonly CopyFailed: {
|
|
16
|
-
|
|
24
|
+
message: Schema.String;
|
|
17
25
|
};
|
|
18
26
|
}>;
|
|
19
27
|
export type ClipboardMessage = typeof ClipboardMessage.Type;
|
|
20
28
|
export declare const ClipboardReadMessage: import("foldkit/message").MessageUnion<{
|
|
21
29
|
readonly Read: {
|
|
22
|
-
|
|
30
|
+
text: Schema.String;
|
|
23
31
|
};
|
|
24
32
|
readonly ReadFailed: {
|
|
25
|
-
|
|
33
|
+
message: Schema.String;
|
|
26
34
|
};
|
|
27
35
|
}>;
|
|
28
36
|
export type ClipboardReadMessage = typeof ClipboardReadMessage.Type;
|
|
@@ -39,15 +47,31 @@ export declare const copyText: (text: string) => Command<ClipboardMessage, never
|
|
|
39
47
|
export declare const readText: () => Command<ClipboardReadMessage, never, never>;
|
|
40
48
|
//#endregion
|
|
41
49
|
//#region src/dom/input-mask.d.ts
|
|
50
|
+
/** What `InputMask` reports after each edit: the masked text shown, and the characters typed. */
|
|
42
51
|
export declare const Input: Schema.TaggedStruct<"Input", {
|
|
43
52
|
readonly value: Schema.String;
|
|
44
53
|
readonly raw: Schema.String;
|
|
45
54
|
}>;
|
|
46
55
|
export type Input = typeof Input.Type;
|
|
56
|
+
/**
|
|
57
|
+
* The mask as a pure function: `#` takes a digit, `A` a letter, `*` either, and
|
|
58
|
+
* any other character of the pattern is written in once input reaches past it.
|
|
59
|
+
* Input that fits no placeholder is skipped. `masked` is what the field shows;
|
|
60
|
+
* `raw` is only the characters typed.
|
|
61
|
+
*/
|
|
47
62
|
export declare const applyMask: (value: string, pattern: string) => {
|
|
48
63
|
readonly masked: string;
|
|
49
64
|
readonly raw: string;
|
|
50
65
|
};
|
|
66
|
+
/**
|
|
67
|
+
* An input mask as a Mount plus a pure mask function. The pattern language
|
|
68
|
+
* is three placeholders — `#` digit, `A` letter, `*` either, all ASCII —
|
|
69
|
+
* with every other character literal. Literals appear only once a later placeholder
|
|
70
|
+
* consumes input, so partial values never dangle a separator. The Mount
|
|
71
|
+
* rewrites the field, restores the caret approximately, and emits `Input`
|
|
72
|
+
* with both the masked and raw values; the parent owns the state, like any
|
|
73
|
+
* controlled input.
|
|
74
|
+
*/
|
|
51
75
|
export declare const InputMask: Mount.MountDefinitionWithArgs<"InputMask", {
|
|
52
76
|
pattern: Schema.String;
|
|
53
77
|
}, {
|
|
@@ -57,6 +81,15 @@ export declare const InputMask: Mount.MountDefinitionWithArgs<"InputMask", {
|
|
|
57
81
|
}>;
|
|
58
82
|
//#endregion
|
|
59
83
|
//#region src/dom/keep-in-view.d.ts
|
|
84
|
+
/**
|
|
85
|
+
* Keeps what is marked in view as a Mount: whenever an element in the mounted
|
|
86
|
+
* one's subtree newly matches `selector`, such as the row just selected in a
|
|
87
|
+
* list, it is scrolled into view the least amount that shows it (`nearest`).
|
|
88
|
+
* The element keeps its identity and its focus: nothing is redrawn to move it.
|
|
89
|
+
*
|
|
90
|
+
* It watches with a `MutationObserver` for as long as it is mounted, which is as
|
|
91
|
+
* long as the list or canvas that can change what is marked.
|
|
92
|
+
*/
|
|
60
93
|
export declare const KeepInView: Mount.MountDefinitionWithArgs<"KeepInView", {
|
|
61
94
|
/** What is marked, as a selector within the element: `[aria-selected="true"]`. */
|
|
62
95
|
selector: Schema.String;
|
|
@@ -66,7 +99,7 @@ export declare const KeepInView: Mount.MountDefinitionWithArgs<"KeepInView", {
|
|
|
66
99
|
export declare const ScriptMessage: import("foldkit/message").MessageUnion<{
|
|
67
100
|
readonly Loaded: {};
|
|
68
101
|
readonly LoadFailed: {
|
|
69
|
-
|
|
102
|
+
message: Schema.String;
|
|
70
103
|
};
|
|
71
104
|
}>;
|
|
72
105
|
export type ScriptMessage = typeof ScriptMessage.Type;
|
|
@@ -84,7 +117,7 @@ export declare const ShareMessage: import("foldkit/message").MessageUnion<{
|
|
|
84
117
|
readonly Shared: {};
|
|
85
118
|
readonly Dismissed: {};
|
|
86
119
|
readonly ShareFailed: {
|
|
87
|
-
|
|
120
|
+
message: Schema.String;
|
|
88
121
|
};
|
|
89
122
|
}>;
|
|
90
123
|
export type ShareMessage = typeof ShareMessage.Type;
|
|
@@ -100,26 +133,43 @@ export declare const measured: (name: string) => {
|
|
|
100
133
|
readonly h: `--fk-${string}-h`;
|
|
101
134
|
readonly display: `--fk-${string}-display`;
|
|
102
135
|
};
|
|
136
|
+
/**
|
|
137
|
+
* Measures marked elements as a Mount, for a view to draw something over them,
|
|
138
|
+
* such as an editor's selection outline, with no Message and no Model: where
|
|
139
|
+
* an element is, is presentation, known to the DOM and to no transition.
|
|
140
|
+
*
|
|
141
|
+
* For each named target, the first element in the mounted one's subtree that
|
|
142
|
+
* matches its selector is measured relative to the mounted element's scroll
|
|
143
|
+
* box, which is what an absolutely placed child of it is laid out in. The
|
|
144
|
+
* mounted element gets `--fk-<name>-x`, `-y`, `-w` and `-h` in pixels, and
|
|
145
|
+
* `--fk-<name>-display`: `block` while a target is found, `none` while none is.
|
|
146
|
+
*
|
|
147
|
+
* It measures again when the subtree changes (a selection moves), in the
|
|
148
|
+
* frame the change is drawn in; and, at most once a frame, when the mounted
|
|
149
|
+
* element scrolls, the window resizes, the mounted element or a measured one
|
|
150
|
+
* changes size, an image or a font inside loads, and on every frame of a
|
|
151
|
+
* transition or an animation inside. What moves a target by any other way,
|
|
152
|
+
* such as a stylesheet added that shifts it without resizing it, is seen at
|
|
153
|
+
* the next of these.
|
|
154
|
+
*/
|
|
103
155
|
export declare const Measure: Mount.MountDefinitionWithArgs<"Measure", {
|
|
104
156
|
/** Each target by name, as a selector within the element: `{ selected: '[aria-selected="true"]' }`. */
|
|
105
157
|
targets: Schema.$Record<Schema.String, Schema.String>;
|
|
106
158
|
}, never>;
|
|
107
159
|
//#endregion
|
|
108
160
|
//#region src/dom/follow-tab-stop.d.ts
|
|
161
|
+
/**
|
|
162
|
+
* Keeps focus that is inside a container of roving tab stops on its stop, as a
|
|
163
|
+
* Mount: when a transition moves the stop (a row made current by a command the
|
|
164
|
+
* container did not see, such as a duplicate) or removes the focused
|
|
165
|
+
* descendant (a deleted row), focus goes to the descendant with
|
|
166
|
+
* `tabindex="0"`. It sends no Message. Focus outside the container is never
|
|
167
|
+
* taken, and focus the user moved away stays where it went.
|
|
168
|
+
*/
|
|
109
169
|
export declare const FollowTabStop: Mount.MountDefinitionNoArgs<"FollowTabStop", never>;
|
|
110
170
|
//#endregion
|
|
111
171
|
//#region src/dom/scroll.d.ts
|
|
112
|
-
/**
|
|
113
|
-
interface Navigation extends EventTarget {
|
|
114
|
-
readonly currentEntry: {
|
|
115
|
-
readonly key: string;
|
|
116
|
-
} | null;
|
|
117
|
-
}
|
|
118
|
-
declare global {
|
|
119
|
-
interface Window {
|
|
120
|
-
readonly navigation?: Navigation;
|
|
121
|
-
}
|
|
122
|
-
}
|
|
172
|
+
/** How `keepScroll` remembers and restores each history entry's offset. */
|
|
123
173
|
export interface KeepScrollOptions {
|
|
124
174
|
/** The `sessionStorage` key holding entry offsets. Default `'foldkit:scroll'`. */
|
|
125
175
|
readonly storageKey?: string | undefined;
|
|
@@ -135,9 +185,19 @@ export interface KeepScrollOptions {
|
|
|
135
185
|
* Keeps the window's scroll across same-document navigations: a pushed entry
|
|
136
186
|
* starts at the top, and Back, Forward or a reload return where that entry
|
|
137
187
|
* was. Without a window the stream is empty instead of throwing. Lift with
|
|
138
|
-
* `Subscription.
|
|
188
|
+
* `Subscription.persistentEntry`; the stream sends no Messages.
|
|
139
189
|
*/
|
|
140
190
|
export declare const keepScroll: (options?: KeepScrollOptions) => Stream.Stream<never>;
|
|
141
191
|
//#endregion
|
|
192
|
+
//#region src/dom/pointed-links.d.ts
|
|
193
|
+
/**
|
|
194
|
+
* The address of the link a reader points at or tabs to, on the page's own
|
|
195
|
+
* origin: where they may go next, for a `Data.preload` before they go. Each
|
|
196
|
+
* link once while they stay on it, since crossing its text sends one event
|
|
197
|
+
* per element inside it. Without a document the stream is empty. Lift with
|
|
198
|
+
* `Subscription.persistentEntry`, mapping each address to a Message.
|
|
199
|
+
*/
|
|
200
|
+
export declare const pointedLinks: () => Stream.Stream<Url>;
|
|
201
|
+
//#endregion
|
|
142
202
|
export { DRAG_THRESHOLD, DragCancelled, DragDropped, DragFact, DragPlace, DragStarted, DragZone, DraggedOver, EditAsked, EditableText, Fact, FocusScope, HideOutside, Move, MoveEnded, MoveStarted, Moved, PointerDrag, ScrollLock, TargetFact, TargetHovered, TargetPressed, Targets, TextCancelled, TextCommitted, TextEdited, TextFact, boxOf, tabbableWithin, targetOf, textOf, zoneOf };
|
|
143
203
|
//# sourceMappingURL=index.d.mts.map
|
package/dist/dom/index.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/dom/autofocus.ts","../../src/dom/clipboard.ts","../../src/dom/input-mask.ts","../../src/dom/keep-in-view.ts","../../src/dom/script-loader.ts","../../src/dom/share.ts","../../src/dom/measure.ts","../../src/dom/follow-tab-stop.ts","../../src/dom/scroll.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/dom/autofocus.ts","../../src/dom/clipboard.ts","../../src/dom/input-mask.ts","../../src/dom/keep-in-view.ts","../../src/dom/script-loader.ts","../../src/dom/share.ts","../../src/dom/measure.ts","../../src/dom/follow-tab-stop.ts","../../src/dom/scroll.ts","../../src/dom/pointed-links.ts"],"mappings":";;;;;;qBAGa,SAAO,OAAA;YACR,iBAAiB,QAAQ;;;;;;;;qBASxB,WAAS,MAAA;;;;;qBCJT,4CAAgB;;;IAEb,SAAO,OAAA;;;YAEX,0BAA0B,iBAAiB;qBAE1C,gDAAoB;;IACvB,MAAI,OAAA;;;IACE,SAAO,OAAA;;;YAEX,8BAA8B,qBAAqB;;;;;;qBAUlD,WAAQ,iBAAmB,QAAQ;;;;;qBAsBnC,gBAAe,QAAQ;;;;qBC/CvB,OAAK,OAAA;;;;YAIN,eAAe,MAAM;;;;;;;qBAiCpB,YAAS,eACP;WAED;WAAyB;;;;;;;;;;;qBA6C1B,WAAS,MAAA;WAAT,OAAA;;;;;;;;;;;;;;;;;qBC7EA,YAAU,MAAA;;YAAV,OAAA;;;;qBCDA,yCAAa;;;IAEV,SAAO,OAAA;;;YAEX,uBAAuB,cAAc;;qBASpC,aAAU,gBAAkB,QAAQ;;;qBCbpC,WAAS,OAAA;;;;;YAKV,mBAAmB,UAAU;qBAE5B,wCAAY;;;;IAGR,SAAO,OAAA;;;YAEZ,sBAAsB,aAAa;;qBAUlC,QAAK,MAAU,cAAY,QAAQ;;;;qBC7BnC,WAAQ;WAEjB;WACA;WACA;WACA;WACA;;;;;;;;;;;;;;;;;;;;;qBAsBS,SAAO,MAAA;;;;;;;;;;;;;;qBCrBP,eAAa,MAAA;;;;iBCuBT;;WAEN;;WAEA;;;;;WAKA;;;;;;;;qBAuHE,aAAU,UAAa,sBAAyB,OAAO;;;;;;;;;;qBCvJvD,oBAAmB,OAAO,OAAO"}
|
package/dist/dom/index.mjs
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
|
-
import { C as MoveEnded, D as ScrollLock, E as HideOutside, O as FocusScope, S as Move, T as Moved, _ as zoneOf, a as TextCommitted, b as Targets, c as DRAG_THRESHOLD, d as DragPlace, f as DragStarted, g as boxOf, h as PointerDrag, i as TextCancelled, k as tabbableWithin, l as DragCancelled, m as DraggedOver, n as EditAsked, o as TextEdited, p as DragZone, r as EditableText, s as textOf, t as FollowTabStop, u as DragDropped, v as TargetHovered, w as MoveStarted, x as targetOf, y as TargetPressed } from "../follow-tab-stop-
|
|
1
|
+
import { C as MoveEnded, D as ScrollLock, E as HideOutside, O as FocusScope, S as Move, T as Moved, _ as zoneOf, a as TextCommitted, b as Targets, c as DRAG_THRESHOLD, d as DragPlace, f as DragStarted, g as boxOf, h as PointerDrag, i as TextCancelled, k as tabbableWithin, l as DragCancelled, m as DraggedOver, n as EditAsked, o as TextEdited, p as DragZone, r as EditableText, s as textOf, t as FollowTabStop, u as DragDropped, v as TargetHovered, w as MoveStarted, x as targetOf, y as TargetPressed } from "../follow-tab-stop-Ci1tqAIW.mjs";
|
|
2
2
|
import { Effect, Option, Queue, Schema, Stream } from "effect";
|
|
3
3
|
import * as Mount from "foldkit/mount";
|
|
4
4
|
import { defineMessageUnion } from "foldkit/message";
|
|
5
|
+
import * as Dom from "foldkit/dom";
|
|
6
|
+
import { fromString, toString } from "foldkit/url";
|
|
5
7
|
//#region src/dom/autofocus.ts
|
|
8
|
+
const Focused = Schema.TaggedStruct("Focused", {});
|
|
6
9
|
/**
|
|
7
10
|
* Autofocus as a Mount: focuses the element on insert, then emits `Focused`.
|
|
8
11
|
* The message means focus was requested — a non-focusable element or a
|
|
@@ -10,7 +13,6 @@ import { defineMessageUnion } from "foldkit/message";
|
|
|
10
13
|
* `focus()`, no scroll options: scroll behavior stays the application's
|
|
11
14
|
* choice.
|
|
12
15
|
*/
|
|
13
|
-
const Focused = Schema.TaggedStruct("Focused", {});
|
|
14
16
|
const Autofocus = Mount.define("Autofocus", {
|
|
15
17
|
messages: [Focused],
|
|
16
18
|
execute: ({ element }) => Effect.sync(() => {
|
|
@@ -67,15 +69,7 @@ const readText = () => ({
|
|
|
67
69
|
});
|
|
68
70
|
//#endregion
|
|
69
71
|
//#region src/dom/input-mask.ts
|
|
70
|
-
/**
|
|
71
|
-
* An input mask as a Mount plus a pure mask function. The pattern language
|
|
72
|
-
* is three placeholders — `#` digit, `A` letter, `*` either, all ASCII —
|
|
73
|
-
* with every other character literal. Literals appear only once a later placeholder
|
|
74
|
-
* consumes input, so partial values never dangle a separator. The Mount
|
|
75
|
-
* rewrites the field, restores the caret approximately, and emits `Input`
|
|
76
|
-
* with both the masked and raw values; the parent owns the state, like any
|
|
77
|
-
* controlled input.
|
|
78
|
-
*/
|
|
72
|
+
/** What `InputMask` reports after each edit: the masked text shown, and the characters typed. */
|
|
79
73
|
const Input = Schema.TaggedStruct("Input", {
|
|
80
74
|
value: Schema.String,
|
|
81
75
|
raw: Schema.String
|
|
@@ -93,6 +87,12 @@ const fillable = (pattern, from, value, at) => {
|
|
|
93
87
|
}
|
|
94
88
|
return false;
|
|
95
89
|
};
|
|
90
|
+
/**
|
|
91
|
+
* The mask as a pure function: `#` takes a digit, `A` a letter, `*` either, and
|
|
92
|
+
* any other character of the pattern is written in once input reaches past it.
|
|
93
|
+
* Input that fits no placeholder is skipped. `masked` is what the field shows;
|
|
94
|
+
* `raw` is only the characters typed.
|
|
95
|
+
*/
|
|
96
96
|
const applyMask = (value, pattern) => {
|
|
97
97
|
let masked = "";
|
|
98
98
|
let raw = "";
|
|
@@ -117,6 +117,15 @@ const asField = (element) => {
|
|
|
117
117
|
const field = element;
|
|
118
118
|
return typeof field.value === "string" && typeof field.addEventListener === "function" ? field : null;
|
|
119
119
|
};
|
|
120
|
+
/**
|
|
121
|
+
* An input mask as a Mount plus a pure mask function. The pattern language
|
|
122
|
+
* is three placeholders — `#` digit, `A` letter, `*` either, all ASCII —
|
|
123
|
+
* with every other character literal. Literals appear only once a later placeholder
|
|
124
|
+
* consumes input, so partial values never dangle a separator. The Mount
|
|
125
|
+
* rewrites the field, restores the caret approximately, and emits `Input`
|
|
126
|
+
* with both the masked and raw values; the parent owns the state, like any
|
|
127
|
+
* controlled input.
|
|
128
|
+
*/
|
|
120
129
|
const InputMask = Mount.defineStream("InputMask", {
|
|
121
130
|
messages: [Input],
|
|
122
131
|
args: { pattern: Schema.String },
|
|
@@ -267,6 +276,14 @@ const share = (data) => ({
|
|
|
267
276
|
});
|
|
268
277
|
//#endregion
|
|
269
278
|
//#region src/dom/measure.ts
|
|
279
|
+
/** The custom properties `Measure` writes for a target named `name`. */
|
|
280
|
+
const measured = (name) => ({
|
|
281
|
+
x: `--fk-${name}-x`,
|
|
282
|
+
y: `--fk-${name}-y`,
|
|
283
|
+
w: `--fk-${name}-w`,
|
|
284
|
+
h: `--fk-${name}-h`,
|
|
285
|
+
display: `--fk-${name}-display`
|
|
286
|
+
});
|
|
270
287
|
/**
|
|
271
288
|
* Measures marked elements as a Mount, for a view to draw something over them,
|
|
272
289
|
* such as an editor's selection outline, with no Message and no Model: where
|
|
@@ -286,14 +303,6 @@ const share = (data) => ({
|
|
|
286
303
|
* such as a stylesheet added that shifts it without resizing it, is seen at
|
|
287
304
|
* the next of these.
|
|
288
305
|
*/
|
|
289
|
-
/** The custom properties `Measure` writes for a target named `name`. */
|
|
290
|
-
const measured = (name) => ({
|
|
291
|
-
x: `--fk-${name}-x`,
|
|
292
|
-
y: `--fk-${name}-y`,
|
|
293
|
-
w: `--fk-${name}-w`,
|
|
294
|
-
h: `--fk-${name}-h`,
|
|
295
|
-
display: `--fk-${name}-display`
|
|
296
|
-
});
|
|
297
306
|
const Measure = Mount.defineStream("Measure", {
|
|
298
307
|
messages: [Schema.Never],
|
|
299
308
|
args: {
|
|
@@ -401,7 +410,7 @@ targets: Schema.Record(Schema.String, Schema.String) },
|
|
|
401
410
|
* the stream attaches nothing and leaves the browser's own behaviour
|
|
402
411
|
* alone.
|
|
403
412
|
*
|
|
404
|
-
* Lift with `Subscription.
|
|
413
|
+
* Lift with `Subscription.persistentEntry`; the stream sends no Messages. Only
|
|
405
414
|
* the window scrolls: a nested container is the route graph's to know, when
|
|
406
415
|
* `Site.transition` arrives.
|
|
407
416
|
*/
|
|
@@ -501,7 +510,7 @@ const attach = (storageKey, kept, patience) => {
|
|
|
501
510
|
* Keeps the window's scroll across same-document navigations: a pushed entry
|
|
502
511
|
* starts at the top, and Back, Forward or a reload return where that entry
|
|
503
512
|
* was. Without a window the stream is empty instead of throwing. Lift with
|
|
504
|
-
* `Subscription.
|
|
513
|
+
* `Subscription.persistentEntry`; the stream sends no Messages.
|
|
505
514
|
*/
|
|
506
515
|
const keepScroll = (options = {}) => {
|
|
507
516
|
if (typeof window === "undefined") return Stream.empty;
|
|
@@ -511,6 +520,31 @@ const keepScroll = (options = {}) => {
|
|
|
511
520
|
return Stream.callback(() => Effect.acquireRelease(Effect.sync(() => attach(storageKey, kept, patience)), (detach) => Effect.sync(detach)));
|
|
512
521
|
};
|
|
513
522
|
//#endregion
|
|
514
|
-
|
|
523
|
+
//#region src/dom/pointed-links.ts
|
|
524
|
+
/**
|
|
525
|
+
* The address of the link a reader points at or tabs to, on the page's own
|
|
526
|
+
* origin: where they may go next, for a `Data.preload` before they go. Each
|
|
527
|
+
* link once while they stay on it, since crossing its text sends one event
|
|
528
|
+
* per element inside it. Without a document the stream is empty. Lift with
|
|
529
|
+
* `Subscription.persistentEntry`, mapping each address to a Message.
|
|
530
|
+
*/
|
|
531
|
+
const pointedLinks = () => {
|
|
532
|
+
if (typeof document === "undefined") return Stream.empty;
|
|
533
|
+
const linkOf = (event) => {
|
|
534
|
+
const link = event.target instanceof Element ? event.target.closest("a[href]") : null;
|
|
535
|
+
return link instanceof HTMLAnchorElement && link.origin === window.location.origin ? fromString(link.href) : Option.none();
|
|
536
|
+
};
|
|
537
|
+
return Stream.merge(Dom.streamFromEventFilterMap({
|
|
538
|
+
target: document,
|
|
539
|
+
type: "pointerover",
|
|
540
|
+
filterMapEvent: linkOf
|
|
541
|
+
}), Dom.streamFromEventFilterMap({
|
|
542
|
+
target: document,
|
|
543
|
+
type: "focusin",
|
|
544
|
+
filterMapEvent: linkOf
|
|
545
|
+
})).pipe(Stream.changesWith((a, b) => toString(a) === toString(b)));
|
|
546
|
+
};
|
|
547
|
+
//#endregion
|
|
548
|
+
export { Autofocus, ClipboardMessage, ClipboardReadMessage, DRAG_THRESHOLD, DragCancelled, DragDropped, DragPlace, DragStarted, DragZone, DraggedOver, EditAsked, EditableText, FocusScope, Focused, FollowTabStop, HideOutside, Input, InputMask, KeepInView, Measure, Move, MoveEnded, MoveStarted, Moved, PointerDrag, ScriptMessage, ScrollLock, ShareData, ShareMessage, TargetHovered, TargetPressed, Targets, TextCancelled, TextCommitted, TextEdited, applyMask, boxOf, copyText, keepScroll, loadScript, measured, pointedLinks, readText, share, tabbableWithin, targetOf, textOf, zoneOf };
|
|
515
549
|
|
|
516
550
|
//# sourceMappingURL=index.mjs.map
|