foldkit-primitives 0.15.3 → 0.15.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/device/index.d.mts +10 -20
- package/dist/device/index.d.mts.map +1 -1
- package/dist/device/index.mjs +6 -11
- package/dist/device/index.mjs.map +1 -1
- package/dist/dom/index.d.mts +1 -37
- package/dist/dom/index.d.mts.map +1 -1
- package/dist/dom/index.mjs +18 -35
- package/dist/dom/index.mjs.map +1 -1
- package/dist/{editable-text-1D31qthY.d.mts → editable-text-Bg7vil7h.d.mts} +1 -13
- package/dist/editable-text-Bg7vil7h.d.mts.map +1 -0
- package/dist/events/index.d.mts +1 -17
- package/dist/events/index.d.mts.map +1 -1
- package/dist/events/index.mjs +10 -18
- package/dist/events/index.mjs.map +1 -1
- package/dist/{follow-tab-stop-Caog2qg1.mjs → follow-tab-stop-DM5EI4Ci.mjs} +8 -15
- package/dist/{follow-tab-stop-Caog2qg1.mjs.map → follow-tab-stop-DM5EI4Ci.mjs.map} +1 -1
- package/dist/{index-CmmxqSEi.d.mts → index-Bomdwb7e.d.mts} +4 -11
- package/dist/index-Bomdwb7e.d.mts.map +1 -0
- package/dist/index.d.mts +3 -3
- package/dist/index.mjs +3 -3
- package/dist/{input-modality-BXD383jg.mjs → input-modality-XwQOFLip.mjs} +2 -3
- package/dist/{input-modality-BXD383jg.mjs.map → input-modality-XwQOFLip.mjs.map} +1 -1
- package/dist/{input-modality-BY-bSrEc.d.mts → input-modality-l7InESYh.d.mts} +1 -3
- package/dist/input-modality-l7InESYh.d.mts.map +1 -0
- package/dist/interaction/index.d.mts +2 -3
- package/dist/interaction/index.d.mts.map +1 -1
- package/dist/interaction/index.mjs +24 -44
- package/dist/interaction/index.mjs.map +1 -1
- package/dist/{internal-DP-xLKbT.mjs → internal-C4gHodLc.mjs} +2 -3
- package/dist/{internal-DP-xLKbT.mjs.map → internal-C4gHodLc.mjs.map} +1 -1
- package/dist/media/index.d.mts +0 -6
- package/dist/media/index.d.mts.map +1 -1
- package/dist/media/index.mjs +3 -6
- package/dist/media/index.mjs.map +1 -1
- package/dist/motion/index.d.mts +1 -1
- package/dist/motion/index.mjs +1 -1
- package/dist/{motion-DmFDppRn.mjs → motion-BmlJCjn6.mjs} +6 -10
- package/dist/{motion-DmFDppRn.mjs.map → motion-BmlJCjn6.mjs.map} +1 -1
- package/dist/net/index.d.mts +0 -10
- package/dist/net/index.d.mts.map +1 -1
- package/dist/net/index.mjs +6 -11
- package/dist/net/index.mjs.map +1 -1
- package/dist/observers/index.d.mts +0 -8
- package/dist/observers/index.d.mts.map +1 -1
- package/dist/observers/index.mjs +4 -8
- package/dist/observers/index.mjs.map +1 -1
- package/dist/{rolldown-runtime-D7D4PA-g.mjs → rolldown-runtime-D8jQpDG7.mjs} +1 -2
- package/dist/state/index.d.mts +0 -12
- package/dist/state/index.d.mts.map +1 -1
- package/dist/state/index.mjs +7 -13
- package/dist/state/index.mjs.map +1 -1
- package/dist/time/index.d.mts +0 -12
- package/dist/time/index.d.mts.map +1 -1
- package/dist/time/index.mjs +6 -12
- package/dist/time/index.mjs.map +1 -1
- package/package.json +3 -3
- package/dist/editable-text-1D31qthY.d.mts.map +0 -1
- package/dist/index-CmmxqSEi.d.mts.map +0 -1
- package/dist/input-modality-BY-bSrEc.d.mts.map +0 -1
package/dist/state/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/state/history.ts","../../src/state/locale.ts","../../src/state/pagination.ts","../../src/state/range.ts","../../src/state/selection.ts","../../src/state/virtual.ts"],"sourcesContent":["import { Schema } from 'effect'\nimport { defineMessageUnion } from 'foldkit/message'\nimport { Bundle } from 'foldkit-bundle'\n\nexport const HistoryModel = <Value>(value: Schema.Codec<Value, unknown>) =>\n Schema.Struct({\n past: Schema.Array(value),\n present: value,\n future: Schema.Array(value),\n /** The group of the last push, so the next push of the same group joins it; `null` for none. */\n group: Schema.NullOr(Schema.String),\n })\nexport type HistoryModel<Value> = {\n readonly past: ReadonlyArray<Value>\n readonly present: Value\n readonly future: ReadonlyArray<Value>\n readonly group: string | null\n}\n\nconst start = <Value>(present: Value): HistoryModel<Value> => ({\n past: [],\n present,\n future: [],\n group: null,\n})\n\n/**\n * No redo steps, keeping an already empty future: a view that reads the\n * future compares it by identity, so a push per keystroke or stroke cell\n * must not hand it a new empty array each time.\n */\nconst noFuture = <Value>(model: HistoryModel<Value>): ReadonlyArray<Value> =>\n model.future.length === 0 ? model.future : []\n\nconst push = <Value>(\n model: HistoryModel<Value>,\n value: Value,\n options: { readonly capacity: number; readonly group?: string | null | undefined },\n): HistoryModel<Value> => {\n const group = options.group ?? null\n // The same group again joins the last step: the present moves, the past stays.\n if (group !== null && group === model.group && model.past.length > 0)\n return { ...model, present: value, future: noFuture(model) }\n return {\n // slice(-0) is slice(0): a zero capacity keeps nothing, explicitly.\n past: options.capacity === 0 ? [] : [...model.past, model.present].slice(-options.capacity),\n present: value,\n future: noFuture(model),\n group,\n }\n}\n\nconst undo = <Value>(model: HistoryModel<Value>): HistoryModel<Value> => {\n const previous = model.past[model.past.length - 1]\n if (previous === undefined) return model\n return {\n past: model.past.slice(0, -1),\n present: previous,\n future: [model.present, ...model.future],\n group: null,\n }\n}\n\nconst redo = <Value>(model: HistoryModel<Value>): HistoryModel<Value> => {\n const next = model.future[0]\n if (next === undefined) return model\n return {\n past: [...model.past, model.present],\n present: next,\n future: model.future.slice(1),\n group: null,\n }\n}\n\nconst goTo = <Value>(model: HistoryModel<Value>, step: number): HistoryModel<Value> => {\n const steps = [...model.past, model.present, ...model.future]\n if (!Number.isInteger(step) || step < 0 || step >= steps.length || step === model.past.length)\n return model\n return {\n past: steps.slice(0, step),\n present: steps[step]!,\n future: steps.slice(step + 1),\n group: null,\n }\n}\n\nconst clear = <Value>(model: HistoryModel<Value>): HistoryModel<Value> =>\n model.past.length === 0 && model.future.length === 0 && model.group === null\n ? model\n : start(model.present)\n\nconst close = <Value>(model: HistoryModel<Value>): HistoryModel<Value> =>\n model.group === null ? model : { ...model, group: null }\n\nconst revert = <Value>(model: HistoryModel<Value>, group: string): HistoryModel<Value> =>\n // The group is ended even where there is nothing to take back (capacity 0).\n model.group === group ? { ...undo(model), future: [], group: null } : model\n\nconst checkCapacity = (name: string, capacity: number): number => {\n // A negative or fractional capacity would silently keep a wrong-sized past;\n // fail where it is given, naming the caller, instead.\n if (!Number.isInteger(capacity) || capacity < 0)\n throw new Error(`History \"${name}\": capacity must be a non-negative integer`)\n return capacity\n}\n\n/** Whether Undo would move: the past is non-empty. */\nexport const canUndo = <Value>(model: HistoryModel<Value>): boolean => model.past.length > 0\n\n/** Whether Redo would move: the future is non-empty. */\nexport const canRedo = <Value>(model: HistoryModel<Value>): boolean => model.future.length > 0\n\n/** The steps of a history as pure functions of its Model. */\nexport const History = {\n /** A history whose present is `value`, with nothing to undo. */\n start,\n /** Records `value` as the present; the same `group` as the last push joins its step. */\n push,\n /** One step back, or the Model as it was when there is none. */\n undo,\n /** One step forward, or the Model as it was when there is none. */\n redo,\n /**\n * The value at `step` made the present, counting every kept value from the\n * oldest (0), so the present is at `past.length`: what a click on a step's\n * thumbnail does. The Model as it was for the present or a step not kept.\n */\n goTo,\n /** Nothing to undo or redo, the present kept. */\n clear,\n /** The next push starts a step of its own, whatever its group: a group ends here. */\n close,\n /**\n * The step `group` is making taken back, and not redoable: what a cancelled\n * edit, or one that ended where it began, leaves. The Model as it was when\n * the last push was not of `group`. What the group's first push dropped\n * stays dropped: the redo future it cleared, and an entry capacity evicted;\n * with a capacity of 0 nothing was kept, so the present stays and only the\n * group ends.\n */\n revert,\n canUndo,\n canRedo,\n}\n\n/**\n * Undo/redo as a bundle factory: the past, present, and future of one value\n * live in the Model, so every step replays. Pushing records, even an unchanged\n * value; skipping duplicates is the application's policy, not the stack's.\n *\n * A push may name a `group`. Consecutive pushes of the same group are one step:\n * the present moves and nothing new is recorded, so typing a word undoes as a\n * whole. Grouping needs no clock; the application names what belongs together.\n *\n * The steps are also pure functions (`History.push`, `undo`, `redo`, `goTo`, `clear`),\n * for a parent that records an edit in the same transition that makes it\n * rather than dispatching a Message to a placed bundle.\n */\nexport const history = <const Name extends string, Value>(config: {\n readonly name: Name\n readonly value: Schema.Codec<Value, unknown>\n readonly capacity?: number | undefined\n}) => {\n const capacity = checkCapacity(config.name, config.capacity ?? 100)\n const Model = HistoryModel(config.value)\n const Message = defineMessageUnion({\n Push: { value: config.value, group: Schema.optional(Schema.String) },\n Undo: {},\n Redo: {},\n GoTo: { step: Schema.Number },\n Clear: {},\n })\n return Object.assign(\n Bundle.make(config.name, {\n Model,\n Message,\n args: Schema.Struct({ initial: config.value }),\n init: args => ({ model: start(args.initial) }),\n update: (model, message) =>\n Message.match(message, {\n Push: ({ value, group }) => ({ model: push(model, value, { capacity, group }) }),\n Undo: () => ({ model: undo(model) }),\n Redo: () => ({ model: redo(model) }),\n GoTo: ({ step }) => ({ model: goTo(model, step) }),\n Clear: () => ({ model: clear(model) }),\n }),\n }),\n // The union object is both the Message codec and its constructors, so a\n // placement dispatches `EditHistory.Message.Push(...)` like any bundle's\n // exported Message.\n { Message },\n )\n}\n","import { Schema } from 'effect'\nimport { defineMessageUnion } from 'foldkit/message'\nimport { Bundle } from 'foldkit-bundle'\n\nexport const LocaleModel = Schema.Struct({ locale: Schema.String })\nexport type LocaleModel = typeof LocaleModel.Type\n\nexport const LocaleMessage = defineMessageUnion({ SetLocale: { locale: Schema.String } })\nexport type LocaleMessage = typeof LocaleMessage.Type\n\n/**\n * Locale as a bundle: the current locale string in the Model. Starts from\n * `navigator.language` where available, falling back to the configured\n * default; changes arrive as Messages. No subscriptions: language changes\n * take effect on reload.\n */\nexport const Locale = Bundle.make('Locale', {\n Model: LocaleModel,\n Message: LocaleMessage,\n args: Schema.Struct({ default: Schema.String }),\n init: args => ({\n model: {\n locale:\n typeof navigator !== 'undefined' && typeof navigator.language === 'string'\n ? navigator.language\n : args.default,\n },\n }),\n update: (model, message) =>\n LocaleMessage.match(message, {\n SetLocale: ({ locale }) =>\n locale === model.locale ? { model } : { model: { ...model, locale } },\n }),\n})\n","import { Schema } from 'effect'\nimport { defineMessageUnion } from 'foldkit/message'\nimport { Bundle } from 'foldkit-bundle'\nimport { unlessSame } from '../internal.js'\n\nexport const PaginationModel = Schema.Struct({\n page: Schema.Number,\n perPage: Schema.Number,\n total: Schema.NullOr(Schema.Number),\n})\nexport type PaginationModel = typeof PaginationModel.Type\n\nexport const PaginationMessage = defineMessageUnion({\n GoToPage: { page: Schema.Number },\n NextPage: {},\n PrevPage: {},\n SetPerPage: { perPage: Schema.Number },\n SetTotal: { total: Schema.NullOr(Schema.Number) },\n})\nexport type PaginationMessage = typeof PaginationMessage.Type\n\nconst clampPage = (page: number, perPage: number, total: number | null): number => {\n if (!Number.isInteger(page)) return 1\n if (page < 1) return 1\n if (total === null) return page\n return Math.min(page, Math.max(1, Math.ceil(total / perPage)))\n}\n\n/** The number of pages, or null while the total is unknown. */\nexport const pageCount = (model: PaginationModel): number | null =>\n model.total === null ? null : Math.max(1, Math.ceil(model.total / model.perPage))\n\n/** The offset of the first item on the page, for a slice or a query. */\nexport const offset = (model: PaginationModel): number => (model.page - 1) * model.perPage\n\n/**\n * Pagination as a bundle: the page, page size, and total live in the Model,\n * so page changes replay and every transition clamps into range. Pure logic,\n * no streams: data loading stays the application's job.\n */\nexport const Pagination = Bundle.make('Pagination', {\n Model: PaginationModel,\n Message: PaginationMessage,\n args: Schema.Struct({\n perPage: Schema.Number.pipe(\n Schema.check(Schema.isGreaterThan(0)),\n Schema.check(Schema.isFinite()),\n ),\n total: Schema.optional(Schema.NullOr(Schema.Number.pipe(Schema.check(Schema.isFinite())))),\n }),\n init: args => ({\n model: { page: 1, perPage: args.perPage, total: args.total ?? null },\n }),\n update: (model, message) =>\n PaginationMessage.match(message, {\n GoToPage: ({ page }) => ({\n model: unlessSame(model, { ...model, page: clampPage(page, model.perPage, model.total) }),\n }),\n NextPage: () => ({\n model: unlessSame(model, {\n ...model,\n page: clampPage(model.page + 1, model.perPage, model.total),\n }),\n }),\n PrevPage: () => ({\n model: unlessSame(model, {\n ...model,\n page: clampPage(model.page - 1, model.perPage, model.total),\n }),\n }),\n SetPerPage: ({ perPage }) =>\n perPage > 0\n ? {\n model: unlessSame(model, {\n ...model,\n perPage,\n page: clampPage(model.page, perPage, model.total),\n }),\n }\n : { model },\n // Sent again on every refetch, usually with the total already held.\n SetTotal: ({ total }) =>\n total === null || total >= 0\n ? {\n model: unlessSame(model, {\n ...model,\n total,\n page: clampPage(model.page, model.perPage, total),\n }),\n }\n : { model },\n }),\n})\n","/**\n * A numeric range as an array: `range(1, 4)` is `[1, 2, 3]`, inclusive of\n * the start and exclusive of the end, like `Array.from` length math. The\n * pagination companion: `range(1, (pageCount(model) ?? 0) + 1)` is the page\n * list. A zero or non-finite step would loop forever, so it throws, naming\n * the caller — like History's capacity check.\n */\nexport const range = (start: number, end: number, step = 1): ReadonlyArray<number> => {\n if (!Number.isFinite(step) || step === 0) {\n throw new Error(`range: step must be a non-zero finite number, got ${step}`)\n }\n const values: Array<number> = []\n if (step > 0) {\n for (let value = start; value < end; value += step) {\n values.push(value)\n }\n } else {\n for (let value = start; value > end; value += step) {\n values.push(value)\n }\n }\n return values\n}\n","import { Schema } from 'effect'\nimport { defineMessageUnion } from 'foldkit/message'\nimport { Bundle } from 'foldkit-bundle'\nimport { sameIds } from '../internal.js'\n\nexport const SelectionSetModel = Schema.Struct({ selected: Schema.Array(Schema.String) })\nexport type SelectionSetModel = typeof SelectionSetModel.Type\n\nexport const SelectionSetMessage = defineMessageUnion({\n Select: { id: Schema.String },\n Deselect: { id: Schema.String },\n Toggle: { id: Schema.String },\n ReplaceAll: { ids: Schema.Array(Schema.String) },\n Clear: {},\n})\nexport type SelectionSetMessage = typeof SelectionSetMessage.Type\n\nconst without = (selected: ReadonlyArray<string>, id: string): ReadonlyArray<string> =>\n selected.filter(other => other !== id)\n\n/** Whether the id is currently selected. */\nexport const isSelected = (model: SelectionSetModel, id: string): boolean =>\n model.selected.includes(id)\n\n/**\n * A selection set as a bundle: the selected ids in the Model, changed one at\n * a time or replaced whole. Order follows first selection; toggling moves a\n * reselected id to the end. Pure logic, no streams.\n */\nexport const SelectionSet = Bundle.make('SelectionSet', {\n Model: SelectionSetModel,\n Message: SelectionSetMessage,\n init: () => ({ model: { selected: [] } }),\n update: (model, message) =>\n SelectionSetMessage.match(message, {\n Select: ({ id }) =>\n isSelected(model, id) ? { model } : { model: { selected: [...model.selected, id] } },\n Deselect: ({ id }) =>\n isSelected(model, id) ? { model: { selected: without(model.selected, id) } } : { model },\n Toggle: ({ id }) =>\n isSelected(model, id)\n ? { model: { selected: without(model.selected, id) } }\n : { model: { selected: [...model.selected, id] } },\n ReplaceAll: ({ ids }) => {\n const selected = [...new Set(ids)]\n return sameIds(selected, model.selected) ? { model } : { model: { selected } }\n },\n Clear: () => (model.selected.length === 0 ? { model } : { model: { selected: [] } }),\n }),\n})\n","import { Effect, Queue, Schema, Stream } from 'effect'\nimport { defineMessageUnion } from 'foldkit/message'\nimport * as Mount from 'foldkit/mount'\nimport type * as Update from 'foldkit/update'\nimport { Bundle } from 'foldkit-bundle'\n\n/** The rows to draw: a half-open range of indexes. */\nexport interface VirtualWindow {\n /** First visible row index, inclusive. */\n readonly start: number\n /** End row index, exclusive. */\n readonly end: number\n}\n\n/** Layout constants: per-row estimate, inter-row gap, and end padding. */\nexport interface VirtualLayout {\n readonly estimatedHeight: number\n readonly gap: number\n readonly paddingStart: number\n readonly paddingEnd: number\n}\n\nconst saneHeight = (height: number, estimatedHeight: number): number =>\n Number.isFinite(height) && height >= 0 ? height : estimatedHeight\n\nconst heightAt = (\n index: number,\n heights: Readonly<Record<string, number>>,\n keys: ReadonlyArray<string>,\n layout: VirtualLayout,\n): number => {\n const key = keys[index]\n if (key === undefined) return layout.estimatedHeight\n return saneHeight(heights[key] ?? layout.estimatedHeight, layout.estimatedHeight)\n}\n\ninterface Offsets {\n readonly heights: Readonly<Record<string, number>>\n readonly layout: VirtualLayout\n /** `tops[i]` is row i's top edge; `tops[count]` is past the last row's gap. */\n readonly tops: Float64Array\n}\n\n// One entry per keys array, replaced when the heights or the layout change: a\n// view that keeps its keys array between renders pays O(n) once per change of\n// heights, not once per call. Keys and heights are compared by identity, so an\n// array or record changed in place reads stale offsets; the Model never is.\nconst offsetsCache = new WeakMap<ReadonlyArray<string>, Offsets>()\n\nconst sameLayout = (a: VirtualLayout, b: VirtualLayout): boolean =>\n a.estimatedHeight === b.estimatedHeight &&\n a.gap === b.gap &&\n a.paddingStart === b.paddingStart &&\n a.paddingEnd === b.paddingEnd\n\nconst topsFor = (\n keys: ReadonlyArray<string>,\n heights: Readonly<Record<string, number>>,\n layout: VirtualLayout,\n): Float64Array => {\n const cached = offsetsCache.get(keys)\n if (cached !== undefined && cached.heights === heights && sameLayout(cached.layout, layout)) {\n return cached.tops\n }\n const tops = new Float64Array(keys.length + 1)\n tops[0] = layout.paddingStart\n for (let index = 0; index < keys.length; index++) {\n tops[index + 1] = tops[index]! + heightAt(index, heights, keys, layout) + layout.gap\n }\n offsetsCache.set(keys, { heights, layout: { ...layout }, tops })\n return tops\n}\n\n/** The first index in `[from, to)` whose value passes `test`, or `to`; `test` must be monotonic. */\nconst firstIndex = (from: number, to: number, test: (index: number) => boolean): number => {\n let low = from\n let high = to\n while (low < high) {\n const middle = (low + high) >>> 1\n if (test(middle)) high = middle\n else low = middle + 1\n }\n return low\n}\n\n/** Total scrollable height: padding, measured rows, estimates, and gaps. */\nexport const totalHeight = (\n keys: ReadonlyArray<string>,\n heights: Readonly<Record<string, number>>,\n layout: VirtualLayout,\n): number => {\n const last = keys.length - 1\n if (last === -1) return layout.paddingStart + layout.paddingEnd\n // The last row's bottom edge, not `tops[count]` less a gap: subtracting a\n // fractional gap back out need not land where the row ends.\n return (\n topsFor(keys, heights, layout)[last]! +\n heightAt(last, heights, keys, layout) +\n layout.paddingEnd\n )\n}\n\n/** Pixel offset of a row's top edge: padding plus the prefix before it. */\nexport const offsetFor = (\n index: number,\n keys: ReadonlyArray<string>,\n heights: Readonly<Record<string, number>>,\n layout: VirtualLayout,\n): number => topsFor(keys, heights, layout)[Math.max(0, Math.min(index, keys.length))]!\n\n/**\n * Which rows to render for a scroll position: the rows intersecting\n * `[scrollTop, scrollTop + viewportHeight)`, widened by `overscan` on both\n * sides and clamped to `[0, count]`. Gaps and padding are dead space — no\n * row — so boxes are tested, not cumulative coverage. An overscan of zero\n * renders exactly the visible rows.\n */\nexport const visibleRange = (\n keys: ReadonlyArray<string>,\n heights: Readonly<Record<string, number>>,\n layout: VirtualLayout,\n scrollTop: number,\n viewportHeight: number,\n overscan: number,\n): VirtualWindow => {\n const count = keys.length\n if (count === 0 || viewportHeight <= 0) return { start: 0, end: 0 }\n const tops = topsFor(keys, heights, layout)\n const top = Math.max(0, scrollTop)\n const bottom = top + viewportHeight\n // Row bottoms and tops only grow with the index, so both edges are searches.\n const start = firstIndex(\n 0,\n count,\n index => tops[index]! + heightAt(index, heights, keys, layout) > top,\n )\n const end = firstIndex(start, count, index => tops[index]! >= bottom)\n return {\n start: Math.max(0, start - Math.max(0, overscan)),\n end: Math.min(count, end + Math.max(0, overscan)),\n }\n}\n\nexport const VirtualModel = Schema.Struct({\n scrollTop: Schema.Number,\n heights: Schema.Record(Schema.String, Schema.Number),\n scrolling: Schema.Boolean,\n generation: Schema.Number,\n estimatedHeight: Schema.Number,\n overscan: Schema.Number,\n gap: Schema.Number,\n paddingStart: Schema.Number,\n paddingEnd: Schema.Number,\n})\nexport type VirtualModel = typeof VirtualModel.Type\n\nexport const VirtualMessage = defineMessageUnion({\n Scrolled: { top: Schema.Number },\n Measured: { key: Schema.String, height: Schema.Number },\n /** Drops heights for keys no longer listed: the bundle never sees the key\n order, so the application tells it what left. */\n Prune: { keys: Schema.Array(Schema.String) },\n /** Fires when scrolling has been silent for `settleMs`: only the latest\n generation counts, so a fling's intermediate timers emit nothing. */\n Settled: { generation: Schema.Number },\n})\nexport type VirtualMessage = typeof VirtualMessage.Type\n\nconst layoutOf = (model: VirtualModel): VirtualLayout => ({\n estimatedHeight: model.estimatedHeight,\n gap: model.gap,\n paddingStart: model.paddingStart,\n paddingEnd: model.paddingEnd,\n})\n\n/**\n * The rows to render plus the spacer height, from the Model, the key order,\n * and the viewport height. Layout and overscan come from the Model, so the\n * call cannot disagree with the placement. Keys stay the application's:\n * render each row keyed, and per-row placements keep identity.\n */\nexport const windowFor = (\n model: VirtualModel,\n keys: ReadonlyArray<string>,\n viewportHeight: number,\n): VirtualWindow & { readonly totalHeight: number } => {\n const layout = layoutOf(model)\n const window = visibleRange(\n keys,\n model.heights,\n layout,\n model.scrollTop,\n viewportHeight,\n model.overscan,\n )\n return { ...window, totalHeight: totalHeight(keys, model.heights, layout) }\n}\n\n/**\n * Pixels from the viewport's bottom edge to the content's end: negative\n * past it, zero exactly there. Prefetch thresholds want this number (\"load\n * when within 500px\"), not just the boolean below.\n */\nexport const distanceToEnd = (\n model: VirtualModel,\n keys: ReadonlyArray<string>,\n viewportHeight: number,\n): number => {\n const total = totalHeight(keys, model.heights, layoutOf(model))\n return total - (model.scrollTop + viewportHeight)\n}\n\n/**\n * Whether the viewport rests at (or past) the end, within `threshold`\n * pixels: the infinite-scroll check. An empty list counts as ended — there\n * is nothing to scroll, so more should load. Thresholds below zero clamp\n * to zero.\n */\nexport const isAtEnd = (\n model: VirtualModel,\n keys: ReadonlyArray<string>,\n viewportHeight: number,\n threshold = 0,\n): boolean => {\n const total = totalHeight(keys, model.heights, layoutOf(model))\n if (total <= 0) return true\n return total - (model.scrollTop + viewportHeight) <= Math.max(0, threshold)\n}\n\nconst saneTop = (top: number): number | null => (Number.isFinite(top) ? Math.max(0, top) : null)\n\nconst saneMeasured = (height: number): number | null =>\n Number.isFinite(height) && height >= 0 ? height : null\n\n/**\n * Windowing math for virtualized lists as pure functions: which rows to\n * render, how tall the scrollable area is, and where each row starts. Row\n * heights come from measured values with a per-row estimate fallback, so\n * unmeasured rows still occupy space and measuring later only corrects.\n * Keys are strings; heights are non-negative, and non-finite measurements\n * fall back to the estimate instead of poisoning the sums.\n *\n * The `Virtual` bundle below owns the scroll position and the measured\n * heights; `Viewport` reports container scrolls and `MeasureRow` reports\n * row heights, both as Mounts on the elements they observe. The application\n * renders `windowFor(...)` rows with its own views (keyed, so `each`\n * placements keep identity) inside a spacer of `totalHeight(...)`.\n */\nexport const Virtual = Bundle.make<\n 'Virtual',\n VirtualModel,\n VirtualMessage,\n {\n readonly estimatedHeight: number\n readonly overscan: number\n readonly gap: number\n readonly paddingStart: number\n readonly paddingEnd: number\n readonly settleMs?: number | undefined\n readonly initialScrollTop?: number | undefined\n readonly initialHeights?: Readonly<Record<string, number>> | undefined\n }\n>('Virtual', {\n Model: VirtualModel,\n Message: VirtualMessage,\n args: Schema.Struct({\n estimatedHeight: Schema.Number.pipe(\n Schema.check(Schema.isGreaterThan(0)),\n Schema.check(Schema.isFinite()),\n ),\n overscan: Schema.Int.pipe(Schema.check(Schema.isGreaterThanOrEqualTo(0))),\n gap: Schema.Number.pipe(\n Schema.check(Schema.isGreaterThanOrEqualTo(0)),\n Schema.check(Schema.isFinite()),\n ),\n paddingStart: Schema.Number.pipe(\n Schema.check(Schema.isGreaterThanOrEqualTo(0)),\n Schema.check(Schema.isFinite()),\n ),\n paddingEnd: Schema.Number.pipe(\n Schema.check(Schema.isGreaterThanOrEqualTo(0)),\n Schema.check(Schema.isFinite()),\n ),\n settleMs: Schema.optional(\n Schema.Number.pipe(Schema.check(Schema.isGreaterThan(0)), Schema.check(Schema.isFinite())),\n ),\n initialScrollTop: Schema.optional(\n Schema.Number.pipe(\n Schema.check(Schema.isGreaterThanOrEqualTo(0)),\n Schema.check(Schema.isFinite()),\n ),\n ),\n initialHeights: Schema.optional(Schema.Record(Schema.String, Schema.Number)),\n }),\n init: args => {\n // Restored measurements pass through the same sanitation as live ones,\n // so a poisoned cache cannot wedge the sums.\n const heights: Record<string, number> = {}\n for (const [key, height] of Object.entries(args.initialHeights ?? {})) {\n const sane = saneMeasured(height)\n if (sane !== null) heights[key] = sane\n }\n return {\n model: {\n scrollTop: args.initialScrollTop ?? 0,\n heights,\n scrolling: false,\n generation: 0,\n estimatedHeight: args.estimatedHeight,\n overscan: args.overscan,\n gap: args.gap,\n paddingStart: args.paddingStart,\n paddingEnd: args.paddingEnd,\n },\n }\n },\n update: (model, message, args) =>\n VirtualMessage.match<Update.ReturnWithOutMessage<VirtualModel, VirtualMessage, never>>(\n message,\n {\n Scrolled: ({ top }) => {\n const sane = saneTop(top)\n // The Viewport reports the position it mounts at, and a horizontal\n // scroll reports an unchanged top. The raw top is compared, so an\n // overscroll past zero still counts as scrolling.\n if (sane === null || top === model.scrollTop) return { model }\n const generation = model.generation + 1\n return {\n model: { ...model, scrollTop: sane, scrolling: true, generation },\n commands: [\n {\n name: 'Virtual.settle',\n args: { generation },\n effect: Effect.as(\n Effect.sleep(args.settleMs ?? 150),\n VirtualMessage.Settled({ generation }),\n ),\n },\n ],\n }\n },\n Measured: ({ key, height }) => {\n const sane = saneMeasured(height)\n // A remounted row, or a width-only resize, reports the height held.\n return sane === null || (Object.hasOwn(model.heights, key) && model.heights[key] === sane)\n ? { model }\n : { model: { ...model, heights: { ...model.heights, [key]: sane } } }\n },\n Prune: ({ keys }) => {\n const kept = new Set(keys)\n const heights: Record<string, number> = {}\n let dropped = false\n for (const [key, height] of Object.entries(model.heights)) {\n if (kept.has(key)) heights[key] = height\n else dropped = true\n }\n return dropped ? { model: { ...model, heights } } : { model }\n },\n // A superseded silence timer carries an old generation: ignore it.\n Settled: ({ generation }) =>\n generation === model.generation ? { model: { ...model, scrolling: false } } : { model },\n },\n ),\n})\n\nexport const ViewportScrolled = Schema.TaggedStruct('ViewportScrolled', { top: Schema.Number })\nexport type ViewportScrolled = typeof ViewportScrolled.Type\n\n/**\n * The scroll container's position, reported on its own scrolls starting\n * with the current one. Attach to the scrolling element — viewport scrolls\n * arrive through the window-level scroll entry instead.\n */\nexport const Viewport = Mount.defineStream('Viewport', {\n messages: [ViewportScrolled],\n execute: ({ element }) => {\n // The mount needs only a scroll position, not a full Element.\n const read = (): ViewportScrolled => {\n const scroller = element as unknown as { readonly scrollTop: number }\n return ViewportScrolled.make({ top: scroller.scrollTop })\n }\n return Stream.concat(\n Stream.make(read()),\n Stream.fromEventListener(element, 'scroll').pipe(Stream.map(read)),\n )\n },\n})\n\nexport const RowMeasured = Schema.TaggedStruct('RowMeasured', {\n key: Schema.String,\n height: Schema.Number,\n})\nexport type RowMeasured = typeof RowMeasured.Type\n\ntype RowObserverCtor = new (callback: ResizeObserverCallback) => ResizeObserver\n\n/**\n * One row's height, reported on every resize starting with the current\n * one. The key is the application's row identity, echoed back so the\n * parent files the height without tracking which Mount sent what.\n */\nexport const MeasureRow = Mount.defineStream('MeasureRow', {\n messages: [RowMeasured],\n args: { key: Schema.String },\n execute: ({ element, key }) =>\n Stream.callback<typeof RowMeasured.Type>(queue =>\n Effect.gen(function* () {\n const Observed = (globalThis as { ResizeObserver?: RowObserverCtor }).ResizeObserver\n if (Observed === undefined) return\n yield* Effect.acquireRelease(\n Effect.sync(() => {\n const observer = new Observed(entries => {\n const rect = entries[0]?.contentRect\n if (rect !== undefined) {\n Queue.offerUnsafe(queue, RowMeasured.make({ key, height: rect.height }))\n }\n })\n observer.observe(element)\n return observer\n }),\n observer => Effect.sync(() => observer.disconnect()),\n )\n }),\n ),\n})\n\n/**\n * Which section header sticks for a window: the last section starting at\n * or before the first rendered row, or null above the first section. Order\n * independent — the scan takes the maximum, so unsorted input still\n * answers. CSS `position: sticky` does the sticking; this answers *what*\n * sticks, for styling and callbacks.\n */\nexport const stickyHeader = (\n sections: ReadonlyArray<{ readonly key: string; readonly index: number }>,\n startIndex: number,\n): string | null => {\n let current: string | null = null\n let currentIndex = -1\n for (const section of sections) {\n if (section.index <= startIndex && section.index > currentIndex) {\n current = section.key\n currentIndex = section.index\n }\n }\n return current\n}\n\n/** Where `masonry` puts one item: its column and its box, in pixels. */\nexport interface MasonryPlacement {\n readonly key: string\n readonly column: number\n readonly x: number\n readonly y: number\n readonly width: number\n readonly height: number\n}\n\n/**\n * Masonry layout as a pure function: fixed column count and width, each\n * item packed into the currently shortest column. Unmeasured items use the\n * estimate; poisoned heights fall back the same way. This is layout only,\n * not windowing — every placed item renders, so it fits hundreds of images,\n * not hundred-thousands. Needing a windowed grid is a different algorithm.\n */\nexport const masonry = (\n keys: ReadonlyArray<string>,\n heights: Readonly<Record<string, number>>,\n options: {\n readonly columns: number\n readonly columnWidth: number\n readonly gap: number\n readonly estimatedHeight: number\n },\n): { readonly placements: ReadonlyArray<MasonryPlacement>; readonly totalHeight: number } => {\n if (!Number.isInteger(options.columns) || options.columns < 1) {\n throw new Error(`masonry: columns must be a positive integer, got ${options.columns}`)\n }\n if (!(options.columnWidth > 0) || !Number.isFinite(options.columnWidth)) {\n throw new Error(\n `masonry: columnWidth must be a positive finite number, got ${options.columnWidth}`,\n )\n }\n if (options.gap < 0 || !Number.isFinite(options.gap)) {\n throw new Error(`masonry: gap must be a non-negative finite number, got ${options.gap}`)\n }\n if (options.estimatedHeight < 0 || !Number.isFinite(options.estimatedHeight)) {\n throw new Error(\n `masonry: estimatedHeight must be a non-negative finite number, got ${options.estimatedHeight}`,\n )\n }\n const columnHeights: Array<number> = new Array(options.columns).fill(0)\n const placements: Array<MasonryPlacement> = []\n for (const key of keys) {\n const raw = heights[key] ?? options.estimatedHeight\n const height = Number.isFinite(raw) && raw >= 0 ? raw : options.estimatedHeight\n let column = 0\n for (let c = 1; c < columnHeights.length; c++) {\n if (columnHeights[c]! < columnHeights[column]!) column = c\n }\n placements.push({\n key,\n column,\n x: column * (options.columnWidth + options.gap),\n y: columnHeights[column]!,\n width: options.columnWidth,\n height,\n })\n columnHeights[column] = columnHeights[column]! + height + options.gap\n }\n return {\n placements,\n totalHeight: placements.length === 0 ? 0 : Math.max(...columnHeights) - options.gap,\n }\n}\n"],"mappings":";;;;;;AAIA,MAAa,g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AAM,MAAM,QAAQ,QAAQ,QAAQ;EACpC,MAAM,SAAS,OAAO,SAAS,GAAG,KAAK,OAAO,IAAI,MAAM,QAAQ;EAChE,IAAI,SAAS;EACb,KAAK,IAAI,IAAI,GAAG,IAAI,cAAc,QAAQ,KACxC,IAAI,cAAc,KAAM,cAAc,SAAU,SAAS;EAE3D,WAAW,KAAK;GACd;GACA;GACA,GAAG,UAAU,QAAQ,cAAc,QAAQ;GAC3C,GAAG,cAAc;GACjB,OAAO,QAAQ;GACf;EACF,CAAC;EACD,cAAc,UAAU,cAAc,UAAW,SAAS,QAAQ;CACpE;CACA,OAAO;EACL;EACA,aAAa,WAAW,WAAW,IAAI,IAAI,KAAK,IAAI,GAAG,aAAa,IAAI,QAAQ;CAClF;AACF"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/state/history.ts","../../src/state/locale.ts","../../src/state/pagination.ts","../../src/state/range.ts","../../src/state/selection.ts","../../src/state/virtual.ts"],"sourcesContent":["import { Schema } from 'effect'\nimport { defineMessageUnion } from 'foldkit/message'\nimport { Bundle } from 'foldkit-bundle'\n\nexport const HistoryModel = <Value>(value: Schema.Codec<Value, unknown>) =>\n Schema.Struct({\n past: Schema.Array(value),\n present: value,\n future: Schema.Array(value),\n /** The group of the last push, so the next push of the same group joins it; `null` for none. */\n group: Schema.NullOr(Schema.String),\n })\nexport type HistoryModel<Value> = {\n readonly past: ReadonlyArray<Value>\n readonly present: Value\n readonly future: ReadonlyArray<Value>\n readonly group: string | null\n}\n\nconst start = <Value>(present: Value): HistoryModel<Value> => ({\n past: [],\n present,\n future: [],\n group: null,\n})\n\n/**\n * No redo steps, keeping an already empty future: a view that reads the\n * future compares it by identity, so a push per keystroke or stroke cell\n * must not hand it a new empty array each time.\n */\nconst noFuture = <Value>(model: HistoryModel<Value>): ReadonlyArray<Value> =>\n model.future.length === 0 ? model.future : []\n\nconst push = <Value>(\n model: HistoryModel<Value>,\n value: Value,\n options: { readonly capacity: number; readonly group?: string | null | undefined },\n): HistoryModel<Value> => {\n const group = options.group ?? null\n // The same group again joins the last step: the present moves, the past stays.\n if (group !== null && group === model.group && model.past.length > 0)\n return { ...model, present: value, future: noFuture(model) }\n return {\n // slice(-0) is slice(0): a zero capacity keeps nothing, explicitly.\n past: options.capacity === 0 ? [] : [...model.past, model.present].slice(-options.capacity),\n present: value,\n future: noFuture(model),\n group,\n }\n}\n\nconst undo = <Value>(model: HistoryModel<Value>): HistoryModel<Value> => {\n const previous = model.past[model.past.length - 1]\n if (previous === undefined) return model\n return {\n past: model.past.slice(0, -1),\n present: previous,\n future: [model.present, ...model.future],\n group: null,\n }\n}\n\nconst redo = <Value>(model: HistoryModel<Value>): HistoryModel<Value> => {\n const next = model.future[0]\n if (next === undefined) return model\n return {\n past: [...model.past, model.present],\n present: next,\n future: model.future.slice(1),\n group: null,\n }\n}\n\nconst goTo = <Value>(model: HistoryModel<Value>, step: number): HistoryModel<Value> => {\n const steps = [...model.past, model.present, ...model.future]\n if (!Number.isInteger(step) || step < 0 || step >= steps.length || step === model.past.length)\n return model\n return {\n past: steps.slice(0, step),\n present: steps[step]!,\n future: steps.slice(step + 1),\n group: null,\n }\n}\n\nconst clear = <Value>(model: HistoryModel<Value>): HistoryModel<Value> =>\n model.past.length === 0 && model.future.length === 0 && model.group === null\n ? model\n : start(model.present)\n\nconst close = <Value>(model: HistoryModel<Value>): HistoryModel<Value> =>\n model.group === null ? model : { ...model, group: null }\n\nconst revert = <Value>(model: HistoryModel<Value>, group: string): HistoryModel<Value> =>\n // The group is ended even where there is nothing to take back (capacity 0).\n model.group === group ? { ...undo(model), future: [], group: null } : model\n\nconst checkCapacity = (name: string, capacity: number): number => {\n // A negative or fractional capacity would silently keep a wrong-sized past;\n // fail where it is given, naming the caller, instead.\n if (!Number.isInteger(capacity) || capacity < 0)\n throw new Error(`History \"${name}\": capacity must be a non-negative integer`)\n return capacity\n}\n\n/** Whether Undo would move: the past is non-empty. */\nexport const canUndo = <Value>(model: HistoryModel<Value>): boolean => model.past.length > 0\n\n/** Whether Redo would move: the future is non-empty. */\nexport const canRedo = <Value>(model: HistoryModel<Value>): boolean => model.future.length > 0\n\n/** The steps of a history as pure functions of its Model. */\nexport const History = {\n /** A history whose present is `value`, with nothing to undo. */\n start,\n /** Records `value` as the present; the same `group` as the last push joins its step. */\n push,\n /** One step back, or the Model as it was when there is none. */\n undo,\n /** One step forward, or the Model as it was when there is none. */\n redo,\n /**\n * The value at `step` made the present, counting every kept value from the\n * oldest (0), so the present is at `past.length`: what a click on a step's\n * thumbnail does. The Model as it was for the present or a step not kept.\n */\n goTo,\n /** Nothing to undo or redo, the present kept. */\n clear,\n /** The next push starts a step of its own, whatever its group: a group ends here. */\n close,\n /**\n * The step `group` is making taken back, and not redoable: what a cancelled\n * edit, or one that ended where it began, leaves. The Model as it was when\n * the last push was not of `group`. What the group's first push dropped\n * stays dropped: the redo future it cleared, and an entry capacity evicted;\n * with a capacity of 0 nothing was kept, so the present stays and only the\n * group ends.\n */\n revert,\n canUndo,\n canRedo,\n}\n\n/**\n * Undo/redo as a bundle factory: the past, present, and future of one value\n * live in the Model, so every step replays. Pushing records, even an unchanged\n * value; skipping duplicates is the application's policy, not the stack's.\n *\n * A push may name a `group`. Consecutive pushes of the same group are one step:\n * the present moves and nothing new is recorded, so typing a word undoes as a\n * whole. Grouping needs no clock; the application names what belongs together.\n *\n * The steps are also pure functions (`History.push`, `undo`, `redo`, `goTo`, `clear`),\n * for a parent that records an edit in the same transition that makes it\n * rather than dispatching a Message to a placed bundle.\n */\nexport const history = <const Name extends string, Value>(config: {\n readonly name: Name\n readonly value: Schema.Codec<Value, unknown>\n readonly capacity?: number | undefined\n}) => {\n const capacity = checkCapacity(config.name, config.capacity ?? 100)\n const Model = HistoryModel(config.value)\n const Message = defineMessageUnion({\n Push: { value: config.value, group: Schema.optional(Schema.String) },\n Undo: {},\n Redo: {},\n GoTo: { step: Schema.Number },\n Clear: {},\n })\n return Object.assign(\n Bundle.make(config.name, {\n Model,\n Message,\n args: Schema.Struct({ initial: config.value }),\n init: args => ({ model: start(args.initial) }),\n update: (model, message) =>\n Message.match(message, {\n Push: ({ value, group }) => ({ model: push(model, value, { capacity, group }) }),\n Undo: () => ({ model: undo(model) }),\n Redo: () => ({ model: redo(model) }),\n GoTo: ({ step }) => ({ model: goTo(model, step) }),\n Clear: () => ({ model: clear(model) }),\n }),\n }),\n // The union object is both the Message codec and its constructors, so a\n // placement dispatches `EditHistory.Message.Push(...)` like any bundle's\n // exported Message.\n { Message },\n )\n}\n","import { Schema } from 'effect'\nimport { defineMessageUnion } from 'foldkit/message'\nimport { Bundle } from 'foldkit-bundle'\n\nexport const LocaleModel = Schema.Struct({ locale: Schema.String })\nexport type LocaleModel = typeof LocaleModel.Type\n\nexport const LocaleMessage = defineMessageUnion({ SetLocale: { locale: Schema.String } })\nexport type LocaleMessage = typeof LocaleMessage.Type\n\n/**\n * Locale as a bundle: the current locale string in the Model. Starts from\n * `navigator.language` where available, falling back to the configured\n * default; changes arrive as Messages. No subscriptions: language changes\n * take effect on reload.\n */\nexport const Locale = Bundle.make('Locale', {\n Model: LocaleModel,\n Message: LocaleMessage,\n args: Schema.Struct({ default: Schema.String }),\n init: args => ({\n model: {\n locale:\n typeof navigator !== 'undefined' && typeof navigator.language === 'string'\n ? navigator.language\n : args.default,\n },\n }),\n update: (model, message) =>\n LocaleMessage.match(message, {\n SetLocale: ({ locale }) =>\n locale === model.locale ? { model } : { model: { ...model, locale } },\n }),\n})\n","import { Schema } from 'effect'\nimport { defineMessageUnion } from 'foldkit/message'\nimport { Bundle } from 'foldkit-bundle'\nimport { unlessSame } from '../internal.js'\n\nexport const PaginationModel = Schema.Struct({\n page: Schema.Number,\n perPage: Schema.Number,\n total: Schema.NullOr(Schema.Number),\n})\nexport type PaginationModel = typeof PaginationModel.Type\n\nexport const PaginationMessage = defineMessageUnion({\n GoToPage: { page: Schema.Number },\n NextPage: {},\n PrevPage: {},\n SetPerPage: { perPage: Schema.Number },\n SetTotal: { total: Schema.NullOr(Schema.Number) },\n})\nexport type PaginationMessage = typeof PaginationMessage.Type\n\nconst clampPage = (page: number, perPage: number, total: number | null): number => {\n if (!Number.isInteger(page)) return 1\n if (page < 1) return 1\n if (total === null) return page\n return Math.min(page, Math.max(1, Math.ceil(total / perPage)))\n}\n\n/** The number of pages, or null while the total is unknown. */\nexport const pageCount = (model: PaginationModel): number | null =>\n model.total === null ? null : Math.max(1, Math.ceil(model.total / model.perPage))\n\n/** The offset of the first item on the page, for a slice or a query. */\nexport const offset = (model: PaginationModel): number => (model.page - 1) * model.perPage\n\n/**\n * Pagination as a bundle: the page, page size, and total live in the Model,\n * so page changes replay and every transition clamps into range. Pure logic,\n * no streams: data loading stays the application's job.\n */\nexport const Pagination = Bundle.make('Pagination', {\n Model: PaginationModel,\n Message: PaginationMessage,\n args: Schema.Struct({\n perPage: Schema.Number.pipe(\n Schema.check(Schema.isGreaterThan(0)),\n Schema.check(Schema.isFinite()),\n ),\n total: Schema.optional(Schema.NullOr(Schema.Number.pipe(Schema.check(Schema.isFinite())))),\n }),\n init: args => ({\n model: { page: 1, perPage: args.perPage, total: args.total ?? null },\n }),\n update: (model, message) =>\n PaginationMessage.match(message, {\n GoToPage: ({ page }) => ({\n model: unlessSame(model, { ...model, page: clampPage(page, model.perPage, model.total) }),\n }),\n NextPage: () => ({\n model: unlessSame(model, {\n ...model,\n page: clampPage(model.page + 1, model.perPage, model.total),\n }),\n }),\n PrevPage: () => ({\n model: unlessSame(model, {\n ...model,\n page: clampPage(model.page - 1, model.perPage, model.total),\n }),\n }),\n SetPerPage: ({ perPage }) =>\n perPage > 0\n ? {\n model: unlessSame(model, {\n ...model,\n perPage,\n page: clampPage(model.page, perPage, model.total),\n }),\n }\n : { model },\n // Sent again on every refetch, usually with the total already held.\n SetTotal: ({ total }) =>\n total === null || total >= 0\n ? {\n model: unlessSame(model, {\n ...model,\n total,\n page: clampPage(model.page, model.perPage, total),\n }),\n }\n : { model },\n }),\n})\n","/**\n * A numeric range as an array: `range(1, 4)` is `[1, 2, 3]`, inclusive of\n * the start and exclusive of the end, like `Array.from` length math. The\n * pagination companion: `range(1, (pageCount(model) ?? 0) + 1)` is the page\n * list. A zero or non-finite step would loop forever, so it throws, naming\n * the caller — like History's capacity check.\n */\nexport const range = (start: number, end: number, step = 1): ReadonlyArray<number> => {\n if (!Number.isFinite(step) || step === 0) {\n throw new Error(`range: step must be a non-zero finite number, got ${step}`)\n }\n const values: Array<number> = []\n if (step > 0) {\n for (let value = start; value < end; value += step) {\n values.push(value)\n }\n } else {\n for (let value = start; value > end; value += step) {\n values.push(value)\n }\n }\n return values\n}\n","import { Schema } from 'effect'\nimport { defineMessageUnion } from 'foldkit/message'\nimport { Bundle } from 'foldkit-bundle'\nimport { sameIds } from '../internal.js'\n\nexport const SelectionSetModel = Schema.Struct({ selected: Schema.Array(Schema.String) })\nexport type SelectionSetModel = typeof SelectionSetModel.Type\n\nexport const SelectionSetMessage = defineMessageUnion({\n Select: { id: Schema.String },\n Deselect: { id: Schema.String },\n Toggle: { id: Schema.String },\n ReplaceAll: { ids: Schema.Array(Schema.String) },\n Clear: {},\n})\nexport type SelectionSetMessage = typeof SelectionSetMessage.Type\n\nconst without = (selected: ReadonlyArray<string>, id: string): ReadonlyArray<string> =>\n selected.filter(other => other !== id)\n\n/** Whether the id is currently selected. */\nexport const isSelected = (model: SelectionSetModel, id: string): boolean =>\n model.selected.includes(id)\n\n/**\n * A selection set as a bundle: the selected ids in the Model, changed one at\n * a time or replaced whole. Order follows first selection; toggling moves a\n * reselected id to the end. Pure logic, no streams.\n */\nexport const SelectionSet = Bundle.make('SelectionSet', {\n Model: SelectionSetModel,\n Message: SelectionSetMessage,\n init: () => ({ model: { selected: [] } }),\n update: (model, message) =>\n SelectionSetMessage.match(message, {\n Select: ({ id }) =>\n isSelected(model, id) ? { model } : { model: { selected: [...model.selected, id] } },\n Deselect: ({ id }) =>\n isSelected(model, id) ? { model: { selected: without(model.selected, id) } } : { model },\n Toggle: ({ id }) =>\n isSelected(model, id)\n ? { model: { selected: without(model.selected, id) } }\n : { model: { selected: [...model.selected, id] } },\n ReplaceAll: ({ ids }) => {\n const selected = [...new Set(ids)]\n return sameIds(selected, model.selected) ? { model } : { model: { selected } }\n },\n Clear: () => (model.selected.length === 0 ? { model } : { model: { selected: [] } }),\n }),\n})\n","import { Effect, Queue, Schema, Stream } from 'effect'\nimport { defineMessageUnion } from 'foldkit/message'\nimport * as Mount from 'foldkit/mount'\nimport type * as Update from 'foldkit/update'\nimport { Bundle } from 'foldkit-bundle'\n\n/** The rows to draw: a half-open range of indexes. */\nexport interface VirtualWindow {\n /** First visible row index, inclusive. */\n readonly start: number\n /** End row index, exclusive. */\n readonly end: number\n}\n\n/** Layout constants: per-row estimate, inter-row gap, and end padding. */\nexport interface VirtualLayout {\n readonly estimatedHeight: number\n readonly gap: number\n readonly paddingStart: number\n readonly paddingEnd: number\n}\n\nconst saneHeight = (height: number, estimatedHeight: number): number =>\n Number.isFinite(height) && height >= 0 ? height : estimatedHeight\n\nconst heightAt = (\n index: number,\n heights: Readonly<Record<string, number>>,\n keys: ReadonlyArray<string>,\n layout: VirtualLayout,\n): number => {\n const key = keys[index]\n if (key === undefined) return layout.estimatedHeight\n return saneHeight(heights[key] ?? layout.estimatedHeight, layout.estimatedHeight)\n}\n\ninterface Offsets {\n readonly heights: Readonly<Record<string, number>>\n readonly layout: VirtualLayout\n /** `tops[i]` is row i's top edge; `tops[count]` is past the last row's gap. */\n readonly tops: Float64Array\n}\n\n// One entry per keys array, replaced when the heights or the layout change: a\n// view that keeps its keys array between renders pays O(n) once per change of\n// heights, not once per call. Keys and heights are compared by identity, so an\n// array or record changed in place reads stale offsets; the Model never is.\nconst offsetsCache = new WeakMap<ReadonlyArray<string>, Offsets>()\n\nconst sameLayout = (a: VirtualLayout, b: VirtualLayout): boolean =>\n a.estimatedHeight === b.estimatedHeight &&\n a.gap === b.gap &&\n a.paddingStart === b.paddingStart &&\n a.paddingEnd === b.paddingEnd\n\nconst topsFor = (\n keys: ReadonlyArray<string>,\n heights: Readonly<Record<string, number>>,\n layout: VirtualLayout,\n): Float64Array => {\n const cached = offsetsCache.get(keys)\n if (cached !== undefined && cached.heights === heights && sameLayout(cached.layout, layout)) {\n return cached.tops\n }\n const tops = new Float64Array(keys.length + 1)\n tops[0] = layout.paddingStart\n for (let index = 0; index < keys.length; index++) {\n tops[index + 1] = tops[index]! + heightAt(index, heights, keys, layout) + layout.gap\n }\n offsetsCache.set(keys, { heights, layout: { ...layout }, tops })\n return tops\n}\n\n/** The first index in `[from, to)` whose value passes `test`, or `to`; `test` must be monotonic. */\nconst firstIndex = (from: number, to: number, test: (index: number) => boolean): number => {\n let low = from\n let high = to\n while (low < high) {\n const middle = (low + high) >>> 1\n if (test(middle)) high = middle\n else low = middle + 1\n }\n return low\n}\n\n/** Total scrollable height: padding, measured rows, estimates, and gaps. */\nexport const totalHeight = (\n keys: ReadonlyArray<string>,\n heights: Readonly<Record<string, number>>,\n layout: VirtualLayout,\n): number => {\n const last = keys.length - 1\n if (last === -1) return layout.paddingStart + layout.paddingEnd\n // The last row's bottom edge, not `tops[count]` less a gap: subtracting a\n // fractional gap back out need not land where the row ends.\n return (\n topsFor(keys, heights, layout)[last]! +\n heightAt(last, heights, keys, layout) +\n layout.paddingEnd\n )\n}\n\n/** Pixel offset of a row's top edge: padding plus the prefix before it. */\nexport const offsetFor = (\n index: number,\n keys: ReadonlyArray<string>,\n heights: Readonly<Record<string, number>>,\n layout: VirtualLayout,\n): number => topsFor(keys, heights, layout)[Math.max(0, Math.min(index, keys.length))]!\n\n/**\n * Which rows to render for a scroll position: the rows intersecting\n * `[scrollTop, scrollTop + viewportHeight)`, widened by `overscan` on both\n * sides and clamped to `[0, count]`. Gaps and padding are dead space — no\n * row — so boxes are tested, not cumulative coverage. An overscan of zero\n * renders exactly the visible rows.\n */\nexport const visibleRange = (\n keys: ReadonlyArray<string>,\n heights: Readonly<Record<string, number>>,\n layout: VirtualLayout,\n scrollTop: number,\n viewportHeight: number,\n overscan: number,\n): VirtualWindow => {\n const count = keys.length\n if (count === 0 || viewportHeight <= 0) return { start: 0, end: 0 }\n const tops = topsFor(keys, heights, layout)\n const top = Math.max(0, scrollTop)\n const bottom = top + viewportHeight\n // Row bottoms and tops only grow with the index, so both edges are searches.\n const start = firstIndex(\n 0,\n count,\n index => tops[index]! + heightAt(index, heights, keys, layout) > top,\n )\n const end = firstIndex(start, count, index => tops[index]! >= bottom)\n return {\n start: Math.max(0, start - Math.max(0, overscan)),\n end: Math.min(count, end + Math.max(0, overscan)),\n }\n}\n\nexport const VirtualModel = Schema.Struct({\n scrollTop: Schema.Number,\n heights: Schema.Record(Schema.String, Schema.Number),\n scrolling: Schema.Boolean,\n generation: Schema.Number,\n estimatedHeight: Schema.Number,\n overscan: Schema.Number,\n gap: Schema.Number,\n paddingStart: Schema.Number,\n paddingEnd: Schema.Number,\n})\nexport type VirtualModel = typeof VirtualModel.Type\n\nexport const VirtualMessage = defineMessageUnion({\n Scrolled: { top: Schema.Number },\n Measured: { key: Schema.String, height: Schema.Number },\n /** Drops heights for keys no longer listed: the bundle never sees the key\n order, so the application tells it what left. */\n Prune: { keys: Schema.Array(Schema.String) },\n /** Fires when scrolling has been silent for `settleMs`: only the latest\n generation counts, so a fling's intermediate timers emit nothing. */\n Settled: { generation: Schema.Number },\n})\nexport type VirtualMessage = typeof VirtualMessage.Type\n\nconst layoutOf = (model: VirtualModel): VirtualLayout => ({\n estimatedHeight: model.estimatedHeight,\n gap: model.gap,\n paddingStart: model.paddingStart,\n paddingEnd: model.paddingEnd,\n})\n\n/**\n * The rows to render plus the spacer height, from the Model, the key order,\n * and the viewport height. Layout and overscan come from the Model, so the\n * call cannot disagree with the placement. Keys stay the application's:\n * render each row keyed, and per-row placements keep identity.\n */\nexport const windowFor = (\n model: VirtualModel,\n keys: ReadonlyArray<string>,\n viewportHeight: number,\n): VirtualWindow & { readonly totalHeight: number } => {\n const layout = layoutOf(model)\n const window = visibleRange(\n keys,\n model.heights,\n layout,\n model.scrollTop,\n viewportHeight,\n model.overscan,\n )\n return { ...window, totalHeight: totalHeight(keys, model.heights, layout) }\n}\n\n/**\n * Pixels from the viewport's bottom edge to the content's end: negative\n * past it, zero exactly there. Prefetch thresholds want this number (\"load\n * when within 500px\"), not just the boolean below.\n */\nexport const distanceToEnd = (\n model: VirtualModel,\n keys: ReadonlyArray<string>,\n viewportHeight: number,\n): number => {\n const total = totalHeight(keys, model.heights, layoutOf(model))\n return total - (model.scrollTop + viewportHeight)\n}\n\n/**\n * Whether the viewport rests at (or past) the end, within `threshold`\n * pixels: the infinite-scroll check. An empty list counts as ended — there\n * is nothing to scroll, so more should load. Thresholds below zero clamp\n * to zero.\n */\nexport const isAtEnd = (\n model: VirtualModel,\n keys: ReadonlyArray<string>,\n viewportHeight: number,\n threshold = 0,\n): boolean => {\n const total = totalHeight(keys, model.heights, layoutOf(model))\n if (total <= 0) return true\n return total - (model.scrollTop + viewportHeight) <= Math.max(0, threshold)\n}\n\nconst saneTop = (top: number): number | null => (Number.isFinite(top) ? Math.max(0, top) : null)\n\nconst saneMeasured = (height: number): number | null =>\n Number.isFinite(height) && height >= 0 ? height : null\n\n/**\n * Windowing math for virtualized lists as pure functions: which rows to\n * render, how tall the scrollable area is, and where each row starts. Row\n * heights come from measured values with a per-row estimate fallback, so\n * unmeasured rows still occupy space and measuring later only corrects.\n * Keys are strings; heights are non-negative, and non-finite measurements\n * fall back to the estimate instead of poisoning the sums.\n *\n * The `Virtual` bundle below owns the scroll position and the measured\n * heights; `Viewport` reports container scrolls and `MeasureRow` reports\n * row heights, both as Mounts on the elements they observe. The application\n * renders `windowFor(...)` rows with its own views (keyed, so `each`\n * placements keep identity) inside a spacer of `totalHeight(...)`.\n */\nexport const Virtual = Bundle.make<\n 'Virtual',\n VirtualModel,\n VirtualMessage,\n {\n readonly estimatedHeight: number\n readonly overscan: number\n readonly gap: number\n readonly paddingStart: number\n readonly paddingEnd: number\n readonly settleMs?: number | undefined\n readonly initialScrollTop?: number | undefined\n readonly initialHeights?: Readonly<Record<string, number>> | undefined\n }\n>('Virtual', {\n Model: VirtualModel,\n Message: VirtualMessage,\n args: Schema.Struct({\n estimatedHeight: Schema.Number.pipe(\n Schema.check(Schema.isGreaterThan(0)),\n Schema.check(Schema.isFinite()),\n ),\n overscan: Schema.Int.pipe(Schema.check(Schema.isGreaterThanOrEqualTo(0))),\n gap: Schema.Number.pipe(\n Schema.check(Schema.isGreaterThanOrEqualTo(0)),\n Schema.check(Schema.isFinite()),\n ),\n paddingStart: Schema.Number.pipe(\n Schema.check(Schema.isGreaterThanOrEqualTo(0)),\n Schema.check(Schema.isFinite()),\n ),\n paddingEnd: Schema.Number.pipe(\n Schema.check(Schema.isGreaterThanOrEqualTo(0)),\n Schema.check(Schema.isFinite()),\n ),\n settleMs: Schema.optional(\n Schema.Number.pipe(Schema.check(Schema.isGreaterThan(0)), Schema.check(Schema.isFinite())),\n ),\n initialScrollTop: Schema.optional(\n Schema.Number.pipe(\n Schema.check(Schema.isGreaterThanOrEqualTo(0)),\n Schema.check(Schema.isFinite()),\n ),\n ),\n initialHeights: Schema.optional(Schema.Record(Schema.String, Schema.Number)),\n }),\n init: args => {\n // Restored measurements pass through the same sanitation as live ones,\n // so a poisoned cache cannot wedge the sums.\n const heights: Record<string, number> = {}\n for (const [key, height] of Object.entries(args.initialHeights ?? {})) {\n const sane = saneMeasured(height)\n if (sane !== null) heights[key] = sane\n }\n return {\n model: {\n scrollTop: args.initialScrollTop ?? 0,\n heights,\n scrolling: false,\n generation: 0,\n estimatedHeight: args.estimatedHeight,\n overscan: args.overscan,\n gap: args.gap,\n paddingStart: args.paddingStart,\n paddingEnd: args.paddingEnd,\n },\n }\n },\n update: (model, message, args) =>\n VirtualMessage.match<Update.ReturnWithOutMessage<VirtualModel, VirtualMessage, never>>(\n message,\n {\n Scrolled: ({ top }) => {\n const sane = saneTop(top)\n // The Viewport reports the position it mounts at, and a horizontal\n // scroll reports an unchanged top. The raw top is compared, so an\n // overscroll past zero still counts as scrolling.\n if (sane === null || top === model.scrollTop) return { model }\n const generation = model.generation + 1\n return {\n model: { ...model, scrollTop: sane, scrolling: true, generation },\n commands: [\n {\n name: 'Virtual.settle',\n args: { generation },\n effect: Effect.as(\n Effect.sleep(args.settleMs ?? 150),\n VirtualMessage.Settled({ generation }),\n ),\n },\n ],\n }\n },\n Measured: ({ key, height }) => {\n const sane = saneMeasured(height)\n // A remounted row, or a width-only resize, reports the height held.\n return sane === null || (Object.hasOwn(model.heights, key) && model.heights[key] === sane)\n ? { model }\n : { model: { ...model, heights: { ...model.heights, [key]: sane } } }\n },\n Prune: ({ keys }) => {\n const kept = new Set(keys)\n const heights: Record<string, number> = {}\n let dropped = false\n for (const [key, height] of Object.entries(model.heights)) {\n if (kept.has(key)) heights[key] = height\n else dropped = true\n }\n return dropped ? { model: { ...model, heights } } : { model }\n },\n // A superseded silence timer carries an old generation: ignore it.\n Settled: ({ generation }) =>\n generation === model.generation ? { model: { ...model, scrolling: false } } : { model },\n },\n ),\n})\n\nexport const ViewportScrolled = Schema.TaggedStruct('ViewportScrolled', { top: Schema.Number })\nexport type ViewportScrolled = typeof ViewportScrolled.Type\n\n/**\n * The scroll container's position, reported on its own scrolls starting\n * with the current one. Attach to the scrolling element — viewport scrolls\n * arrive through the window-level scroll entry instead.\n */\nexport const Viewport = Mount.defineStream('Viewport', {\n messages: [ViewportScrolled],\n execute: ({ element }) => {\n // The mount needs only a scroll position, not a full Element.\n const read = (): ViewportScrolled => {\n const scroller = element as unknown as { readonly scrollTop: number }\n return ViewportScrolled.make({ top: scroller.scrollTop })\n }\n return Stream.concat(\n Stream.make(read()),\n Stream.fromEventListener(element, 'scroll').pipe(Stream.map(read)),\n )\n },\n})\n\nexport const RowMeasured = Schema.TaggedStruct('RowMeasured', {\n key: Schema.String,\n height: Schema.Number,\n})\nexport type RowMeasured = typeof RowMeasured.Type\n\ntype RowObserverCtor = new (callback: ResizeObserverCallback) => ResizeObserver\n\n/**\n * One row's height, reported on every resize starting with the current\n * one. The key is the application's row identity, echoed back so the\n * parent files the height without tracking which Mount sent what.\n */\nexport const MeasureRow = Mount.defineStream('MeasureRow', {\n messages: [RowMeasured],\n args: { key: Schema.String },\n execute: ({ element, key }) =>\n Stream.callback<typeof RowMeasured.Type>(queue =>\n Effect.gen(function* () {\n const Observed = (globalThis as { ResizeObserver?: RowObserverCtor }).ResizeObserver\n if (Observed === undefined) return\n yield* Effect.acquireRelease(\n Effect.sync(() => {\n const observer = new Observed(entries => {\n const rect = entries[0]?.contentRect\n if (rect !== undefined) {\n Queue.offerUnsafe(queue, RowMeasured.make({ key, height: rect.height }))\n }\n })\n observer.observe(element)\n return observer\n }),\n observer => Effect.sync(() => observer.disconnect()),\n )\n }),\n ),\n})\n\n/**\n * Which section header sticks for a window: the last section starting at\n * or before the first rendered row, or null above the first section. Order\n * independent — the scan takes the maximum, so unsorted input still\n * answers. CSS `position: sticky` does the sticking; this answers *what*\n * sticks, for styling and callbacks.\n */\nexport const stickyHeader = (\n sections: ReadonlyArray<{ readonly key: string; readonly index: number }>,\n startIndex: number,\n): string | null => {\n let current: string | null = null\n let currentIndex = -1\n for (const section of sections) {\n if (section.index <= startIndex && section.index > currentIndex) {\n current = section.key\n currentIndex = section.index\n }\n }\n return current\n}\n\n/** Where `masonry` puts one item: its column and its box, in pixels. */\nexport interface MasonryPlacement {\n readonly key: string\n readonly column: number\n readonly x: number\n readonly y: number\n readonly width: number\n readonly height: number\n}\n\n/**\n * Masonry layout as a pure function: fixed column count and width, each\n * item packed into the currently shortest column. Unmeasured items use the\n * estimate; poisoned heights fall back the same way. This is layout only,\n * not windowing — every placed item renders, so it fits hundreds of images,\n * not hundred-thousands. Needing a windowed grid is a different algorithm.\n */\nexport const masonry = (\n keys: ReadonlyArray<string>,\n heights: Readonly<Record<string, number>>,\n options: {\n readonly columns: number\n readonly columnWidth: number\n readonly gap: number\n readonly estimatedHeight: number\n },\n): { readonly placements: ReadonlyArray<MasonryPlacement>; readonly totalHeight: number } => {\n if (!Number.isInteger(options.columns) || options.columns < 1) {\n throw new Error(`masonry: columns must be a positive integer, got ${options.columns}`)\n }\n if (!(options.columnWidth > 0) || !Number.isFinite(options.columnWidth)) {\n throw new Error(\n `masonry: columnWidth must be a positive finite number, got ${options.columnWidth}`,\n )\n }\n if (options.gap < 0 || !Number.isFinite(options.gap)) {\n throw new Error(`masonry: gap must be a non-negative finite number, got ${options.gap}`)\n }\n if (options.estimatedHeight < 0 || !Number.isFinite(options.estimatedHeight)) {\n throw new Error(\n `masonry: estimatedHeight must be a non-negative finite number, got ${options.estimatedHeight}`,\n )\n }\n const columnHeights: Array<number> = new Array(options.columns).fill(0)\n const placements: Array<MasonryPlacement> = []\n for (const key of keys) {\n const raw = heights[key] ?? options.estimatedHeight\n const height = Number.isFinite(raw) && raw >= 0 ? raw : options.estimatedHeight\n let column = 0\n for (let c = 1; c < columnHeights.length; c++) {\n if (columnHeights[c]! < columnHeights[column]!) column = c\n }\n placements.push({\n key,\n column,\n x: column * (options.columnWidth + options.gap),\n y: columnHeights[column]!,\n width: options.columnWidth,\n height,\n })\n columnHeights[column] = columnHeights[column]! + height + options.gap\n }\n return {\n placements,\n totalHeight: placements.length === 0 ? 0 : Math.max(...columnHeights) - options.gap,\n }\n}\n"],"mappings":";;;;;;AAIA,MAAa,gBAAuB,UAClC,OAAO,OAAO;CACZ,MAAM,OAAO,MAAM,KAAK;CACxB,SAAS;CACT,QAAQ,OAAO,MAAM,KAAK;;CAE1B,OAAO,OAAO,OAAO,OAAO,MAAM;AACpC,CAAC;AAQH,MAAM,SAAgB,aAAyC;CAC7D,MAAM,CAAC;CACP;CACA,QAAQ,CAAC;CACT,OAAO;AACT;;;;;;AAOA,MAAM,YAAmB,UACvB,MAAM,OAAO,WAAW,IAAI,MAAM,SAAS,CAAC;AAE9C,MAAM,QACJ,OACA,OACA,YACwB;CACxB,MAAM,QAAQ,QAAQ,SAAS;CAE/B,IAAI,UAAU,QAAQ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WAAW,WAAW,IAAI,IAAI,KAAK,IAAI,GAAG,aAAa,IAAI,QAAQ;CAClF;AACF"}
|
package/dist/time/index.d.mts
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { Option, Schema } from "effect";
|
|
2
2
|
import * as Subscription from "foldkit/subscription";
|
|
3
3
|
import { Bundle } from "foldkit-bundle";
|
|
4
|
-
//#region src/time/debounce.d.ts
|
|
5
4
|
/**
|
|
6
5
|
* Debounced input as a bundle factory: `Changed` restarts a timer, and the
|
|
7
6
|
* latest value settles as an OutMessage the placement must handle with
|
|
@@ -42,8 +41,6 @@ export declare const debounce: <const Name extends string, Value>(config: {
|
|
|
42
41
|
readonly value: Schema.Codec<Value, unknown, never, never>;
|
|
43
42
|
}>;
|
|
44
43
|
};
|
|
45
|
-
//#endregion
|
|
46
|
-
//#region src/time/interval.d.ts
|
|
47
44
|
export declare const IntervalModel: Schema.Struct<{
|
|
48
45
|
readonly running: Schema.Boolean;
|
|
49
46
|
readonly lastAt: Schema.NullOr<Schema.Number>;
|
|
@@ -78,8 +75,6 @@ export declare const Interval: Bundle.Bundle<"Interval", {
|
|
|
78
75
|
readonly _tag: "Ticked";
|
|
79
76
|
readonly at: number;
|
|
80
77
|
}, never, never, never, void, {}, {}>;
|
|
81
|
-
//#endregion
|
|
82
|
-
//#region src/time/relative.d.ts
|
|
83
78
|
/**
|
|
84
79
|
* Relative time as a pure function: picks the unit (seconds through years)
|
|
85
80
|
* and delegates the wording to `Intl.RelativeTimeFormat`, so locales come
|
|
@@ -87,8 +82,6 @@ export declare const Interval: Bundle.Bundle<"Interval", {
|
|
|
87
82
|
* swap the arguments for future phrasing ("in 3 days").
|
|
88
83
|
*/
|
|
89
84
|
export declare const formatRelativeTime: (from: Date, to: Date, locale?: string) => string;
|
|
90
|
-
//#endregion
|
|
91
|
-
//#region src/time/throttle.d.ts
|
|
92
85
|
export declare const ThrottleModel: Schema.Struct<{
|
|
93
86
|
readonly lastAt: Schema.NullOr<Schema.Number>;
|
|
94
87
|
}>;
|
|
@@ -124,8 +117,6 @@ export declare const Throttle: Bundle.Bundle<"Throttle", {
|
|
|
124
117
|
readonly _tag: "Throttled";
|
|
125
118
|
readonly at: number;
|
|
126
119
|
}, never, never, void, {}, {}>;
|
|
127
|
-
//#endregion
|
|
128
|
-
//#region src/time/ticks.d.ts
|
|
129
120
|
declare const TickDependencies: {
|
|
130
121
|
intervalMs: Schema.Option<Schema.Number>;
|
|
131
122
|
};
|
|
@@ -143,8 +134,6 @@ export declare const ticks: <Model, Message>(config: {
|
|
|
143
134
|
/** The Message a tick sends, given its time on Effect's clock. */
|
|
144
135
|
readonly onTick: (at: number) => Message;
|
|
145
136
|
}) => Subscription.Subscription<Model, Message, TickDependencies>;
|
|
146
|
-
//#endregion
|
|
147
|
-
//#region src/time/timer.d.ts
|
|
148
137
|
export declare const TimerModel: Schema.Struct<{
|
|
149
138
|
readonly count: Schema.Number;
|
|
150
139
|
readonly running: Schema.Boolean;
|
|
@@ -174,6 +163,5 @@ export declare const Timer: Bundle.Bundle<"Timer", {
|
|
|
174
163
|
} | {
|
|
175
164
|
readonly _tag: "Ticked";
|
|
176
165
|
}, never, never, never, void, {}, {}>;
|
|
177
|
-
//#endregion
|
|
178
166
|
export {};
|
|
179
167
|
//# sourceMappingURL=index.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/time/debounce.ts","../../src/time/interval.ts","../../src/time/relative.ts","../../src/time/throttle.ts","../../src/time/ticks.ts","../../src/time/timer.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/time/debounce.ts","../../src/time/interval.ts","../../src/time/relative.ts","../../src/time/throttle.ts","../../src/time/ticks.ts","../../src/time/timer.ts"],"mappings":";;;;;;;;;;;qBAaa,iBAAkB,qBAAqB,OAAK;WAC9C,MAAM;WACN,OAAO,OAAO,MAAM;MAC9B,OAAA,OAAA;;;;;;;;;;;;;;;;;;MAQc,OAAK,OAAA,MAAA;;;MACL,OAAK,OAAA,MAAA;MAAgB,YAAU,OAAA;;;;;;;qBCnBjC,eAAa,OAAA;;;;YAId,uBAAuB,cAAc;qBAEpC,2CAAe;;;;IAGhB,IAAE,OAAA;;;YAEF,yBAAyB,gBAAgB;;;;;;;;;qBAUxC,UAAQ,OAAA;;;;;;;;;;;;;;;;;;;qBCrBR,qBAAkB,MAAU,MAAI,IAAM,MAAI;qBCD1C,eAAa,OAAA;;;YACd,uBAAuB,cAAc;qBAEpC,2CAAe;;;IAEb,KAAG,OAAA;;;YAEN,yBAAyB,gBAAgB;qBAExC,WAAS,OAAA;;;YACV,mBAAmB,UAAU;;;;;;;;qBAS5B,UAAQ,OAAA;;;;;;;;;;;;;cCff;EAAqB,YAAU,OAAA,OAAA,OAAA;;KAChC;WAA8B,YAAY,OAAO;;;;;;;qBAezC,QAAS,OAAO,SAAO;;WAEzB,aAAa,OAAO,UAAU,OAAO;;WAErC,SAAS,eAAe;MAC/B,aAAa,aAAa,OAAO,SAAS;qBCzBjC,YAAU,OAAA;;;;YACX,oBAAoB,WAAW;qBAE9B,wCAAY;;;;;YAKb,sBAAsB,aAAa;;;;;;;qBAQlC,OAAK,OAAA"}
|
package/dist/time/index.mjs
CHANGED
|
@@ -2,7 +2,7 @@ import { Clock, Effect, Option, Schema, Stream } from "effect";
|
|
|
2
2
|
import { defineMessageUnion } from "foldkit/message";
|
|
3
3
|
import * as Subscription from "foldkit/subscription";
|
|
4
4
|
import { Bundle } from "foldkit-bundle";
|
|
5
|
-
|
|
5
|
+
// src/time/debounce.ts
|
|
6
6
|
/**
|
|
7
7
|
* Debounced input as a bundle factory: `Changed` restarts a timer, and the
|
|
8
8
|
* latest value settles as an OutMessage the placement must handle with
|
|
@@ -61,8 +61,7 @@ const debounce = (config) => {
|
|
|
61
61
|
Debounced
|
|
62
62
|
});
|
|
63
63
|
};
|
|
64
|
-
|
|
65
|
-
//#region src/time/ticks.ts
|
|
64
|
+
// src/time/ticks.ts
|
|
66
65
|
/**
|
|
67
66
|
* A clock the parent owns, as an entry: whether it ticks and how fast are
|
|
68
67
|
* functions of the parent's Model, so nothing keeps a second running flag or
|
|
@@ -87,8 +86,7 @@ const ticks = (config) => Subscription.make()((entry) => ({ ticks: entry(TickDep
|
|
|
87
86
|
onSome: (started) => Stream.fromEffectRepeat(Effect.suspend(() => Effect.sleep(Option.getOrElse(readDependencies().intervalMs, () => started))).pipe(Effect.andThen(Clock.currentTimeMillis), Effect.map(config.onTick)))
|
|
88
87
|
})
|
|
89
88
|
}) })).ticks;
|
|
90
|
-
|
|
91
|
-
//#region src/time/interval.ts
|
|
89
|
+
// src/time/interval.ts
|
|
92
90
|
const IntervalModel = Schema.Struct({
|
|
93
91
|
running: Schema.Boolean,
|
|
94
92
|
lastAt: Schema.NullOr(Schema.Number)
|
|
@@ -133,8 +131,7 @@ const Interval = Bundle.make("Interval", {
|
|
|
133
131
|
onTick: (at) => IntervalMessage.Ticked({ at })
|
|
134
132
|
}) })
|
|
135
133
|
});
|
|
136
|
-
|
|
137
|
-
//#region src/time/relative.ts
|
|
134
|
+
// src/time/relative.ts
|
|
138
135
|
/**
|
|
139
136
|
* Relative time as a pure function: picks the unit (seconds through years)
|
|
140
137
|
* and delegates the wording to `Intl.RelativeTimeFormat`, so locales come
|
|
@@ -158,8 +155,7 @@ const formatRelativeTime = (from, to, locale = "en") => {
|
|
|
158
155
|
if (abs < 31536e3) return format.format(-months, "month");
|
|
159
156
|
return format.format(-Math.round(seconds / 31536e3), "year");
|
|
160
157
|
};
|
|
161
|
-
|
|
162
|
-
//#region src/time/throttle.ts
|
|
158
|
+
// src/time/throttle.ts
|
|
163
159
|
const ThrottleModel = Schema.Struct({ lastAt: Schema.NullOr(Schema.Number) });
|
|
164
160
|
const ThrottleMessage = defineMessageUnion({
|
|
165
161
|
Attempted: {},
|
|
@@ -192,8 +188,7 @@ const Throttle = Bundle.make("Throttle", {
|
|
|
192
188
|
} : { model }
|
|
193
189
|
})
|
|
194
190
|
});
|
|
195
|
-
|
|
196
|
-
//#region src/time/timer.ts
|
|
191
|
+
// src/time/timer.ts
|
|
197
192
|
const TimerModel = Schema.Struct({
|
|
198
193
|
count: Schema.Number,
|
|
199
194
|
running: Schema.Boolean
|
|
@@ -236,7 +231,6 @@ const Timer = Bundle.make("Timer", {
|
|
|
236
231
|
onTick: () => TimerMessage.Ticked()
|
|
237
232
|
}) })
|
|
238
233
|
});
|
|
239
|
-
//#endregion
|
|
240
234
|
export { Interval, IntervalMessage, IntervalModel, Throttle, ThrottleMessage, ThrottleModel, Throttled, Timer, TimerMessage, TimerModel, debounce, formatRelativeTime, ticks };
|
|
241
235
|
|
|
242
236
|
//# sourceMappingURL=index.mjs.map
|
package/dist/time/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/time/debounce.ts","../../src/time/ticks.ts","../../src/time/interval.ts","../../src/time/relative.ts","../../src/time/throttle.ts","../../src/time/timer.ts"],"sourcesContent":["import { Effect, Schema } from 'effect'\nimport { defineMessageUnion } from 'foldkit/message'\nimport type * as Update from 'foldkit/update'\nimport { Bundle } from 'foldkit-bundle'\n\n/**\n * Debounced input as a bundle factory: `Changed` restarts a timer, and the\n * latest value settles as an OutMessage the placement must handle with\n * `onOut`. Each `Changed` bumps a generation carried by the `Settled` fact\n * it schedules, so a superseded timer's fact emits nothing — the same guard\n * as Presence's exit timeout. Generic over the value Schema, like History.\n * The clock is Effect's, so tests drive it with TestClock.\n */\nexport const debounce = <const Name extends string, Value>(config: {\n readonly name: Name\n readonly value: Schema.Codec<Value, unknown>\n}) => {\n const Model = Schema.Struct({\n latest: Schema.NullOr(config.value),\n generation: Schema.Number,\n })\n type Model = typeof Model.Type\n\n const Message = defineMessageUnion({\n Changed: { value: config.value },\n Settled: { value: config.value, generation: Schema.Number },\n })\n type Message = typeof Message.Type\n\n const Debounced = Schema.TaggedStruct('Debounced', { value: config.value })\n type Debounced = typeof Debounced.Type\n\n const bundle = Bundle.make(config.name, {\n Model,\n Message,\n args: Schema.Struct({\n delayMs: Schema.Number.pipe(\n Schema.check(Schema.isGreaterThan(0)),\n Schema.check(Schema.isFinite()),\n ),\n }),\n init: () => ({ model: { latest: null, generation: 0 } }),\n update: (model, message, args) =>\n Message.match<Update.ReturnWithOutMessage<Model, Message, Debounced>>(message, {\n Changed: ({ value }) => {\n const generation = model.generation + 1\n return {\n model: { latest: value, generation },\n commands: [\n {\n name: `${config.name}.settle`,\n args: { generation },\n effect: Effect.as(\n Effect.sleep(args.delayMs),\n Message.Settled({ value, generation }),\n ),\n },\n ],\n }\n },\n // A superseded timer's fact arrives with an old generation: no\n // OutMessage, so the placement never sees it.\n Settled: ({ generation, value }) =>\n generation === model.generation\n ? { model, outMessage: Debounced.make({ value }) }\n : { model },\n }),\n })\n\n return Object.assign(bundle, { Message, Debounced })\n}\n","/**\n * A clock the parent owns, as an entry: whether it ticks and how fast are\n * functions of the parent's Model, so nothing keeps a second running flag or\n * interval beside the state they derive from (a game's phase and score).\n * Timer and Interval are built on it, for a clock that owns its own flag.\n */\nimport { Clock, Effect, Option, Schema, Stream } from 'effect'\nimport * as Subscription from 'foldkit/subscription'\n\nconst TickDependencies = { intervalMs: Schema.Option(Schema.Number) }\ntype TickDependencies = { readonly intervalMs: Option.Option<number> }\n\nconst checked = (intervalMs: Option.Option<number>): Option.Option<number> => {\n // A zero, negative or non-finite interval would spin or never tick; the\n // runtime crashes on a defect here, which names the mistake where it is made.\n if (Option.isSome(intervalMs) && !(intervalMs.value > 0 && Number.isFinite(intervalMs.value)))\n throw new Error(`ticks: intervalMs must be positive and finite, got ${intervalMs.value}`)\n return intervalMs\n}\n\n/**\n * Ticks while `intervalMs` answers `Some`, each tick one interval after the\n * last and the first one interval after starting. A changed interval applies\n * from the next tick, with no restart; other Model changes do nothing.\n */\nexport const ticks = <Model, Message>(config: {\n /** The time between ticks for this Model, in milliseconds; `None` stops the clock. */\n readonly intervalMs: (model: Model) => Option.Option<number>\n /** The Message a tick sends, given its time on Effect's clock. */\n readonly onTick: (at: number) => Message\n}): Subscription.Subscription<Model, Message, TickDependencies> =>\n Subscription.make<Model, Message>()(entry => ({\n ticks: entry(TickDependencies, {\n modelToDependencies: model => ({ intervalMs: checked(config.intervalMs(model)) }),\n // Stopping and starting restart the stream; a new interval does not, so\n // a clock that speeds up keeps its phase instead of ticking at once.\n keepAliveEquivalence: (a, b) => Option.isSome(a.intervalMs) === Option.isSome(b.intervalMs),\n dependenciesToStream: ({ intervalMs }, readDependencies) =>\n Option.match(intervalMs, {\n onNone: () => Stream.empty,\n onSome: started =>\n Stream.fromEffectRepeat(\n Effect.suspend(() =>\n Effect.sleep(Option.getOrElse(readDependencies().intervalMs, () => started)),\n ).pipe(Effect.andThen(Clock.currentTimeMillis), Effect.map(config.onTick)),\n ),\n }),\n }),\n })).ticks\n","import { Option, Schema } from 'effect'\nimport { defineMessageUnion } from 'foldkit/message'\nimport type * as Update from 'foldkit/update'\nimport { Bundle } from 'foldkit-bundle'\nimport { ticks } from './ticks.js'\n\nexport const IntervalModel = Schema.Struct({\n running: Schema.Boolean,\n lastAt: Schema.NullOr(Schema.Number),\n})\nexport type IntervalModel = typeof IntervalModel.Type\n\nexport const IntervalMessage = defineMessageUnion({\n Started: {},\n Stopped: {},\n Ticked: { at: Schema.Number },\n})\nexport type IntervalMessage = typeof IntervalMessage.Type\n\n/**\n * A wall-clock interval as a bundle: the last tick time in the Model,\n * advanced by a tick stream while running. Sibling of Timer (which counts\n * ticks); this one records *when* they happened, so views can render clocks\n * and elapsed times. The clock is Effect's, so tests drive it with TestClock.\n * For a clock whose running or interval the parent's Model decides, use the\n * `ticks` entry instead.\n */\nexport const Interval = Bundle.make('Interval', {\n Model: IntervalModel,\n Message: IntervalMessage,\n args: Schema.Struct({\n intervalMs: Schema.Number.pipe(\n Schema.check(Schema.isGreaterThan(0)),\n Schema.check(Schema.isFinite()),\n ),\n }),\n init: () => ({ model: { running: false, lastAt: null } }),\n update: (model, message) =>\n IntervalMessage.match<Update.ReturnWithOutMessage<IntervalModel, IntervalMessage, never>>(\n message,\n {\n Started: () => (model.running ? { model } : { model: { ...model, running: true } }),\n Stopped: () => (model.running ? { model: { ...model, running: false } } : { model }),\n Ticked: ({ at }) => ({ model: { ...model, lastAt: at } }),\n },\n ),\n subscriptions: ({ intervalMs }) => ({\n ticks: ticks<IntervalModel, IntervalMessage>({\n intervalMs: model => (model.running ? Option.some(intervalMs) : Option.none()),\n onTick: at => IntervalMessage.Ticked({ at }),\n }),\n }),\n})\n","/**\n * Relative time as a pure function: picks the unit (seconds through years)\n * and delegates the wording to `Intl.RelativeTimeFormat`, so locales come\n * from the platform, not a phrase table. `from` is the earlier moment;\n * swap the arguments for future phrasing (\"in 3 days\").\n */\nexport const formatRelativeTime = (from: Date, to: Date, locale = 'en'): string => {\n const format = new Intl.RelativeTimeFormat(locale, { numeric: 'auto' })\n const seconds = Math.round((to.getTime() - from.getTime()) / 1000)\n const abs = Math.abs(seconds)\n if (abs < 60) return format.format(-seconds, 'second')\n const minutes = Math.round(seconds / 60)\n if (abs < 60 * 60) return format.format(-minutes, 'minute')\n const hours = Math.round(seconds / (60 * 60))\n if (abs < 24 * 60 * 60) return format.format(-hours, 'hour')\n const days = Math.round(seconds / (24 * 60 * 60))\n if (abs < 7 * 24 * 60 * 60) return format.format(-days, 'day')\n const weeks = Math.round(seconds / (7 * 24 * 60 * 60))\n if (abs < 30 * 24 * 60 * 60) return format.format(-weeks, 'week')\n const months = Math.round(seconds / (30 * 24 * 60 * 60))\n if (abs < 365 * 24 * 60 * 60) return format.format(-months, 'month')\n return format.format(-Math.round(seconds / (365 * 24 * 60 * 60)), 'year')\n}\n","import { Clock, Effect, Schema } from 'effect'\nimport { defineMessageUnion } from 'foldkit/message'\nimport type * as Update from 'foldkit/update'\nimport { Bundle } from 'foldkit-bundle'\n\nexport const ThrottleModel = Schema.Struct({ lastAt: Schema.NullOr(Schema.Number) })\nexport type ThrottleModel = typeof ThrottleModel.Type\n\nexport const ThrottleMessage = defineMessageUnion({\n Attempted: {},\n Evaluated: { now: Schema.Number },\n})\nexport type ThrottleMessage = typeof ThrottleMessage.Type\n\nexport const Throttled = Schema.TaggedStruct('Throttled', { at: Schema.Number })\nexport type Throttled = typeof Throttled.Type\n\n/**\n * Leading-edge throttle as a bundle: the first `Attempted` in an interval\n * surfaces a `Throttled` OutMessage, the rest are dropped. `Attempted`\n * reads the clock through a Command, so the check runs against Effect time\n * and tests drive it with TestClock. Trailing-edge needs are Debounce's:\n * pair the two rather than adding a second timer here.\n */\nexport const Throttle = Bundle.make('Throttle', {\n Model: ThrottleModel,\n Message: ThrottleMessage,\n args: Schema.Struct({\n intervalMs: Schema.Number.pipe(\n Schema.check(Schema.isGreaterThan(0)),\n Schema.check(Schema.isFinite()),\n ),\n }),\n init: () => ({ model: { lastAt: null } }),\n update: (model, message, args) =>\n ThrottleMessage.match<Update.ReturnWithOutMessage<ThrottleModel, ThrottleMessage, Throttled>>(\n message,\n {\n Attempted: () => ({\n model,\n commands: [\n {\n name: 'Throttle.evaluate',\n effect: Effect.map(Clock.currentTimeMillis, now =>\n ThrottleMessage.Evaluated({ now }),\n ),\n },\n ],\n }),\n // First attempt ever, or the interval has passed: fire and stamp.\n Evaluated: ({ now }) =>\n model.lastAt === null || now - model.lastAt >= args.intervalMs\n ? { model: { lastAt: now }, outMessage: Throttled.make({ at: now }) }\n : { model },\n },\n ),\n})\n","import { Option, Schema } from 'effect'\nimport { defineMessageUnion } from 'foldkit/message'\nimport { Bundle } from 'foldkit-bundle'\nimport { ticks } from './ticks.js'\n\nexport const TimerModel = Schema.Struct({ count: Schema.Number, running: Schema.Boolean })\nexport type TimerModel = typeof TimerModel.Type\n\nexport const TimerMessage = defineMessageUnion({\n Started: {},\n Stopped: {},\n Ticked: {},\n})\nexport type TimerMessage = typeof TimerMessage.Type\n\n/**\n * A timer as a bundle: a count in the Model, advanced by a tick stream while\n * running. The clock is Effect's, so tests drive it with TestClock instead of\n * waiting. For a clock whose running or interval the parent's Model decides,\n * use the `ticks` entry instead.\n */\nexport const Timer = Bundle.make('Timer', {\n Model: TimerModel,\n Message: TimerMessage,\n args: Schema.Struct({\n intervalMs: Schema.Number.pipe(\n Schema.check(Schema.isGreaterThan(0)),\n Schema.check(Schema.isFinite()),\n ),\n }),\n init: () => ({ model: { count: 0, running: false } }),\n update: (model, message) =>\n TimerMessage.match(message, {\n Started: () => (model.running ? { model } : { model: { ...model, running: true } }),\n Stopped: () => (model.running ? { model: { ...model, running: false } } : { model }),\n Ticked: () => ({ model: { ...model, count: model.count + 1 } }),\n }),\n subscriptions: ({ intervalMs }) => ({\n ticks: ticks<TimerModel, TimerMessage>({\n intervalMs: model => (model.running ? Option.some(intervalMs) : Option.none()),\n onTick: () => TimerMessage.Ticked(),\n }),\n }),\n})\n"],"mappings":";;;;;;;;;;;;;AAaA,MAAa,YAA8C,WAGrD;CACJ,MAAM,QAAQ,OAAO,OAAO;EAC1B,QAAQ,OAAO,OAAO,OAAO,KAAK;EAClC,YAAY,OAAO;CACrB,CAAC;CAGD,MAAM,UAAU,mBAAmB;EACjC,SAAS,EAAE,OAAO,OAAO,MAAM;EAC/B,SAAS;GAAE,OAAO,OAAO;GAAO,YAAY,OAAO;EAAO;CAC5D,CAAC;CAGD,MAAM,YAAY,OAAO,aAAa,aAAa,EAAE,OAAO,OAAO,MAAM,CAAC;CAG1E,MAAM,SAAS,OAAO,KAAK,OAAO,MAAM;EACtC;EACA;EACA,MAAM,OAAO,OAAO,EAClB,SAAS,OAAO,OAAO,KACrB,OAAO,MAAM,OAAO,cAAc,CAAC,CAAC,GACpC,OAAO,MAAM,OAAO,SAAS,CAAC,CAChC,EACF,CAAC;EACD,aAAa,EAAE,OAAO;GAAE,QAAQ;GAAM,YAAY;EAAE,EAAE;EACtD,SAAS,OAAO,SAAS,SACvB,QAAQ,MAA8D,SAAS;GAC7E,UAAU,EAAE,YAAY;IACtB,MAAM,aAAa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EAC5E,cAAc,aAAa,OAAO;CACpC,CAAC,EACH;AACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/time/debounce.ts","../../src/time/ticks.ts","../../src/time/interval.ts","../../src/time/relative.ts","../../src/time/throttle.ts","../../src/time/timer.ts"],"sourcesContent":["import { Effect, Schema } from 'effect'\nimport { defineMessageUnion } from 'foldkit/message'\nimport type * as Update from 'foldkit/update'\nimport { Bundle } from 'foldkit-bundle'\n\n/**\n * Debounced input as a bundle factory: `Changed` restarts a timer, and the\n * latest value settles as an OutMessage the placement must handle with\n * `onOut`. Each `Changed` bumps a generation carried by the `Settled` fact\n * it schedules, so a superseded timer's fact emits nothing — the same guard\n * as Presence's exit timeout. Generic over the value Schema, like History.\n * The clock is Effect's, so tests drive it with TestClock.\n */\nexport const debounce = <const Name extends string, Value>(config: {\n readonly name: Name\n readonly value: Schema.Codec<Value, unknown>\n}) => {\n const Model = Schema.Struct({\n latest: Schema.NullOr(config.value),\n generation: Schema.Number,\n })\n type Model = typeof Model.Type\n\n const Message = defineMessageUnion({\n Changed: { value: config.value },\n Settled: { value: config.value, generation: Schema.Number },\n })\n type Message = typeof Message.Type\n\n const Debounced = Schema.TaggedStruct('Debounced', { value: config.value })\n type Debounced = typeof Debounced.Type\n\n const bundle = Bundle.make(config.name, {\n Model,\n Message,\n args: Schema.Struct({\n delayMs: Schema.Number.pipe(\n Schema.check(Schema.isGreaterThan(0)),\n Schema.check(Schema.isFinite()),\n ),\n }),\n init: () => ({ model: { latest: null, generation: 0 } }),\n update: (model, message, args) =>\n Message.match<Update.ReturnWithOutMessage<Model, Message, Debounced>>(message, {\n Changed: ({ value }) => {\n const generation = model.generation + 1\n return {\n model: { latest: value, generation },\n commands: [\n {\n name: `${config.name}.settle`,\n args: { generation },\n effect: Effect.as(\n Effect.sleep(args.delayMs),\n Message.Settled({ value, generation }),\n ),\n },\n ],\n }\n },\n // A superseded timer's fact arrives with an old generation: no\n // OutMessage, so the placement never sees it.\n Settled: ({ generation, value }) =>\n generation === model.generation\n ? { model, outMessage: Debounced.make({ value }) }\n : { model },\n }),\n })\n\n return Object.assign(bundle, { Message, Debounced })\n}\n","/**\n * A clock the parent owns, as an entry: whether it ticks and how fast are\n * functions of the parent's Model, so nothing keeps a second running flag or\n * interval beside the state they derive from (a game's phase and score).\n * Timer and Interval are built on it, for a clock that owns its own flag.\n */\nimport { Clock, Effect, Option, Schema, Stream } from 'effect'\nimport * as Subscription from 'foldkit/subscription'\n\nconst TickDependencies = { intervalMs: Schema.Option(Schema.Number) }\ntype TickDependencies = { readonly intervalMs: Option.Option<number> }\n\nconst checked = (intervalMs: Option.Option<number>): Option.Option<number> => {\n // A zero, negative or non-finite interval would spin or never tick; the\n // runtime crashes on a defect here, which names the mistake where it is made.\n if (Option.isSome(intervalMs) && !(intervalMs.value > 0 && Number.isFinite(intervalMs.value)))\n throw new Error(`ticks: intervalMs must be positive and finite, got ${intervalMs.value}`)\n return intervalMs\n}\n\n/**\n * Ticks while `intervalMs` answers `Some`, each tick one interval after the\n * last and the first one interval after starting. A changed interval applies\n * from the next tick, with no restart; other Model changes do nothing.\n */\nexport const ticks = <Model, Message>(config: {\n /** The time between ticks for this Model, in milliseconds; `None` stops the clock. */\n readonly intervalMs: (model: Model) => Option.Option<number>\n /** The Message a tick sends, given its time on Effect's clock. */\n readonly onTick: (at: number) => Message\n}): Subscription.Subscription<Model, Message, TickDependencies> =>\n Subscription.make<Model, Message>()(entry => ({\n ticks: entry(TickDependencies, {\n modelToDependencies: model => ({ intervalMs: checked(config.intervalMs(model)) }),\n // Stopping and starting restart the stream; a new interval does not, so\n // a clock that speeds up keeps its phase instead of ticking at once.\n keepAliveEquivalence: (a, b) => Option.isSome(a.intervalMs) === Option.isSome(b.intervalMs),\n dependenciesToStream: ({ intervalMs }, readDependencies) =>\n Option.match(intervalMs, {\n onNone: () => Stream.empty,\n onSome: started =>\n Stream.fromEffectRepeat(\n Effect.suspend(() =>\n Effect.sleep(Option.getOrElse(readDependencies().intervalMs, () => started)),\n ).pipe(Effect.andThen(Clock.currentTimeMillis), Effect.map(config.onTick)),\n ),\n }),\n }),\n })).ticks\n","import { Option, Schema } from 'effect'\nimport { defineMessageUnion } from 'foldkit/message'\nimport type * as Update from 'foldkit/update'\nimport { Bundle } from 'foldkit-bundle'\nimport { ticks } from './ticks.js'\n\nexport const IntervalModel = Schema.Struct({\n running: Schema.Boolean,\n lastAt: Schema.NullOr(Schema.Number),\n})\nexport type IntervalModel = typeof IntervalModel.Type\n\nexport const IntervalMessage = defineMessageUnion({\n Started: {},\n Stopped: {},\n Ticked: { at: Schema.Number },\n})\nexport type IntervalMessage = typeof IntervalMessage.Type\n\n/**\n * A wall-clock interval as a bundle: the last tick time in the Model,\n * advanced by a tick stream while running. Sibling of Timer (which counts\n * ticks); this one records *when* they happened, so views can render clocks\n * and elapsed times. The clock is Effect's, so tests drive it with TestClock.\n * For a clock whose running or interval the parent's Model decides, use the\n * `ticks` entry instead.\n */\nexport const Interval = Bundle.make('Interval', {\n Model: IntervalModel,\n Message: IntervalMessage,\n args: Schema.Struct({\n intervalMs: Schema.Number.pipe(\n Schema.check(Schema.isGreaterThan(0)),\n Schema.check(Schema.isFinite()),\n ),\n }),\n init: () => ({ model: { running: false, lastAt: null } }),\n update: (model, message) =>\n IntervalMessage.match<Update.ReturnWithOutMessage<IntervalModel, IntervalMessage, never>>(\n message,\n {\n Started: () => (model.running ? { model } : { model: { ...model, running: true } }),\n Stopped: () => (model.running ? { model: { ...model, running: false } } : { model }),\n Ticked: ({ at }) => ({ model: { ...model, lastAt: at } }),\n },\n ),\n subscriptions: ({ intervalMs }) => ({\n ticks: ticks<IntervalModel, IntervalMessage>({\n intervalMs: model => (model.running ? Option.some(intervalMs) : Option.none()),\n onTick: at => IntervalMessage.Ticked({ at }),\n }),\n }),\n})\n","/**\n * Relative time as a pure function: picks the unit (seconds through years)\n * and delegates the wording to `Intl.RelativeTimeFormat`, so locales come\n * from the platform, not a phrase table. `from` is the earlier moment;\n * swap the arguments for future phrasing (\"in 3 days\").\n */\nexport const formatRelativeTime = (from: Date, to: Date, locale = 'en'): string => {\n const format = new Intl.RelativeTimeFormat(locale, { numeric: 'auto' })\n const seconds = Math.round((to.getTime() - from.getTime()) / 1000)\n const abs = Math.abs(seconds)\n if (abs < 60) return format.format(-seconds, 'second')\n const minutes = Math.round(seconds / 60)\n if (abs < 60 * 60) return format.format(-minutes, 'minute')\n const hours = Math.round(seconds / (60 * 60))\n if (abs < 24 * 60 * 60) return format.format(-hours, 'hour')\n const days = Math.round(seconds / (24 * 60 * 60))\n if (abs < 7 * 24 * 60 * 60) return format.format(-days, 'day')\n const weeks = Math.round(seconds / (7 * 24 * 60 * 60))\n if (abs < 30 * 24 * 60 * 60) return format.format(-weeks, 'week')\n const months = Math.round(seconds / (30 * 24 * 60 * 60))\n if (abs < 365 * 24 * 60 * 60) return format.format(-months, 'month')\n return format.format(-Math.round(seconds / (365 * 24 * 60 * 60)), 'year')\n}\n","import { Clock, Effect, Schema } from 'effect'\nimport { defineMessageUnion } from 'foldkit/message'\nimport type * as Update from 'foldkit/update'\nimport { Bundle } from 'foldkit-bundle'\n\nexport const ThrottleModel = Schema.Struct({ lastAt: Schema.NullOr(Schema.Number) })\nexport type ThrottleModel = typeof ThrottleModel.Type\n\nexport const ThrottleMessage = defineMessageUnion({\n Attempted: {},\n Evaluated: { now: Schema.Number },\n})\nexport type ThrottleMessage = typeof ThrottleMessage.Type\n\nexport const Throttled = Schema.TaggedStruct('Throttled', { at: Schema.Number })\nexport type Throttled = typeof Throttled.Type\n\n/**\n * Leading-edge throttle as a bundle: the first `Attempted` in an interval\n * surfaces a `Throttled` OutMessage, the rest are dropped. `Attempted`\n * reads the clock through a Command, so the check runs against Effect time\n * and tests drive it with TestClock. Trailing-edge needs are Debounce's:\n * pair the two rather than adding a second timer here.\n */\nexport const Throttle = Bundle.make('Throttle', {\n Model: ThrottleModel,\n Message: ThrottleMessage,\n args: Schema.Struct({\n intervalMs: Schema.Number.pipe(\n Schema.check(Schema.isGreaterThan(0)),\n Schema.check(Schema.isFinite()),\n ),\n }),\n init: () => ({ model: { lastAt: null } }),\n update: (model, message, args) =>\n ThrottleMessage.match<Update.ReturnWithOutMessage<ThrottleModel, ThrottleMessage, Throttled>>(\n message,\n {\n Attempted: () => ({\n model,\n commands: [\n {\n name: 'Throttle.evaluate',\n effect: Effect.map(Clock.currentTimeMillis, now =>\n ThrottleMessage.Evaluated({ now }),\n ),\n },\n ],\n }),\n // First attempt ever, or the interval has passed: fire and stamp.\n Evaluated: ({ now }) =>\n model.lastAt === null || now - model.lastAt >= args.intervalMs\n ? { model: { lastAt: now }, outMessage: Throttled.make({ at: now }) }\n : { model },\n },\n ),\n})\n","import { Option, Schema } from 'effect'\nimport { defineMessageUnion } from 'foldkit/message'\nimport { Bundle } from 'foldkit-bundle'\nimport { ticks } from './ticks.js'\n\nexport const TimerModel = Schema.Struct({ count: Schema.Number, running: Schema.Boolean })\nexport type TimerModel = typeof TimerModel.Type\n\nexport const TimerMessage = defineMessageUnion({\n Started: {},\n Stopped: {},\n Ticked: {},\n})\nexport type TimerMessage = typeof TimerMessage.Type\n\n/**\n * A timer as a bundle: a count in the Model, advanced by a tick stream while\n * running. The clock is Effect's, so tests drive it with TestClock instead of\n * waiting. For a clock whose running or interval the parent's Model decides,\n * use the `ticks` entry instead.\n */\nexport const Timer = Bundle.make('Timer', {\n Model: TimerModel,\n Message: TimerMessage,\n args: Schema.Struct({\n intervalMs: Schema.Number.pipe(\n Schema.check(Schema.isGreaterThan(0)),\n Schema.check(Schema.isFinite()),\n ),\n }),\n init: () => ({ model: { count: 0, running: false } }),\n update: (model, message) =>\n TimerMessage.match(message, {\n Started: () => (model.running ? { model } : { model: { ...model, running: true } }),\n Stopped: () => (model.running ? { model: { ...model, running: false } } : { model }),\n Ticked: () => ({ model: { ...model, count: model.count + 1 } }),\n }),\n subscriptions: ({ intervalMs }) => ({\n ticks: ticks<TimerModel, TimerMessage>({\n intervalMs: model => (model.running ? Option.some(intervalMs) : Option.none()),\n onTick: () => TimerMessage.Ticked(),\n }),\n }),\n})\n"],"mappings":";;;;;;;;;;;;;AAaA,MAAa,YAA8C,WAGrD;CACJ,MAAM,QAAQ,OAAO,OAAO;EAC1B,QAAQ,OAAO,OAAO,OAAO,KAAK;EAClC,YAAY,OAAO;CACrB,CAAC;CAGD,MAAM,UAAU,mBAAmB;EACjC,SAAS,EAAE,OAAO,OAAO,MAAM;EAC/B,SAAS;GAAE,OAAO,OAAO;GAAO,YAAY,OAAO;EAAO;CAC5D,CAAC;CAGD,MAAM,YAAY,OAAO,aAAa,aAAa,EAAE,OAAO,OAAO,MAAM,CAAC;CAG1E,MAAM,SAAS,OAAO,KAAK,OAAO,MAAM;EACtC;EACA;EACA,MAAM,OAAO,OAAO,EAClB,SAAS,OAAO,OAAO,KACrB,OAAO,MAAM,OAAO,cAAc,CAAC,CAAC,GACpC,OAAO,MAAM,OAAO,SAAS,CAAC,CAChC,EACF,CAAC;EACD,aAAa,EAAE,OAAO;GAAE,QAAQ;GAAM,YAAY;EAAE,EAAE;EACtD,SAAS,OAAO,SAAS,SACvB,QAAQ,MAA8D,SAAS;GAC7E,UAAU,EAAE,YAAY;IACtB,MAAM,aAAa,MAAM,aAAa;IACtC,OAAO;KACL,OAAO;MAAE,QAAQ;MAAO;KAAW;KACnC,UAAU,CACR;MACE,MAAM,GAAG,OAAO,KAAK;MACrB,MAAM,EAAE,WAAW;MACnB,QAAQ,OAAO,GACb,OAAO,MAAM,KAAK,OAAO,GACzB,QAAQ,QAAQ;OAAE;OAAO;MAAW,CAAC,CACvC;KACF,CACF;IACF;GACF;GAGA,UAAU,EAAE,YAAY,YACtB,eAAe,MAAM,aACjB;IAAE;IAAO,YAAY,UAAU,KAAK,EAAE,MAAM,CAAC;GAAE,IAC/C,EAAE,MAAM;EAChB,CAAC;CACL,CAAC;CAED,OAAO,OAAO,OAAO,QAAQ;EAAE;EAAS;CAAU,CAAC;AACrD;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,eAAe,mBAAmB;CAC7C,SAAS,CAAC;CACV,SAAS,CAAC;CACV,QAAQ,CAAC;AACX,CAAC;;;;;;;AASD,MAAa,QAAQ,OAAO,KAAK,SAAS;CACxC,OAAO;CACP,SAAS;CACT,MAAM,OAAO,OAAO,EAClB,YAAY,OAAO,OAAO,KACxB,OAAO,MAAM,OAAO,cAAc,CAAC,CAAC,GACpC,OAAO,MAAM,OAAO,SAAS,CAAC,CAChC,EACF,CAAC;CACD,aAAa,EAAE,OAAO;EAAE,OAAO;EAAG,SAAS;CAAM,EAAE;CACnD,SAAS,OAAO,YACd,aAAa,MAAM,SAAS;EAC1B,eAAgB,MAAM,UAAU,EAAE,MAAM,IAAI,EAAE,OAAO;GAAE,GAAG;GAAO,SAAS;EAAK,EAAE;EACjF,eAAgB,MAAM,UAAU,EAAE,OAAO;GAAE,GAAG;GAAO,SAAS;EAAM,EAAE,IAAI,EAAE,MAAM;EAClF,eAAe,EAAE,OAAO;GAAE,GAAG;GAAO,OAAO,MAAM,QAAQ;EAAE,EAAE;CAC/D,CAAC;CACH,gBAAgB,EAAE,kBAAkB,EAClC,OAAO,MAAgC;EACrC,aAAY,UAAU,MAAM,UAAU,OAAO,KAAK,UAAU,IAAI,OAAO,KAAK;EAC5E,cAAc,aAAa,OAAO;CACpC,CAAC,EACH;AACF,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "foldkit-primitives",
|
|
3
|
-
"version": "0.15.
|
|
3
|
+
"version": "0.15.4",
|
|
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",
|
|
@@ -94,7 +94,7 @@
|
|
|
94
94
|
"peerDependencies": {
|
|
95
95
|
"effect": "^4.0.0",
|
|
96
96
|
"foldkit": "^0.169.0",
|
|
97
|
-
"foldkit-mixins": "^0.
|
|
97
|
+
"foldkit-mixins": "^0.20.0"
|
|
98
98
|
},
|
|
99
99
|
"devDependencies": {
|
|
100
100
|
"@effect/platform-browser": "^4.0.5",
|
|
@@ -105,7 +105,7 @@
|
|
|
105
105
|
"tsdown": "^0.23.1",
|
|
106
106
|
"typescript": "7.0.2",
|
|
107
107
|
"ws": "^8.22.0",
|
|
108
|
-
"foldkit-mixins": "0.
|
|
108
|
+
"foldkit-mixins": "0.20.0"
|
|
109
109
|
},
|
|
110
110
|
"peerDependenciesMeta": {
|
|
111
111
|
"foldkit-mixins": {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"editable-text-1D31qthY.d.mts","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"],"mappings":";;;;cAmBa,iBAAc,MAAU,YAAU,cAAc;;;;;;;;cAmBhD,YAAU,MAAA;;;;;;;;;;;;cCtBV,YAAU,MAAA;;cAWV,aAAW,MAAA;;;cCxBX,aAAW,OAAA;;;;KAIZ,qBAAqB,YAAY;cAEhC,OAAK,OAAA;;;;;;;KAON,eAAe,MAAM;cAEpB,WAAS,OAAA;;;;;KAKV,mBAAmB,UAAU;KAE7B,OAAO,cAAc,QAAQ;;;;;;;;cAsB5B,MAAI,MAAA;;;;;;;;;;;;;;;;;cC5CJ,eAAa,OAAA;;;;KAId,uBAAuB,cAAc;cAEpC,eAAa,OAAA;;;;;;;KAOd,uBAAuB,cAAc;KAErC,aAAa,gBAAgB;;cAU5B,WAAQ,WAAe,SAAO,MAAQ,oBAAkB;;;;;;;;;;;cAgBxD,SAAO,MAAA;;;;;;;;;;;;;;;;;;cCxCP,UAAQ,OAAA;KACT,kBAAkB,SAAS;;;;;;cAO1B,WAAS,OAAA;;;;;KAKV,mBAAmB,UAAU;cAE5B,aAAW,OAAA;;eAAX,OAAA;;KAID,qBAAqB,YAAY;cAE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;cAEhC,yCAAa;;;;IAGd,OAAK,OAAA;IAAiB,UAAQ,OAAA;;;;IAE5B,OAAK,OAAA;;;KAEP,uBAAuB,cAAc;;;;;;;;cAoBpC,QAAM,OAAA;;;;;;;;;;;;;;;;;;;;;;;cClCN,YAAU,OAAA;;;;KACX,oBAAoB,WAAW;cAE9B,wCAAY;;;;IAGb,OAAK,OAAA;;;;IAEH,OAAK,OAAA;;;KAEP,sBAAsB,aAAa;;;;;;;cAQlC,OAAK,OAAA"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"input-modality-BY-bSrEc.d.mts","names":[],"sources":["../src/events/input-modality.ts"],"mappings":";;;cAKa,UAAQ,OAAA;KACT,kBAAkB,SAAS;cAE1B,oBAAkB,OAAA;qBAAlB,OAAA;;KACD,4BAA4B,mBAAmB;cAE9C,gDAAoB;;IAAmC,UAAQ,OAAA;;;KAChE,8BAA8B,qBAAqB;;cAKlD,gBAAa,gBAAkB;;;;;;;;cA0B/B,eAAa,OAAA"}
|