@symbiotejs/symbiote 3.9.0 → 3.10.1

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 (131) hide show
  1. package/README.md +12 -0
  2. package/core/AppRouter.js +97 -58
  3. package/core/PubSub.js +42 -11
  4. package/core/Symbiote.js +70 -46
  5. package/core/itemizeProcessor-keyed.js +88 -188
  6. package/core/itemizeProcessor.js +1 -12
  7. package/core/itemizeSetup.js +26 -3
  8. package/core/ownElements.js +1 -4
  9. package/core/resolveTemplate.js +12 -0
  10. package/core/tpl-processors.js +1 -2
  11. package/docs/README.md +2 -0
  12. package/docs/html-app-vs-htmx.md +55 -0
  13. package/docs/lifecycle.md +2 -0
  14. package/docs/list-rendering.md +10 -2
  15. package/docs/pubsub.md +3 -0
  16. package/docs/routing.md +15 -4
  17. package/html-app/BaseClass.js +203 -0
  18. package/html-app/README.md +369 -0
  19. package/html-app/action-data.js +168 -0
  20. package/html-app/actions.js +366 -0
  21. package/html-app/collection-actions.js +104 -0
  22. package/html-app/collection-data.js +234 -0
  23. package/html-app/collection-items.js +45 -0
  24. package/html-app/conditions.js +42 -0
  25. package/html-app/context-data.js +185 -0
  26. package/html-app/context-requests.js +374 -0
  27. package/html-app/context-storage.js +376 -0
  28. package/html-app/declarations.js +55 -0
  29. package/html-app/examples/assets/actions.html +56 -0
  30. package/html-app/examples/assets/collections.html +72 -0
  31. package/html-app/examples/assets/components.html +25 -0
  32. package/html-app/examples/assets/conditional.html +29 -0
  33. package/html-app/examples/assets/data.html +31 -0
  34. package/html-app/examples/assets/guide.html +4 -0
  35. package/html-app/examples/assets/imports.html +11 -0
  36. package/html-app/examples/assets/not-found.html +4 -0
  37. package/html-app/examples/assets/routes.json +58 -0
  38. package/html-app/examples/assets/routing.html +27 -0
  39. package/html-app/examples/assets/state.html +32 -0
  40. package/html-app/examples/assets/storage.html +28 -0
  41. package/html-app/examples/assets/tasks.json +25 -0
  42. package/html-app/examples/full-app.html +147 -0
  43. package/html-app/examples/todo-ref.html +37 -0
  44. package/html-app/fetch-source.js +147 -0
  45. package/html-app/fragment-content.js +29 -0
  46. package/html-app/fragment-source.js +169 -0
  47. package/html-app/index.js +34 -0
  48. package/html-app/initial-data.js +88 -0
  49. package/html-app/pub-map.js +93 -0
  50. package/html-app/router-data.js +50 -0
  51. package/html-app/router-navigation.js +70 -0
  52. package/html-app/storage-revisions.js +130 -0
  53. package/html-app/sym-collection.js +142 -0
  54. package/html-app/sym-component.js +20 -0
  55. package/html-app/sym-conditional.js +141 -0
  56. package/html-app/sym-context.js +176 -0
  57. package/html-app/sym-import.js +218 -0
  58. package/html-app/sym-router.js +107 -0
  59. package/package.json +18 -6
  60. package/scripts/check-html-app-package.js +117 -0
  61. package/scripts/check-html-app-size.js +91 -0
  62. package/scripts/update-exports.js +4 -0
  63. package/skills/symbiote/SKILL.md +64 -15
  64. package/skills/symbiote/agents/openai.yaml +1 -1
  65. package/types/core/AppRouter.d.ts +13 -4
  66. package/types/core/AppRouter.d.ts.map +1 -1
  67. package/types/core/PubSub.d.ts +1 -1
  68. package/types/core/PubSub.d.ts.map +1 -1
  69. package/types/core/Symbiote.d.ts +4 -1
  70. package/types/core/Symbiote.d.ts.map +1 -1
  71. package/types/core/itemizeProcessor-keyed.d.ts.map +1 -1
  72. package/types/core/itemizeProcessor.d.ts.map +1 -1
  73. package/types/core/itemizeSetup.d.ts +1 -0
  74. package/types/core/itemizeSetup.d.ts.map +1 -1
  75. package/types/core/ownElements.d.ts +1 -1
  76. package/types/core/ownElements.d.ts.map +1 -1
  77. package/types/core/resolveTemplate.d.ts +2 -0
  78. package/types/core/resolveTemplate.d.ts.map +1 -0
  79. package/types/core/tpl-processors.d.ts.map +1 -1
  80. package/types/html-app/BaseClass.d.ts +24 -0
  81. package/types/html-app/BaseClass.d.ts.map +1 -0
  82. package/types/html-app/action-data.d.ts +15 -0
  83. package/types/html-app/action-data.d.ts.map +1 -0
  84. package/types/html-app/actions.d.ts +104 -0
  85. package/types/html-app/actions.d.ts.map +1 -0
  86. package/types/html-app/collection-actions.d.ts +12 -0
  87. package/types/html-app/collection-actions.d.ts.map +1 -0
  88. package/types/html-app/collection-data.d.ts +13 -0
  89. package/types/html-app/collection-data.d.ts.map +1 -0
  90. package/types/html-app/collection-items.d.ts +7 -0
  91. package/types/html-app/collection-items.d.ts.map +1 -0
  92. package/types/html-app/conditions.d.ts +5 -0
  93. package/types/html-app/conditions.d.ts.map +1 -0
  94. package/types/html-app/context-data.d.ts +31 -0
  95. package/types/html-app/context-data.d.ts.map +1 -0
  96. package/types/html-app/context-requests.d.ts +97 -0
  97. package/types/html-app/context-requests.d.ts.map +1 -0
  98. package/types/html-app/context-storage.d.ts +102 -0
  99. package/types/html-app/context-storage.d.ts.map +1 -0
  100. package/types/html-app/declarations.d.ts +3 -0
  101. package/types/html-app/declarations.d.ts.map +1 -0
  102. package/types/html-app/fetch-source.d.ts +23 -0
  103. package/types/html-app/fetch-source.d.ts.map +1 -0
  104. package/types/html-app/fragment-content.d.ts +6 -0
  105. package/types/html-app/fragment-content.d.ts.map +1 -0
  106. package/types/html-app/fragment-source.d.ts +14 -0
  107. package/types/html-app/fragment-source.d.ts.map +1 -0
  108. package/types/html-app/index.d.ts +9 -0
  109. package/types/html-app/index.d.ts.map +1 -0
  110. package/types/html-app/initial-data.d.ts +8 -0
  111. package/types/html-app/initial-data.d.ts.map +1 -0
  112. package/types/html-app/pub-map.d.ts +19 -0
  113. package/types/html-app/pub-map.d.ts.map +1 -0
  114. package/types/html-app/router-data.d.ts +4 -0
  115. package/types/html-app/router-data.d.ts.map +1 -0
  116. package/types/html-app/router-navigation.d.ts +3 -0
  117. package/types/html-app/router-navigation.d.ts.map +1 -0
  118. package/types/html-app/storage-revisions.d.ts +11 -0
  119. package/types/html-app/storage-revisions.d.ts.map +1 -0
  120. package/types/html-app/sym-collection.d.ts +16 -0
  121. package/types/html-app/sym-collection.d.ts.map +1 -0
  122. package/types/html-app/sym-component.d.ts +5 -0
  123. package/types/html-app/sym-component.d.ts.map +1 -0
  124. package/types/html-app/sym-conditional.d.ts +10 -0
  125. package/types/html-app/sym-conditional.d.ts.map +1 -0
  126. package/types/html-app/sym-context.d.ts +16 -0
  127. package/types/html-app/sym-context.d.ts.map +1 -0
  128. package/types/html-app/sym-import.d.ts +19 -0
  129. package/types/html-app/sym-import.d.ts.map +1 -0
  130. package/types/html-app/sym-router.d.ts +12 -0
  131. package/types/html-app/sym-router.d.ts.map +1 -0
