foldkit-ssr 0.11.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/README.md +656 -83
  2. package/dist/{client-qmdYY-Eb.d.ts → client-cumvT9XN.d.ts} +10 -7
  3. package/dist/client-cumvT9XN.d.ts.map +1 -0
  4. package/dist/client.d.ts +6 -5
  5. package/dist/client.js +64 -16
  6. package/dist/client.js.map +1 -1
  7. package/dist/context.d.ts +1 -1
  8. package/dist/context.js.map +1 -1
  9. package/dist/diagnostics.d.ts +2 -2
  10. package/dist/diagnostics.js +7 -1
  11. package/dist/diagnostics.js.map +1 -1
  12. package/dist/handoff.d.ts +23 -0
  13. package/dist/handoff.d.ts.map +1 -0
  14. package/dist/handoff.js +15 -0
  15. package/dist/handoff.js.map +1 -0
  16. package/dist/index.d.ts +66 -26
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js +282 -56
  19. package/dist/index.js.map +1 -1
  20. package/dist/keep.d.ts +3 -1
  21. package/dist/keep.d.ts.map +1 -1
  22. package/dist/keep.js +21 -6
  23. package/dist/keep.js.map +1 -1
  24. package/dist/{listen-DaUPRKVR.d.ts → listen-7HzKBhqU.d.ts} +11 -2
  25. package/dist/{listen-DaUPRKVR.d.ts.map → listen-7HzKBhqU.d.ts.map} +1 -1
  26. package/dist/listen.d.ts +2 -2
  27. package/dist/listen.js +17 -7
  28. package/dist/listen.js.map +1 -1
  29. package/dist/loader.d.ts +13 -0
  30. package/dist/loader.d.ts.map +1 -0
  31. package/dist/loader.js +156 -0
  32. package/dist/loader.js.map +1 -0
  33. package/dist/marks-CX15BwOw.d.ts +39 -0
  34. package/dist/marks-CX15BwOw.d.ts.map +1 -0
  35. package/dist/marks.d.ts +2 -0
  36. package/dist/marks.js +41 -0
  37. package/dist/marks.js.map +1 -0
  38. package/dist/{resumable-BPN_qQHU.d.ts → resumable-BV9_OKxr.d.ts} +7 -10
  39. package/dist/resumable-BV9_OKxr.d.ts.map +1 -0
  40. package/dist/resumable.d.ts +2 -1
  41. package/dist/resumable.js +16 -19
  42. package/dist/resumable.js.map +1 -1
  43. package/dist/runtimeChunk.d.ts +13 -0
  44. package/dist/runtimeChunk.d.ts.map +1 -0
  45. package/dist/runtimeChunk.js +36 -0
  46. package/dist/runtimeChunk.js.map +1 -0
  47. package/dist/runtimeUrl.d.ts +10 -0
  48. package/dist/runtimeUrl.d.ts.map +1 -0
  49. package/dist/runtimeUrl.js +13 -0
  50. package/dist/runtimeUrl.js.map +1 -0
  51. package/dist/{shared-CJN-m58Z.d.ts → shared-BuCOwm57.d.ts} +62 -20
  52. package/dist/shared-BuCOwm57.d.ts.map +1 -0
  53. package/dist/shared.d.ts +3 -2
  54. package/dist/shared.js +36 -13
  55. package/dist/shared.js.map +1 -1
  56. package/dist/vite.d.ts +19 -5
  57. package/dist/vite.d.ts.map +1 -1
  58. package/dist/vite.js +9 -2
  59. package/dist/vite.js.map +1 -1
  60. package/package.json +13 -8
  61. package/dist/client-qmdYY-Eb.d.ts.map +0 -1
  62. package/dist/resumable-BPN_qQHU.d.ts.map +0 -1
  63. package/dist/shared-CJN-m58Z.d.ts.map +0 -1
package/dist/keep.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { n as DecodedBinding } from "./listen-DaUPRKVR.js";
1
+ import { n as DecodedBinding } from "./listen-7HzKBhqU.js";
2
2
  import { Result } from "effect";
3
3
  type Field = HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement;
4
4
  /** A marked field and the binding whose Message replays its typing. */
