foldkit-primitives 0.4.0 → 0.6.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.
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["failMessage","failMessage"],"sources":["../../src/net/broadcast.ts","../../src/net/online.ts","../../src/net/sse.ts","../../src/net/websocket.ts"],"sourcesContent":["/**\n * Cross-tab messaging as an entry plus a Command — not a bundle, because the\n * channel owns no state: the parent maps `Received` into its own Message and\n * stores whatever it keeps. One assembly may open the same name twice (two\n * listeners); share the entry instead. By spec a post never echoes to its\n * own channel, so a tab never hears itself.\n */\nimport { Effect, Queue, Schema, Stream } from 'effect'\nimport type { Command } from 'foldkit/command'\nimport { defineMessageUnion } from 'foldkit/message'\n\nexport const BroadcastMessage = defineMessageUnion({\n /** Notifies without storing: project the payload into your own field to keep it. */\n Received: { data: Schema.Unknown },\n Posted: {},\n BroadcastFailed: { message: Schema.String },\n})\nexport type BroadcastMessage = typeof BroadcastMessage.Type\n\n/** The slice of a BroadcastChannel this module needs; satisfied by the platform class. */\nexport interface BroadcastChannelHandle {\n postMessage(data: unknown): void\n close(): void\n onmessage: ((event: { readonly data: unknown }) => void) | null\n}\n\ntype ChannelFactory = (name: string) => BroadcastChannelHandle\n\nconst failMessage = (error: unknown): string =>\n error instanceof Error ? error.message : String(error)\n\nconst createChannel = (\n factory: ChannelFactory | undefined,\n name: string,\n): BroadcastChannelHandle | null => {\n if (factory !== undefined) return factory(name)\n if (typeof BroadcastChannel === 'undefined') return null\n return new BroadcastChannel(name) as unknown as BroadcastChannelHandle\n}\n\n/**\n * Every post to `name` from another channel, as Messages. Without a\n * BroadcastChannel API the stream is empty instead of throwing; closing the\n * stream closes the channel.\n */\nexport const broadcastMessages = (\n name: string,\n /** Read lazily so tests can substitute a double, like the SSE bundle. */\n create?: ChannelFactory | undefined,\n): Stream.Stream<BroadcastMessage> =>\n Stream.unwrap(\n Effect.gen(function* () {\n const channel = createChannel(create, name)\n if (channel === null) return Stream.empty\n const queue = yield* Queue.unbounded<BroadcastMessage>()\n channel.onmessage = event => {\n Effect.runFork(Queue.offer(queue, BroadcastMessage.Received({ data: event.data })))\n }\n yield* Effect.addFinalizer(() =>\n Effect.sync(() => {\n channel.onmessage = null\n channel.close()\n }),\n )\n return Stream.fromQueue(queue)\n }),\n )\n\n/**\n * Posts one message to `name`. Opens a channel, posts, and closes it: the\n * send is one-shot, so it is a Command, not a resource. Without a\n * BroadcastChannel API — or when the post throws — it yields\n * `BroadcastFailed` instead of throwing.\n */\nexport const postBroadcast = (\n name: string,\n data: unknown,\n create?: ChannelFactory | undefined,\n): Command<BroadcastMessage, never, never> => ({\n name: 'Broadcast.post',\n args: { name, data },\n // One path for every failure: no factory and no platform API, or a post\n // that throws (a closed channel) all become BroadcastFailed.\n effect: Effect.matchEffect(\n Effect.try({\n try: () => {\n const channel = createChannel(create, name)\n if (channel === null) throw new Error('broadcast is unavailable')\n try {\n channel.postMessage(data)\n } finally {\n channel.close()\n }\n },\n catch: failMessage,\n }),\n {\n onFailure: message => Effect.succeed(BroadcastMessage.BroadcastFailed({ message })),\n onSuccess: () => Effect.succeed(BroadcastMessage.Posted()),\n },\n ),\n})\n","/**\n * Online presence as a bundle: `online` in the Model, kept current by the\n * window's online/offline events. The browser reports facts; the Model owns\n * the state, so presence replays like any other transition.\n */\nimport { Schema, Stream } from 'effect'\nimport { defineMessageUnion } from 'foldkit/message'\nimport * as Subscription from 'foldkit/subscription'\nimport { Bundle } from 'foldkit-bundle'\n\nexport const OnlineModel = Schema.Struct({ online: Schema.Boolean })\nexport type OnlineModel = typeof OnlineModel.Type\n\nexport const OnlineMessage = defineMessageUnion({ Changed: { online: Schema.Boolean } })\nexport type OnlineMessage = typeof OnlineMessage.Type\n\nconst presenceStream = (): Stream.Stream<OnlineMessage> => {\n // No window (SSR): nothing to listen to, so the slice keeps its default.\n if (typeof window === 'undefined') return Stream.empty\n return Stream.mergeAll(\n [\n Stream.fromEventListener(window, 'online').pipe(\n Stream.map(() => OnlineMessage.Changed({ online: true })),\n ),\n Stream.fromEventListener(window, 'offline').pipe(\n Stream.map(() => OnlineMessage.Changed({ online: false })),\n ),\n ],\n { concurrency: 'unbounded' },\n )\n}\n\nexport const Online = Bundle.make('Online', {\n Model: OnlineModel,\n Message: OnlineMessage,\n init: () => ({\n // navigator.onLine is the browser's current answer; true elsewhere (SSR).\n model: {\n online:\n typeof navigator !== 'undefined' && typeof navigator.onLine === 'boolean'\n ? navigator.onLine\n : true,\n },\n }),\n update: (model, message) =>\n message.online === model.online ? { model } : { model: { online: message.online } },\n subscriptions: (): Subscription.Subscriptions<OnlineModel, OnlineMessage> =>\n Subscription.make<OnlineModel, OnlineMessage>()(() => ({\n changes: Subscription.persistent(presenceStream()),\n })),\n})\n","/**\n * Server-sent events as a bundle: connection lifecycle in the Model, the\n * event stream through one Managed Resource. One-directional, so there is no\n * send: the server speaks, the Model listens. The browser reconnects dropped\n * streams itself; a Failed only records the error.\n */\nimport { Effect, Option, Queue, Schema, Stream } from 'effect'\nimport { defineMessageUnion } from 'foldkit/message'\nimport { defineTaggedUnion } from 'foldkit/schema'\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\n/** The slice of an EventSource the bundle needs; satisfied by the platform class. */\nexport interface SourceHandle {\n readonly readyState: number\n close(): void\n onopen: ((event: any) => void) | null\n onmessage: ((event: any) => void) | null\n onerror: ((event: any) => void) | null\n}\n\nexport const SseModel = Schema.Struct({\n url: Schema.String,\n status: Schema.Literals(['closed', 'connecting', 'open']),\n lastError: Schema.NullOr(Schema.String),\n})\nexport type SseModel = typeof SseModel.Type\n\nexport const SseMessage = defineMessageUnion({\n Connecting: {},\n Opened: {},\n /** Notifies without storing: project the payload into your own field to keep it. */\n Received: { data: Schema.String },\n Closed: {},\n Failed: { message: Schema.String },\n})\nexport type SseMessage = typeof SseMessage.Type\n\n/**\n * What the reader sees: the stream's state, or its error. A page derives\n * this instead of keeping its own connection state machine. `lastError`\n * carries the stored failure text: the runtime error sentence (`event stream\n * error for …`) or the acquire error's own message.\n */\nexport const SseView = defineTaggedUnion({\n Disconnected: {},\n Connecting: {},\n Connected: {},\n Error: { error: Schema.String },\n})\nexport type SseView = typeof SseView.Type\n\n/**\n * Whether the stream is live: open with no error outstanding. The browser\n * reconnects a dropped stream itself; a `Failed` only records the error.\n */\nexport const isLive = (model: SseModel): boolean =>\n model.status === 'open' && model.lastError === null\n\n/**\n * The view of a stream, and whether its page still wants it. An error stands\n * until the page stops wanting the stream; a retry still waiting for its\n * stream reads as connecting, so it answers at once.\n */\nexport const viewOfSse = (model: SseModel, wanted: boolean): SseView => {\n if (model.lastError !== null)\n return model.status === 'open' || !wanted\n ? SseView.Error({ error: model.lastError })\n : SseView.Connecting()\n if (model.status === 'open') return SseView.Connected()\n if (model.status === 'connecting' || wanted) return SseView.Connecting()\n return SseView.Disconnected()\n}\n\n/** The registry value behind the source tag: the live source and its incoming queue. */\nexport interface AcquiredSource {\n readonly source: SourceHandle\n readonly events: Queue.Queue<SseMessage>\n}\n\n/** The live stream, for the incoming subscription. One assembly holds one. */\nexport const Source = ManagedResource.tag<AcquiredSource>()('sse')\n\n/** The source service a placed SSE stream requires. */\nexport type SourceService = ManagedResource.ServiceOf<typeof Source>\n\ntype SourceResources = Readonly<{\n source: ManagedResource.Entry<\n SseModel,\n SseMessage,\n Option.Option<string>,\n AcquiredSource,\n SourceService,\n () => SseMessage\n >\n}>\n\nconst failMessage = (error: unknown): string =>\n error instanceof Error ? error.message : String(error)\n\nexport const sse = <const Name extends string>(config: {\n readonly name: Name\n /** Defaults to the platform EventSource, read lazily so tests can substitute a double. */\n readonly createSource?: ((url: string) => SourceHandle) | undefined\n}) => {\n const createSource: (url: string) => SourceHandle =\n config.createSource ?? (url => new EventSource(url) as unknown as SourceHandle)\n return Bundle.make<\n Name,\n SseModel,\n SseMessage,\n { readonly url: string },\n never,\n SourceService,\n SourceService,\n void,\n SourceResources,\n {}\n >(config.name, {\n Model: SseModel,\n Message: SseMessage,\n args: Schema.Struct({ url: Schema.String }),\n init: (args): Update.Return<SseModel, SseMessage, SourceService> => ({\n model: { url: args.url, status: 'closed', lastError: null },\n }),\n update: (\n model,\n message,\n ): Update.ReturnWithOutMessage<SseModel, SseMessage, never, SourceService> =>\n SseMessage.match(message, {\n Connecting: () => ({ model: unlessSame(model, { ...model, status: 'connecting' }) }),\n Opened: () => ({\n model: unlessSame(model, { ...model, status: 'open', lastError: null }),\n }),\n Received: () => ({ model }),\n Closed: () => ({ model: unlessSame(model, { ...model, status: 'closed' }) }),\n // EventSource retries on its own, erroring the same way on every attempt.\n Failed: ({ message }) => ({\n model: unlessSame(model, { ...model, status: 'connecting', lastError: message }),\n }),\n }),\n resources: () =>\n ManagedResource.make<SseModel, SseMessage>()(entry => ({\n source: entry(Schema.Option(Schema.String), {\n resource: Source,\n modelToMaybeRequirements: model => Option.some(model.url),\n acquire: (url: string) =>\n Effect.gen(function* () {\n const events = yield* Queue.unbounded<SseMessage>()\n const source = createSource(url)\n // Offers run in arrival order; see the WebSocket bundle.\n let tail: Promise<void> = Promise.resolve()\n const enqueue = (effect: Effect.Effect<unknown>): void => {\n const run = () =>\n Effect.runPromise(effect).then(\n () => undefined,\n () => undefined,\n )\n tail = tail.then(run, run)\n }\n const offer = (message: SseMessage) => enqueue(Queue.offer(events, message))\n source.onopen = () => offer(SseMessage.Opened())\n // Event data is always text per the SSE spec.\n source.onmessage = event => offer(SseMessage.Received({ data: String(event.data) }))\n source.onerror = () =>\n offer(SseMessage.Failed({ message: `event stream error for ${url}` }))\n return { source, events }\n }),\n onAcquired: () => SseMessage.Connecting(),\n onReleased: () => SseMessage.Closed(),\n onAcquireError: error => SseMessage.Failed({ message: failMessage(error) }),\n // Daemon teardown: close the stream and drain the queue.\n release: ({ source, events }) =>\n Effect.asVoid(\n Effect.andThen(\n Effect.sync(() => {\n source.onopen = null\n source.onmessage = null\n source.onerror = null\n source.close()\n }),\n Queue.shutdown(events),\n ),\n ),\n }),\n })),\n subscriptions: (): Subscription.Subscriptions<SseModel, SseMessage, SourceService> =>\n Subscription.make<SseModel, SseMessage, SourceService>()(entry => ({\n incoming: entry(\n // Connecting to open is no reason to restart: the stream reads the\n // same queue, and replays an open it attached too late to see.\n { live: Schema.Boolean },\n {\n modelToDependencies: model => ({ live: model.status !== 'closed' }),\n dependenciesToStream: ({ live }) =>\n !live\n ? Stream.empty\n : Stream.unwrap(\n Effect.matchEffect(Source.get, {\n // Released between the dependency read and attach: end\n // quietly; onReleased reports Closed through update.\n onFailure: () => Effect.succeed(Stream.empty),\n onSuccess: ({ source, events }) =>\n Effect.succeed(\n Stream.concat(\n // A fast server opens before the stream attaches.\n // 1 is OPEN for EventSource everywhere.\n source.readyState === 1\n ? Stream.make(SseMessage.Opened())\n : Stream.empty,\n Stream.fromQueue(events),\n ),\n ),\n }),\n ),\n },\n ),\n })),\n })\n}\n","/**\n * A WebSocket as a bundle: connection lifecycle in the Model, full duplex\n * through one Managed Resource. The resource owns the socket; a `send`\n * helper writes through its tag service (lifted to the parent like every\n * helper); a subscription stream reads incoming messages through the same\n * tag. No hidden hub: everything the bundle touches is the Model, the\n * resource registry, or a Message.\n */\nimport { Effect, Option, Queue, Schema, Stream } from 'effect'\nimport { defineMessageUnion } from 'foldkit/message'\nimport { defineTaggedUnion } from 'foldkit/schema'\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\n/** The slice of a WebSocket the bundle needs; satisfied by the platform socket and test doubles. Handler events are `any`: the DOM and `ws` type them differently, and only `data` is read. */\nexport interface SocketHandle {\n readonly readyState: number\n send(data: string): void\n close(): void\n onopen: ((event: any) => void) | null\n onmessage: ((event: any) => void) | null\n onclose: ((event: any) => void) | null\n onerror: ((event: any) => void) | null\n}\n\nexport const WebSocketModel = Schema.Struct({\n url: Schema.String,\n status: Schema.Literals(['closed', 'connecting', 'open']),\n lastError: Schema.NullOr(Schema.String),\n /** Whether this connection attempt ever reached open; reset on Connecting. */\n opened: Schema.Boolean,\n})\nexport type WebSocketModel = typeof WebSocketModel.Type\n\nexport const WebSocketMessage = defineMessageUnion({\n Connecting: {},\n Opened: {},\n /** Notifies without storing: project the payload into your own field to keep it. */\n Received: { data: Schema.String },\n Closed: {},\n Failed: { message: Schema.String },\n SendFailed: { message: Schema.String },\n /** Acknowledges dispatch of `data`, not its delivery; update ignores it. */\n Sent: { data: Schema.String },\n /** The socket was still connecting when `connectTimeoutMs` ran out, and was closed. */\n TimedOut: {},\n})\nexport type WebSocketMessage = typeof WebSocketMessage.Type\n\n/** The registry value behind the socket tag: the live socket and its incoming queue. */\nexport interface Acquired {\n readonly socket: SocketHandle\n readonly events: Queue.Queue<WebSocketMessage>\n}\n\n/**\n * What the reader sees: the socket's state, or its error. A page derives\n * this instead of keeping its own connection state machine. `lastError` is\n * already worded for the reader (`Failed to connect to WebSocket`, never the\n * socket's own text, which error handling drops in favor of the sentence).\n */\nexport const SocketView = defineTaggedUnion({\n Disconnected: {},\n Connecting: {},\n Connected: {},\n Error: { error: Schema.String },\n})\nexport type SocketView = typeof SocketView.Type\n\n/**\n * Whether the socket is usable: open with no error outstanding. Gates sends\n * and received frames.\n */\nexport const isOpen = (model: WebSocketModel): boolean =>\n model.status === 'open' && model.lastError === null\n\n/**\n * The view of a socket, and whether its page still wants it. An error stands\n * until the page stops wanting the socket; a retry still waiting for its\n * socket reads as connecting, so it answers at once. An error on an open\n * socket always reads as an error.\n */\nexport const viewOf = (model: WebSocketModel, wanted: boolean): SocketView => {\n if (model.lastError !== null)\n return model.status === 'open' || !wanted\n ? SocketView.Error({ error: model.lastError })\n : SocketView.Connecting()\n if (model.status === 'open') return SocketView.Connected()\n if (model.status === 'connecting' || wanted) return SocketView.Connecting()\n return SocketView.Disconnected()\n}\n\n/** The live connection, for `send` and the incoming stream. One assembly holds one. */\nexport const Socket = ManagedResource.tag<Acquired>()('websocket')\n\n/** The socket service a placed WebSocket's streams and send commands require. */\nexport type SocketService = ManagedResource.ServiceOf<typeof Socket>\n\ntype SocketResources = Readonly<{\n socket: ManagedResource.Entry<\n WebSocketModel,\n WebSocketMessage,\n Option.Option<string>,\n Acquired,\n SocketService,\n () => WebSocketMessage\n >\n}>\n\ntype SendHelpers = Readonly<{\n send: (\n model: WebSocketModel,\n data: string,\n ) => Update.ReturnWithOutMessage<WebSocketModel, WebSocketMessage, never, SocketService>\n}>\n\nconst textOf = (data: unknown): Effect.Effect<string> =>\n typeof data === 'string'\n ? Effect.succeed(data)\n : data instanceof Blob\n ? Effect.promise(() => data.text())\n : data instanceof ArrayBuffer || ArrayBuffer.isView(data)\n ? Effect.succeed(new TextDecoder().decode(data))\n : Effect.succeed(String(data))\n\n/** Closes the socket with its handlers detached first, so the close reports nothing. */\nconst closeSilently = (socket: SocketHandle): void => {\n socket.onopen = null\n socket.onmessage = null\n socket.onclose = null\n socket.onerror = null\n socket.close()\n}\n\nconst failMessage = (error: unknown): string =>\n error instanceof Error ? error.message : String(error)\n\nexport const websocket = <const Name extends string>(config: {\n readonly name: Name\n /** Defaults to the platform WebSocket, read lazily so tests can substitute a double. */\n readonly createSocket?: ((url: string) => SocketHandle) | undefined\n}) => {\n const createSocket: (url: string) => SocketHandle =\n config.createSocket ?? (url => new WebSocket(url) as unknown as SocketHandle)\n return Bundle.make<\n Name,\n WebSocketModel,\n WebSocketMessage,\n { readonly url: string; readonly connectTimeoutMs?: number | undefined },\n never,\n SocketService,\n SocketService,\n void,\n SocketResources,\n SendHelpers\n >(config.name, {\n Model: WebSocketModel,\n Message: WebSocketMessage,\n args: Schema.Struct({\n url: Schema.String,\n /** How long a socket may stay connecting before it is closed as `TimedOut`; unbounded when absent. */\n connectTimeoutMs: Schema.optional(\n Schema.Number.pipe(Schema.check(Schema.isGreaterThan(0)), Schema.check(Schema.isFinite())),\n ),\n }),\n init: (args): Update.Return<WebSocketModel, WebSocketMessage, SocketService> => ({\n model: { url: args.url, status: 'closed', lastError: null, opened: false },\n }),\n update: (\n model,\n message,\n ): Update.ReturnWithOutMessage<WebSocketModel, WebSocketMessage, never, SocketService> =>\n WebSocketMessage.match(message, {\n Connecting: () => ({\n model: unlessSame(model, {\n ...model,\n status: 'connecting',\n lastError: null,\n opened: false,\n }),\n }),\n Opened: () => ({\n model: unlessSame(model, { ...model, status: 'open', lastError: null, opened: true }),\n }),\n Received: () => ({ model }),\n // The close that follows an error, and the release after it, find it closed.\n Closed: () => ({ model: unlessSame(model, { ...model, status: 'closed' }) }),\n // Worded by whether the socket had opened: the socket's own text is\n // dropped in favor of the sentence, as a page would word it.\n Failed: () => ({\n model: unlessSame(model, {\n ...model,\n status: 'closed',\n lastError:\n model.status === 'open' ? 'Connection error' : 'Failed to connect to WebSocket',\n }),\n }),\n SendFailed: () => ({\n model: unlessSame(model, { ...model, lastError: 'Socket unavailable' }),\n }),\n Sent: () => ({ model }),\n TimedOut: () => ({\n model: unlessSame(model, {\n ...model,\n status: 'closed',\n lastError: 'Connection timeout',\n }),\n }),\n }),\n resources: () =>\n ManagedResource.make<WebSocketModel, WebSocketMessage>()(entry => ({\n socket: entry(Schema.Option(Schema.String), {\n resource: Socket,\n modelToMaybeRequirements: model => Option.some(model.url),\n acquire: (url: string) =>\n Effect.gen(function* () {\n const events = yield* Queue.unbounded<WebSocketMessage>()\n const socket = createSocket(url)\n // Offers run in arrival order: an async decode (Blob text) must\n // not overtake a later message. Rejections settle the chain\n // without breaking it; shutdown races are expected at teardown.\n let tail: Promise<void> = Promise.resolve()\n const enqueue = (effect: Effect.Effect<unknown>): void => {\n const run = () =>\n Effect.runPromise(effect).then(\n () => undefined,\n () => undefined,\n )\n tail = tail.then(run, run)\n }\n const offer = (message: WebSocketMessage) => enqueue(Queue.offer(events, message))\n socket.onopen = () => offer(WebSocketMessage.Opened())\n socket.onmessage = event => {\n enqueue(\n Effect.flatMap(textOf(event.data), text =>\n Queue.offer(events, WebSocketMessage.Received({ data: text })),\n ),\n )\n }\n socket.onclose = () => offer(WebSocketMessage.Closed())\n socket.onerror = () =>\n offer(WebSocketMessage.Failed({ message: `websocket error for ${url}` }))\n return { socket, events }\n }),\n onAcquired: () => WebSocketMessage.Connecting(),\n onReleased: () => WebSocketMessage.Closed(),\n onAcquireError: error => WebSocketMessage.Failed({ message: failMessage(error) }),\n // Daemon teardown: close the socket and drain the queue.\n release: ({ socket, events }) =>\n Effect.asVoid(\n Effect.andThen(\n Effect.sync(() => closeSilently(socket)),\n Queue.shutdown(events),\n ),\n ),\n }),\n })),\n subscriptions: ({\n connectTimeoutMs,\n }): Subscription.Subscriptions<WebSocketModel, WebSocketMessage, SocketService> =>\n Subscription.make<WebSocketModel, WebSocketMessage, SocketService>()(entry => ({\n connectTimeout: entry(\n { connecting: Schema.Boolean },\n {\n modelToDependencies: model => ({ connecting: model.status === 'connecting' }),\n dependenciesToStream: ({ connecting }) =>\n !connecting || connectTimeoutMs === undefined\n ? Stream.empty\n : Stream.unwrap(\n Effect.matchEffect(Effect.andThen(Effect.sleep(connectTimeoutMs), Socket.get), {\n // Released while waiting: onReleased reports Closed.\n onFailure: () => Effect.succeed(Stream.empty),\n onSuccess: ({ socket }) =>\n Effect.sync((): Stream.Stream<WebSocketMessage> => {\n // 0 is WebSocket.CONNECTING. An open that beat the\n // timer wins; the handlers go before the close, so\n // the error and close it causes report nothing.\n if (socket.readyState !== 0) return Stream.empty\n closeSilently(socket)\n return Stream.make(WebSocketMessage.TimedOut())\n }),\n }),\n ),\n },\n ),\n incoming: entry(\n // Connecting to open is no reason to restart: the stream reads the\n // same queue, and replays an open it attached too late to see.\n { live: Schema.Boolean },\n {\n modelToDependencies: model => ({ live: model.status !== 'closed' }),\n dependenciesToStream: ({ live }) =>\n !live\n ? Stream.empty\n : Stream.unwrap(\n Effect.matchEffect(Socket.get, {\n // Released between the dependency read and attach: end\n // quietly; onReleased reports Closed through update.\n onFailure: () => Effect.succeed(Stream.empty),\n onSuccess: ({ socket, events }) =>\n Effect.succeed(\n Stream.concat(\n // A fast server opens before the stream attaches; without\n // this the status would stick at connecting while\n // messages flow. 1 is WebSocket.OPEN everywhere.\n socket.readyState === 1\n ? Stream.make(WebSocketMessage.Opened())\n : Stream.empty,\n Stream.fromQueue(events),\n ),\n ),\n }),\n ),\n },\n ),\n })),\n helpers: {\n send: (model, data) => ({\n model,\n commands: [\n {\n name: 'WebSocket.send',\n args: { data },\n effect: Effect.matchEffect(\n Effect.flatMap(Socket.get, ({ socket }) =>\n // A closed socket's send is a silent no-op per spec (only a\n // connecting socket throws), so check first: SendFailed either way.\n socket.readyState === 1\n ? Effect.map(\n Effect.sync(() => {\n socket.send(data)\n }),\n () => WebSocketMessage.Sent({ data }),\n )\n : Effect.fail(\n new Error(\n `cannot send: socket is not open (readyState ${socket.readyState})`,\n ),\n ),\n ),\n {\n onFailure: error =>\n Effect.succeed(WebSocketMessage.SendFailed({ message: failMessage(error) })),\n onSuccess: message => Effect.succeed(message),\n },\n ),\n },\n ],\n }),\n },\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;AAWA,MAAa,mBAAmB,mBAAmB;;CAEjD,UAAU,EAAE,MAAM,OAAO,QAAQ;CACjC,QAAQ,CAAC;CACT,iBAAiB,EAAE,SAAS,OAAO,OAAO;AAC5C,CAAC;AAYD,MAAMA,iBAAe,UACnB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAEvD,MAAM,iBACJ,SACA,SACkC;CAClC,IAAI,YAAY,KAAA,GAAW,OAAO,QAAQ,IAAI;CAC9C,IAAI,OAAO,qBAAqB,aAAa,OAAO;CACpD,OAAO,IAAI,iBAAiB,IAAI;AAClC;;;;;;AAOA,MAAa,qBACX,MAEA,WAEA,OAAO,OACL,OAAO,IAAI,aAAa;CACtB,MAAM,UAAU,cAAc,QAAQ,IAAI;CAC1C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KACE,YAAW,UACT,OAAO,QAAQ,iBAAiB,WAAW,EAAE,SAAS,YAAY,KAAK,EAAE,CAAC,CAAC;KAC7E,YAAW,YAAW,OAAO,QAAQ,OAAO;IAC9C,CACF;GACF,CACF;EACF,GACF;CACF,CAAC;AACH"}
1
+ {"version":3,"file":"index.mjs","names":["failMessage","failMessage"],"sources":["../../src/net/broadcast.ts","../../src/net/online.ts","../../src/net/sharedHost.ts","../../src/net/sse.ts","../../src/net/websocket.ts"],"sourcesContent":["/**\n * Cross-tab messaging as an entry plus a Command — not a bundle, because the\n * channel owns no state: the parent maps `Received` into its own Message and\n * stores whatever it keeps. One assembly may open the same name twice (two\n * listeners); share the entry instead. By spec a post never echoes to its\n * own channel, so a tab never hears itself.\n */\nimport { Effect, Queue, Schema, Stream } from 'effect'\nimport type { Command } from 'foldkit/command'\nimport { defineMessageUnion } from 'foldkit/message'\n\nexport const BroadcastMessage = defineMessageUnion({\n /** Notifies without storing: project the payload into your own field to keep it. */\n Received: { data: Schema.Unknown },\n Posted: {},\n BroadcastFailed: { message: Schema.String },\n})\nexport type BroadcastMessage = typeof BroadcastMessage.Type\n\n/** The slice of a BroadcastChannel this module needs; satisfied by the platform class. */\nexport interface BroadcastChannelHandle {\n postMessage(data: unknown): void\n close(): void\n onmessage: ((event: { readonly data: unknown }) => void) | null\n}\n\ntype ChannelFactory = (name: string) => BroadcastChannelHandle\n\nconst failMessage = (error: unknown): string =>\n error instanceof Error ? error.message : String(error)\n\nconst createChannel = (\n factory: ChannelFactory | undefined,\n name: string,\n): BroadcastChannelHandle | null => {\n if (factory !== undefined) return factory(name)\n if (typeof BroadcastChannel === 'undefined') return null\n return new BroadcastChannel(name) as unknown as BroadcastChannelHandle\n}\n\n/**\n * Every post to `name` from another channel, as Messages. Without a\n * BroadcastChannel API the stream is empty instead of throwing; closing the\n * stream closes the channel.\n */\nexport const broadcastMessages = (\n name: string,\n /** Read lazily so tests can substitute a double, like the SSE bundle. */\n create?: ChannelFactory | undefined,\n): Stream.Stream<BroadcastMessage> =>\n Stream.unwrap(\n Effect.gen(function* () {\n const channel = createChannel(create, name)\n if (channel === null) return Stream.empty\n const queue = yield* Queue.unbounded<BroadcastMessage>()\n channel.onmessage = event => {\n Effect.runFork(Queue.offer(queue, BroadcastMessage.Received({ data: event.data })))\n }\n yield* Effect.addFinalizer(() =>\n Effect.sync(() => {\n channel.onmessage = null\n channel.close()\n }),\n )\n return Stream.fromQueue(queue)\n }),\n )\n\n/**\n * Posts one message to `name`. Opens a channel, posts, and closes it: the\n * send is one-shot, so it is a Command, not a resource. Without a\n * BroadcastChannel API — or when the post throws — it yields\n * `BroadcastFailed` instead of throwing.\n */\nexport const postBroadcast = (\n name: string,\n data: unknown,\n create?: ChannelFactory | undefined,\n): Command<BroadcastMessage, never, never> => ({\n name: 'Broadcast.post',\n args: { name, data },\n // One path for every failure: no factory and no platform API, or a post\n // that throws (a closed channel) all become BroadcastFailed.\n effect: Effect.matchEffect(\n Effect.try({\n try: () => {\n const channel = createChannel(create, name)\n if (channel === null) throw new Error('broadcast is unavailable')\n try {\n channel.postMessage(data)\n } finally {\n channel.close()\n }\n },\n catch: failMessage,\n }),\n {\n onFailure: message => Effect.succeed(BroadcastMessage.BroadcastFailed({ message })),\n onSuccess: () => Effect.succeed(BroadcastMessage.Posted()),\n },\n ),\n})\n","/**\n * Online presence as a bundle: `online` in the Model, kept current by the\n * window's online/offline events. The browser reports facts; the Model owns\n * the state, so presence replays like any other transition.\n */\nimport { Schema, Stream } from 'effect'\nimport { defineMessageUnion } from 'foldkit/message'\nimport * as Subscription from 'foldkit/subscription'\nimport { Bundle } from 'foldkit-bundle'\n\nexport const OnlineModel = Schema.Struct({ online: Schema.Boolean })\nexport type OnlineModel = typeof OnlineModel.Type\n\nexport const OnlineMessage = defineMessageUnion({ Changed: { online: Schema.Boolean } })\nexport type OnlineMessage = typeof OnlineMessage.Type\n\nconst presenceStream = (): Stream.Stream<OnlineMessage> => {\n // No window (SSR): nothing to listen to, so the slice keeps its default.\n if (typeof window === 'undefined') return Stream.empty\n return Stream.mergeAll(\n [\n Stream.fromEventListener(window, 'online').pipe(\n Stream.map(() => OnlineMessage.Changed({ online: true })),\n ),\n Stream.fromEventListener(window, 'offline').pipe(\n Stream.map(() => OnlineMessage.Changed({ online: false })),\n ),\n ],\n { concurrency: 'unbounded' },\n )\n}\n\nexport const Online = Bundle.make('Online', {\n Model: OnlineModel,\n Message: OnlineMessage,\n init: () => ({\n // navigator.onLine is the browser's current answer; true elsewhere (SSR).\n model: {\n online:\n typeof navigator !== 'undefined' && typeof navigator.onLine === 'boolean'\n ? navigator.onLine\n : true,\n },\n }),\n update: (model, message) =>\n message.online === model.online ? { model } : { model: { online: message.online } },\n subscriptions: (): Subscription.Subscriptions<OnlineModel, OnlineMessage> =>\n Subscription.make<OnlineModel, OnlineMessage>()(() => ({\n changes: Subscription.persistent(presenceStream()),\n })),\n})\n","/**\n * One server in the browser for many documents: every tab and frame of an\n * application meets the same host. A page opens conversations, each a\n * `MessagePort` with a decoded opening that says what it is for; the host, in\n * a SharedWorker shared by every tab, or in the top document where there is no\n * SharedWorker, is handed each one with a signal that aborts when the page\n * that opened it is gone.\n *\n * It owns the host's lifetime and the routing of conversations, nothing\n * spoken over them: Sync's `portSocket` and Remote's `port` do that.\n */\nimport { Option, Schema } from 'effect'\n\n/** One conversation a page opened: its port, and a signal that aborts once the page is gone. */\nexport interface Conversation {\n readonly port: MessagePort\n readonly signal: AbortSignal\n}\n\n/** What the host does with each conversation, told what the page opened it for. */\nexport type ConversationHandler<Opening> = (opening: Opening, conversation: Conversation) => void\n\n/** Starts the host, once, the first time a conversation needs it. */\nexport type StartHost<Opening> = () =>\n ConversationHandler<Opening> | Promise<ConversationHandler<Opening>>\n\nexport interface SharedHostOptions<Opening> {\n /**\n * The SharedWorker whose entry calls `serve`. Constructed by the\n * application, since a bundler finds a worker only in a literal\n * `new SharedWorker(new URL('./worker.ts', import.meta.url), …)`.\n */\n readonly worker: () => { readonly port: MessagePort }\n /** The host, for a browser without SharedWorker: started in the top document. */\n readonly inPage: StartHost<Opening>\n}\n\n/** A page's way to the host. */\nexport interface SharedHostConnection<Opening> {\n /** Opens a conversation for `opening`, returning the page's end of it. */\n readonly open: (opening: Opening) => MessagePort\n}\n\nexport interface SharedHost<Opening> {\n readonly name: string\n /** A SharedWorker's entry: hands the host every conversation a page opens. */\n readonly serve: (start: StartHost<Opening>) => void\n /**\n * A page's connection: through the SharedWorker, or, without one, to the\n * host in the top document. Call it in the top document too when that\n * document frames the pages, so that it is the one the frames meet.\n */\n readonly connect: (options: SharedHostOptions<Opening>) => SharedHostConnection<Opening>\n}\n\n/**\n * A shared host: its `name`, which keeps two on one origin apart, and\n * the schema of what opens a conversation, which the host decodes before\n * anything else, ignoring a message that does not decode.\n */\nconst define = <Opening, Encoded>(options: {\n readonly name: string\n readonly opening: Schema.Codec<Opening, Encoded, never, never>\n}): SharedHost<Opening> => {\n const { name } = options\n const Envelope = Schema.Struct({\n host: Schema.Literal(name),\n conversation: Schema.String,\n opening: options.opening,\n })\n const encode = Schema.encodeSync(Envelope)\n const decode = Schema.decodeUnknownOption(Envelope)\n const lockOf = (conversation: string) => `foldkit-shared-host:${name}:${conversation}`\n const marker = `foldkit-shared-host:${name}`\n\n const receive = (\n host: () => Promise<ConversationHandler<Opening>>,\n data: unknown,\n port: MessagePort | undefined,\n ) =>\n Option.match(\n Option.zipWith(decode(data), Option.fromUndefinedOr(port), (envelope, given) => ({\n envelope,\n given,\n })),\n {\n // Not a page's opening, or one without its port: nothing to answer.\n onNone: () => {},\n onSome: ({ envelope, given }) => {\n const ended = new AbortController()\n // The page holds this lock while it lives, so the host is granted it\n // when the page's document unloads or crashes.\n Option.match(locks(), {\n onNone: () => {},\n onSome: held => {\n void held.request(lockOf(envelope.conversation), () => ended.abort())\n },\n })\n void host()\n .then(started => started(envelope.opening, { port: given, signal: ended.signal }))\n .catch(reportError)\n },\n },\n )\n\n const once = (start: StartHost<Opening>): (() => Promise<ConversationHandler<Opening>>) => {\n let started: Promise<ConversationHandler<Opening>> | undefined\n return () => (started ??= Promise.resolve().then(start))\n }\n\n const serve = (start: StartHost<Opening>): void => {\n const host = once(start)\n self.addEventListener('connect', event => {\n if (!(event instanceof MessageEvent)) return\n const [connection] = event.ports\n connection?.addEventListener('message', message =>\n receive(host, message.data, message.ports[0]),\n )\n connection?.start()\n })\n }\n\n const connect = ({\n worker,\n inPage,\n }: SharedHostOptions<Opening>): SharedHostConnection<Opening> => {\n const send = routeOf(worker, inPage)\n return {\n open: opening => {\n const { port1, port2 } = new MessageChannel()\n const conversation = crypto.randomUUID()\n const envelope = encode({ host: name, conversation, opening })\n // The opening goes once the lock is held, so the host cannot be\n // granted it first and end the conversation before it began.\n void hold(lockOf(conversation)).then(() => send(envelope, port2))\n return port1\n },\n }\n }\n\n const routeOf = (\n worker: SharedHostOptions<Opening>['worker'],\n inPage: StartHost<Opening>,\n ): ((envelope: unknown, port: MessagePort) => void) => {\n if (typeof SharedWorker !== 'undefined') {\n const { port } = worker()\n return (envelope, given) => port.postMessage(envelope, [given])\n }\n return Option.match(acceptingTop(marker), {\n onSome: top => (envelope, given) => top.postMessage(envelope, location.origin, [given]),\n onNone: () => {\n const host = once(inPage)\n Reflect.set(window, marker, true)\n window.addEventListener('message', event => {\n if (event.origin === location.origin) receive(host, event.data, event.ports[0])\n })\n return (envelope, given) => receive(host, envelope, given)\n },\n })\n }\n\n return { name, serve, connect }\n}\n\n/** The top document, when it is another of this origin's and runs this host. */\nconst acceptingTop = (marker: string): Option.Option<Window> => {\n const top = window.top\n if (top === null || top === window) return Option.none()\n try {\n return Reflect.get(top, marker) === true ? Option.some(top) : Option.none()\n } catch {\n // Another origin's top document: reading it throws.\n return Option.none()\n }\n}\n\n/** Resolves once this document holds `lock`, which it then holds while it lives. */\nconst hold = (lock: string): Promise<void> =>\n Option.match(locks(), {\n onNone: () => Promise.resolve(),\n onSome: held =>\n new Promise(granted => {\n void held.request(lock, () => {\n granted()\n return new Promise(() => {})\n })\n }),\n })\n\n/** Web Locks, which a page outside a secure context, or an older browser, lacks. */\nconst locks = (): Option.Option<LockManager> => Option.fromUndefinedOr(navigator.locks)\n\nexport const SharedHost = { define }\n","/**\n * Server-sent events as a bundle: connection lifecycle in the Model, the\n * event stream through one Managed Resource. One-directional, so there is no\n * send: the server speaks, the Model listens. The browser reconnects dropped\n * streams itself; a Failed only records the error.\n */\nimport { Effect, Option, Queue, Schema, Stream } from 'effect'\nimport { defineMessageUnion } from 'foldkit/message'\nimport { defineTaggedUnion } from 'foldkit/schema'\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\n/** The slice of an EventSource the bundle needs; satisfied by the platform class. */\nexport interface SourceHandle {\n readonly readyState: number\n close(): void\n onopen: ((event: any) => void) | null\n onmessage: ((event: any) => void) | null\n onerror: ((event: any) => void) | null\n}\n\nexport const SseModel = Schema.Struct({\n url: Schema.String,\n status: Schema.Literals(['closed', 'connecting', 'open']),\n lastError: Schema.NullOr(Schema.String),\n})\nexport type SseModel = typeof SseModel.Type\n\nexport const SseMessage = defineMessageUnion({\n Connecting: {},\n Opened: {},\n /** Notifies without storing: project the payload into your own field to keep it. */\n Received: { data: Schema.String },\n Closed: {},\n Failed: { message: Schema.String },\n})\nexport type SseMessage = typeof SseMessage.Type\n\n/**\n * What the reader sees: the stream's state, or its error. A page derives\n * this instead of keeping its own connection state machine. `lastError`\n * carries the stored failure text: the runtime error sentence (`event stream\n * error for …`) or the acquire error's own message.\n */\nexport const SseView = defineTaggedUnion({\n Disconnected: {},\n Connecting: {},\n Connected: {},\n Error: { error: Schema.String },\n})\nexport type SseView = typeof SseView.Type\n\n/**\n * Whether the stream is live: open with no error outstanding. The browser\n * reconnects a dropped stream itself; a `Failed` only records the error.\n */\nexport const isLive = (model: SseModel): boolean =>\n model.status === 'open' && model.lastError === null\n\n/**\n * The view of a stream, and whether its page still wants it. An error stands\n * until the page stops wanting the stream; a retry still waiting for its\n * stream reads as connecting, so it answers at once.\n */\nexport const viewOfSse = (model: SseModel, wanted: boolean): SseView => {\n if (model.lastError !== null)\n return model.status === 'open' || !wanted\n ? SseView.Error({ error: model.lastError })\n : SseView.Connecting()\n if (model.status === 'open') return SseView.Connected()\n if (model.status === 'connecting' || wanted) return SseView.Connecting()\n return SseView.Disconnected()\n}\n\n/** The registry value behind the source tag: the live source and its incoming queue. */\nexport interface AcquiredSource {\n readonly source: SourceHandle\n readonly events: Queue.Queue<SseMessage>\n}\n\n/** The live stream, for the incoming subscription. One assembly holds one. */\nexport const Source = ManagedResource.tag<AcquiredSource>()('sse')\n\n/** The source service a placed SSE stream requires. */\nexport type SourceService = ManagedResource.ServiceOf<typeof Source>\n\ntype SourceResources = Readonly<{\n source: ManagedResource.Entry<\n SseModel,\n SseMessage,\n Option.Option<string>,\n AcquiredSource,\n SourceService,\n () => SseMessage\n >\n}>\n\nconst failMessage = (error: unknown): string =>\n error instanceof Error ? error.message : String(error)\n\nexport const sse = <const Name extends string>(config: {\n readonly name: Name\n /** Defaults to the platform EventSource, read lazily so tests can substitute a double. */\n readonly createSource?: ((url: string) => SourceHandle) | undefined\n}) => {\n const createSource: (url: string) => SourceHandle =\n config.createSource ?? (url => new EventSource(url) as unknown as SourceHandle)\n return Bundle.make<\n Name,\n SseModel,\n SseMessage,\n { readonly url: string },\n never,\n SourceService,\n SourceService,\n void,\n SourceResources,\n {}\n >(config.name, {\n Model: SseModel,\n Message: SseMessage,\n args: Schema.Struct({ url: Schema.String }),\n init: (args): Update.Return<SseModel, SseMessage, SourceService> => ({\n model: { url: args.url, status: 'closed', lastError: null },\n }),\n update: (\n model,\n message,\n ): Update.ReturnWithOutMessage<SseModel, SseMessage, never, SourceService> =>\n SseMessage.match(message, {\n Connecting: () => ({ model: unlessSame(model, { ...model, status: 'connecting' }) }),\n Opened: () => ({\n model: unlessSame(model, { ...model, status: 'open', lastError: null }),\n }),\n Received: () => ({ model }),\n Closed: () => ({ model: unlessSame(model, { ...model, status: 'closed' }) }),\n // EventSource retries on its own, erroring the same way on every attempt.\n Failed: ({ message }) => ({\n model: unlessSame(model, { ...model, status: 'connecting', lastError: message }),\n }),\n }),\n resources: () =>\n ManagedResource.make<SseModel, SseMessage>()(entry => ({\n source: entry(Schema.Option(Schema.String), {\n resource: Source,\n modelToMaybeRequirements: model => Option.some(model.url),\n acquire: (url: string) =>\n Effect.gen(function* () {\n const events = yield* Queue.unbounded<SseMessage>()\n const source = createSource(url)\n // Offers run in arrival order; see the WebSocket bundle.\n let tail: Promise<void> = Promise.resolve()\n const enqueue = (effect: Effect.Effect<unknown>): void => {\n const run = () =>\n Effect.runPromise(effect).then(\n () => undefined,\n () => undefined,\n )\n tail = tail.then(run, run)\n }\n const offer = (message: SseMessage) => enqueue(Queue.offer(events, message))\n source.onopen = () => offer(SseMessage.Opened())\n // Event data is always text per the SSE spec.\n source.onmessage = event => offer(SseMessage.Received({ data: String(event.data) }))\n source.onerror = () =>\n offer(SseMessage.Failed({ message: `event stream error for ${url}` }))\n return { source, events }\n }),\n onAcquired: () => SseMessage.Connecting(),\n onReleased: () => SseMessage.Closed(),\n onAcquireError: error => SseMessage.Failed({ message: failMessage(error) }),\n // Daemon teardown: close the stream and drain the queue.\n release: ({ source, events }) =>\n Effect.asVoid(\n Effect.andThen(\n Effect.sync(() => {\n source.onopen = null\n source.onmessage = null\n source.onerror = null\n source.close()\n }),\n Queue.shutdown(events),\n ),\n ),\n }),\n })),\n subscriptions: (): Subscription.Subscriptions<SseModel, SseMessage, SourceService> =>\n Subscription.make<SseModel, SseMessage, SourceService>()(entry => ({\n incoming: entry(\n // Connecting to open is no reason to restart: the stream reads the\n // same queue, and replays an open it attached too late to see.\n { live: Schema.Boolean },\n {\n modelToDependencies: model => ({ live: model.status !== 'closed' }),\n dependenciesToStream: ({ live }) =>\n !live\n ? Stream.empty\n : Stream.unwrap(\n Effect.matchEffect(Source.get, {\n // Released between the dependency read and attach: end\n // quietly; onReleased reports Closed through update.\n onFailure: () => Effect.succeed(Stream.empty),\n onSuccess: ({ source, events }) =>\n Effect.succeed(\n Stream.concat(\n // A fast server opens before the stream attaches.\n // 1 is OPEN for EventSource everywhere.\n source.readyState === 1\n ? Stream.make(SseMessage.Opened())\n : Stream.empty,\n Stream.fromQueue(events),\n ),\n ),\n }),\n ),\n },\n ),\n })),\n })\n}\n","/**\n * A WebSocket as a bundle: connection lifecycle in the Model, full duplex\n * through one Managed Resource. The resource owns the socket; a `send`\n * helper writes through its tag service (lifted to the parent like every\n * helper); a subscription stream reads incoming messages through the same\n * tag. No hidden hub: everything the bundle touches is the Model, the\n * resource registry, or a Message.\n */\nimport { Effect, Option, Queue, Schema, Stream } from 'effect'\nimport { defineMessageUnion } from 'foldkit/message'\nimport { defineTaggedUnion } from 'foldkit/schema'\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\n/** The slice of a WebSocket the bundle needs; satisfied by the platform socket and test doubles. Handler events are `any`: the DOM and `ws` type them differently, and only `data` is read. */\nexport interface SocketHandle {\n readonly readyState: number\n send(data: string): void\n close(): void\n onopen: ((event: any) => void) | null\n onmessage: ((event: any) => void) | null\n onclose: ((event: any) => void) | null\n onerror: ((event: any) => void) | null\n}\n\nexport const WebSocketModel = Schema.Struct({\n url: Schema.String,\n status: Schema.Literals(['closed', 'connecting', 'open']),\n lastError: Schema.NullOr(Schema.String),\n /** Whether this connection attempt ever reached open; reset on Connecting. */\n opened: Schema.Boolean,\n})\nexport type WebSocketModel = typeof WebSocketModel.Type\n\nexport const WebSocketMessage = defineMessageUnion({\n Connecting: {},\n Opened: {},\n /** Notifies without storing: project the payload into your own field to keep it. */\n Received: { data: Schema.String },\n Closed: {},\n Failed: { message: Schema.String },\n SendFailed: { message: Schema.String },\n /** Acknowledges dispatch of `data`, not its delivery; update ignores it. */\n Sent: { data: Schema.String },\n /** The socket was still connecting when `connectTimeoutMs` ran out, and was closed. */\n TimedOut: {},\n})\nexport type WebSocketMessage = typeof WebSocketMessage.Type\n\n/** The registry value behind the socket tag: the live socket and its incoming queue. */\nexport interface Acquired {\n readonly socket: SocketHandle\n readonly events: Queue.Queue<WebSocketMessage>\n}\n\n/**\n * What the reader sees: the socket's state, or its error. A page derives\n * this instead of keeping its own connection state machine. `lastError` is\n * already worded for the reader (`Failed to connect to WebSocket`, never the\n * socket's own text, which error handling drops in favor of the sentence).\n */\nexport const SocketView = defineTaggedUnion({\n Disconnected: {},\n Connecting: {},\n Connected: {},\n Error: { error: Schema.String },\n})\nexport type SocketView = typeof SocketView.Type\n\n/**\n * Whether the socket is usable: open with no error outstanding. Gates sends\n * and received frames.\n */\nexport const isOpen = (model: WebSocketModel): boolean =>\n model.status === 'open' && model.lastError === null\n\n/**\n * The view of a socket, and whether its page still wants it. An error stands\n * until the page stops wanting the socket; a retry still waiting for its\n * socket reads as connecting, so it answers at once. An error on an open\n * socket always reads as an error.\n */\nexport const viewOf = (model: WebSocketModel, wanted: boolean): SocketView => {\n if (model.lastError !== null)\n return model.status === 'open' || !wanted\n ? SocketView.Error({ error: model.lastError })\n : SocketView.Connecting()\n if (model.status === 'open') return SocketView.Connected()\n if (model.status === 'connecting' || wanted) return SocketView.Connecting()\n return SocketView.Disconnected()\n}\n\n/** The live connection, for `send` and the incoming stream. One assembly holds one. */\nexport const Socket = ManagedResource.tag<Acquired>()('websocket')\n\n/** The socket service a placed WebSocket's streams and send commands require. */\nexport type SocketService = ManagedResource.ServiceOf<typeof Socket>\n\ntype SocketResources = Readonly<{\n socket: ManagedResource.Entry<\n WebSocketModel,\n WebSocketMessage,\n Option.Option<string>,\n Acquired,\n SocketService,\n () => WebSocketMessage\n >\n}>\n\ntype SendHelpers = Readonly<{\n send: (\n model: WebSocketModel,\n data: string,\n ) => Update.ReturnWithOutMessage<WebSocketModel, WebSocketMessage, never, SocketService>\n}>\n\nconst textOf = (data: unknown): Effect.Effect<string> =>\n typeof data === 'string'\n ? Effect.succeed(data)\n : data instanceof Blob\n ? Effect.promise(() => data.text())\n : data instanceof ArrayBuffer || ArrayBuffer.isView(data)\n ? Effect.succeed(new TextDecoder().decode(data))\n : Effect.succeed(String(data))\n\n/** Closes the socket with its handlers detached first, so the close reports nothing. */\nconst closeSilently = (socket: SocketHandle): void => {\n socket.onopen = null\n socket.onmessage = null\n socket.onclose = null\n socket.onerror = null\n socket.close()\n}\n\nconst failMessage = (error: unknown): string =>\n error instanceof Error ? error.message : String(error)\n\nexport const websocket = <const Name extends string>(config: {\n readonly name: Name\n /** Defaults to the platform WebSocket, read lazily so tests can substitute a double. */\n readonly createSocket?: ((url: string) => SocketHandle) | undefined\n}) => {\n const createSocket: (url: string) => SocketHandle =\n config.createSocket ?? (url => new WebSocket(url) as unknown as SocketHandle)\n return Bundle.make<\n Name,\n WebSocketModel,\n WebSocketMessage,\n { readonly url: string; readonly connectTimeoutMs?: number | undefined },\n never,\n SocketService,\n SocketService,\n void,\n SocketResources,\n SendHelpers\n >(config.name, {\n Model: WebSocketModel,\n Message: WebSocketMessage,\n args: Schema.Struct({\n url: Schema.String,\n /** How long a socket may stay connecting before it is closed as `TimedOut`; unbounded when absent. */\n connectTimeoutMs: Schema.optional(\n Schema.Number.pipe(Schema.check(Schema.isGreaterThan(0)), Schema.check(Schema.isFinite())),\n ),\n }),\n init: (args): Update.Return<WebSocketModel, WebSocketMessage, SocketService> => ({\n model: { url: args.url, status: 'closed', lastError: null, opened: false },\n }),\n update: (\n model,\n message,\n ): Update.ReturnWithOutMessage<WebSocketModel, WebSocketMessage, never, SocketService> =>\n WebSocketMessage.match(message, {\n Connecting: () => ({\n model: unlessSame(model, {\n ...model,\n status: 'connecting',\n lastError: null,\n opened: false,\n }),\n }),\n Opened: () => ({\n model: unlessSame(model, { ...model, status: 'open', lastError: null, opened: true }),\n }),\n Received: () => ({ model }),\n // The close that follows an error, and the release after it, find it closed.\n Closed: () => ({ model: unlessSame(model, { ...model, status: 'closed' }) }),\n // Worded by whether the socket had opened: the socket's own text is\n // dropped in favor of the sentence, as a page would word it.\n Failed: () => ({\n model: unlessSame(model, {\n ...model,\n status: 'closed',\n lastError:\n model.status === 'open' ? 'Connection error' : 'Failed to connect to WebSocket',\n }),\n }),\n SendFailed: () => ({\n model: unlessSame(model, { ...model, lastError: 'Socket unavailable' }),\n }),\n Sent: () => ({ model }),\n TimedOut: () => ({\n model: unlessSame(model, {\n ...model,\n status: 'closed',\n lastError: 'Connection timeout',\n }),\n }),\n }),\n resources: () =>\n ManagedResource.make<WebSocketModel, WebSocketMessage>()(entry => ({\n socket: entry(Schema.Option(Schema.String), {\n resource: Socket,\n modelToMaybeRequirements: model => Option.some(model.url),\n acquire: (url: string) =>\n Effect.gen(function* () {\n const events = yield* Queue.unbounded<WebSocketMessage>()\n const socket = createSocket(url)\n // Offers run in arrival order: an async decode (Blob text) must\n // not overtake a later message. Rejections settle the chain\n // without breaking it; shutdown races are expected at teardown.\n let tail: Promise<void> = Promise.resolve()\n const enqueue = (effect: Effect.Effect<unknown>): void => {\n const run = () =>\n Effect.runPromise(effect).then(\n () => undefined,\n () => undefined,\n )\n tail = tail.then(run, run)\n }\n const offer = (message: WebSocketMessage) => enqueue(Queue.offer(events, message))\n socket.onopen = () => offer(WebSocketMessage.Opened())\n socket.onmessage = event => {\n enqueue(\n Effect.flatMap(textOf(event.data), text =>\n Queue.offer(events, WebSocketMessage.Received({ data: text })),\n ),\n )\n }\n socket.onclose = () => offer(WebSocketMessage.Closed())\n socket.onerror = () =>\n offer(WebSocketMessage.Failed({ message: `websocket error for ${url}` }))\n return { socket, events }\n }),\n onAcquired: () => WebSocketMessage.Connecting(),\n onReleased: () => WebSocketMessage.Closed(),\n onAcquireError: error => WebSocketMessage.Failed({ message: failMessage(error) }),\n // Daemon teardown: close the socket and drain the queue.\n release: ({ socket, events }) =>\n Effect.asVoid(\n Effect.andThen(\n Effect.sync(() => closeSilently(socket)),\n Queue.shutdown(events),\n ),\n ),\n }),\n })),\n subscriptions: ({\n connectTimeoutMs,\n }): Subscription.Subscriptions<WebSocketModel, WebSocketMessage, SocketService> =>\n Subscription.make<WebSocketModel, WebSocketMessage, SocketService>()(entry => ({\n connectTimeout: entry(\n { connecting: Schema.Boolean },\n {\n modelToDependencies: model => ({ connecting: model.status === 'connecting' }),\n dependenciesToStream: ({ connecting }) =>\n !connecting || connectTimeoutMs === undefined\n ? Stream.empty\n : Stream.unwrap(\n Effect.matchEffect(Effect.andThen(Effect.sleep(connectTimeoutMs), Socket.get), {\n // Released while waiting: onReleased reports Closed.\n onFailure: () => Effect.succeed(Stream.empty),\n onSuccess: ({ socket }) =>\n Effect.sync((): Stream.Stream<WebSocketMessage> => {\n // 0 is WebSocket.CONNECTING. An open that beat the\n // timer wins; the handlers go before the close, so\n // the error and close it causes report nothing.\n if (socket.readyState !== 0) return Stream.empty\n closeSilently(socket)\n return Stream.make(WebSocketMessage.TimedOut())\n }),\n }),\n ),\n },\n ),\n incoming: entry(\n // Connecting to open is no reason to restart: the stream reads the\n // same queue, and replays an open it attached too late to see.\n { live: Schema.Boolean },\n {\n modelToDependencies: model => ({ live: model.status !== 'closed' }),\n dependenciesToStream: ({ live }) =>\n !live\n ? Stream.empty\n : Stream.unwrap(\n Effect.matchEffect(Socket.get, {\n // Released between the dependency read and attach: end\n // quietly; onReleased reports Closed through update.\n onFailure: () => Effect.succeed(Stream.empty),\n onSuccess: ({ socket, events }) =>\n Effect.succeed(\n Stream.concat(\n // A fast server opens before the stream attaches; without\n // this the status would stick at connecting while\n // messages flow. 1 is WebSocket.OPEN everywhere.\n socket.readyState === 1\n ? Stream.make(WebSocketMessage.Opened())\n : Stream.empty,\n Stream.fromQueue(events),\n ),\n ),\n }),\n ),\n },\n ),\n })),\n helpers: {\n send: (model, data) => ({\n model,\n commands: [\n {\n name: 'WebSocket.send',\n args: { data },\n effect: Effect.matchEffect(\n Effect.flatMap(Socket.get, ({ socket }) =>\n // A closed socket's send is a silent no-op per spec (only a\n // connecting socket throws), so check first: SendFailed either way.\n socket.readyState === 1\n ? Effect.map(\n Effect.sync(() => {\n socket.send(data)\n }),\n () => WebSocketMessage.Sent({ data }),\n )\n : Effect.fail(\n new Error(\n `cannot send: socket is not open (readyState ${socket.readyState})`,\n ),\n ),\n ),\n {\n onFailure: error =>\n Effect.succeed(WebSocketMessage.SendFailed({ message: failMessage(error) })),\n onSuccess: message => Effect.succeed(message),\n },\n ),\n },\n ],\n }),\n },\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;AAWA,MAAa,mBAAmB,mBAAmB;;CAEjD,UAAU,EAAE,MAAM,OAAO,QAAQ;CACjC,QAAQ,CAAC;CACT,iBAAiB,EAAE,SAAS,OAAO,OAAO;AAC5C,CAAC;AAYD,MAAMA,iBAAe,UACnB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAEvD,MAAM,iBACJ,SACA,SACkC;CAClC,IAAI,YAAY,KAAA,GAAW,OAAO,QAAQ,IAAI;CAC9C,IAAI,OAAO,qBAAqB,aAAa,OAAO;CACpD,OAAO,IAAI,iBAAiB,IAAI;AAClC;;;;;;AAOA,MAAa,qBACX,MAEA,WAEA,OAAO,OACL,OAAO,IAAI,aAAa;CACtB,MAAM,UAAU,cAAc,QAAQ,IAAI;CAC1C,IAAI,YAAY,MAAM,OAAO,OAAO;CACpC,MAAM,QAAQ,OAAO,MAAM,UAA4B;CACvD,QAAQ,aAAY,UAAS;EAC3B,OAAO,QAAQ,MAAM,MAAM,OAAO,iBAAiB,SAAS,EAAE,MAAM,MAAM,KAAK,CAAC,CAAC,CAAC;CACpF;CACA,OAAO,OAAO,mBACZ,OAAO,WAAW;EAChB,QAAQ,YAAY;EACpB,QAAQ,MAAM;CAChB,CAAC,CACH;CACA,OAAO,OAAO,UAAU,KAAK;AAC/B,CAAC,CACH;;;;;;;AAQF,MAAa,iBACX,MACA,M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O,QAAQ,OAAO;IAC9C,CACF;GACF,CACF;EACF,GACF;CACF,CAAC;AACH"}
@@ -61,8 +61,6 @@ export declare const history: <const Name extends string, Value>(config: {
61
61
  }) => Bundle.Bundle<Name, {
62
62
  readonly initial: Value;
63
63
  }, HistoryModel<Value>, {
64
- readonly _tag: "Clear";
65
- } | {
66
64
  readonly _tag: "Push";
67
65
  readonly value: Value;
68
66
  readonly group?: string | undefined;
@@ -73,6 +71,8 @@ export declare const history: <const Name extends string, Value>(config: {
73
71
  } | {
74
72
  readonly _tag: "GoTo";
75
73
  readonly step: number;
74
+ } | {
75
+ readonly _tag: "Clear";
76
76
  }, never, never, never, void, {}, {}> & {
77
77
  Message: import("foldkit/message").MessageUnion<{
78
78
  readonly Push: {
@@ -191,6 +191,8 @@ export declare const isSelected: (model: SelectionSetModel, id: string) => boole
191
191
  export declare const SelectionSet: Bundle.Bundle<"SelectionSet", void, {
192
192
  readonly selected: readonly string[];
193
193
  }, {
194
+ readonly _tag: "Clear";
195
+ } | {
194
196
  readonly _tag: "Select";
195
197
  readonly id: string;
196
198
  } | {
@@ -202,8 +204,6 @@ export declare const SelectionSet: Bundle.Bundle<"SelectionSet", void, {
202
204
  } | {
203
205
  readonly _tag: "ReplaceAll";
204
206
  readonly ids: readonly string[];
205
- } | {
206
- readonly _tag: "Clear";
207
207
  }, never, never, never, void, {}, {}>;
208
208
  //#endregion
209
209
  //#region src/state/virtual.d.ts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "foldkit-primitives",
3
- "version": "0.4.0",
3
+ "version": "0.6.0",
4
4
  "description": "Ready-made primitives for the Elm architecture, packaged with foldkit-bundle: media queries, presence, timers, pagination, history, sockets, observers, clipboard, and interaction Bundles with their Behaviors.",
5
5
  "keywords": [
6
6
  "foldkit",
@@ -89,23 +89,23 @@
89
89
  "LICENSE"
90
90
  ],
91
91
  "dependencies": {
92
- "foldkit-bundle": "0.4.0"
92
+ "foldkit-bundle": "0.5.0"
93
93
  },
94
94
  "peerDependencies": {
95
- "effect": ">=4.0.0-rc.116 <4.0.0-rc.118",
96
- "foldkit": "^0.163.0",
97
- "foldkit-mixins": "^0.5.0"
95
+ "effect": "^4.0.0",
96
+ "foldkit": "^0.165.0",
97
+ "foldkit-mixins": "^0.7.0"
98
98
  },
99
99
  "devDependencies": {
100
- "@effect/platform-browser": "4.0.0-rc.116",
100
+ "@effect/platform-browser": "4.0.0",
101
101
  "@types/ws": "^8.5.12",
102
- "effect": "4.0.0-rc.116",
103
- "foldkit": "0.163.0",
102
+ "effect": "4.0.0",
103
+ "foldkit": "0.165.0",
104
104
  "jsdom": "26.1.0",
105
105
  "tsdown": "^0.23.0",
106
106
  "typescript": "5.9.3",
107
107
  "ws": "^8.18.0",
108
- "foldkit-mixins": "0.5.0"
108
+ "foldkit-mixins": "0.7.0"
109
109
  },
110
110
  "peerDependenciesMeta": {
111
111
  "foldkit-mixins": {
@@ -1 +0,0 @@
1
- {"version":3,"file":"follow-tab-stop-DpxwLXvU.mjs","names":[],"sources":["../src/dom/focus-scope.ts","../src/dom/layers.ts","../src/dom/move.ts","../src/dom/targets.ts","../src/dom/pointer-drag.ts","../src/dom/editable-text.ts","../src/dom/follow-tab-stop.ts"],"sourcesContent":["/**\n * A focus scope as a Mount: on insert it remembers what was focused, focuses\n * an initial element inside, and with `contain` keeps Tab and Shift+Tab\n * cycling inside; on unmount it gives focus back. Nothing crosses to the\n * Model: which element had focus is a DOM fact, so this is element lifecycle,\n * not state. It emits no Messages.\n */\nimport { Effect, Schema, Stream } from 'effect'\nimport * as Mount from 'foldkit/mount'\n\nconst FOCUSABLE = [\n 'a[href]',\n 'button:not([disabled])',\n 'input:not([disabled]):not([type=\"hidden\"])',\n 'select:not([disabled])',\n 'textarea:not([disabled])',\n '[tabindex]',\n '[contenteditable=\"true\"]',\n].join(', ')\n\nconst isVisible = (element: Element): boolean => {\n const probe = element as { checkVisibility?: () => boolean }\n return element.closest('[hidden], [inert]') === null && (probe.checkVisibility?.() ?? true)\n}\n\n/** Tabbable descendants in DOM order: focusable, visible, and not `tabindex=\"-1\"`. */\nexport const tabbableWithin = (root: Element): ReadonlyArray<HTMLElement> =>\n Array.from(root.querySelectorAll<HTMLElement>(FOCUSABLE)).filter(\n element => element.tabIndex >= 0 && isVisible(element),\n )\n\nconst focusFirst = (elements: ReadonlyArray<HTMLElement>): boolean => {\n const first = elements[0]\n if (first === undefined) return false\n first.focus()\n return true\n}\n\nexport const FocusScope = Mount.defineStream('FocusScope', {\n messages: [Schema.Never],\n args: {\n /** Keep Tab, Shift+Tab, and a stray focus inside. */\n contain: Schema.Boolean,\n /** Give focus back to what had it, on unmount. */\n restore: Schema.Boolean,\n /** A selector inside the element to focus first; else the first tabbable\n * descendant, else the element itself when it is focusable. */\n initialFocus: Schema.NullOr(Schema.String),\n },\n execute: ({ element, contain, restore, initialFocus }) =>\n Stream.callback<never>(() =>\n Effect.acquireRelease(\n Effect.sync(() => {\n const ownerDocument = element.ownerDocument\n const previous = ownerDocument.activeElement\n const initial =\n initialFocus === null ? null : element.querySelector<HTMLElement>(initialFocus)\n if (initial !== null) initial.focus()\n else if (!focusFirst(tabbableWithin(element)) && element instanceof HTMLElement) {\n element.focus()\n }\n const onKeyDown = (event: Event) => {\n const key = event as KeyboardEvent\n if (key.key !== 'Tab') return\n const tabbable = tabbableWithin(element)\n const first = tabbable[0]\n const last = tabbable[tabbable.length - 1]\n if (first === undefined || last === undefined) {\n key.preventDefault()\n return\n }\n const active = ownerDocument.activeElement\n if (key.shiftKey && (active === first || !element.contains(active))) {\n key.preventDefault()\n last.focus()\n } else if (!key.shiftKey && (active === last || !element.contains(active))) {\n key.preventDefault()\n first.focus()\n }\n }\n const onFocusIn = (event: Event) => {\n const target = event.target\n if (target instanceof Node && element.contains(target)) return\n focusFirst(tabbableWithin(element))\n }\n if (contain) {\n element.addEventListener('keydown', onKeyDown)\n ownerDocument.addEventListener('focusin', onFocusIn)\n }\n return { previous, onKeyDown, onFocusIn, ownerDocument }\n }),\n ({ previous, onKeyDown, onFocusIn, ownerDocument }) =>\n Effect.sync(() => {\n if (contain) {\n element.removeEventListener('keydown', onKeyDown)\n ownerDocument.removeEventListener('focusin', onFocusIn)\n }\n if (restore && previous instanceof HTMLElement && ownerDocument.contains(previous)) {\n previous.focus()\n }\n }),\n ),\n ),\n})\n","/**\n * Two Mounts over Foldkit's own DOM helpers, for an overlay that is not a\n * native `<dialog>` or `popover`:\n *\n * - `ScrollLock` locks the document's scroll while mounted. Foldkit's lock is\n * refcounted, so nested overlays release it only when the last one goes.\n * - `HideOutside` marks everything outside the element inert while mounted,\n * through `Dom.inertOthers`, keyed by an id this Mount mints.\n *\n * Both emit no Messages; they are element lifecycle.\n */\nimport { Effect, Schema, Stream } from 'effect'\nimport * as Dom from 'foldkit/dom'\nimport * as Mount from 'foldkit/mount'\n\nexport const ScrollLock = Mount.defineStream('ScrollLock', {\n messages: [Schema.Never],\n execute: () =>\n Stream.callback<never>(() => Effect.acquireRelease(Dom.lockScroll, () => Dom.unlockScroll)),\n})\n\nconst HIDE_OUTSIDE_ATTRIBUTE = 'data-foldkit-plus-hide-outside'\n\nlet minted = 0\n\nexport const HideOutside = Mount.defineStream('HideOutside', {\n messages: [Schema.Never],\n execute: ({ element }) =>\n Stream.callback<never>(() =>\n Effect.acquireRelease(\n Effect.gen(function* () {\n // A per-mount id: Foldkit keys the inert set by it, so two overlays\n // restore independently. The attribute is how the element is found.\n const id = `hide-outside-${(minted += 1)}`\n element.setAttribute(HIDE_OUTSIDE_ATTRIBUTE, id)\n yield* Dom.inertOthers(id, [`[${HIDE_OUTSIDE_ATTRIBUTE}=\"${id}\"]`])\n return id\n }),\n id =>\n Effect.andThen(Dom.restoreInert(id), () =>\n Effect.sync(() => element.removeAttribute(HIDE_OUTSIDE_ATTRIBUTE)),\n ),\n ),\n ),\n})\n","/**\n * Pointer movement on an element as a Mount: a primary-button pointer down\n * captures the pointer, each move reports the delta from where it started,\n * and up, cancel, or lost capture ends it. Nothing is decided here: a drag\n * threshold, a snap, or a constraint is the parent's `update`. Capture is\n * released with the Mount.\n */\nimport { Effect, Queue, Schema, Stream } from 'effect'\nimport * as Mount from 'foldkit/mount'\n\nexport const MoveStarted = Schema.TaggedStruct('MoveStarted', {\n pointerId: Schema.Number,\n pointerType: Schema.String,\n})\nexport type MoveStarted = typeof MoveStarted.Type\n\nexport const Moved = Schema.TaggedStruct('Moved', {\n pointerId: Schema.Number,\n /** From where the pointer went down, in CSS pixels. */\n deltaX: Schema.Number,\n deltaY: Schema.Number,\n pointerType: Schema.String,\n})\nexport type Moved = typeof Moved.Type\n\nexport const MoveEnded = Schema.TaggedStruct('MoveEnded', {\n pointerId: Schema.Number,\n /** `false` when the pointer was cancelled or capture was lost. */\n completed: Schema.Boolean,\n})\nexport type MoveEnded = typeof MoveEnded.Type\n\nexport type Fact = MoveStarted | Moved | MoveEnded\n\ntype PointerLike = Event & {\n readonly pointerId?: number\n readonly button?: number\n readonly pointerType?: string\n readonly clientX?: number\n readonly clientY?: number\n}\n\ntype Capturing = Element & {\n setPointerCapture?: (pointerId: number) => void\n releasePointerCapture?: (pointerId: number) => void\n}\n\nexport const Move = Mount.defineStream('Move', {\n messages: [MoveStarted, Moved, MoveEnded],\n execute: ({ element }) =>\n Stream.callback<Fact>(queue =>\n Effect.acquireRelease(\n Effect.sync(() => {\n const target = element as Capturing\n let active: {\n readonly pointerId: number\n readonly x: number\n readonly y: number\n } | null = null\n const offer = (fact: Fact) => Queue.offerUnsafe(queue, fact)\n const end = (pointerId: number, completed: boolean) => {\n if (active === null || active.pointerId !== pointerId) return\n active = null\n try {\n target.releasePointerCapture?.(pointerId)\n } catch {\n // Capture may already be gone; the end is still reported.\n }\n offer(MoveEnded.make({ pointerId, completed }))\n }\n const listeners: ReadonlyArray<readonly [string, (event: Event) => void]> = [\n [\n 'pointerdown',\n event => {\n const pointer = event as PointerLike\n if ((pointer.button ?? 0) !== 0 || active !== null) return\n const pointerId = pointer.pointerId ?? 0\n active = { pointerId, x: pointer.clientX ?? 0, y: pointer.clientY ?? 0 }\n try {\n target.setPointerCapture?.(pointerId)\n } catch {\n // Without capture the move still reports while over the element.\n }\n offer(MoveStarted.make({ pointerId, pointerType: pointer.pointerType ?? 'mouse' }))\n },\n ],\n [\n 'pointermove',\n event => {\n const pointer = event as PointerLike\n const pointerId = pointer.pointerId ?? 0\n if (active === null || active.pointerId !== pointerId) return\n offer(\n Moved.make({\n pointerId,\n deltaX: (pointer.clientX ?? 0) - active.x,\n deltaY: (pointer.clientY ?? 0) - active.y,\n pointerType: pointer.pointerType ?? 'mouse',\n }),\n )\n },\n ],\n ['pointerup', event => end((event as PointerLike).pointerId ?? 0, true)],\n ['pointercancel', event => end((event as PointerLike).pointerId ?? 0, false)],\n ['lostpointercapture', event => end((event as PointerLike).pointerId ?? 0, false)],\n ]\n for (const [type, listener] of listeners) element.addEventListener(type, listener)\n return { listeners, current: () => active }\n }),\n ({ listeners, current }) =>\n Effect.sync(() => {\n for (const [type, listener] of listeners) element.removeEventListener(type, listener)\n const pointer = current()\n if (pointer !== null) {\n try {\n ;(element as Capturing).releasePointerCapture?.(pointer.pointerId)\n } catch {\n // Already released.\n }\n }\n }),\n ),\n ),\n})\n","/**\n * Which marked descendant of an element the pointer is over, and which one was\n * pressed, as a Mount: one set of listeners on the container, not one per item.\n * A descendant is marked by an attribute whose value is its id, such as a\n * canvas's `data-composition-node` or a table's `data-row`. The nearest marked\n * ancestor of the event's target, inside the container, is the one reported.\n *\n * What hovering or pressing means (a selection, an outline, a menu) is the\n * parent's `update`.\n */\nimport { Effect, Queue, Schema, Stream } from 'effect'\nimport * as Mount from 'foldkit/mount'\n\nexport const TargetHovered = Schema.TaggedStruct('TargetHovered', {\n /** The marked descendant under the pointer, or `null` when there is none. */\n id: Schema.NullOr(Schema.String),\n})\nexport type TargetHovered = typeof TargetHovered.Type\n\nexport const TargetPressed = Schema.TaggedStruct('TargetPressed', {\n id: Schema.String,\n shiftKey: Schema.Boolean,\n altKey: Schema.Boolean,\n ctrlKey: Schema.Boolean,\n metaKey: Schema.Boolean,\n})\nexport type TargetPressed = typeof TargetPressed.Type\n\nexport type TargetFact = TargetHovered | TargetPressed\n\ntype Modified = Event & {\n readonly shiftKey?: boolean\n readonly altKey?: boolean\n readonly ctrlKey?: boolean\n readonly metaKey?: boolean\n}\n\n/** The id of the nearest marked element at or above `from`, inside `container`. */\nexport const targetOf = (container: Element, from: EventTarget | null, attribute: string) => {\n if (!(from instanceof Element)) return null\n const marked = from.closest(`[${attribute}]`)\n return marked !== null && container.contains(marked) ? marked.getAttribute(attribute) : null\n}\n\nexport const Targets = Mount.defineStream('Targets', {\n messages: [TargetHovered, TargetPressed],\n args: {\n /** The attribute that marks a descendant, holding its id. */\n attribute: Schema.String,\n /** Prevent a press's default, such as a link navigating inside an editor's canvas. */\n preventDefault: Schema.Boolean,\n },\n execute: ({ element, attribute, preventDefault }) =>\n Stream.callback<TargetFact>(queue =>\n Effect.acquireRelease(\n Effect.sync(() => {\n let hovered: string | null = null\n const hover = (id: string | null) => {\n if (id === hovered) return\n hovered = id\n Queue.offerUnsafe(queue, TargetHovered.make({ id }))\n }\n const listeners: ReadonlyArray<readonly [string, (event: Event) => void]> = [\n ['pointerover', event => hover(targetOf(element, event.target, attribute))],\n ['pointerleave', () => hover(null)],\n [\n 'click',\n event => {\n const id = targetOf(element, event.target, attribute)\n if (id === null) return\n if (preventDefault) event.preventDefault()\n const modified = event as Modified\n Queue.offerUnsafe(\n queue,\n TargetPressed.make({\n id,\n shiftKey: modified.shiftKey === true,\n altKey: modified.altKey === true,\n ctrlKey: modified.ctrlKey === true,\n metaKey: modified.metaKey === true,\n }),\n )\n },\n ],\n ]\n for (const [type, listener] of listeners) element.addEventListener(type, listener)\n return listeners\n }),\n listeners =>\n Effect.sync(() => {\n for (const [type, listener] of listeners) element.removeEventListener(type, listener)\n }),\n ),\n ),\n})\n","/**\n * Dragging one marked descendant of an element onto another, as a Mount. A\n * descendant is marked by an attribute whose value is its id, as `Targets`\n * marks them; a press on one that then moves past a threshold starts a drag,\n * and the pointer's place over another marked descendant is reported with the\n * zone of it the pointer is in: its first third (`before`), its middle\n * (`inside`), or its last third (`after`). Releasing drops, and Escape or a\n * cancelled pointer ends the drag with nothing dropped.\n *\n * It writes no roles, no `tabindex` and no key handling, so the marked\n * elements can be anything: a tree's rows, a canvas's nodes. The keyboard's way\n * to do what a drag does is the parent's to give. Geometry is measured when the\n * pointer moves and never kept; what a drop means is the parent's `update`.\n */\nimport { Effect, Queue, Schema, Stream } from 'effect'\nimport * as Mount from 'foldkit/mount'\nimport { targetOf } from './targets.js'\n\nexport const DragZone = Schema.Literals(['before', 'inside', 'after'])\nexport type DragZone = typeof DragZone.Type\n\n/** A marked descendant under the pointer, and the zone of it the pointer is in. */\nexport const DragPlace = Schema.Struct({ id: Schema.String, zone: DragZone })\nexport type DragPlace = typeof DragPlace.Type\n\nexport const DragStarted = Schema.TaggedStruct('DragStarted', {\n /** The marked descendant being dragged. */\n id: Schema.String,\n})\nexport type DragStarted = typeof DragStarted.Type\n\nexport const DraggedOver = Schema.TaggedStruct('DraggedOver', {\n /** Where the pointer is, or `null` over nothing marked, or over what is dragged. */\n over: Schema.NullOr(DragPlace),\n /**\n * For a drag onto `targets`: whether the pointer is inside the region they\n * are in, so `over: null` with `region: true` is its empty space (an empty\n * page, the space below the last node). Absent for a drag among its own.\n */\n region: Schema.optionalKey(Schema.Boolean),\n})\nexport type DraggedOver = typeof DraggedOver.Type\n\nexport const DragDropped = Schema.TaggedStruct('DragDropped', {\n id: Schema.String,\n over: Schema.NullOr(DragPlace),\n /** As `DraggedOver`'s: released inside the `targets` region. */\n region: Schema.optionalKey(Schema.Boolean),\n})\nexport type DragDropped = typeof DragDropped.Type\n\nexport const DragCancelled = Schema.TaggedStruct('DragCancelled', { id: Schema.String })\nexport type DragCancelled = typeof DragCancelled.Type\n\nexport type DragFact = DragStarted | DraggedOver | DragDropped | DragCancelled\n\n/** How far, in CSS pixels, a press moves before it is a drag rather than a click. */\nexport const DRAG_THRESHOLD = 4\n\ninterface Box {\n readonly top: number\n readonly height: number\n}\n\n/** The zone of a box a vertical position falls in, by thirds. */\nexport const zoneOf = (box: Box, y: number): DragZone => {\n if (box.height <= 0) return 'inside'\n const at = (y - box.top) / box.height\n return at < 1 / 3 ? 'before' : at > 2 / 3 ? 'after' : 'inside'\n}\n\n/**\n * An element's box. An element drawn as `display: contents` has none, so its\n * first child's stands for it, as an editor's node wrapper's does.\n */\nexport const boxOf = (element: Element): Box => {\n const own = element.getBoundingClientRect()\n if (own.width > 0 || own.height > 0) return own\n const child = element.firstElementChild\n return child === null ? own : boxOf(child)\n}\n\ntype Positioned = Event & {\n readonly clientX?: number\n readonly clientY?: number\n readonly button?: number\n readonly buttons?: number\n readonly pointerId?: number\n readonly key?: string\n}\n\nexport const PointerDrag = Mount.defineStream('PointerDrag', {\n messages: [DragStarted, DraggedOver, DragDropped, DragCancelled],\n args: {\n /** The attribute that marks a descendant, holding its id. */\n attribute: Schema.String,\n /**\n * Where a drag may land, when not on the element's own marked descendants:\n * the elements marked by `attribute` inside the one `within` selects, such\n * as a palette's Blocks dragged onto a page. A drop's `over` is then one of\n * those; what is dragged is still one of the element's own. `within` is\n * looked for nearest first, under the element's closest ancestor that holds\n * a match, so two editors on one page each drop onto their own.\n */\n targets: Schema.optionalKey(Schema.Struct({ attribute: Schema.String, within: Schema.String })),\n },\n execute: ({ element, attribute, targets }) =>\n Stream.callback<DragFact>(queue =>\n Effect.acquireRelease(\n Effect.sync(() => {\n const owner = element.ownerDocument\n // What a drop lands on: the element's own marked descendants, or those of `targets`.\n const landsOn = targets?.attribute ?? attribute\n // Looked for at each move, so a redraw that replaced it is followed.\n const regionOf = (within: string): Element | null => {\n for (let at = element.parentElement; at !== null; at = at.parentElement) {\n const found = at.querySelector(within)\n if (found !== null) return found\n }\n return null\n }\n const find = (from: EventTarget | null) => {\n if (!(from instanceof Element)) return { marked: null, inRegion: false }\n const region = targets === undefined ? element : regionOf(targets.within)\n const marked = from.closest(`[${landsOn}]`)\n return {\n marked: marked !== null && region !== null && region.contains(marked) ? marked : null,\n // Only a drag onto `targets` tells its region's empty space from elsewhere.\n inRegion: targets !== undefined && region !== null && region.contains(from),\n }\n }\n // A press not yet a drag, or a drag under way: one pointer's, the first down.\n let pressed: {\n readonly id: string\n readonly pointer: number | undefined\n readonly x: number\n readonly y: number\n } | null = null\n let dragging: string | null = null\n let over: DragPlace | null = null\n let inRegion = false\n // The click that ends a drag is not a press on what it ends over.\n let swallowClick = false\n\n const placeAt = (event: Positioned) => {\n // Touch and pen capture the pointer to where it went down, so the\n // event's target is the dragged element: ask what is under it instead.\n const under =\n typeof owner.elementFromPoint === 'function' && event.clientX !== undefined\n ? owner.elementFromPoint(event.clientX, event.clientY ?? 0)\n : null\n const { marked, inRegion: region } = find(under ?? event.target)\n const id = marked?.getAttribute(landsOn) ?? null\n // Over itself is over nothing, where what is dragged is among what it lands on.\n const place: DragPlace | null =\n marked === null || id === null || (targets === undefined && id === dragging)\n ? null\n : { id, zone: zoneOf(boxOf(marked), event.clientY ?? 0) }\n return { place, region }\n }\n /** The region flag a fact carries: only for a drag onto `targets`. */\n const withRegion = (region: boolean) => (targets === undefined ? {} : { region })\n const ours = (event: Positioned) =>\n pressed !== null &&\n (pressed.pointer === undefined || event.pointerId === pressed.pointer)\n // `inside`: the release was on the container, so its click will reach it.\n const end = (dropped: boolean, inside = false) => {\n const id = dragging\n pressed = null\n dragging = null\n const last = over\n const lastRegion = inRegion\n over = null\n inRegion = false\n release()\n if (id === null) return\n swallowClick = dropped && inside\n Queue.offerUnsafe(\n queue,\n dropped\n ? DragDropped.make({ id, over: last, ...withRegion(lastRegion) })\n : DragCancelled.make({ id }),\n )\n }\n\n const onDocument: ReadonlyArray<readonly [string, (event: Event) => void]> = [\n [\n 'pointermove',\n event => {\n const positioned = event as Positioned\n if (!ours(positioned) || pressed === null) return\n // Released where no pointerup reached us, such as over a frame.\n if (positioned.buttons !== undefined && (positioned.buttons & 1) === 0)\n return end(false)\n if (dragging === null) {\n const moved = Math.hypot(\n (positioned.clientX ?? 0) - pressed.x,\n (positioned.clientY ?? 0) - pressed.y,\n )\n if (moved < DRAG_THRESHOLD) return\n dragging = pressed.id\n owner.getSelection()?.removeAllRanges()\n Queue.offerUnsafe(queue, DragStarted.make({ id: dragging }))\n }\n const { place, region } = placeAt(positioned)\n if (place?.id === over?.id && place?.zone === over?.zone && region === inRegion)\n return\n over = place\n inRegion = region\n Queue.offerUnsafe(queue, DraggedOver.make({ over: place, ...withRegion(region) }))\n },\n ],\n [\n 'pointerup',\n event => {\n if (!ours(event as Positioned)) return\n if (dragging === null) end(false)\n else end(true, event.target instanceof Node && element.contains(event.target))\n },\n ],\n [\n 'pointercancel',\n event => {\n if (ours(event as Positioned)) end(false)\n },\n ],\n ]\n // Heard on the way down, and kept there: an Escape that ends a drag is the\n // drag's, not also the focused element's (a canvas that would deselect).\n const onEscape = (event: Event) => {\n if (pressed === null || (event as Positioned).key !== 'Escape') return\n event.preventDefault()\n event.stopPropagation()\n end(false)\n }\n // The document is listened to only while a press is under way.\n let listening = false\n const listen = () => {\n if (listening) return\n listening = true\n for (const [type, listener] of onDocument) owner.addEventListener(type, listener)\n owner.addEventListener('keydown', onEscape, true)\n }\n const release = () => {\n if (!listening) return\n listening = false\n for (const [type, listener] of onDocument) owner.removeEventListener(type, listener)\n owner.removeEventListener('keydown', onEscape, true)\n }\n\n const onElement: ReadonlyArray<readonly [string, (event: Event) => void, boolean]> = [\n [\n 'pointerdown',\n event => {\n const positioned = event as Positioned\n // Any press is past the drop a swallowed click was waiting for.\n swallowClick = false\n // A second pointer while one is down is not a new drag.\n if (pressed !== null) return\n if ((positioned.button ?? 0) !== 0) return\n // A press in text being edited selects text: it is no drag.\n if (\n event.target instanceof Element &&\n event.target.closest('[contenteditable]:not([contenteditable=\"false\"])') !== null\n )\n return\n const id = targetOf(element, event.target, attribute)\n if (id === null) return\n pressed = {\n id,\n pointer: positioned.pointerId,\n x: positioned.clientX ?? 0,\n y: positioned.clientY ?? 0,\n }\n listen()\n },\n false,\n ],\n [\n 'click',\n event => {\n if (!swallowClick) return\n swallowClick = false\n event.preventDefault()\n event.stopImmediatePropagation()\n },\n true,\n ],\n // A link or an image would start the browser's own drag instead.\n ['dragstart', event => event.preventDefault(), false],\n ]\n for (const [type, listener, capture] of onElement)\n element.addEventListener(type, listener, capture)\n return { onElement, release }\n }),\n ({ onElement, release }) =>\n Effect.sync(() => {\n for (const [type, listener, capture] of onElement)\n element.removeEventListener(type, listener, capture)\n release()\n }),\n ),\n ),\n})\n","/**\n * Text typed into an editable descendant of an element, as a Mount: one set of\n * listeners on the container, like `Targets`. A field is a descendant marked\n * by an attribute whose value names it, while it is `contenteditable`. The\n * view decides which one is; the Mount focuses it as it becomes so (made\n * editable, or drawn editable), with the caret at its end, and at no other\n * time. When Enter or Escape ends an edit and the view then removes the field\n * or makes it no longer editable, focus, left on nothing, comes back to the\n * container, so the next key reaches it; give the container a `tabindex`. A double-click on a marked field that is not editable yet asks for it\n * to be (`EditAsked`).\n *\n * It reads `innerText`, never `innerHTML`, so what arrives is text. A field is\n * one line unless it carries `aria-multiline=\"true\"`: in one line, a line\n * break becomes a space. Nothing is reported while an input method composes;\n * the composed text arrives once, when it is done.\n *\n * Enter commits (Shift+Enter breaks a line in a multiline field), and so does\n * leaving the field. Escape cancels, and puts the text the field had when\n * editing began back in the DOM, since a view that stopped redrawing the field\n * while it was edited will not. Where the browser lacks `plaintext-only`, a\n * paste is inserted as text. What an edit means is the parent's `update`.\n */\nimport { Effect, Queue, Schema, Stream } from 'effect'\nimport * as Mount from 'foldkit/mount'\n\nexport const TextEdited = Schema.TaggedStruct('TextEdited', {\n /** The field, by its marking attribute's value. */\n field: Schema.String,\n text: Schema.String,\n})\nexport type TextEdited = typeof TextEdited.Type\n\nexport const TextCommitted = Schema.TaggedStruct('TextCommitted', {\n field: Schema.String,\n text: Schema.String,\n})\nexport type TextCommitted = typeof TextCommitted.Type\n\nexport const TextCancelled = Schema.TaggedStruct('TextCancelled', {\n field: Schema.String,\n /** The text the field had when editing began, which the DOM shows again. */\n initial: Schema.String,\n})\nexport type TextCancelled = typeof TextCancelled.Type\n\nexport const EditAsked = Schema.TaggedStruct('EditAsked', {\n /** A marked field, not editable yet, that was double-clicked. */\n field: Schema.String,\n})\nexport type EditAsked = typeof EditAsked.Type\n\nexport type TextFact = TextEdited | TextCommitted | TextCancelled | EditAsked\n\n/** Whether a field takes more than one line. */\nconst multiline = (element: HTMLElement) => element.getAttribute('aria-multiline') === 'true'\n\n/**\n * A field's text. A browser ends an edited element with a line break it adds\n * itself, which is not the author's; in one line, the author's breaks are spaces.\n */\nexport const textOf = (element: HTMLElement): string => {\n const text = element.innerText.replace(/\\r\\n?/g, '\\n').replace(/\\n$/, '')\n return multiline(element) ? text : text.replace(/\\n+/g, ' ')\n}\n\n/** Puts the caret at the end of a field, which focuses it too. */\nconst caretAtEnd = (field: HTMLElement) => {\n // Chromium also focuses on the selection below; no standard says a browser must.\n field.focus()\n const caret = document.createRange()\n caret.selectNodeContents(field)\n caret.collapse(false)\n const selection = window.getSelection()\n selection?.removeAllRanges()\n selection?.addRange(caret)\n}\n\n/** Whether a key press belongs to an input method still composing, not to the field. */\nconst composing = (event: KeyboardEvent) => event.isComposing || event.keyCode === 229\n\nexport const EditableText = Mount.defineStream('EditableText', {\n messages: [TextEdited, TextCommitted, TextCancelled, EditAsked],\n args: {\n /** The attribute that marks a field, holding its name. */\n attribute: Schema.String,\n },\n execute: ({ element, attribute }) =>\n Stream.callback<TextFact>(queue =>\n Effect.acquireRelease(\n Effect.sync(() => {\n /** The field being edited: its name, its text when editing began, and the last reported. */\n let current:\n | {\n readonly field: HTMLElement\n readonly name: string\n readonly initial: string\n reported: string\n ended: boolean\n }\n | undefined\n let composingText = false\n // A field whose edit a key ended: when it leaves with focus on nothing, focus\n // comes back to the container, where the keys that began the edit are.\n let ending: HTMLElement | undefined\n\n /** The marked field at or above an event's target, inside the container. */\n const markedOf = (target: EventTarget | null): HTMLElement | undefined => {\n if (!(target instanceof Element)) return undefined\n const field = target.closest(`[${attribute}]`)\n return field instanceof HTMLElement && element.contains(field) ? field : undefined\n }\n /** The same, while it is editable. */\n const fieldOf = (target: EventTarget | null): HTMLElement | undefined => {\n const field = markedOf(target)\n return field?.isContentEditable === true ? field : undefined\n }\n /** Begins an edit of `field`, unless one of it is under way: on focus, or typing. */\n const begin = (field: HTMLElement) => {\n if (current?.field === field && !current.ended) return current\n const text = textOf(field)\n current = {\n field,\n name: field.getAttribute(attribute) ?? '',\n initial: text,\n reported: text,\n ended: false,\n }\n return current\n }\n /**\n * The edit of `field`: the one under way or just ended, else one begun\n * now, for a field focused before these listeners came. An ended edit\n * reports nothing more, so the blur that follows a commit or a cancel\n * does not commit again.\n */\n const editOf = (field: HTMLElement) => (current?.field === field ? current : begin(field))\n const report = (field: HTMLElement) => {\n const edit = editOf(field)\n if (edit.ended) return\n const text = textOf(field)\n // A browser may follow a composition with an input of the same text.\n if (text === edit.reported) return\n edit.reported = text\n Queue.offerUnsafe(queue, TextEdited.make({ field: edit.name, text }))\n }\n const commit = (field: HTMLElement) => {\n const edit = editOf(field)\n if (edit.ended) return\n edit.ended = true\n Queue.offerUnsafe(queue, TextCommitted.make({ field: edit.name, text: textOf(field) }))\n }\n const cancel = (field: HTMLElement) => {\n const edit = editOf(field)\n if (edit.ended) return\n edit.ended = true\n field.innerText = edit.initial\n // Writing the text moved the caret to its start; typing on goes after it.\n caretAtEnd(field)\n Queue.offerUnsafe(\n queue,\n TextCancelled.make({ field: edit.name, initial: edit.initial }),\n )\n }\n\n const listeners: ReadonlyArray<readonly [string, (event: Event) => void]> = [\n [\n 'dblclick',\n event => {\n const field = markedOf(event.target)\n // In an editable field, a double-click selects a word.\n if (field === undefined || field.isContentEditable) return\n Queue.offerUnsafe(\n queue,\n EditAsked.make({ field: field.getAttribute(attribute) ?? '' }),\n )\n },\n ],\n [\n 'focusin',\n event => {\n // A composition that never ended, in a field left, holds no other field silent.\n composingText = false\n const field = fieldOf(event.target)\n if (field !== undefined) begin(field)\n },\n ],\n // Before the change: a field focused before these listeners came is begun here.\n [\n 'beforeinput',\n event => {\n const field = fieldOf(event.target)\n if (field !== undefined) begin(field)\n },\n ],\n ['compositionstart', () => (composingText = true)],\n [\n 'compositionend',\n event => {\n composingText = false\n const field = fieldOf(event.target)\n if (field !== undefined) report(field)\n },\n ],\n [\n 'input',\n event => {\n const field = fieldOf(event.target)\n if (field !== undefined && !composingText) report(field)\n },\n ],\n [\n 'keydown',\n event => {\n const field = fieldOf(event.target)\n const key = event as KeyboardEvent\n if (field === undefined || composing(key)) return\n if (key.key === 'Escape') {\n event.preventDefault()\n ending = field\n cancel(field)\n } else if (key.key === 'Enter' && !(key.shiftKey && multiline(field))) {\n event.preventDefault()\n ending = field\n commit(field)\n }\n },\n ],\n [\n 'focusout',\n event => {\n const field = fieldOf(event.target)\n if (field === undefined) return\n // Left while still there and editable, asked once the change that may have\n // taken it away is done: the author went elsewhere, and focus is theirs.\n queueMicrotask(() => {\n if (field === ending && field.isConnected && field.isContentEditable)\n ending = undefined\n })\n commit(field)\n },\n ],\n [\n 'paste',\n event => {\n const field = fieldOf(event.target)\n // `plaintext-only` pastes text itself; elsewhere, markup would arrive.\n if (field === undefined || field.contentEditable === 'plaintext-only') return\n const pasted = (event as ClipboardEvent).clipboardData?.getData('text/plain') ?? ''\n event.preventDefault()\n // `insertText` fires no `beforeinput`: begun here, a paste after Enter is an edit.\n begin(field)\n // As typing is, so the browser's undo takes it back; `textOf` makes one line of it.\n document.execCommand('insertText', false, pasted)\n },\n ],\n ]\n // Focuses a field as it becomes editable, and only then: made so, or drawn so.\n // A field editable all along, or another going away, moves no focus.\n const editable = `[${attribute}][contenteditable]:not([contenteditable=\"false\"])`\n const becoming = new MutationObserver(records => {\n if (ending !== undefined && !(ending.isConnected && ending.isContentEditable)) {\n ending = undefined\n const focused = document.activeElement\n if ((focused === null || focused === document.body) && element instanceof HTMLElement)\n element.focus({ preventScroll: true })\n }\n for (const record of records) {\n const changed =\n record.type === 'attributes' ? [record.target] : Array.from(record.addedNodes)\n for (const node of changed) {\n if (!(node instanceof HTMLElement)) continue\n const field = node.matches(editable) ? node : node.querySelector(editable)\n if (field instanceof HTMLElement) return caretAtEnd(field)\n }\n }\n })\n\n for (const [type, listener] of listeners) element.addEventListener(type, listener)\n // A field made editable, drawn editable, or leaving.\n becoming.observe(element, {\n subtree: true,\n childList: true,\n attributes: true,\n attributeFilter: ['contenteditable'],\n })\n return { listeners, becoming }\n }),\n ({ listeners, becoming }) =>\n Effect.sync(() => {\n becoming.disconnect()\n for (const [type, listener] of listeners) element.removeEventListener(type, listener)\n }),\n ),\n ),\n})\n","/**\n * Keeps focus that is inside a container of roving tab stops on its stop, as a\n * Mount: when a transition moves the stop (a row made current by a command the\n * container did not see, such as a duplicate) or removes the focused\n * descendant (a deleted row), focus goes to the descendant with\n * `tabindex=\"0\"`. It sends no Message. Focus outside the container is never\n * taken, and focus the user moved away stays where it went.\n */\nimport { Effect, Schema, Stream } from 'effect'\nimport * as Mount from 'foldkit/mount'\n\nexport const FollowTabStop = Mount.defineStream('FollowTabStop', {\n messages: [Schema.Never],\n execute: ({ element }) =>\n Stream.callback<never>(() =>\n Effect.acquireRelease(\n Effect.sync(() => {\n let within = element.contains(document.activeElement)\n const entered = () => {\n within = true\n }\n const left = (event: Event) => {\n const next = (event as FocusEvent).relatedTarget\n if (next instanceof Node && element.contains(next)) return\n const from = event.target\n // Asked once the change that may have taken it away is done: a descendant\n // removed with focus in it keeps the claim, one the user left does not.\n queueMicrotask(() => {\n if (!(from instanceof Node) || from.isConnected) within = false\n })\n }\n const follow = () => {\n if (!within) return\n const stop = element.querySelector('[tabindex=\"0\"]')\n const focused = document.activeElement\n if (!(stop instanceof HTMLElement) || stop === focused) return\n const lost = focused === null || focused === document.body\n const passed =\n focused !== null &&\n element.contains(focused) &&\n focused.getAttribute('tabindex') === '-1'\n if (lost || passed) stop.focus()\n }\n const changes = new MutationObserver(follow)\n element.addEventListener('focusin', entered)\n element.addEventListener('focusout', left)\n // A stop moved, or a descendant drawn or removed.\n changes.observe(element, {\n subtree: true,\n childList: true,\n attributes: true,\n attributeFilter: ['tabindex'],\n })\n return () => {\n changes.disconnect()\n element.removeEventListener('focusin', entered)\n element.removeEventListener('focusout', left)\n }\n }),\n stop => Effect.sync(stop),\n ),\n ),\n})\n"],"mappings":";;;;;;;;;;;AAUA,MAAM,YAAY;CAChB;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI;AAEX,MAAM,aAAa,YAA8B;CAC/C,MAAM,QAAQ;CACd,OAAO,QAAQ,QAAQ,mBAAmB,MAAM,SAAS,MAAM,kBAAkB,KAAK;AACxF;;AAGA,MAAa,kBAAkB,SAC7B,MAAM,KAAK,KAAK,iBAA8B,SAAS,CAAC,CAAC,CAAC,QACxD,YAAW,QAAQ,YAAY,KAAK,UAAU,OAAO,CACvD;AAEF,MAAM,cAAc,aAAkD;CACpE,MAAM,QAAQ,SAAS;CACvB,IAAI,UAAU,KAAA,GAAW,OAAO;CAChC,MAAM,MAAM;CACZ,OAAO;AACT;AAEA,MAAa,aAAa,MAAM,aAAa,cAAc;CACzD,UAAU,CAAC,OAAO,KAAK;CACvB,MAAM;;EAEJ,SAAS,OAAO;;EAEhB,SAAS,OAAO;;;EAGhB,cAAc,OAAO,OAAO,OAAO,MAAM;CAC3C;CACA,UAAU,EAAE,SAAS,SAAS,SAAS,mBACrC,OAAO,eACL,OAAO,eACL,OAAO,WAAW;EAChB,MAAM,gBAAgB,QAAQ;EAC9B,MAAM,WAAW,cAAc;EAC/B,MAAM,UACJ,iBAAiB,OAAO,OAAO,QAAQ,cAA2B,YAAY;EAChF,IAAI,YAAY,MAAM,QAAQ,MAAM;OAC/B,IAAI,CAAC,WAAW,eAAe,OAAO,CAAC,KAAK,mBAAmB,aAClE,QAAQ,MAAM;EAEhB,MAAM,aAAa,UAAi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