@@ -0,0 +1,168 @@
1
+ import { isDataKey } from './initial-data.js';
2
+ /**
3
+ * @param {string} reference
4
+ * @param {boolean} [computed]
5
+ */
6
+ export function isDataReference(reference, computed = false) {
7
+ if (!reference || /[\s:;,\[\]]/.test(reference)) {
8
+ return false;
9
+ }
10
+ let name = reference;
11
+ if (name.startsWith('^') || name.startsWith('*')) {
12
+ name = name.slice(1);
13
+ }
14
+ else if (name.includes('/')) {
15
+ let index = name.indexOf('/');
16
+ if (!index) {
17
+ return false;
18
+ }
19
+ name = name.slice(index + 1);
20
+ }
21
+ if (computed && name.startsWith('+')) {
22
+ name = name.slice(1);
23
+ }
24
+ return isDataKey(name);
25
+ }
26
+ /**
27
+ * @param {import('./BaseClass.js').BaseClass} owner
28
+ * @param {string} reference
29
+ * @param {boolean} [computed]
30
+ */
31
+ export function resolveData(owner, reference, computed = false) {
32
+ if (!isDataReference(reference, computed)) {
33
+ throw new TypeError('Expected a data context reference: ' + reference);
34
+ }
35
+ let result = dataReference(owner, reference, computed);
36
+ if (!result || !result.ctx.has(result.name)) {
37
+ throw new TypeError('Unknown data target: ' + reference);
38
+ }
39
+ return result;
40
+ }
41
+ /**
42
+ * Resolve a validated read reference even before a named field arrives.
43
+ * @param {import('./BaseClass.js').BaseClass} owner
44
+ * @param {string} reference
45
+ * @param {boolean} [computed]
46
+ */
47
+ export function dataReference(owner, reference, computed = false) {
48
+ if (!isDataReference(reference, computed)) {
49
+ throw new TypeError('Expected a data context reference: ' + reference);
50
+ }
51
+ return owner.Symbiote.parseProp(reference, owner);
52
+ }
53
+
54
+ /** @param {string} source */
55
+ export function parseAction(source) {
56
+ let match = /^\[(toggle|set|pub-to|append|prepend|patch-matching|remove-matching|item-pub|item-toggle|item-remove|load|sync|persist|restore|navigate)(?:-(\d+))?\](.*)$/.exec(source);
57
+ let operation = match?.[1];
58
+ let reference = match?.[3] || '';
59
+ let validReference = [
60
+ 'load',
61
+ 'sync',
62
+ 'persist',
63
+ 'restore',
64
+ 'navigate',
65
+ ].includes(operation)
66
+ ? !!reference && !/[\s/:;,\[\]@*^+]/.test(reference)
67
+ : operation === 'item-remove' ? !reference
68
+ : operation?.startsWith('item-') ? isDataKey(reference) && !/[\s:;,\[\]]/.test(reference)
69
+ : isDataReference(reference);
70
+ if (!match || (match[2] !== undefined && ![
71
+ 'pub-to',
72
+ 'item-pub',
73
+ ].includes(operation)) || !validReference) {
74
+ throw new TypeError('Invalid HTML-app action: ' + source);
75
+ }
76
+ let delay = match[2] === undefined ? 0 : Number(match[2]);
77
+ if (!Number.isSafeInteger(delay) || delay > 2147483647) {
78
+ throw new TypeError('Invalid action debounce delay.');
79
+ }
80
+ return {
81
+ operation: match[1],
82
+ reference: match[3],
83
+ delay,
84
+ };
85
+ }
86
+ /**
87
+ * @param {Element} element
88
+ * @param {import('./BaseClass.js').BaseClass} owner
89
+ */
90
+ export function unavailable(element, owner) {
91
+ return !owner.isConnected || !element.isConnected || element.matches(':disabled')
92
+ || !!element.closest('[inert], [aria-disabled="true"]') || element.hasAttribute('readonly');
93
+ }
94
+ /**
95
+ * @param {Element} element
96
+ * @param {unknown} current
97
+ * @returns {{ skip?: boolean, value?: unknown }}
98
+ */
99
+ export function controlValue(element, current) {
100
+ if (element instanceof HTMLInputElement) {
101
+ if (element.type === 'checkbox') {
102
+ return {
103
+ value: element.checked,
104
+ };
105
+ }
106
+ if (element.type === 'radio' && !element.checked) {
107
+ return {
108
+ skip: true,
109
+ };
110
+ }
111
+ if (element.type === 'number' || element.type === 'range') {
112
+ let value = element.value === '' ? null : element.valueAsNumber;
113
+ if (value !== null && !Number.isFinite(value)) {
114
+ throw new TypeError('Invalid numeric input.');
115
+ }
116
+ return {
117
+ value,
118
+ };
119
+ }
120
+ if (element.type === 'file') {
121
+ throw new TypeError('File inputs require an explicit upload workflow.');
122
+ }
123
+ return {
124
+ value: element.value,
125
+ };
126
+ }
127
+ if (element instanceof HTMLSelectElement) {
128
+ return {
129
+ value: element.multiple ? [
130
+ ...element.selectedOptions,
131
+ ].map((option) => option.value) : element.value,
132
+ };
133
+ }
134
+ if (element instanceof HTMLTextAreaElement) {
135
+ return {
136
+ value: element.value,
137
+ };
138
+ }
139
+ if (!element.hasAttribute('value')) {
140
+ throw new TypeError('The action requires value or action-data.');
141
+ }
142
+ let value = element.getAttribute('value');
143
+ if (typeof current === 'boolean') {
144
+ if (value !== 'true' && value !== 'false') {
145
+ throw new TypeError('Expected a boolean value.');
146
+ }
147
+ return {
148
+ value: value === 'true',
149
+ };
150
+ }
151
+ return {
152
+ value,
153
+ };
154
+ }
155
+ /**
156
+ * @param {unknown} current
157
+ * @param {unknown} value
158
+ */
159
+ export function validateValue(current, value) {
160
+ if (value === undefined || typeof value === 'function' || typeof value === 'symbol'
161
+ || typeof value === 'bigint' || (typeof value === 'number' && !Number.isFinite(value))) {
162
+ throw new TypeError('Actions publish data values only.');
163
+ }
164
+ if (current !== null && current !== undefined && value !== null
165
+ && (typeof current !== typeof value || Array.isArray(current) !== Array.isArray(value))) {
166
+ throw new TypeError('The action value does not match the target type.');
167
+ }
168
+ }
@@ -0,0 +1,366 @@
1
+ import { DICT } from '../core/dictionary.js';
2
+ import { ownElements } from '../core/ownElements.js';
3
+ import { controlValue, parseAction, resolveData, unavailable, validateValue } from './action-data.js';
4
+ import { prepareCollectionAction } from './collection-actions.js';
5
+ import { contextRequests, observeDataTarget } from './context-requests.js';
6
+ import { navigateAction } from './router-navigation.js';
7
+ /**
8
+ * @typedef {Object} ActionEvent
9
+ * @property {boolean} [defaultPrevented]
10
+ * @property {boolean} [isComposing]
11
+ * @property {number} [button]
12
+ * @property {boolean} [ctrlKey]
13
+ * @property {boolean} [metaKey]
14
+ * @property {boolean} [shiftKey]
15
+ * @property {boolean} [altKey]
16
+ * @property {Element | null} [submitter]
17
+ * @property {() => void} [preventDefault]
18
+ *
19
+ * @typedef {Object} Binding
20
+ * @property {Element} element
21
+ * @property {string} property
22
+ * @property {string} source
23
+ * @property {string} key
24
+ * @property {ReturnType<typeof parseAction>} action
25
+ * @property {boolean} composing
26
+ * @property {(() => boolean) | undefined} pending
27
+ * @property {ReturnType<typeof setTimeout> | undefined} timer
28
+ * @property {(() => void)[]} cleanup
29
+ * @property {{ remove(): void }[]} subscriptions
30
+ */
31
+ let configuredForms = new WeakSet();
32
+ /**
33
+ * @param {Element | DocumentFragment} root
34
+ * @param {import('./BaseClass.js').BaseClass} owner
35
+ */
36
+ export function actionProcessor(root, owner) {
37
+ // Preserve authored descriptors for browser hydration; SSR never invokes UI actions.
38
+ if (!globalThis.__SYMBIOTE_SSR) {
39
+ owner.actionBindings.process(root);
40
+ }
41
+ }
42
+ export class ActionBindings {
43
+ /** @type {Binding[]} */
44
+ bindings = [];
45
+ connected = false;
46
+ version = 0;
47
+ sequence = 0;
48
+ /** @param {import('./BaseClass.js').BaseClass} owner */
49
+ constructor(owner) {
50
+ this.owner = owner;
51
+ }
52
+ connect() {
53
+ this.connected = true;
54
+ if (this.bindings.some((binding) => [
55
+ 'pub-to',
56
+ 'item-pub',
57
+ ].includes(binding.action.operation))) {
58
+ this.owner.ownerDocument.addEventListener('submit', this.onSubmit, true);
59
+ }
60
+ }
61
+ disconnect() {
62
+ this.connected = false;
63
+ this.version += 1;
64
+ this.owner.ownerDocument.removeEventListener('submit', this.onSubmit, true);
65
+ for (let binding of this.bindings) {
66
+ this.cancel(binding);
67
+ binding.composing = false;
68
+ }
69
+ }
70
+ invalidate() {
71
+ this.version += 1;
72
+ for (let binding of this.bindings) {
73
+ this.cancel(binding);
74
+ }
75
+ }
76
+ /**
77
+ * @param {Element | DocumentFragment} root
78
+ */
79
+ process(root) {
80
+ for (let element of ownElements(root, '[bind]')) {
81
+ let parts = element.getAttribute('bind').split(';');
82
+ let events = parts.map((part) => part.split(':')[0].trim());
83
+ let changed = false;
84
+ let compiled = parts.map((part) => {
85
+ let colon = part.indexOf(':');
86
+ if (colon < 0) {
87
+ return part;
88
+ }
89
+ let property = part.slice(0, colon).trim();
90
+ let source = part.slice(colon + 1).trim();
91
+ if (!source.startsWith('[')) {
92
+ if (/^!+\[/.test(source)) {
93
+ throw new TypeError('Actions cannot use boolean binding casts.');
94
+ }
95
+ return part;
96
+ }
97
+ if (!/^on[a-z]+$/.test(property) || events.filter((event) => event === property).length !== 1) {
98
+ throw new TypeError('Each declarative action requires one event binding.');
99
+ }
100
+ let action = parseAction(source);
101
+ let old = this.bindings.find((binding) => binding.element === element && binding.property === property);
102
+ if (old) {
103
+ this.drop(old);
104
+ }
105
+ let key = '__htmlAppAction' + this.sequence++;
106
+ while (this.owner.localCtx.has(key)) {
107
+ key = '__htmlAppAction' + this.sequence++;
108
+ }
109
+ /** @type {Binding} */
110
+ let binding = {
111
+ element,
112
+ property,
113
+ source,
114
+ key,
115
+ action,
116
+ composing: false,
117
+ pending: undefined,
118
+ timer: undefined,
119
+ cleanup: [],
120
+ subscriptions: [],
121
+ };
122
+ this.bindings.push(binding);
123
+ this.owner.localCtx.add(key, (/** @type {ActionEvent} */ event) => this.activate(binding, event));
124
+ if (element instanceof HTMLFormElement && property === 'onsubmit') {
125
+ configuredForms.add(element);
126
+ }
127
+ if (property === 'oninput' && [
128
+ 'pub-to',
129
+ 'item-pub',
130
+ ].includes(action.operation)) {
131
+ let start = () => {
132
+ this.cancel(binding);
133
+ binding.composing = true;
134
+ };
135
+ let end = () => {
136
+ binding.composing = false;
137
+ this.activate(binding);
138
+ };
139
+ element.addEventListener('compositionstart', start);
140
+ element.addEventListener('compositionend', end);
141
+ binding.cleanup.push(() => {
142
+ element.removeEventListener('compositionstart', start);
143
+ element.removeEventListener('compositionend', end);
144
+ });
145
+ }
146
+ changed = true;
147
+ return property + ': ' + key;
148
+ });
149
+ if (changed) {
150
+ element.setAttribute('bind', compiled.join(';'));
151
+ }
152
+ }
153
+ }
154
+ /** @param {Binding} binding */
155
+ cancel(binding) {
156
+ clearTimeout(binding.timer);
157
+ binding.timer = undefined;
158
+ binding.pending = undefined;
159
+ for (let subscription of binding.subscriptions) {
160
+ subscription.remove();
161
+ }
162
+ binding.subscriptions = [];
163
+ }
164
+ /** @param {Binding} binding */
165
+ drop(binding) {
166
+ this.cancel(binding);
167
+ for (let cleanup of binding.cleanup) {
168
+ cleanup();
169
+ }
170
+ if (binding.element instanceof HTMLFormElement) {
171
+ configuredForms.delete(binding.element);
172
+ }
173
+ this.owner.localCtx.delete(binding.key);
174
+ this.bindings.splice(this.bindings.indexOf(binding), 1);
175
+ }
176
+ destroy() {
177
+ this.disconnect();
178
+ for (let binding of [
179
+ ...this.bindings,
180
+ ]) {
181
+ this.drop(binding);
182
+ }
183
+ }
184
+ /** @param {SubmitEvent} event */
185
+ onSubmit = (event) => {
186
+ if (!(event.target instanceof HTMLFormElement) || event.defaultPrevented) {
187
+ return;
188
+ }
189
+ if (!this.flushForm(event.target) && configuredForms.has(event.target)) {
190
+ event.preventDefault();
191
+ }
192
+ };
193
+ /** @param {HTMLFormElement} form */
194
+ flushForm(form) {
195
+ let ready = true;
196
+ for (let binding of this.bindings) {
197
+ if (Reflect.get(binding.element, 'form') !== form) {
198
+ continue;
199
+ }
200
+ if (binding.composing) {
201
+ ready = false;
202
+ }
203
+ let commit = binding.pending;
204
+ if (commit) {
205
+ commit();
206
+ }
207
+ }
208
+ return ready;
209
+ }
210
+ identity() {
211
+ /** @type {Element | null} */
212
+ let node = this.owner;
213
+ while (node) {
214
+ let runtime = Reflect.get(node, 'actionBindings');
215
+ if (Reflect.has(node, DICT.MCP_ITEM_INDEX_KEY) && runtime instanceof ActionBindings) {
216
+ return {
217
+ runtime,
218
+ version: runtime.version,
219
+ };
220
+ }
221
+ node = node.parentElement;
222
+ }
223
+ }
224
+ /**
225
+ * @param {Binding} binding
226
+ * @param {ActionEvent} [event]
227
+ */
228
+ activate(binding, event = {}) {
229
+ let element = binding.element;
230
+ if (!this.bindings.includes(binding) || event.defaultPrevented || unavailable(element, this.owner)) {
231
+ return {
232
+ changed: false,
233
+ };
234
+ }
235
+ let operand = element;
236
+ if (element instanceof HTMLFormElement && binding.property === 'onsubmit') {
237
+ event.preventDefault?.();
238
+ if (!this.flushForm(element)) {
239
+ return {
240
+ changed: false,
241
+ };
242
+ }
243
+ if (event.submitter) {
244
+ operand = event.submitter;
245
+ }
246
+ if (unavailable(operand, this.owner) || (!element.noValidate
247
+ && !operand.hasAttribute('formnovalidate') && !element.checkValidity())) {
248
+ return {
249
+ changed: false,
250
+ };
251
+ }
252
+ }
253
+ this.cancel(binding);
254
+ if (binding.composing || event.isComposing) {
255
+ return {
256
+ changed: false,
257
+ };
258
+ }
259
+ let operation = binding.action.operation;
260
+ if (operation === 'navigate') {
261
+ return navigateAction(this.owner, binding.action.reference, element, operand, event);
262
+ }
263
+ if (operation === 'load' || operation === 'sync') {
264
+ let requests = contextRequests(binding.action.reference);
265
+ return operation === 'load'
266
+ ? requests.load(operand.hasAttribute('action-overwrite') || element.hasAttribute('action-overwrite'))
267
+ : requests.sync();
268
+ }
269
+ if (operation === 'persist' || operation === 'restore') {
270
+ let storage = contextRequests(binding.action.reference).owner.storage;
271
+ return operation === 'persist'
272
+ ? storage.persist(operand.hasAttribute('action-overwrite') || element.hasAttribute('action-overwrite'))
273
+ : storage.restore();
274
+ }
275
+ if (operation === 'item-pub' && Reflect.get(element, 'validity')?.valid === false) {
276
+ return {
277
+ changed: false,
278
+ };
279
+ }
280
+ let isCollection = ![
281
+ 'toggle',
282
+ 'set',
283
+ 'pub-to',
284
+ ].includes(operation);
285
+ let prepared = isCollection ? prepareCollectionAction(this.owner, binding.action, element, operand) : undefined;
286
+ if (isCollection && !prepared) {
287
+ return {
288
+ changed: false,
289
+ };
290
+ }
291
+ let target = prepared?.target || resolveData(this.owner, binding.action.reference);
292
+ let before = target.ctx.read(target.name);
293
+ let value;
294
+ if (prepared) {
295
+ value = prepared.value;
296
+ } else if (binding.action.operation === 'toggle') {
297
+ if (typeof before !== 'boolean') {
298
+ throw new TypeError('toggle requires a boolean target.');
299
+ }
300
+ value = !before;
301
+ }
302
+ else {
303
+ let data = operand.getAttribute('action-data') ?? element.getAttribute('action-data');
304
+ if (data !== null && binding.action.operation === 'set') {
305
+ let source = resolveData(this.owner, data, true);
306
+ value = source.ctx.read(source.name);
307
+ }
308
+ else {
309
+ let result = controlValue(operand, before);
310
+ if (result.skip) {
311
+ return {
312
+ changed: false,
313
+ };
314
+ }
315
+ value = result.value;
316
+ }
317
+ validateValue(before, value);
318
+ }
319
+ let identity = this.identity();
320
+ let commit = () => {
321
+ this.cancel(binding);
322
+ if (unavailable(element, this.owner)
323
+ || (identity && identity.runtime.version !== identity.version)) {
324
+ return false;
325
+ }
326
+ let latest;
327
+ try {
328
+ latest = prepared ? prepared.resolve() : resolveData(this.owner, binding.action.reference);
329
+ }
330
+ catch {
331
+ return false;
332
+ }
333
+ if (latest.ctx !== target.ctx || latest.name !== target.name || !Object.is(latest.ctx.read(latest.name), before)) {
334
+ return false;
335
+ }
336
+ if (Object.is(before, value)) {
337
+ return false;
338
+ }
339
+ observeDataTarget(latest);
340
+ latest.ctx.pub(latest.name, value);
341
+ prepared?.after?.();
342
+ return true;
343
+ };
344
+ if (binding.action.delay) {
345
+ if (!Object.is(before, value)) {
346
+ let intent = observeDataTarget(target)?.intent(target.name, value);
347
+ if (intent) {
348
+ binding.subscriptions.push(intent);
349
+ }
350
+ }
351
+ binding.pending = commit;
352
+ let subscription = target.ctx.sub(target.name, () => this.cancel(binding), false);
353
+ if (subscription) {
354
+ binding.subscriptions.push(subscription);
355
+ }
356
+ binding.timer = setTimeout(commit, binding.action.delay);
357
+ return {
358
+ changed: false,
359
+ pending: true,
360
+ };
361
+ }
362
+ return {
363
+ changed: commit(),
364
+ };
365
+ }
366
+ }
@@ -0,0 +1,104 @@
1
+ import { resolveData, controlValue, validateValue } from './action-data.js';
2
+ import { initialDefaults } from './initial-data.js';
3
+ import { appendRecord, prependRecord, cloneData, collectionData, recordData, updateMatching, updateRecord } from './collection-data.js';
4
+ import { findCollectionItem } from './collection-items.js';
5
+
6
+ let insertionActions = {
7
+ append: appendRecord,
8
+ prepend: prependRecord,
9
+ };
10
+
11
+ /**
12
+ * @param {import('./BaseClass.js').BaseClass} owner
13
+ * @param {Element} element
14
+ * @param {Element} operand
15
+ * @param {string} name
16
+ */
17
+ function readOperand(owner, element, operand, name) {
18
+ let reference = operand.getAttribute(name) ?? element.getAttribute(name);
19
+ if (!reference) {
20
+ throw new TypeError('Collection action requires ' + name + '.');
21
+ }
22
+ let target = resolveData(owner, reference, true);
23
+ return target.ctx.read(target.name);
24
+ }
25
+
26
+ /**
27
+ * Prepare a validated immutable update; publication remains in the action runtime.
28
+ * @param {import('./BaseClass.js').BaseClass} owner
29
+ * @param {ReturnType<import('./action-data.js').parseAction>} action
30
+ * @param {Element} element
31
+ * @param {Element} operand
32
+ */
33
+ export function prepareCollectionAction(owner, action, element, operand) {
34
+ if (action.operation.startsWith('item-')) {
35
+ let {
36
+ collection,
37
+ id,
38
+ } = findCollectionItem(owner);
39
+ let target = collection.source();
40
+ let before = collectionData(target.ctx.read(target.name));
41
+ let record = before.find((item) => item.id === id);
42
+ if (!record) {
43
+ throw new TypeError('The collection record no longer exists.');
44
+ }
45
+ let patch = null;
46
+ if (action.operation !== 'item-remove') {
47
+ let field = action.reference;
48
+ if (field === 'id' || !Object.hasOwn(record, field)) {
49
+ throw new TypeError('Item actions require an existing mutable field.');
50
+ }
51
+ let value;
52
+ if (action.operation === 'item-toggle') {
53
+ if (typeof record[field] !== 'boolean') {
54
+ throw new TypeError('item-toggle requires a boolean field.');
55
+ }
56
+ value = !record[field];
57
+ } else {
58
+ let control = controlValue(operand, record[field]);
59
+ if (control.skip) {
60
+ return;
61
+ }
62
+ value = control.value;
63
+ validateValue(record[field], value);
64
+ }
65
+ patch = {
66
+ [field]: value,
67
+ };
68
+ }
69
+ return {
70
+ target,
71
+ value: updateRecord(before, id, patch),
72
+ resolve: () => collection.source(),
73
+ };
74
+ }
75
+ let target = resolveData(owner, action.reference);
76
+ let before = target.ctx.read(target.name);
77
+ let value;
78
+ /** @type {(() => void) | undefined} */
79
+ let after;
80
+ if (Object.hasOwn(insertionActions, action.operation)) {
81
+ value = insertionActions[action.operation](before, readOperand(owner, element, operand, 'action-data'));
82
+ let reference = operand.getAttribute('action-reset') ?? element.getAttribute('action-reset');
83
+ if (reference !== null) {
84
+ let reset = resolveData(owner, reference);
85
+ let defaults = initialDefaults.get(reset.ctx);
86
+ if (!defaults || !Object.hasOwn(defaults, reset.name)) {
87
+ throw new TypeError('action-reset requires a declared JSON default.');
88
+ }
89
+ let initial = cloneData(recordData(defaults[reset.name]));
90
+ after = () => reset.ctx.pub(reset.name, initial);
91
+ }
92
+ } else {
93
+ let match = readOperand(owner, element, operand, 'action-match');
94
+ value = action.operation === 'patch-matching'
95
+ ? updateMatching(before, match, readOperand(owner, element, operand, 'action-data'))
96
+ : updateMatching(before, match);
97
+ }
98
+ return {
99
+ target,
100
+ value,
101
+ after,
102
+ resolve: () => resolveData(owner, action.reference),
103
+ };
104
+ }