@@ -21,6 +21,8 @@ export declare const typedMessages: (fields: ReadonlyArray<KeptField>) => Readon
21
21
  export interface Held {
22
22
  readonly element: Field;
23
23
  readonly value: string;
24
+ /** A checkbox's or radio's. */
25
+ readonly checked?: boolean | undefined;
24
26
  /** A `multiple` select's selected option indices: its `value` names only the first. */
25
27
  readonly selected?: readonly number[] | undefined;
26
28
  readonly selection?: readonly [number, number, 'forward' | 'backward' | 'none'] | undefined;
@@ -1 +1 @@
1
- {"version":3,"file":"keep.d.ts","names":[],"sources":["../src/keep.ts"],"mappings":";;KAeK,QAAQ,mBAAmB,sBAAsB;;iBAGrC;WACN,SAAS;WACT,SAAS;;;;;;;;qBAcP,aAAU,MACf,SAAO,UACH,cAAc,oBACvB,OAAO,OAAO,cAAc;;qBA0DlB,UAAO,OAAW;;qBAalB,gBAAa,QAAY,cAAc,eAAa;;iBAIhD;WACN,SAAS;WACT;;WAEA;WACA;;;qBAIE,OAAI,QAAY,cAAc,eAAa,cAAc;;;;;qBA0BzD,UAAO,MAAU,cAAc"}
1
+ {"version":3,"file":"keep.d.ts","names":[],"sources":["../src/keep.ts"],"mappings":";;KAgBK,QAAQ,mBAAmB,sBAAsB;;iBAGrC;WACN,SAAS;WACT,SAAS;;;;;;;;qBAkBP,aAAU,MACf,SAAO,UACH,cAAc,oBACvB,OAAO,OAAO,cAAc;;qBA8DlB,UAAO,OAAW;;qBAqBlB,gBAAa,QAAY,cAAc,eAAa;;iBAQhD;WACN,SAAS;WACT;;WAEA;;WAEA;WACA;;;qBAIE,OAAI,QAAY,cAAc,eAAa,cAAc;;;;;qBA2BzD,UAAO,MAAU,cAAc"}
package/dist/keep.js CHANGED
@@ -1,4 +1,4 @@
1
- import { KEEP_ATTRIBUTE } from "./resumable.js";
1
+ import { KEEP_ATTRIBUTE } from "./marks.js";
2
2
  import { typedMessage } from "./listen.js";
3
3
  import { Result } from "effect";
4
4
  // src/keep.ts
@@ -11,8 +11,11 @@ import { Result } from "effect";
11
11
  * the marked fields when its script runs, turns each changed one into its
12
12
  * binding's Message, and after the first render puts the value and the
13
13
  * selection back, so the Message that follows finds the field already
14
- * holding its value and writes nothing.
14
+ * holding its value and writes nothing. A checkbox or radio keeps its
15
+ * `checked` the same way, against its `defaultChecked`.
15
16
  */
17
+ /** A checkbox or radio: what it holds is `checked`, not its `value`. */
18
+ const isCheckable = (element) => element instanceof HTMLInputElement && (element.type === "checkbox" || element.type === "radio");
16
19
  const isField = (element) => element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement || element instanceof HTMLSelectElement;
17
20
  /**
18
21
  * The fields in `root` marked to keep their typing, each with its binding.
@@ -25,8 +28,8 @@ const keptFields = (root, bindings) => {
25
28
  for (const element of Array.from(root.querySelectorAll(`[${KEEP_ATTRIBUTE}]`))) {
26
29
  const token = element.getAttribute("data-foldkit-plus-keep") ?? "";
27
30
  const binding = bindings[Number(token)];
28
- if (!/^\d+$/.test(token) || binding === void 0 || binding.event !== "input" && binding.event !== "change") return Result.fail(`the marker ${KEEP_ATTRIBUTE}="${token}" names no input or change binding the page carries`);
29
31
  if (!isField(element)) return Result.fail(`the marker ${KEEP_ATTRIBUTE} is on a ${element.localName}, not a field`);
32
+ if (!/^\d+$/.test(token) || binding === void 0 || !(binding.event === "input" || binding.event === "change" || binding.event === "click" && isCheckable(element))) return Result.fail(`the marker ${KEEP_ATTRIBUTE}="${token}" names no input or change binding (or click, on a checkbox or radio) the page carries`);
30
33
  kept.push({
31
34
  element,
32
35
  binding
@@ -59,6 +62,7 @@ const indicesOf = (select, chosen) => Array.from(select.options).flatMap((option
59
62
  /** Whether the field holds something other than what the server rendered. */
60
63
  const changed = (field) => {
61
64
  const { element } = field;
65
+ if (isCheckable(element)) return element.checked !== element.defaultChecked;
62
66
  if (element instanceof HTMLSelectElement && element.multiple) {
63
67
  const selected = indicesOf(element, (option) => option.selected);
64
68
  const served = indicesOf(element, (option) => option.defaultSelected);
@@ -66,10 +70,20 @@ const changed = (field) => {
66
70
  }
67
71
  return element.value !== servedValue(element);
68
72
  };
73
+ /**
74
+ * Whether the browser sent the field's event for its change: a radio the
75
+ * person left for another sent none, so only the one now checked replays.
76
+ */
77
+ const sentChange = (field) => !(isCheckable(field.element) && field.element.type === "radio" && !field.element.checked);
69
78
  /** The Messages that carry each changed field's typing, in document order. */
70
- const typedMessages = (fields) => fields.filter(changed).map((field) => typedMessage(field.binding, field.element.value));
79
+ const typedMessages = (fields) => fields.filter((field) => changed(field) && sentChange(field)).map(({ binding, element }) => binding.hole === void 0 ? binding.message : typedMessage(binding, element.value));
71
80
  /** Each changed field's state, to put back once hydration has re-asserted the served value. */
72
81
  const hold = (fields) => fields.filter(changed).map(({ element }) => {
82
+ if (isCheckable(element)) return {
83
+ element,
84
+ value: element.value,
85
+ checked: element.checked
86
+ };
73
87
  if (element instanceof HTMLSelectElement) return element.multiple ? {
74
88
  element,
75
89
  value: element.value,
@@ -94,8 +108,9 @@ const hold = (fields) => fields.filter(changed).map(({ element }) => {
94
108
  * the same element, which the person may still be typing into.
95
109
  */
96
110
  const restore = (held) => {
97
- for (const { element, value, selected, selection } of held) {
98
- if (element instanceof HTMLSelectElement && selected !== void 0) {
111
+ for (const { element, value, checked, selected, selection } of held) {
112
+ if (checked !== void 0 && element instanceof HTMLInputElement) element.checked = checked;
113
+ else if (element instanceof HTMLSelectElement && selected !== void 0) {
99
114
  const chosen = new Set(selected);
100
115
  Array.from(element.options).forEach((option, index) => {
101
116
  option.selected = chosen.has(index);
package/dist/keep.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"keep.js","names":[],"sources":["../src/keep.ts"],"sourcesContent":["/**\n * What is typed before the runtime starts, read from the fields themselves.\n *\n * A field the view marks with `KeepTyped` keeps its typing in the browser's\n * own state (its value, its selection) until the runtime adopts it, and\n * hydration then re-asserts the value the server rendered. The page reads\n * the marked fields when its script runs, turns each changed one into its\n * binding's Message, and after the first render puts the value and the\n * selection back, so the Message that follows finds the field already\n * holding its value and writes nothing.\n */\nimport { Result } from 'effect'\nimport { typedMessage, type DecodedBinding } from './listen.js'\nimport { KEEP_ATTRIBUTE } from './resumable.js'\n\ntype Field = HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement\n\n/** A marked field and the binding whose Message replays its typing. */\nexport interface KeptField {\n readonly element: Field\n readonly binding: DecodedBinding\n}\n\nconst isField = (element: Element): element is Field =>\n element instanceof HTMLInputElement ||\n element instanceof HTMLTextAreaElement ||\n element instanceof HTMLSelectElement\n\n/**\n * The fields in `root` marked to keep their typing, each with its binding.\n * Refused, with the reason, when a marker names no `OnInput` or `OnChange`\n * binding, or sits on an element that is not a field: the server writes\n * neither, so the page was altered.\n */\nexport const keptFields = (\n root: Element,\n bindings: ReadonlyArray<DecodedBinding>,\n): Result.Result<ReadonlyArray<KeptField>, string> => {\n const kept: Array<KeptField> = []\n for (const element of Array.from(root.querySelectorAll(`[${KEEP_ATTRIBUTE}]`))) {\n const token = element.getAttribute(KEEP_ATTRIBUTE) ?? ''\n const binding = bindings[Number(token)]\n // A binding of either event has a hole: a closure is no binding at all.\n if (\n !/^\\d+$/.test(token) ||\n binding === undefined ||\n (binding.event !== 'input' && binding.event !== 'change')\n ) {\n return Result.fail(\n `the marker ${KEEP_ATTRIBUTE}=\"${token}\" names no input or change binding the page carries`,\n )\n }\n if (!isField(element)) {\n return Result.fail(`the marker ${KEEP_ATTRIBUTE} is on a ${element.localName}, not a field`)\n }\n kept.push({ element, binding })\n }\n return Result.succeed(kept)\n}\n\n/** Whether an option is disabled by its own attribute or by a disabled `optgroup` around it. */\nconst disabledOption = (option: HTMLOptionElement): boolean =>\n option.disabled || (option.closest('optgroup')?.disabled ?? false)\n\n/** A select's display size: its `size` when it parses above zero, else 4 for `multiple` and 1 otherwise. */\nconst displaySize = (select: HTMLSelectElement): number => {\n const size = select.getAttribute('size')\n const parsed = size === null ? null : /^\\s*(\\d+)\\s*$/.exec(size)\n if (parsed !== null && Number(parsed[1]) > 0) return Number(parsed[1])\n return select.multiple ? 4 : 1\n}\n\n/**\n * The value the server rendered into a field: its default, which typing\n * leaves alone. A `select`'s follows the HTML reset algorithm: the last option\n * marked `selected` wins, else a single-line select takes its first option\n * that is not disabled, through an `optgroup` included.\n */\nconst servedValue = (element: Field): string => {\n if (!(element instanceof HTMLSelectElement)) return element.defaultValue\n const options = Array.from(element.options)\n const chosen =\n options.filter(option => option.defaultSelected).at(-1) ??\n (displaySize(element) === 1 ? options.find(option => !disabledOption(option)) : undefined)\n return chosen?.value ?? ''\n}\n\n/** The indices of a `select`'s options that `chosen` picks, in document order. */\nconst indicesOf = (\n select: HTMLSelectElement,\n chosen: (option: HTMLOptionElement) => boolean,\n): ReadonlyArray<number> =>\n Array.from(select.options).flatMap((option, index) => (chosen(option) ? [index] : []))\n\n/** Whether the field holds something other than what the server rendered. */\nexport const changed = (field: KeptField): boolean => {\n const { element } = field\n // A multiple select holds a set of selections, which its `value`, the first\n // of them, cannot tell apart: compare the whole set with the served one.\n if (element instanceof HTMLSelectElement && element.multiple) {\n const selected = indicesOf(element, option => option.selected)\n const served = indicesOf(element, option => option.defaultSelected)\n return selected.length !== served.length || selected.some((index, at) => index !== served[at])\n }\n return element.value !== servedValue(element)\n}\n\n/** The Messages that carry each changed field's typing, in document order. */\nexport const typedMessages = (fields: ReadonlyArray<KeptField>): ReadonlyArray<unknown> =>\n fields.filter(changed).map(field => typedMessage(field.binding, field.element.value))\n\n/** A changed field's value and selection, as they were just before the runtime started. */\nexport interface Held {\n readonly element: Field\n readonly value: string\n /** A `multiple` select's selected option indices: its `value` names only the first. */\n readonly selected?: readonly number[] | undefined\n readonly selection?: readonly [number, number, 'forward' | 'backward' | 'none'] | undefined\n}\n\n/** Each changed field's state, to put back once hydration has re-asserted the served value. */\nexport const hold = (fields: ReadonlyArray<KeptField>): ReadonlyArray<Held> =>\n fields.filter(changed).map(({ element }) => {\n if (element instanceof HTMLSelectElement) {\n return element.multiple\n ? {\n element,\n value: element.value,\n selected: indicesOf(element, option => option.selected),\n }\n : { element, value: element.value }\n }\n // An input type with no selection (`email`, `number`) reads null.\n const { selectionStart: start, selectionEnd: end } = element\n return {\n element,\n value: element.value,\n ...(start === null || end === null\n ? {}\n : { selection: [start, end, element.selectionDirection ?? 'none'] as const }),\n }\n })\n\n/**\n * Puts each held field back as it was. The first render adopted it, so it is\n * the same element, which the person may still be typing into.\n */\nexport const restore = (held: ReadonlyArray<Held>): void => {\n for (const { element, value, selected, selection } of held) {\n if (element instanceof HTMLSelectElement && selected !== undefined) {\n const chosen = new Set(selected)\n Array.from(element.options).forEach((option, index) => {\n option.selected = chosen.has(index)\n })\n } else {\n element.value = value\n }\n if (selection !== undefined && !(element instanceof HTMLSelectElement)) {\n element.setSelectionRange(...selection)\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAuBA,MAAM,WAAW,YACf,mBAAmB,oBACnB,mBAAmB,uBACnB,mBAAmB;;;;;;;AAQrB,MAAa,cACX,MACA,aACoD;CACpD,MAAM,OAAyB,CAAC;CAChC,KAAK,MAAM,WAAW,MAAM,KAAK,KAAK,iBAAiB,IAAI,eAAe,EAAE,CAAC,GAAG;EAC9E,MAAM,QAAQ,QAAQ,aAAA,wBAA2B,KAAK;EACtD,MAAM,UAAU,SAAS,OAAO,KAAK;EAErC,IACE,CAAC,QAAQ,KAAK,KAAK,KACnB,YAAY,KAAA,KACX,QAAQ,UAAU,WAAW,QAAQ,UAAU,UAEhD,OAAO,OAAO,KACZ,cAAc,eAAe,IAAI,MAAM,oDACzC;EAEF,IAAI,CAAC,QAAQ,OAAO,GAClB,OAAO,OAAO,KAAK,cAAc,eAAe,WAAW,QAAQ,UAAU,cAAc;EAE7F,KAAK,KAAK;GAAE;GAAS;EAAQ,CAAC;CAChC;CACA,OAAO,OAAO,QAAQ,IAAI;AAC5B;;AAGA,MAAM,kBAAkB,WACtB,OAAO,aAAa,OAAO,QAAQ,UAAU,CAAC,EAAE,YAAY;;AAG9D,MAAM,eAAe,WAAsC;CACzD,MAAM,OAAO,OAAO,aAAa,MAAM;CACvC,MAAM,SAAS,SAAS,OAAO,OAAO,gBAAgB,KAAK,IAAI;CAC/D,IAAI,WAAW,QAAQ,OAAO,OAAO,EAAE,IAAI,GAAG,OAAO,OAAO,OAAO,EAAE;CACrE,OAAO,OAAO,WAAW,IAAI;AAC/B;;;;;;;AAQA,MAAM,eAAe,YAA2B;CAC9C,IAAI,EAAE,mBAAmB,oBAAoB,OAAO,QAAQ;CAC5D,MAA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MAAa,WAAW,SAAoC;CAC1D,KAAK,MAAM,EAAE,SAAS,OAAO,UAAU,eAAe,MAAM;EAC1D,IAAI,mBAAmB,qBAAqB,aAAa,KAAA,GAAW;GAClE,MAAM,SAAS,IAAI,IAAI,QAAQ;GAC/B,MAAM,KAAK,QAAQ,OAAO,CAAC,CAAC,SAAS,QAAQ,UAAU;IACrD,OAAO,WAAW,OAAO,IAAI,KAAK;GACpC,CAAC;EACH,OACE,QAAQ,QAAQ;EAElB,IAAI,cAAc,KAAA,KAAa,EAAE,mBAAmB,oBAClD,QAAQ,kBAAkB,GAAG,SAAS;CAE1C;AACF"}
1
+ {"version":3,"file":"keep.js","names":[],"sources":["../src/keep.ts"],"sourcesContent":["/**\n * What is typed before the runtime starts, read from the fields themselves.\n *\n * A field the view marks with `KeepTyped` keeps its typing in the browser's\n * own state (its value, its selection) until the runtime adopts it, and\n * hydration then re-asserts the value the server rendered. The page reads\n * the marked fields when its script runs, turns each changed one into its\n * binding's Message, and after the first render puts the value and the\n * selection back, so the Message that follows finds the field already\n * holding its value and writes nothing. A checkbox or radio keeps its\n * `checked` the same way, against its `defaultChecked`.\n */\nimport { Result } from 'effect'\nimport { typedMessage, type DecodedBinding } from './listen.js'\nimport { KEEP_ATTRIBUTE } from './resumable.js'\n\ntype Field = HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement\n\n/** A marked field and the binding whose Message replays its typing. */\nexport interface KeptField {\n readonly element: Field\n readonly binding: DecodedBinding\n}\n\n/** A checkbox or radio: what it holds is `checked`, not its `value`. */\nconst isCheckable = (element: Field): element is HTMLInputElement =>\n element instanceof HTMLInputElement && (element.type === 'checkbox' || element.type === 'radio')\n\nconst isField = (element: Element): element is Field =>\n element instanceof HTMLInputElement ||\n element instanceof HTMLTextAreaElement ||\n element instanceof HTMLSelectElement\n\n/**\n * The fields in `root` marked to keep their typing, each with its binding.\n * Refused, with the reason, when a marker names no `OnInput` or `OnChange`\n * binding, or sits on an element that is not a field: the server writes\n * neither, so the page was altered.\n */\nexport const keptFields = (\n root: Element,\n bindings: ReadonlyArray<DecodedBinding>,\n): Result.Result<ReadonlyArray<KeptField>, string> => {\n const kept: Array<KeptField> = []\n for (const element of Array.from(root.querySelectorAll(`[${KEEP_ATTRIBUTE}]`))) {\n const token = element.getAttribute(KEEP_ATTRIBUTE) ?? ''\n const binding = bindings[Number(token)]\n if (!isField(element)) {\n return Result.fail(`the marker ${KEEP_ATTRIBUTE} is on a ${element.localName}, not a field`)\n }\n // A closure is no binding at all; a checkbox or radio may replay a click.\n if (\n !/^\\d+$/.test(token) ||\n binding === undefined ||\n !(\n binding.event === 'input' ||\n binding.event === 'change' ||\n (binding.event === 'click' && isCheckable(element))\n )\n ) {\n return Result.fail(\n `the marker ${KEEP_ATTRIBUTE}=\"${token}\" names no input or change binding (or click, on a checkbox or radio) the page carries`,\n )\n }\n kept.push({ element, binding })\n }\n return Result.succeed(kept)\n}\n\n/** Whether an option is disabled by its own attribute or by a disabled `optgroup` around it. */\nconst disabledOption = (option: HTMLOptionElement): boolean =>\n option.disabled || (option.closest('optgroup')?.disabled ?? false)\n\n/** A select's display size: its `size` when it parses above zero, else 4 for `multiple` and 1 otherwise. */\nconst displaySize = (select: HTMLSelectElement): number => {\n const size = select.getAttribute('size')\n const parsed = size === null ? null : /^\\s*(\\d+)\\s*$/.exec(size)\n if (parsed !== null && Number(parsed[1]) > 0) return Number(parsed[1])\n return select.multiple ? 4 : 1\n}\n\n/**\n * The value the server rendered into a field: its default, which typing\n * leaves alone. A `select`'s follows the HTML reset algorithm: the last option\n * marked `selected` wins, else a single-line select takes its first option\n * that is not disabled, through an `optgroup` included.\n */\nconst servedValue = (element: Field): string => {\n if (!(element instanceof HTMLSelectElement)) return element.defaultValue\n const options = Array.from(element.options)\n const chosen =\n options.filter(option => option.defaultSelected).at(-1) ??\n (displaySize(element) === 1 ? options.find(option => !disabledOption(option)) : undefined)\n return chosen?.value ?? ''\n}\n\n/** The indices of a `select`'s options that `chosen` picks, in document order. */\nconst indicesOf = (\n select: HTMLSelectElement,\n chosen: (option: HTMLOptionElement) => boolean,\n): ReadonlyArray<number> =>\n Array.from(select.options).flatMap((option, index) => (chosen(option) ? [index] : []))\n\n/** Whether the field holds something other than what the server rendered. */\nexport const changed = (field: KeptField): boolean => {\n const { element } = field\n if (isCheckable(element)) return element.checked !== element.defaultChecked\n // A multiple select holds a set of selections, which its `value`, the first\n // of them, cannot tell apart: compare the whole set with the served one.\n if (element instanceof HTMLSelectElement && element.multiple) {\n const selected = indicesOf(element, option => option.selected)\n const served = indicesOf(element, option => option.defaultSelected)\n return selected.length !== served.length || selected.some((index, at) => index !== served[at])\n }\n return element.value !== servedValue(element)\n}\n\n/**\n * Whether the browser sent the field's event for its change: a radio the\n * person left for another sent none, so only the one now checked replays.\n */\nconst sentChange = (field: KeptField): boolean =>\n !(isCheckable(field.element) && field.element.type === 'radio' && !field.element.checked)\n\n/** The Messages that carry each changed field's typing, in document order. */\nexport const typedMessages = (fields: ReadonlyArray<KeptField>): ReadonlyArray<unknown> =>\n fields\n .filter(field => changed(field) && sentChange(field))\n .map(({ binding, element }) =>\n binding.hole === undefined ? binding.message : typedMessage(binding, element.value),\n )\n\n/** A changed field's value and selection, as they were just before the runtime started. */\nexport interface Held {\n readonly element: Field\n readonly value: string\n /** A checkbox's or radio's. */\n readonly checked?: boolean | undefined\n /** A `multiple` select's selected option indices: its `value` names only the first. */\n readonly selected?: readonly number[] | undefined\n readonly selection?: readonly [number, number, 'forward' | 'backward' | 'none'] | undefined\n}\n\n/** Each changed field's state, to put back once hydration has re-asserted the served value. */\nexport const hold = (fields: ReadonlyArray<KeptField>): ReadonlyArray<Held> =>\n fields.filter(changed).map(({ element }): Held => {\n if (isCheckable(element)) return { element, value: element.value, checked: element.checked }\n if (element instanceof HTMLSelectElement) {\n return element.multiple\n ? {\n element,\n value: element.value,\n selected: indicesOf(element, option => option.selected),\n }\n : { element, value: element.value }\n }\n // An input type with no selection (`email`, `number`) reads null.\n const { selectionStart: start, selectionEnd: end } = element\n return {\n element,\n value: element.value,\n ...(start === null || end === null\n ? {}\n : { selection: [start, end, element.selectionDirection ?? 'none'] as const }),\n }\n })\n\n/**\n * Puts each held field back as it was. The first render adopted it, so it is\n * the same element, which the person may still be typing into.\n */\nexport const restore = (held: ReadonlyArray<Held>): void => {\n for (const { element, value, checked, selected, selection } of held) {\n if (checked !== undefined && element instanceof HTMLInputElement) {\n element.checked = checked\n } else if (element instanceof HTMLSelectElement && selected !== undefined) {\n const chosen = new Set(selected)\n Array.from(element.options).forEach((option, index) => {\n option.selected = chosen.has(index)\n })\n } else {\n element.value = value\n }\n if (selection !== undefined && !(element instanceof HTMLSelectElement)) {\n element.setSelectionRange(...selection)\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAyBA,MAAM,eAAe,YACnB,mBAAmB,qBAAqB,QAAQ,SAAS,cAAc,QAAQ,SAAS;AAE1F,MAAM,WAAW,YACf,mBAAmB,oBACnB,mBAAmB,uBACnB,mBAAmB;;;;;;;AAQrB,MAAa,cACX,MACA,aACoD;CACpD,MAAM,OAAyB,CAAC;CAChC,KAAK,MAAM,WAAW,MAAM,KAAK,KAAK,iBAAiB,IAAI,eAAe,EAAE,CAAC,GAAG;EAC9E,MAAM,QAAQ,QAAQ,aAAA,wBAA2B,KAAK;EACtD,MAAM,UAAU,SAAS,OAAO,KAAK;EACrC,IAAI,CAAC,QAAQ,OAAO,GAClB,OAAO,OAAO,KAAK,cAAc,eAAe,WAAW,QAAQ,UAAU,cAAc;EAG7F,IACE,CAAC,QAAQ,KAAK,KAAK,KACnB,YAAY,KAAA,KACZ,EACE,QAAQ,UAAU,WAClB,QAAQ,UAAU,YACjB,QAAQ,UAAU,WAAW,YAAY,OAAO,IAGnD,OAAO,OAAO,KACZ,cAAc,eAAe,IAAI,MAAM,uFACzC;EAEF,KAAK,KAAK;GAAE;GAAS;EAAQ,CAAC;CAChC;CACA,OAAO,OAAO,QAAQ,IAAI;AAC5B;;AAGA,MAAM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
68
  */
69
69
  declare const listen: (root: Element, options: ListenOptions) => (() => void);
70
- export { decodeBindings as a, typedMessage as c, ListenOptions as i, DecodedBinding as n, listen as o, EncodedBinding as r, readBindings as s, Answer as t };
71
- //# sourceMappingURL=listen-DaUPRKVR.d.ts.map
70
+ /**
71
+ * `listen`, and also what answers an event already dispatched, from the
72
+ * elements it passed (`pathOf` as it happened): one `foldkit-ssr/loader`
73
+ * held, whose own path the browser has since emptied.
74
+ */
75
+ declare const listening: (root: Element, options: ListenOptions) => {
76
+ readonly stop: () => void;
77
+ readonly answer: (event: Event, path: ReadonlyArray<EventTarget>) => void;
78
+ };
79
+ export { decodeBindings as a, readBindings as c, ListenOptions as i, typedMessage as l, DecodedBinding as n, listen as o, EncodedBinding as r, listening as s, Answer as t };
80
+ //# sourceMappingURL=listen-7HzKBhqU.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"listen-DaUPRKVR.d.ts","names":[],"sources":["../src/listen.ts"],"mappings":";;;;;;;;;UA0BiB;WACN;WACA;WACA,OAAO;WACP;WACA;;;;;;;;;cAaE,eAAY,mBAEtB,OAAO,OAAO,cAAc;;UA+Bd;WACN;WACA;WACA;WACA,OAAO;WACP;WACA;;;;;;;;cASE,iBAAc,SAChB,OAAO,iBAAe,SACtB,cAAc,iBAAe,MAChC,YAAU,SACP,wBACR,OAAO,OAAO,cAAc;;cA+FlB,eAAY,SAAa,gBAAc;;;;;;;UAgCnC;WACN,OAAO;WACP,UAAU;WACV,UAAU;;UAGJ;WACN,UAAU,cAAc;WACxB,WAAW,QAAQ;;;;;;;WAOnB,SAAS;;;;;;cAOP,SAAM,MAAU,SAAO,SAAW"}
1
+ {"version":3,"file":"listen-7HzKBhqU.d.ts","names":[],"sources":["../src/listen.ts"],"mappings":";;;;;;;;;UA2BiB;WACN;WACA;WACA,OAAO;WACP;WACA;;;;;;;;;cAaE,eAAY,mBAEtB,OAAO,OAAO,cAAc;;UA+Bd;WACN;WACA;WACA;WACA,OAAO;WACP;WACA;;;;;;;;cASE,iBAAc,SAChB,OAAO,iBAAe,SACtB,cAAc,iBAAe,MAChC,YAAU,SACP,wBACR,OAAO,OAAO,cAAc;;cA+FlB,eAAY,SAAa,gBAAc;;;;;;;UAgCnC;WACN,OAAO;WACP,UAAU;WACV,UAAU;;UAGJ;WACN,UAAU,cAAc;WACxB,WAAW,QAAQ;;;;;;;WAOnB,SAAS;;;;;;cAOP,SAAM,MAAU,SAAO,SAAW;;;;;;cAQlC,YAAS,MACd,SAAO,SACJ;WAEA;WACA,SAAS,OAAO,OAAO,MAAM,cAAc"}
package/dist/listen.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { a as decodeBindings, c as typedMessage, i as ListenOptions, n as DecodedBinding, o as listen, r as EncodedBinding, s as readBindings, t as Answer } from "./listen-DaUPRKVR.js";
2
- export { Answer, DecodedBinding, EncodedBinding, ListenOptions, decodeBindings, listen, readBindings, typedMessage };
1
+ import { a as decodeBindings, c as readBindings, i as ListenOptions, l as typedMessage, n as DecodedBinding, o as listen, r as EncodedBinding, s as listening, t as Answer } from "./listen-7HzKBhqU.js";
2
+ export { Answer, DecodedBinding, EncodedBinding, ListenOptions, decodeBindings, listen, listening, readBindings, typedMessage };
package/dist/listen.js CHANGED
@@ -1,4 +1,5 @@
1
- import { BINDING_ATTRIBUTE, EVENT_OF } from "./resumable.js";
1
+ import { BINDING_ATTRIBUTE, pathOf } from "./marks.js";
2
+ import { EVENT_OF } from "./resumable.js";
2
3
  import { Predicate, Result, Schema } from "effect";
3
4
  // src/listen.ts
4
5
  /**
@@ -127,7 +128,13 @@ const messageFor = (binding, event) => {
127
128
  * Listens at `root` for every event the bindings name, and answers each from
128
129
  * the markers. Returns what removes the listeners.
129
130
  */
130
- const listen = (root, options) => {
131
+ const listen = (root, options) => listening(root, options).stop;
132
+ /**
133
+ * `listen`, and also what answers an event already dispatched, from the
134
+ * elements it passed (`pathOf` as it happened): one `foldkit-ssr/loader`
135
+ * held, whose own path the browser has since emptied.
136
+ */
137
+ const listening = (root, options) => {
131
138
  const markers = /* @__PURE__ */ new Map();
132
139
  for (const element of [root, ...Array.from(root.querySelectorAll("*"))]) for (const name of element.getAttributeNames()) {
133
140
  if (!name.startsWith("data-foldkit-plus-on-")) continue;
@@ -138,10 +145,9 @@ const listen = (root, options) => {
138
145
  const events = new Set(options.bindings.map((binding) => binding.event));
139
146
  if (options.events !== void 0) for (const event of options.events) events.add(event);
140
147
  else for (const held of markers.values()) for (const event of held.keys()) events.add(event);
141
- const handler = (event) => {
148
+ const answer = (event, path) => {
142
149
  const type = event.type;
143
150
  const messages = [];
144
- const path = event.bubbles ? event.composedPath() : [event.target];
145
151
  for (const node of path) {
146
152
  if (!(node instanceof Element)) continue;
147
153
  const tokens = markers.get(node)?.get(type);
@@ -177,11 +183,15 @@ const listen = (root, options) => {
177
183
  messages
178
184
  });
179
185
  };
186
+ const handler = (event) => answer(event, pathOf(event));
180
187
  for (const type of events) root.addEventListener(type, handler, true);
181
- return () => {
182
- for (const type of events) root.removeEventListener(type, handler, true);
188
+ return {
189
+ stop: () => {
190
+ for (const type of events) root.removeEventListener(type, handler, true);
191
+ },
192
+ answer
183
193
  };
184
194
  };
185
- export { decodeBindings, listen, readBindings, typedMessage };
195
+ export { decodeBindings, listen, listening, readBindings, typedMessage };
186
196
 
187
197
  //# sourceMappingURL=listen.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"listen.js","names":[],"sources":["../src/listen.ts"],"sourcesContent":["/**\n * Delegated dispatch: the page answers an event from its markers, before the\n * application has booted.\n *\n * One capture-phase listener per event type sits at the root, so events that\n * do not bubble (`focus`, `blur`) are caught, and it runs before anything\n * Foldkit attaches later. On an event it walks from the target to the root\n * and, for every marker of that event on the way, collects each binding's\n * Message in order, the way Foldkit's own handler would dispatch it: a hole is\n * filled from the event, `OnClick`'s options are honoured, `OnSubmit`\n * prevents the default. A marker token the page could not name (`*`) means\n * the live page does something here the page cannot describe, so the walk\n * ends and the answer names that element.\n */\nimport { Predicate, Result, Schema } from 'effect'\nimport type { KeyboardModifiers } from 'foldkit/html'\nimport { BINDING_ATTRIBUTE, EVENT_OF, UNNAMED_HANDLER } from './resumable.js'\n\n/**\n * A binding as the envelope carries it: Foldkit's attribute (`OnSubmit`,\n * `OnBlur`), whose tag says what its handler does beside dispatching; the\n * Message, encoded through the application's Message Schema (for a hole, with\n * the hole filled by a placeholder); the fields the event fills, `depth`\n * placement wrappers down; and the attribute's options. Its ordinal is its\n * index.\n */\nexport interface EncodedBinding {\n readonly attribute: string\n readonly message: unknown\n readonly hole?: ReadonlyArray<string>\n readonly depth?: number\n readonly options?: unknown\n}\n\nconst isRecord = (value: unknown): value is Readonly<Record<string, unknown>> =>\n typeof value === 'object' && value !== null && !Array.isArray(value)\n\n/**\n * The page's list of bindings, read as untrusted input: each entry checked,\n * and only its known keys kept, or the reason the list is refused. Checked by\n * hand rather than through a Schema, which at a thousand rows took most of a\n * frame for a shape this plain; the Message inside each entry is still decoded\n * through the application's Schema by `decodeBindings`.\n */\nexport const readBindings = (\n value: unknown,\n): Result.Result<ReadonlyArray<EncodedBinding>, string> => {\n if (!Array.isArray(value)) return Result.fail('the list is not an array')\n const out: Array<EncodedBinding> = []\n for (const [index, entry] of value.entries()) {\n if (!isRecord(entry)) return Result.fail(`entry ${index} is not an object`)\n if (typeof entry.attribute !== 'string') {\n return Result.fail(`entry ${index} has no attribute`)\n }\n if (!Object.hasOwn(entry, 'message')) return Result.fail(`entry ${index} has no message`)\n const { hole, depth } = entry\n if (\n hole !== undefined &&\n !(Array.isArray(hole) && hole.every(field => typeof field === 'string'))\n ) {\n return Result.fail(`entry ${index} has a hole that is not a list of fields`)\n }\n if (depth !== undefined && !(Number.isInteger(depth) && (depth as number) >= 0)) {\n return Result.fail(`entry ${index} has a depth that is not a count`)\n }\n out.push({\n attribute: entry.attribute,\n message: entry.message,\n ...(hole === undefined ? {} : { hole: hole as ReadonlyArray<string> }),\n ...(depth === undefined ? {} : { depth: depth as number }),\n ...(Object.hasOwn(entry, 'options') ? { options: entry.options } : {}),\n })\n }\n return Result.succeed(out)\n}\n\n/** A binding decoded from the page: its Message is one of the application's. */\nexport interface DecodedBinding {\n readonly attribute: string\n readonly event: string\n readonly message: unknown\n readonly hole?: ReadonlyArray<string> | undefined\n readonly depth?: number | undefined\n readonly options?: unknown\n}\n\n/**\n * The page's bindings, decoded through the application's Message Schema, and\n * every marker in `root` checked against them. A page whose markers name a\n * binding it does not carry, or whose entry is not one of the application's\n * Messages, is refused whole, with the reason.\n */\nexport const decodeBindings = (\n Message: Schema.Top | undefined,\n encoded: ReadonlyArray<EncodedBinding>,\n root: ParentNode,\n allowed: ReadonlySet<string>,\n): Result.Result<ReadonlyArray<DecodedBinding>, string> => {\n if (encoded.length > 0 && Message === undefined) {\n return Result.fail(\n 'the page has bindings and the plan has no Message Schema to decode them with',\n )\n }\n const decode =\n Message === undefined\n ? undefined\n : Schema.decodeUnknownResult(Message as Schema.Codec<unknown, unknown>)\n const bindings: Array<DecodedBinding> = []\n for (const [index, entry] of encoded.entries()) {\n const event = EVENT_OF[entry.attribute]\n if (event === undefined) {\n return Result.fail(\n `binding ${index} is for \"${entry.attribute}\", which is no event attribute`,\n )\n }\n const message = decode!(entry.message)\n if (Result.isFailure(message)) {\n return Result.fail(\n `binding ${index} does not decode as a Message: ${message.failure.message}`,\n )\n }\n const tag = Predicate.hasProperty(message.success, '_tag') ? message.success._tag : undefined\n if (typeof tag !== 'string' || !allowed.has(tag)) {\n return Result.fail(\n `binding ${index} dispatches ${typeof tag === 'string' ? tag : 'an untagged Message'}, which no active Surface lists in its messages`,\n )\n }\n bindings.push({\n attribute: entry.attribute,\n event,\n message: message.success,\n ...(entry.hole === undefined ? {} : { hole: entry.hole }),\n ...(entry.depth === undefined ? {} : { depth: entry.depth }),\n ...(entry.options === undefined ? {} : { options: entry.options }),\n })\n }\n for (const element of Array.from(root.querySelectorAll('*'))) {\n for (const attribute of element.getAttributeNames()) {\n if (!attribute.startsWith(BINDING_ATTRIBUTE)) continue\n for (const token of (element.getAttribute(attribute) ?? '').split(' ')) {\n if (token === UNNAMED_HANDLER) continue\n const ordinal = Number(token)\n if (!Number.isInteger(ordinal) || bindings[ordinal] === undefined) {\n return Result.fail(`the marker ${attribute}=\"${token}\" names no binding the page carries`)\n }\n }\n }\n }\n return Result.succeed(bindings)\n}\n\n/** A string property of the target, if it has one. */\nconst stringProperty = (target: EventTarget | null, name: string): string | undefined => {\n if (target === null || !(name in target)) return undefined\n const value: unknown = Reflect.get(target, name)\n return typeof value === 'string' ? value : undefined\n}\n\n/**\n * Foldkit's reading of an input's value (`inputEventValue`): any target's\n * string `value`, a custom element's included, else its `innerText`, else its\n * `textContent`.\n */\nconst inputValue = (target: EventTarget | null): string =>\n stringProperty(target, 'value') ??\n stringProperty(target, 'innerText') ??\n stringProperty(target, 'textContent') ??\n ''\n\nconst modifiersOf = (event: KeyboardEvent): KeyboardModifiers => ({\n shiftKey: event.shiftKey,\n ctrlKey: event.ctrlKey,\n altKey: event.altKey,\n metaKey: event.metaKey,\n})\n\n/** A binding's Message with its hole filled by `fill`, inside each placement wrapper's `message`. */\nconst filled = (\n binding: DecodedBinding,\n fill: (template: Readonly<Record<string, unknown>>) => unknown,\n): unknown => {\n const inside = (template: Readonly<Record<string, unknown>>, depth: number): unknown =>\n depth === 0\n ? fill(template)\n : {\n ...template,\n message: inside(template.message as Readonly<Record<string, unknown>>, depth - 1),\n }\n return inside(binding.message as Readonly<Record<string, unknown>>, binding.depth ?? 0)\n}\n\n/** The Message an `OnInput` or `OnChange` hole binding dispatches for a field holding `value`. */\nexport const typedMessage = (binding: DecodedBinding, value: string): unknown =>\n filled(binding, template => {\n const [field] = binding.hole ?? []\n return { ...template, [field ?? 'value']: value }\n })\n\n/** The Message a binding dispatches for this event: its own, with the hole filled. */\nconst messageFor = (binding: DecodedBinding, event: Event): unknown => {\n if (binding.hole === undefined) return binding.message\n if (binding.event === 'input' || binding.event === 'change') {\n return typedMessage(binding, inputValue(event.target))\n }\n return filled(binding, template =>\n event instanceof KeyboardEvent\n ? { ...template, key: event.key, modifiers: modifiersOf(event) }\n : template,\n )\n}\n\n/** What `OnClick` declares beside its Message. */\ninterface ClickOptions {\n readonly defaultAction?: 'Allow' | 'Prevent'\n readonly propagation?: 'Bubble' | 'Stop'\n readonly focusSelector?: string\n}\n\n/**\n * What the markers make of one event: the Messages its bindings dispatch, in\n * the order the live page would, and, when the walk met a handler the page\n * could not name, that element. An answer with `unnamed` is incomplete: the\n * live page would do more than its Messages say.\n */\nexport interface Answer {\n readonly event: Event\n readonly messages: ReadonlyArray<unknown>\n readonly unnamed?: Element | undefined\n}\n\nexport interface ListenOptions {\n readonly bindings: ReadonlyArray<DecodedBinding>\n readonly onAnswer: (answer: Answer) => void\n /**\n * Every event the page's markers name, as the envelope lists them. Given,\n * `listen` needs no pass over the page to find the events a marker names\n * with `*` alone; without it, it reads every element's attributes, which on\n * a large page is most of its cost.\n */\n readonly events?: Iterable<string> | undefined\n}\n\n/**\n * Listens at `root` for every event the bindings name, and answers each from\n * the markers. Returns what removes the listeners.\n */\nexport const listen = (root: Element, options: ListenOptions): (() => void) => {\n // The markers as served, read once: the boot takes them off the page before\n // Foldkit adopts it, and an event landing before the first render is still\n // answered from them.\n const markers = new Map<Element, Map<string, string>>()\n for (const element of [root, ...Array.from(root.querySelectorAll('*'))]) {\n for (const name of element.getAttributeNames()) {\n if (!name.startsWith(BINDING_ATTRIBUTE)) continue\n const held = markers.get(element) ?? new Map<string, string>()\n held.set(name.slice(BINDING_ATTRIBUTE.length), element.getAttribute(name) ?? '')\n markers.set(element, held)\n }\n }\n // The bindings name most events; a marker whose handlers the page could not\n // name is `*` alone, so the markers themselves say the rest.\n const events = new Set(options.bindings.map(binding => binding.event))\n if (options.events !== undefined) {\n for (const event of options.events) events.add(event)\n } else {\n for (const held of markers.values()) for (const event of held.keys()) events.add(event)\n }\n const handler = (event: Event) => {\n const type = event.type\n const messages: Array<unknown> = []\n // An event that does not bubble (`focus`, `blur`, `mouseenter`) reaches only\n // its target's own handlers on the live page, so only those answer it here.\n const path = event.bubbles ? event.composedPath() : [event.target]\n for (const node of path) {\n if (!(node instanceof Element)) continue\n const tokens = markers.get(node)?.get(type)\n // Foldkit chains an element's handlers in one listener, so a Stop among\n // them keeps the event from other elements, not from its siblings.\n let stopped = false\n if (tokens !== undefined) {\n for (const token of tokens.split(' ')) {\n if (token === UNNAMED_HANDLER) {\n options.onAnswer({ event, messages, unnamed: node })\n return\n }\n const binding = options.bindings[Number(token)]\n if (binding === undefined) continue\n if (binding.attribute === 'OnSubmit') event.preventDefault()\n if (binding.attribute === 'OnClick') {\n const click = (binding.options ?? {}) as ClickOptions\n if (click.defaultAction === 'Prevent') event.preventDefault()\n if (click.propagation === 'Stop') event.stopPropagation()\n if (click.focusSelector !== undefined) {\n const focusTarget = document.querySelector(click.focusSelector)\n if (focusTarget instanceof HTMLElement) focusTarget.focus()\n }\n if (click.propagation === 'Stop') stopped = true\n }\n messages.push(messageFor(binding, event))\n }\n }\n if (stopped || node === root) break\n }\n options.onAnswer({ event, messages })\n }\n for (const type of events) root.addEventListener(type, handler, true)\n return () => {\n for (const type of events) root.removeEventListener(type, handler, true)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAkCA,MAAM,YAAY,UAChB,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;;;;;;;;AASrE,MAAa,gBACX,UACyD;CACzD,IAAI,CAAC,MAAM,QAAQ,KAAK,GAAG,OAAO,OAAO,KAAK,0BAA0B;CACxE,MAAM,MAA6B,CAAC;CACpC,KAAK,MAAM,CAAC,OAAO,UAAU,MAAM,QAAQ,GAAG;EAC5C,IAAI,CAAC,SAAS,KAAK,GAAG,OAAO,OAAO,KAAK,SAAS,MAAM,kBAAkB;EAC1E,IAAI,OAAO,MAAM,cAAc,UAC7B,OAAO,OAAO,KAAK,SAAS,MAAM,kBAAkB;EAEtD,IAAI,CAAC,OAAO,OAAO,OAAO,SAAS,GA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AK,MAAM,QAAQ,QAAQ,KAAK,iBAAiB,MAAM,SAAS,IAAI;CACpE,aAAa;EACX,KAAK,MAAM,QAAQ,QAAQ,KAAK,oBAAoB,MAAM,SAAS,IAAI;CACzE;AACF"}
1
+ {"version":3,"file":"listen.js","names":[],"sources":["../src/listen.ts"],"sourcesContent":["/**\n * Delegated dispatch: the page answers an event from its markers, before the\n * application has booted.\n *\n * One capture-phase listener per event type sits at the root, so events that\n * do not bubble (`focus`, `blur`) are caught, and it runs before anything\n * Foldkit attaches later. On an event it walks from the target to the root\n * and, for every marker of that event on the way, collects each binding's\n * Message in order, the way Foldkit's own handler would dispatch it: a hole is\n * filled from the event, `OnClick`'s options are honoured, `OnSubmit`\n * prevents the default. A marker token the page could not name (`*`) means\n * the live page does something here the page cannot describe, so the walk\n * ends and the answer names that element.\n */\nimport { Predicate, Result, Schema } from 'effect'\nimport type { KeyboardModifiers } from 'foldkit/html'\nimport { BINDING_ATTRIBUTE, EVENT_OF, UNNAMED_HANDLER } from './resumable.js'\nimport { pathOf } from './marks.js'\n\n/**\n * A binding as the envelope carries it: Foldkit's attribute (`OnSubmit`,\n * `OnBlur`), whose tag says what its handler does beside dispatching; the\n * Message, encoded through the application's Message Schema (for a hole, with\n * the hole filled by a placeholder); the fields the event fills, `depth`\n * placement wrappers down; and the attribute's options. Its ordinal is its\n * index.\n */\nexport interface EncodedBinding {\n readonly attribute: string\n readonly message: unknown\n readonly hole?: ReadonlyArray<string>\n readonly depth?: number\n readonly options?: unknown\n}\n\nconst isRecord = (value: unknown): value is Readonly<Record<string, unknown>> =>\n typeof value === 'object' && value !== null && !Array.isArray(value)\n\n/**\n * The page's list of bindings, read as untrusted input: each entry checked,\n * and only its known keys kept, or the reason the list is refused. Checked by\n * hand rather than through a Schema, which at a thousand rows took most of a\n * frame for a shape this plain; the Message inside each entry is still decoded\n * through the application's Schema by `decodeBindings`.\n */\nexport const readBindings = (\n value: unknown,\n): Result.Result<ReadonlyArray<EncodedBinding>, string> => {\n if (!Array.isArray(value)) return Result.fail('the list is not an array')\n const out: Array<EncodedBinding> = []\n for (const [index, entry] of value.entries()) {\n if (!isRecord(entry)) return Result.fail(`entry ${index} is not an object`)\n if (typeof entry.attribute !== 'string') {\n return Result.fail(`entry ${index} has no attribute`)\n }\n if (!Object.hasOwn(entry, 'message')) return Result.fail(`entry ${index} has no message`)\n const { hole, depth } = entry\n if (\n hole !== undefined &&\n !(Array.isArray(hole) && hole.every(field => typeof field === 'string'))\n ) {\n return Result.fail(`entry ${index} has a hole that is not a list of fields`)\n }\n if (depth !== undefined && !(Number.isInteger(depth) && (depth as number) >= 0)) {\n return Result.fail(`entry ${index} has a depth that is not a count`)\n }\n out.push({\n attribute: entry.attribute,\n message: entry.message,\n ...(hole === undefined ? {} : { hole: hole as ReadonlyArray<string> }),\n ...(depth === undefined ? {} : { depth: depth as number }),\n ...(Object.hasOwn(entry, 'options') ? { options: entry.options } : {}),\n })\n }\n return Result.succeed(out)\n}\n\n/** A binding decoded from the page: its Message is one of the application's. */\nexport interface DecodedBinding {\n readonly attribute: string\n readonly event: string\n readonly message: unknown\n readonly hole?: ReadonlyArray<string> | undefined\n readonly depth?: number | undefined\n readonly options?: unknown\n}\n\n/**\n * The page's bindings, decoded through the application's Message Schema, and\n * every marker in `root` checked against them. A page whose markers name a\n * binding it does not carry, or whose entry is not one of the application's\n * Messages, is refused whole, with the reason.\n */\nexport const decodeBindings = (\n Message: Schema.Top | undefined,\n encoded: ReadonlyArray<EncodedBinding>,\n root: ParentNode,\n allowed: ReadonlySet<string>,\n): Result.Result<ReadonlyArray<DecodedBinding>, string> => {\n if (encoded.length > 0 && Message === undefined) {\n return Result.fail(\n 'the page has bindings and the plan has no Message Schema to decode them with',\n )\n }\n const decode =\n Message === undefined\n ? undefined\n : Schema.decodeUnknownResult(Message as Schema.Codec<unknown, unknown>)\n const bindings: Array<DecodedBinding> = []\n for (const [index, entry] of encoded.entries()) {\n const event = EVENT_OF[entry.attribute]\n if (event === undefined) {\n return Result.fail(\n `binding ${index} is for \"${entry.attribute}\", which is no event attribute`,\n )\n }\n const message = decode!(entry.message)\n if (Result.isFailure(message)) {\n return Result.fail(\n `binding ${index} does not decode as a Message: ${message.failure.message}`,\n )\n }\n const tag = Predicate.hasProperty(message.success, '_tag') ? message.success._tag : undefined\n if (typeof tag !== 'string' || !allowed.has(tag)) {\n return Result.fail(\n `binding ${index} dispatches ${typeof tag === 'string' ? tag : 'an untagged Message'}, which no active Surface lists in its messages`,\n )\n }\n bindings.push({\n attribute: entry.attribute,\n event,\n message: message.success,\n ...(entry.hole === undefined ? {} : { hole: entry.hole }),\n ...(entry.depth === undefined ? {} : { depth: entry.depth }),\n ...(entry.options === undefined ? {} : { options: entry.options }),\n })\n }\n for (const element of Array.from(root.querySelectorAll('*'))) {\n for (const attribute of element.getAttributeNames()) {\n if (!attribute.startsWith(BINDING_ATTRIBUTE)) continue\n for (const token of (element.getAttribute(attribute) ?? '').split(' ')) {\n if (token === UNNAMED_HANDLER) continue\n const ordinal = Number(token)\n if (!Number.isInteger(ordinal) || bindings[ordinal] === undefined) {\n return Result.fail(`the marker ${attribute}=\"${token}\" names no binding the page carries`)\n }\n }\n }\n }\n return Result.succeed(bindings)\n}\n\n/** A string property of the target, if it has one. */\nconst stringProperty = (target: EventTarget | null, name: string): string | undefined => {\n if (target === null || !(name in target)) return undefined\n const value: unknown = Reflect.get(target, name)\n return typeof value === 'string' ? value : undefined\n}\n\n/**\n * Foldkit's reading of an input's value (`inputEventValue`): any target's\n * string `value`, a custom element's included, else its `innerText`, else its\n * `textContent`.\n */\nconst inputValue = (target: EventTarget | null): string =>\n stringProperty(target, 'value') ??\n stringProperty(target, 'innerText') ??\n stringProperty(target, 'textContent') ??\n ''\n\nconst modifiersOf = (event: KeyboardEvent): KeyboardModifiers => ({\n shiftKey: event.shiftKey,\n ctrlKey: event.ctrlKey,\n altKey: event.altKey,\n metaKey: event.metaKey,\n})\n\n/** A binding's Message with its hole filled by `fill`, inside each placement wrapper's `message`. */\nconst filled = (\n binding: DecodedBinding,\n fill: (template: Readonly<Record<string, unknown>>) => unknown,\n): unknown => {\n const inside = (template: Readonly<Record<string, unknown>>, depth: number): unknown =>\n depth === 0\n ? fill(template)\n : {\n ...template,\n message: inside(template.message as Readonly<Record<string, unknown>>, depth - 1),\n }\n return inside(binding.message as Readonly<Record<string, unknown>>, binding.depth ?? 0)\n}\n\n/** The Message an `OnInput` or `OnChange` hole binding dispatches for a field holding `value`. */\nexport const typedMessage = (binding: DecodedBinding, value: string): unknown =>\n filled(binding, template => {\n const [field] = binding.hole ?? []\n return { ...template, [field ?? 'value']: value }\n })\n\n/** The Message a binding dispatches for this event: its own, with the hole filled. */\nconst messageFor = (binding: DecodedBinding, event: Event): unknown => {\n if (binding.hole === undefined) return binding.message\n if (binding.event === 'input' || binding.event === 'change') {\n return typedMessage(binding, inputValue(event.target))\n }\n return filled(binding, template =>\n event instanceof KeyboardEvent\n ? { ...template, key: event.key, modifiers: modifiersOf(event) }\n : template,\n )\n}\n\n/** What `OnClick` declares beside its Message. */\ninterface ClickOptions {\n readonly defaultAction?: 'Allow' | 'Prevent'\n readonly propagation?: 'Bubble' | 'Stop'\n readonly focusSelector?: string\n}\n\n/**\n * What the markers make of one event: the Messages its bindings dispatch, in\n * the order the live page would, and, when the walk met a handler the page\n * could not name, that element. An answer with `unnamed` is incomplete: the\n * live page would do more than its Messages say.\n */\nexport interface Answer {\n readonly event: Event\n readonly messages: ReadonlyArray<unknown>\n readonly unnamed?: Element | undefined\n}\n\nexport interface ListenOptions {\n readonly bindings: ReadonlyArray<DecodedBinding>\n readonly onAnswer: (answer: Answer) => void\n /**\n * Every event the page's markers name, as the envelope lists them. Given,\n * `listen` needs no pass over the page to find the events a marker names\n * with `*` alone; without it, it reads every element's attributes, which on\n * a large page is most of its cost.\n */\n readonly events?: Iterable<string> | undefined\n}\n\n/**\n * Listens at `root` for every event the bindings name, and answers each from\n * the markers. Returns what removes the listeners.\n */\nexport const listen = (root: Element, options: ListenOptions): (() => void) =>\n listening(root, options).stop\n\n/**\n * `listen`, and also what answers an event already dispatched, from the\n * elements it passed (`pathOf` as it happened): one `foldkit-ssr/loader`\n * held, whose own path the browser has since emptied.\n */\nexport const listening = (\n root: Element,\n options: ListenOptions,\n): {\n readonly stop: () => void\n readonly answer: (event: Event, path: ReadonlyArray<EventTarget>) => void\n} => {\n // The markers as served, read once: the boot takes them off the page before\n // Foldkit adopts it, and an event landing before the first render is still\n // answered from them.\n const markers = new Map<Element, Map<string, string>>()\n for (const element of [root, ...Array.from(root.querySelectorAll('*'))]) {\n for (const name of element.getAttributeNames()) {\n if (!name.startsWith(BINDING_ATTRIBUTE)) continue\n const held = markers.get(element) ?? new Map<string, string>()\n held.set(name.slice(BINDING_ATTRIBUTE.length), element.getAttribute(name) ?? '')\n markers.set(element, held)\n }\n }\n // The bindings name most events; a marker whose handlers the page could not\n // name is `*` alone, so the markers themselves say the rest.\n const events = new Set(options.bindings.map(binding => binding.event))\n if (options.events !== undefined) {\n for (const event of options.events) events.add(event)\n } else {\n for (const held of markers.values()) for (const event of held.keys()) events.add(event)\n }\n const answer = (event: Event, path: ReadonlyArray<EventTarget>) => {\n const type = event.type\n const messages: Array<unknown> = []\n for (const node of path) {\n if (!(node instanceof Element)) continue\n const tokens = markers.get(node)?.get(type)\n // Foldkit chains an element's handlers in one listener, so a Stop among\n // them keeps the event from other elements, not from its siblings.\n let stopped = false\n if (tokens !== undefined) {\n for (const token of tokens.split(' ')) {\n if (token === UNNAMED_HANDLER) {\n options.onAnswer({ event, messages, unnamed: node })\n return\n }\n const binding = options.bindings[Number(token)]\n if (binding === undefined) continue\n if (binding.attribute === 'OnSubmit') event.preventDefault()\n if (binding.attribute === 'OnClick') {\n const click = (binding.options ?? {}) as ClickOptions\n if (click.defaultAction === 'Prevent') event.preventDefault()\n if (click.propagation === 'Stop') event.stopPropagation()\n if (click.focusSelector !== undefined) {\n const focusTarget = document.querySelector(click.focusSelector)\n if (focusTarget instanceof HTMLElement) focusTarget.focus()\n }\n if (click.propagation === 'Stop') stopped = true\n }\n messages.push(messageFor(binding, event))\n }\n }\n if (stopped || node === root) break\n }\n options.onAnswer({ event, messages })\n }\n const handler = (event: Event) => answer(event, pathOf(event))\n for (const type of events) root.addEventListener(type, handler, true)\n return {\n stop: () => {\n for (const type of events) root.removeEventListener(type, handler, true)\n },\n answer,\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAmCA,MAAM,YAAY,UAChB,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;;;;;;;;AASrE,MAAa,gBACX,UACyD;CACzD,IAAI,CAAC,MAAM,QAAQ,KAAK,GAAG,OAAO,OAAO,KAAK,0BAA0B;CACxE,MAAM,MAA6B,CAAC;CACpC,KAAK,MAAM,CAAC,OAAO,UAAU,MAAM,QAAQ,GAAG;EAC5C,IAAI,CAAC,SAAS,KAAK,GAAG,OAAO,OAAO,KAAK,SAAS,MAAM,kBAAkB;EAC1E,IAAI,OAAO,MAAM,cAAc,UAC7B,OAAO,OAAO,KAAK,SAAS,MAAM,kBAAkB;EAEtD,IAAI,CAAC,OAAO,OAAO,OAAO,SAAS,GAAG,OAAO,OAAO,KAAK,SAAS,MAAM,gBAAgB;EACxF,MAAM,EAAE,MAAM,UAAU;EACxB,IACE,SAAS,KAAA,KACT,EAAE,MAAM,QAAQ,IAAI,KAAK,KAAK,OAAM,UAAS,OAAO,UAAU,QAAQ,IAEtE,OAAO,OAAO,KAAK,SAAS,MAAM,yCAAyC;EAE7E,IAAI,UAAU,KAAA,KAAa,EAAE,OAAO,UAAU,KAAK,KAAM,SAAoB,IAC3E,OAAO,OAAO,KAAK,SAAS,MAAM,iCAAiC;EAErE,IAAI,KAAK;GACP,WAAW,MAAM;GACjB,SAAS,MAAM;GACf,GAAI,SAAS,KAAA,IAAY,CAAC,IAAI,EAAQ,KAA8B;GACpE,GAAI,UAAU,KAAA,IAAY,CAAC,IAAI,EAAS,MAAgB;GACxD,G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GACb,KAAK,MAAM,SAAS,OAAO,MAAM,GAAG,GAAG;IACrC,IAAI,UAAA,KAA2B;KAC7B,QAAQ,SAAS;MAAE;MAAO;MAAU,SAAS;KAAK,CAAC;KACnD;IACF;IACA,MAAM,UAAU,QAAQ,SAAS,OAAO,KAAK;IAC7C,IAAI,YAAY,KAAA,GAAW;IAC3B,IAAI,QAAQ,cAAc,YAAY,MAAM,eAAe;IAC3D,IAAI,QAAQ,cAAc,WAAW;KACnC,MAAM,QAAS,QAAQ,WAAW,CAAC;KACnC,IAAI,MAAM,kBAAkB,WAAW,MAAM,eAAe;KAC5D,IAAI,MAAM,gBAAgB,QAAQ,MAAM,gBAAgB;KACxD,IAAI,MAAM,kBAAkB,KAAA,GAAW;MACrC,MAAM,cAAc,SAAS,cAAc,MAAM,aAAa;MAC9D,IAAI,uBAAuB,aAAa,YAAY,MAAM;KAC5D;KACA,IAAI,MAAM,gBAAgB,QAAQ,UAAU;IAC9C;IACA,SAAS,KAAK,WAAW,SAAS,KAAK,CAAC;GAC1C;GAEF,IAAI,WAAW,SAAS,MAAM;EAChC;EACA,QAAQ,SAAS;GAAE;GAAO;EAAS,CAAC;CACtC;CACA,MAAM,WAAW,UAAiB,OAAO,OAAO,OAAO,KAAK,CAAC;CAC7D,KAAK,MAAM,QAAQ,QAAQ,KAAK,iBAAiB,MAAM,SAAS,IAAI;CACpE,OAAO;EACL,YAAY;GACV,KAAK,MAAM,QAAQ,QAAQ,KAAK,oBAAoB,MAAM,SAAS,IAAI;EACzE;EACA;CACF;AACF"}
@@ -0,0 +1,13 @@
1
+ export interface LoaderOptions {
2
+ /**
3
+ * Runs the runtime's chunk: a dynamic import of the module that calls
4
+ * `SSR.hydrate`, such as `() => import('./entry.js')`. Called once. With
5
+ * `runtimeChunk` from `foldkit-ssr/vite` naming the same module, a build
6
+ * also fetches the chunk as the loader starts, without running it
7
+ * (`<link rel="modulepreload">`); without it, the chunk is fetched as it runs.
8
+ */
9
+ readonly runtime: () => Promise<unknown>;
10
+ }
11
+ /** Starts the page's runtime as its plan says, holding what it must answer until it runs. */
12
+ export declare const load: (options: LoaderOptions) => void;
13
+ //# sourceMappingURL=loader.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"loader.d.ts","names":[],"sources":["../src/loader.ts"],"mappings":"A,iBA8BiB;;;;;;;;WAQN,eAAe;;;qBAgEb,OAAI,SAAa"}
package/dist/loader.js ADDED
@@ -0,0 +1,156 @@
1
+ import { offer } from "./handoff.js";
2
+ import { BINDING_ATTRIBUTE, FOLDKIT_APP_ATTRIBUTE, RESUME_ATTRIBUTE, UNTIL_LIMIT_MS, pathOf } from "./marks.js";
3
+ import "./runtimeUrl.js";
4
+ // src/loader.ts
5
+ /**
6
+ * `foldkit-ssr/loader`: a served page's entry script when the runtime's chunk
7
+ * should not run at load. It imports only modules that import nothing, so
8
+ * the page loads it without `effect`, Foldkit or the application.
9
+ *
10
+ * It follows the plan's `start`, which the server writes into the envelope:
11
+ * `'now'` runs the chunk at once; `'idle'` fetches it at once and runs it when
12
+ * the page is idle after load and the chunk has arrived; `'on-interaction'`
13
+ * fetches it at once and runs it on the first intent, a pointer over or down, focus or
14
+ * a key on an element the server marked (a binding or a kept field), or a
15
+ * scroll. Until `SSR.hydrate` in the chunk takes over, it holds each event a
16
+ * marker names, a form's submission prevented, and hands them over to be
17
+ * answered from the markers once. A held event the runtime has not taken
18
+ * `UNTIL_LIMIT_MS` after it happened is released: a submission goes to the
19
+ * browser (`requestSubmit`), anything else is dropped. A chunk that fails to
20
+ * load releases everything at once, and the loader holds nothing after.
21
+ */
22
+ /** The events that say a person is about to use the page. */
23
+ const INTENT = [
24
+ "pointerover",
25
+ "pointerdown",
26
+ "focusin",
27
+ "keydown"
28
+ ];
29
+ /** What the loader reads of the envelope: when to start, and the events the markers name. */
30
+ const envelopeOf = (root) => {
31
+ const carried = root.getAttribute(RESUME_ATTRIBUTE);
32
+ if (carried === null) return void 0;
33
+ try {
34
+ const parsed = JSON.parse(carried);
35
+ if (typeof parsed !== "object" || parsed === null) return void 0;
36
+ const { start, events } = parsed;
37
+ return {
38
+ start: start === "idle" || start === "on-interaction" ? start : "now",
39
+ events: Array.isArray(events) ? events.filter((event) => typeof event === "string") : []
40
+ };
41
+ } catch {
42
+ return;
43
+ }
44
+ };
45
+ /** Whether the server marked `node`: a binding of any event, or a kept field. */
46
+ const marked = (node) => node instanceof Element && node.getAttributeNames().some((name) => name.startsWith("data-foldkit-plus-on-") || name === "data-foldkit-plus-keep");
47
+ const whenIdle = (run) => {
48
+ if (typeof window.requestIdleCallback === "function") window.requestIdleCallback(run);
49
+ else setTimeout(run, 0);
50
+ };
51
+ /** Runs `run` when the page is idle after its `load` event. */
52
+ const afterLoad = (run) => {
53
+ if (document.readyState === "complete") whenIdle(run);
54
+ else window.addEventListener("load", () => whenIdle(run), { once: true });
55
+ };
56
+ /**
57
+ * Asks for the runtime's chunk now, without running it, and settles when it
58
+ * has arrived or failed (a failure is the import's to report). With no built
59
+ * address there is nothing to ask for and it settles at once.
60
+ */
61
+ const fetchChunk = () => Promise.resolve();
62
+ /** Starts the page's runtime as its plan says, holding what it must answer until it runs. */
63
+ const load = (options) => {
64
+ const root = document.querySelector(`[${FOLDKIT_APP_ATTRIBUTE}]`);
65
+ const envelope = root === null ? void 0 : envelopeOf(root);
66
+ if (root === null || envelope === void 0) {
67
+ options.runtime();
68
+ return;
69
+ }
70
+ let ran = false;
71
+ let releasing = false;
72
+ const held = [];
73
+ const releaseEach = (entry) => {
74
+ const { event } = entry;
75
+ if (event.type !== "submit" || !(event.target instanceof HTMLFormElement)) return;
76
+ const form = event.target;
77
+ if (!form.isConnected) return;
78
+ const submitter = event.submitter;
79
+ releasing = true;
80
+ try {
81
+ if (submitter !== null && submitter.isConnected && "form" in submitter && submitter.form === form) form.requestSubmit(submitter);
82
+ else form.requestSubmit();
83
+ } finally {
84
+ releasing = false;
85
+ }
86
+ };
87
+ const hold = (event) => {
88
+ if (releasing) return;
89
+ if (event.target instanceof Element && event.target.hasAttribute("data-foldkit-plus-keep")) return;
90
+ const path = pathOf(event);
91
+ const name = `${BINDING_ATTRIBUTE}${event.type}`;
92
+ if (!path.some((node) => node instanceof Element && node.hasAttribute(name))) return;
93
+ if (event.type === "submit") event.preventDefault();
94
+ const entry = {
95
+ event,
96
+ path,
97
+ deadline: setTimeout(() => {
98
+ const at = held.indexOf(entry);
99
+ if (at === -1) return;
100
+ held.splice(at, 1);
101
+ releaseEach(entry);
102
+ }, UNTIL_LIMIT_MS)
103
+ };
104
+ held.push(entry);
105
+ run();
106
+ };
107
+ const intent = (event) => {
108
+ if (pathOf(event).some(marked)) run();
109
+ };
110
+ const scrolled = () => run();
111
+ const stop = () => {
112
+ for (const type of envelope.events) root.removeEventListener(type, hold, true);
113
+ for (const type of INTENT) root.removeEventListener(type, intent, true);
114
+ window.removeEventListener("scroll", scrolled);
115
+ };
116
+ const releaseAll = () => {
117
+ stop();
118
+ for (const entry of held.splice(0)) {
119
+ clearTimeout(entry.deadline);
120
+ releaseEach(entry);
121
+ }
122
+ };
123
+ function run() {
124
+ if (ran) return;
125
+ ran = true;
126
+ offer({
127
+ take: () => {
128
+ stop();
129
+ return held.splice(0).map(({ event, path, deadline }) => {
130
+ clearTimeout(deadline);
131
+ return {
132
+ event,
133
+ path
134
+ };
135
+ });
136
+ },
137
+ release: releaseAll
138
+ });
139
+ options.runtime().catch(releaseAll);
140
+ }
141
+ for (const type of envelope.events) root.addEventListener(type, hold, true);
142
+ if (envelope.start === "now") {
143
+ run();
144
+ return;
145
+ }
146
+ for (const type of INTENT) root.addEventListener(type, intent, true);
147
+ if (envelope.start === "on-interaction") window.addEventListener("scroll", scrolled, {
148
+ passive: true,
149
+ once: true
150
+ });
151
+ const fetched = fetchChunk();
152
+ if (envelope.start === "idle") afterLoad(() => void fetched.then(() => whenIdle(run)));
153
+ };
154
+ export { load };
155
+
156
+ //# sourceMappingURL=loader.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"loader.js","names":[],"sources":["../src/loader.ts"],"sourcesContent":["/**\n * `foldkit-ssr/loader`: a served page's entry script when the runtime's chunk\n * should not run at load. It imports only modules that import nothing, so\n * the page loads it without `effect`, Foldkit or the application.\n *\n * It follows the plan's `start`, which the server writes into the envelope:\n * `'now'` runs the chunk at once; `'idle'` fetches it at once and runs it when\n * the page is idle after load and the chunk has arrived; `'on-interaction'`\n * fetches it at once and runs it on the first intent, a pointer over or down, focus or\n * a key on an element the server marked (a binding or a kept field), or a\n * scroll. Until `SSR.hydrate` in the chunk takes over, it holds each event a\n * marker names, a form's submission prevented, and hands them over to be\n * answered from the markers once. A held event the runtime has not taken\n * `UNTIL_LIMIT_MS` after it happened is released: a submission goes to the\n * browser (`requestSubmit`), anything else is dropped. A chunk that fails to\n * load releases everything at once, and the loader holds nothing after.\n */\nimport { offer, type HeldEvent } from './handoff.js'\nimport { UNBUILT, runtimeUrl } from './runtimeUrl.js'\nimport {\n BINDING_ATTRIBUTE,\n FOLDKIT_APP_ATTRIBUTE,\n KEEP_ATTRIBUTE,\n RESUME_ATTRIBUTE,\n UNTIL_LIMIT_MS,\n pathOf,\n} from './marks.js'\n// A type alone, which the build erases: `shared.ts` imports `effect`.\nimport type { Start } from './shared.js'\n\nexport interface LoaderOptions {\n /**\n * Runs the runtime's chunk: a dynamic import of the module that calls\n * `SSR.hydrate`, such as `() => import('./entry.js')`. Called once. With\n * `runtimeChunk` from `foldkit-ssr/vite` naming the same module, a build\n * also fetches the chunk as the loader starts, without running it\n * (`<link rel=\"modulepreload\">`); without it, the chunk is fetched as it runs.\n */\n readonly runtime: () => Promise<unknown>\n}\n\n/** The events that say a person is about to use the page. */\nconst INTENT = ['pointerover', 'pointerdown', 'focusin', 'keydown'] as const\n\n/** What the loader reads of the envelope: when to start, and the events the markers name. */\nconst envelopeOf = (\n root: Element,\n): { readonly start: Start; readonly events: ReadonlyArray<string> } | undefined => {\n const carried = root.getAttribute(RESUME_ATTRIBUTE)\n if (carried === null) return undefined\n try {\n const parsed: unknown = JSON.parse(carried)\n if (typeof parsed !== 'object' || parsed === null) return undefined\n const { start, events } = parsed as { readonly start?: unknown; readonly events?: unknown }\n return {\n start: start === 'idle' || start === 'on-interaction' ? start : 'now',\n events: Array.isArray(events) ? events.filter(event => typeof event === 'string') : [],\n }\n } catch {\n return undefined\n }\n}\n\n/** A held event and the deadline that releases it. */\ntype Holding = HeldEvent & { readonly deadline: ReturnType<typeof setTimeout> }\n\n/** Whether the server marked `node`: a binding of any event, or a kept field. */\nconst marked = (node: EventTarget): boolean =>\n node instanceof Element &&\n node\n .getAttributeNames()\n .some(name => name.startsWith(BINDING_ATTRIBUTE) || name === KEEP_ATTRIBUTE)\n\nconst whenIdle = (run: () => void): void => {\n if (typeof window.requestIdleCallback === 'function') window.requestIdleCallback(run)\n else setTimeout(run, 0)\n}\n\n/** Runs `run` when the page is idle after its `load` event. */\nconst afterLoad = (run: () => void): void => {\n if (document.readyState === 'complete') whenIdle(run)\n else window.addEventListener('load', () => whenIdle(run), { once: true })\n}\n\n/**\n * Asks for the runtime's chunk now, without running it, and settles when it\n * has arrived or failed (a failure is the import's to report). With no built\n * address there is nothing to ask for and it settles at once.\n */\nconst fetchChunk = (): Promise<void> =>\n runtimeUrl === UNBUILT\n ? Promise.resolve()\n : new Promise(settle => {\n const link = document.createElement('link')\n link.rel = 'modulepreload'\n link.href = runtimeUrl\n link.addEventListener('load', () => settle(), { once: true })\n link.addEventListener('error', () => settle(), { once: true })\n document.head.append(link)\n })\n\n/** Starts the page's runtime as its plan says, holding what it must answer until it runs. */\nexport const load = (options: LoaderOptions): void => {\n const root = document.querySelector(`[${FOLDKIT_APP_ATTRIBUTE}]`)\n const envelope = root === null ? undefined : envelopeOf(root)\n // No served page to hold for: `SSR.hydrate` renders afresh or refuses.\n if (root === null || envelope === undefined) {\n void options.runtime()\n return\n }\n let ran = false\n // Set while a release resubmits a form, so its new submission passes.\n let releasing = false\n const held: Array<Holding> = []\n\n const releaseEach = (entry: HeldEvent): void => {\n const { event } = entry\n if (event.type !== 'submit' || !(event.target instanceof HTMLFormElement)) return\n const form = event.target\n if (!form.isConnected) return\n const submitter = (event as SubmitEvent).submitter\n releasing = true\n try {\n if (\n submitter !== null &&\n submitter.isConnected &&\n 'form' in submitter &&\n submitter.form === form\n ) {\n form.requestSubmit(submitter as HTMLButtonElement)\n } else form.requestSubmit()\n } finally {\n releasing = false\n }\n }\n\n const hold = (event: Event): void => {\n if (releasing) return\n // A kept field carries what happened to it in its own state, which\n // `SSR.hydrate` reads: held as well, it would be answered twice.\n if (event.target instanceof Element && event.target.hasAttribute(KEEP_ATTRIBUTE)) return\n const path = pathOf(event)\n const name = `${BINDING_ATTRIBUTE}${event.type}`\n if (!path.some(node => node instanceof Element && node.hasAttribute(name))) return\n if (event.type === 'submit') event.preventDefault()\n const entry: Holding = {\n event,\n path,\n deadline: setTimeout(() => {\n const at = held.indexOf(entry)\n if (at === -1) return\n held.splice(at, 1)\n releaseEach(entry)\n }, UNTIL_LIMIT_MS),\n }\n held.push(entry)\n run()\n }\n\n const intent = (event: Event): void => {\n if (pathOf(event).some(marked)) run()\n }\n const scrolled = (): void => run()\n\n // Until `SSR.hydrate` takes the events or the loader lets go of them.\n const stop = (): void => {\n for (const type of envelope.events) root.removeEventListener(type, hold, true)\n for (const type of INTENT) root.removeEventListener(type, intent, true)\n window.removeEventListener('scroll', scrolled)\n }\n const releaseAll = (): void => {\n stop()\n for (const entry of held.splice(0)) {\n clearTimeout(entry.deadline)\n releaseEach(entry)\n }\n }\n\n function run(): void {\n if (ran) return\n ran = true\n offer({\n take: () => {\n stop()\n return held.splice(0).map(({ event, path, deadline }) => {\n clearTimeout(deadline)\n return { event, path }\n })\n },\n release: releaseAll,\n })\n options.runtime().catch(releaseAll)\n }\n\n for (const type of envelope.events) root.addEventListener(type, hold, true)\n if (envelope.start === 'now') {\n run()\n return\n }\n for (const type of INTENT) root.addEventListener(type, intent, true)\n if (envelope.start === 'on-interaction') {\n window.addEventListener('scroll', scrolled, { pass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/C;CACA,MAAM,mBAAyB;EAC7B,KAAK;EACL,KAAK,MAAM,SAAS,KAAK,OAAO,CAAC,GAAG;GAClC,aAAa,MAAM,QAAQ;GAC3B,YAAY,KAAK;EACnB;CACF;CAEA,SAAS,MAAY;EACnB,IAAI,KAAK;EACT,MAAM;EACN,MAAM;GACJ,YAAY;IACV,KAAK;IACL,OAAO,KAAK,OAAO,CAAC,CAAC,CAAC,KAAK,EAAE,OAAO,MAAM,eAAe;KACvD,aAAa,QAAQ;KACrB,OAAO;MAAE;MAAO;KAAK;IACvB,CAAC;GACH;GACA,SAAS;EACX,CAAC;EACD,QAAQ,QAAQ,CAAC,CAAC,MAAM,UAAU;CACpC;CAEA,KAAK,MAAM,QAAQ,SAAS,QAAQ,KAAK,iBAAiB,MAAM,MAAM,IAAI;CAC1E,IAAI,SAAS,UAAU,OAAO;EAC5B,IAAI;EACJ;CACF;CACA,KAAK,MAAM,QAAQ,QAAQ,KAAK,iBAAiB,MAAM,QAAQ,IAAI;CACnE,IAAI,SAAS,UAAU,kBACrB,OAAO,iBAAiB,UAAU,UAAU;EAAE,SAAS;EAAM,MAAM;CAAK,CAAC;CAE3E,MAAM,UAAU,WAAW;CAC3B,IAAI,SAAS,UAAU,QAAQ,gBAAgB,KAAK,QAAQ,WAAW,SAAS,GAAG,CAAC,CAAC;AACvF"}
@@ -0,0 +1,39 @@
1
+ /**
2
+ * What the server writes into a page for the browser to read, and the one
3
+ * limit a served page waits for. This module imports nothing, so
4
+ * `foldkit-ssr/loader` reads the same names as the runtime without carrying
5
+ * `effect`, Foldkit or the application.
6
+ */
7
+ /**
8
+ * The attribute Foldkit's server stamps on an application's root, as
9
+ * `foldkit/experimental/server` exports it. Written out here so a page can
10
+ * find its root without that module; a test pins the two together.
11
+ */
12
+ declare const FOLDKIT_APP_ATTRIBUTE = "data-foldkit-app";
13
+ /**
14
+ * The attribute on the stamped root that carries a page's resume envelope.
15
+ * Foldkit pairs its own handoff the same way: the build id rides on the root
16
+ * beside the app stamp, and the client reads it before adopting anything.
17
+ */
18
+ declare const RESUME_ATTRIBUTE = "data-foldkit-plus-resume";
19
+ /** The attribute prefix of an element's binding marker. */
20
+ declare const BINDING_ATTRIBUTE = "data-foldkit-plus-on-";
21
+ /**
22
+ * The attribute on a field whose typing before boot is kept (`KeepTyped`),
23
+ * naming the binding whose Message replays it.
24
+ */
25
+ declare const KEEP_ATTRIBUTE = "data-foldkit-plus-keep";
26
+ /**
27
+ * The longest a served page waits on the runtime: for a fresh application to
28
+ * satisfy `until`, and for the runtime's chunk to answer a press the loader
29
+ * holds, counted from the press.
30
+ */
31
+ declare const UNTIL_LIMIT_MS = 3000;
32
+ /**
33
+ * The elements whose handlers the live page would run for an event: the
34
+ * whole path for one that bubbles, its target alone for one that does not
35
+ * (`focus`, `mouseenter`).
36
+ */
37
+ declare const pathOf: (event: Event) => ReadonlyArray<EventTarget>;
38
+ export { UNTIL_LIMIT_MS as a, RESUME_ATTRIBUTE as i, FOLDKIT_APP_ATTRIBUTE as n, pathOf as o, KEEP_ATTRIBUTE as r, BINDING_ATTRIBUTE as t };
39
+ //# sourceMappingURL=marks-CX15BwOw.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"marks-CX15BwOw.d.ts","names":[],"sources":["../src/marks.ts"],"mappings":";;;;;;;;;;;cAYa;;;;;;cAOA;;cAGA;;;;;cAMA;;;;;;cAOA;;;;;;cAOA,SAAM,OAAW,UAAQ,cAAc"}
@@ -0,0 +1,2 @@
1
+ import { a as UNTIL_LIMIT_MS, i as RESUME_ATTRIBUTE, n as FOLDKIT_APP_ATTRIBUTE, o as pathOf, r as KEEP_ATTRIBUTE, t as BINDING_ATTRIBUTE } from "./marks-CX15BwOw.js";
2
+ export { BINDING_ATTRIBUTE, FOLDKIT_APP_ATTRIBUTE, KEEP_ATTRIBUTE, RESUME_ATTRIBUTE, UNTIL_LIMIT_MS, pathOf };
package/dist/marks.js ADDED
@@ -0,0 +1,41 @@
1
+ // src/marks.ts
2
+ /**
3
+ * What the server writes into a page for the browser to read, and the one
4
+ * limit a served page waits for. This module imports nothing, so
5
+ * `foldkit-ssr/loader` reads the same names as the runtime without carrying
6
+ * `effect`, Foldkit or the application.
7
+ */
8
+ /**
9
+ * The attribute Foldkit's server stamps on an application's root, as
10
+ * `foldkit/experimental/server` exports it. Written out here so a page can
11
+ * find its root without that module; a test pins the two together.
12
+ */
13
+ const FOLDKIT_APP_ATTRIBUTE = "data-foldkit-app";
14
+ /**
15
+ * The attribute on the stamped root that carries a page's resume envelope.
16
+ * Foldkit pairs its own handoff the same way: the build id rides on the root
17
+ * beside the app stamp, and the client reads it before adopting anything.
18
+ */
19
+ const RESUME_ATTRIBUTE = "data-foldkit-plus-resume";
20
+ /** The attribute prefix of an element's binding marker. */
21
+ const BINDING_ATTRIBUTE = "data-foldkit-plus-on-";
22
+ /**
23
+ * The attribute on a field whose typing before boot is kept (`KeepTyped`),
24
+ * naming the binding whose Message replays it.
25
+ */
26
+ const KEEP_ATTRIBUTE = "data-foldkit-plus-keep";
27
+ /**
28
+ * The longest a served page waits on the runtime: for a fresh application to
29
+ * satisfy `until`, and for the runtime's chunk to answer a press the loader
30
+ * holds, counted from the press.
31
+ */
32
+ const UNTIL_LIMIT_MS = 3e3;
33
+ /**
34
+ * The elements whose handlers the live page would run for an event: the
35
+ * whole path for one that bubbles, its target alone for one that does not
36
+ * (`focus`, `mouseenter`).
37
+ */
38
+ const pathOf = (event) => event.bubbles ? event.composedPath() : event.target === null ? [] : [event.target];
39
+ export { BINDING_ATTRIBUTE, FOLDKIT_APP_ATTRIBUTE, KEEP_ATTRIBUTE, RESUME_ATTRIBUTE, UNTIL_LIMIT_MS, pathOf };
40
+
41
+ //# sourceMappingURL=marks.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"marks.js","names":[],"sources":["../src/marks.ts"],"sourcesContent":["/**\n * What the server writes into a page for the browser to read, and the one\n * limit a served page waits for. This module imports nothing, so\n * `foldkit-ssr/loader` reads the same names as the runtime without carrying\n * `effect`, Foldkit or the application.\n */\n\n/**\n * The attribute Foldkit's server stamps on an application's root, as\n * `foldkit/experimental/server` exports it. Written out here so a page can\n * find its root without that module; a test pins the two together.\n */\nexport const FOLDKIT_APP_ATTRIBUTE = 'data-foldkit-app'\n\n/**\n * The attribute on the stamped root that carries a page's resume envelope.\n * Foldkit pairs its own handoff the same way: the build id rides on the root\n * beside the app stamp, and the client reads it before adopting anything.\n */\nexport const RESUME_ATTRIBUTE = 'data-foldkit-plus-resume'\n\n/** The attribute prefix of an element's binding marker. */\nexport const BINDING_ATTRIBUTE = 'data-foldkit-plus-on-'\n\n/**\n * The attribute on a field whose typing before boot is kept (`KeepTyped`),\n * naming the binding whose Message replays it.\n */\nexport const KEEP_ATTRIBUTE = 'data-foldkit-plus-keep'\n\n/**\n * The longest a served page waits on the runtime: for a fresh application to\n * satisfy `until`, and for the runtime's chunk to answer a press the loader\n * holds, counted from the press.\n */\nexport const UNTIL_LIMIT_MS = 3000\n\n/**\n * The elements whose handlers the live page would run for an event: the\n * whole path for one that bubbles, its target alone for one that does not\n * (`focus`, `mouseenter`).\n */\nexport const pathOf = (event: Event): ReadonlyArray<EventTarget> =>\n event.bubbles ? event.composedPath() : event.target === null ? [] : [event.target]\n"],"mappings":";;;;;;;;;;;;AAYA,MAAa,wBAAwB;;;;;;AAOrC,MAAa,mBAAmB;;AAGhC,MAAa,oBAAoB;;;;;AAMjC,MAAa,iBAAiB;;;;;;AAO9B,MAAa,iBAAiB;;;;;;AAO9B,MAAa,UAAU,UACrB,MAAM,UAAU,MAAM,aAAa,IAAI,MAAM,WAAW,OAAO,CAAC,IAAI,CAAC,MAAM,MAAM"}