@thomas-siegfried/tapout 0.0.1 → 0.0.3

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 (52) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +1207 -1205
  3. package/decorator-config.md +220 -0
  4. package/dist/wireParams.d.ts.map +1 -1
  5. package/dist/wireParams.js +27 -4
  6. package/dist/wireParams.js.map +1 -1
  7. package/llms.txt +360 -0
  8. package/package.json +57 -55
  9. package/src/applyBindings.ts +372 -372
  10. package/src/arrayToDomMapping.ts +300 -300
  11. package/src/attributeInterpolationMarkup.ts +91 -91
  12. package/src/bindingContext.ts +207 -207
  13. package/src/bindingEvent.ts +198 -198
  14. package/src/bindingProvider.ts +260 -260
  15. package/src/bindings.ts +963 -963
  16. package/src/compareArrays.ts +122 -122
  17. package/src/componentBinding.ts +318 -318
  18. package/src/componentDecorator.ts +62 -62
  19. package/src/components.ts +367 -367
  20. package/src/computed.ts +439 -439
  21. package/src/configure.ts +52 -52
  22. package/src/controlFlowBindings.ts +206 -206
  23. package/src/core.ts +60 -60
  24. package/src/decorators.ts +407 -407
  25. package/src/dependencyDetection.ts +76 -76
  26. package/src/disposable.ts +36 -36
  27. package/src/domData.ts +42 -42
  28. package/src/domNodeDisposal.ts +94 -94
  29. package/src/effects.ts +29 -29
  30. package/src/event.ts +173 -173
  31. package/src/expressionRewriting.ts +219 -219
  32. package/src/extenders.ts +102 -102
  33. package/src/filters.ts +91 -91
  34. package/src/index.ts +150 -150
  35. package/src/interpolationMarkup.ts +130 -130
  36. package/src/memoization.ts +71 -71
  37. package/src/namespacedBindings.ts +132 -132
  38. package/src/observable.ts +48 -48
  39. package/src/observableArray.ts +397 -397
  40. package/src/options.ts +25 -25
  41. package/src/selectExtensions.ts +68 -68
  42. package/src/slotBinding.ts +84 -84
  43. package/src/subscribable.ts +266 -266
  44. package/src/tasks.ts +79 -79
  45. package/src/templateEngine.ts +108 -108
  46. package/src/templateRendering.ts +399 -399
  47. package/src/templateRewriting.ts +94 -94
  48. package/src/templateSources.ts +134 -134
  49. package/src/utils.ts +123 -123
  50. package/src/utilsDom.ts +87 -87
  51. package/src/virtualElements.ts +153 -153
  52. package/src/wireParams.ts +69 -49
@@ -1,399 +1,399 @@
1
- import { Computed } from './computed.js';
2
- import { ignore } from './dependencyDetection.js';
3
- import { BindingContext } from './bindingContext.js';
4
- import { domDataGet, domDataSet, domDataNextKey } from './domData.js';
5
- import { addDisposeCallback } from './domNodeDisposal.js';
6
- import { bindingEvent } from './bindingEvent.js';
7
- import { applyBindings, applyBindingsToDescendants } from './applyBindings.js';
8
- import { instance as providerInstance } from './bindingProvider.js';
9
- import type { BindingHandler } from './bindingProvider.js';
10
- import { bindingHandlers } from './bindingProvider.js';
11
- import { allowedVirtualElementBindings, virtualChildNodes, virtualEmptyNode, virtualSetChildren, virtualNextSibling } from './virtualElements.js';
12
- import { isReadableSubscribable } from './subscribable.js';
13
- import { isObservableArray, type ObservableArray } from './observableArray.js';
14
- import { AnonymousSource } from './templateSources.js';
15
- import { getTemplateEngine } from './templateEngine.js';
16
- import type { TemplateEngine, TemplateRenderOptions } from './templateEngine.js';
17
- import { setDomNodeChildrenFromArrayMapping } from './arrayToDomMapping.js';
18
- import type { ArrayChange } from './compareArrays.js';
19
- import { unmemoizeDomNodeAndDescendants } from './memoization.js';
20
- import { ensureTemplateIsRewritten } from './templateRewriting.js';
21
- import { unwrapObservable } from './utils.js';
22
- import {
23
- fixUpContinuousNodeArray,
24
- replaceDomNodes,
25
- moveCleanedNodesToContainerElement,
26
- domNodeIsAttachedToDocument,
27
- } from './utilsDom.js';
28
-
29
- function invokeForEachNodeInContinuousRange(
30
- firstNode: Node,
31
- lastNode: Node,
32
- action: (node: Node, nextInRange?: Node) => void,
33
- ): void {
34
- const firstOutOfRange = virtualNextSibling(lastNode);
35
- let nextInQueue: Node | null = firstNode;
36
- while (nextInQueue && nextInQueue !== firstOutOfRange) {
37
- const node = nextInQueue;
38
- nextInQueue = virtualNextSibling(node);
39
- action(node, nextInQueue ?? undefined);
40
- }
41
- }
42
-
43
- function activateBindingsOnContinuousNodeArray(
44
- continuousNodeArray: Node[],
45
- bindingContext: BindingContext,
46
- ): void {
47
- if (continuousNodeArray.length) {
48
- let firstNode = continuousNodeArray[0];
49
- let lastNode = continuousNodeArray[continuousNodeArray.length - 1];
50
- const parentNode = firstNode.parentNode!;
51
- const provider = providerInstance;
52
- const preprocessNode = (provider as { preprocessNode?(node: Node): Node[] | void }).preprocessNode;
53
-
54
- if (preprocessNode) {
55
- invokeForEachNodeInContinuousRange(firstNode, lastNode, (node, nextNodeInRange) => {
56
- const nodePreviousSibling = node.previousSibling;
57
- const newNodes = preprocessNode.call(provider, node);
58
- if (newNodes) {
59
- if (node === firstNode)
60
- firstNode = newNodes[0] || nextNodeInRange!;
61
- if (node === lastNode)
62
- lastNode = newNodes[newNodes.length - 1] || nodePreviousSibling!;
63
- }
64
- });
65
-
66
- continuousNodeArray.length = 0;
67
- if (!firstNode) return;
68
- if (firstNode === lastNode) {
69
- continuousNodeArray.push(firstNode);
70
- } else {
71
- continuousNodeArray.push(firstNode, lastNode);
72
- fixUpContinuousNodeArray(continuousNodeArray, parentNode);
73
- }
74
- }
75
-
76
- // Apply bindings before unmemoization — unmemoization may introduce new nodes
77
- // that shouldn't be re-bound, whereas regular applyBindings won't add memoized nodes
78
- invokeForEachNodeInContinuousRange(firstNode, lastNode, (node) => {
79
- if (node.nodeType === 1 || node.nodeType === 8)
80
- applyBindings(bindingContext, node);
81
- });
82
- invokeForEachNodeInContinuousRange(firstNode, lastNode, (node) => {
83
- if (node.nodeType === 1 || node.nodeType === 8)
84
- unmemoizeDomNodeAndDescendants(node, [bindingContext]);
85
- });
86
-
87
- fixUpContinuousNodeArray(continuousNodeArray, parentNode);
88
- }
89
- }
90
-
91
- function getFirstNodeFromPossibleArray(nodeOrNodeArray: Node | Node[]): Node | null {
92
- if ('nodeType' in nodeOrNodeArray && (nodeOrNodeArray as Node).nodeType) {
93
- return nodeOrNodeArray as Node;
94
- }
95
- const arr = nodeOrNodeArray as Node[];
96
- return arr.length > 0 ? arr[0] : null;
97
- }
98
-
99
- function executeTemplate(
100
- targetNodeOrNodeArray: Node | Node[],
101
- renderMode: string,
102
- template: string | Node,
103
- bindingContext: BindingContext,
104
- options: TemplateRenderOptions,
105
- ): Node[] {
106
- options = options || {};
107
- const firstTargetNode = targetNodeOrNodeArray && getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
108
- const templateDocument = ((firstTargetNode || template) as Node)?.ownerDocument;
109
- const templateEngineToUse: TemplateEngine = options.templateEngine || getTemplateEngine();
110
- ensureTemplateIsRewritten(template, templateEngineToUse, templateDocument ?? undefined);
111
- const renderedNodesArray = templateEngineToUse.renderTemplate(template, bindingContext, options, templateDocument ?? undefined);
112
-
113
- if (typeof renderedNodesArray.length !== 'number' || (renderedNodesArray.length > 0 && typeof renderedNodesArray[0].nodeType !== 'number'))
114
- throw new Error('Template engine must return an array of DOM nodes');
115
-
116
- let haveAddedNodesToParent = false;
117
- switch (renderMode) {
118
- case 'replaceChildren':
119
- virtualSetChildren(targetNodeOrNodeArray as Node, renderedNodesArray);
120
- haveAddedNodesToParent = true;
121
- break;
122
- case 'replaceNode':
123
- replaceDomNodes(targetNodeOrNodeArray, renderedNodesArray);
124
- haveAddedNodesToParent = true;
125
- break;
126
- case 'ignoreTargetNode':
127
- break;
128
- default:
129
- throw new Error('Unknown renderMode: ' + renderMode);
130
- }
131
-
132
- if (haveAddedNodesToParent) {
133
- activateBindingsOnContinuousNodeArray(renderedNodesArray, bindingContext);
134
- if (options.afterRender) {
135
- ignore(() => options.afterRender!(renderedNodesArray, (bindingContext as Record<string, unknown>)[options.as || '$data']));
136
- }
137
- if (renderMode === 'replaceChildren') {
138
- bindingEvent.notify(targetNodeOrNodeArray as Node, bindingEvent.childrenComplete);
139
- }
140
- }
141
-
142
- return renderedNodesArray;
143
- }
144
-
145
- function resolveTemplateName(
146
- template: unknown,
147
- data: unknown,
148
- context: BindingContext,
149
- ): string | Node {
150
- if (isReadableSubscribable(template)) {
151
- return template.get() as string | Node;
152
- } else if (typeof template === 'function') {
153
- return (template as (data: unknown, context: BindingContext) => string | Node)(data, context);
154
- } else {
155
- return template as string | Node;
156
- }
157
- }
158
-
159
- const templateComputedDomDataKey = domDataNextKey();
160
-
161
- function disposeOldComputed(element: Node): void {
162
- const oldComputed = domDataGet(element, templateComputedDomDataKey) as Computed<void> | undefined;
163
- if (oldComputed && typeof oldComputed.dispose === 'function')
164
- oldComputed.dispose();
165
- }
166
-
167
- function storeNewComputed(element: Node, newComputed: Computed<void> | { dispose(): void } | undefined): void {
168
- domDataSet(element, templateComputedDomDataKey,
169
- newComputed && (!('isActive' in newComputed) || (newComputed as Computed<void>).isActive()) ? newComputed : undefined);
170
- }
171
-
172
- export function renderTemplate(
173
- template: unknown,
174
- dataOrBindingContext: unknown,
175
- options: TemplateRenderOptions,
176
- targetNodeOrNodeArray: Node | Node[],
177
- renderMode?: string,
178
- ): Computed<void> {
179
- options = options || {};
180
- if ((options.templateEngine || getTemplateEngine()) == null)
181
- throw new Error('Set a template engine before calling renderTemplate');
182
- renderMode = renderMode || 'replaceChildren';
183
-
184
- const firstTargetNode = getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
185
- const whenToDispose = () => !firstTargetNode || !domNodeIsAttachedToDocument(firstTargetNode);
186
- const activelyDisposeWhenNodeIsRemoved = (firstTargetNode && renderMode === 'replaceNode')
187
- ? firstTargetNode.parentNode
188
- : firstTargetNode;
189
-
190
- let currentTargetNodeOrNodeArray = targetNodeOrNodeArray;
191
-
192
- const computed = new Computed<void>(() => {
193
- const bindingContext = (dataOrBindingContext instanceof BindingContext)
194
- ? dataOrBindingContext
195
- : new BindingContext(dataOrBindingContext, undefined, undefined, undefined, { exportDependencies: true });
196
-
197
- const templateName = resolveTemplateName(template, bindingContext.$data, bindingContext);
198
- const renderedNodesArray = executeTemplate(currentTargetNodeOrNodeArray, renderMode!, templateName, bindingContext, options);
199
-
200
- if (renderMode === 'replaceNode') {
201
- currentTargetNodeOrNodeArray = renderedNodesArray;
202
- }
203
- });
204
-
205
- if (activelyDisposeWhenNodeIsRemoved) {
206
- addDisposeCallback(activelyDisposeWhenNodeIsRemoved, () => computed.dispose());
207
- }
208
-
209
- // Also add a check to dispose when detached from DOM
210
- const sub = computed.subscribe(() => {
211
- if (whenToDispose()) {
212
- computed.dispose();
213
- sub.dispose();
214
- }
215
- });
216
-
217
- return computed;
218
- }
219
-
220
- export function renderTemplateForEach(
221
- template: unknown,
222
- arrayOrObservableArray: unknown,
223
- options: TemplateRenderOptions,
224
- targetNode: Node,
225
- parentBindingContext: BindingContext,
226
- ): { dispose(): void } {
227
- let arrayItemContext: BindingContext | null;
228
- const asName = options.as;
229
-
230
- const executeTemplateForArrayItem = (arrayValue: unknown, index: unknown) => {
231
- arrayItemContext = parentBindingContext.createChildContext(arrayValue, {
232
- as: asName,
233
- noChildContext: options.noChildContext,
234
- extend(context: BindingContext) {
235
- context.$index = index;
236
- if (asName) {
237
- context[asName + 'Index'] = index;
238
- }
239
- },
240
- });
241
-
242
- const templateName = resolveTemplateName(template, arrayValue, arrayItemContext);
243
- return executeTemplate(targetNode, 'ignoreTargetNode', templateName, arrayItemContext, options);
244
- };
245
-
246
- const activateBindingsCallback = (arrayValue: unknown, addedNodesArray: Node[]) => {
247
- activateBindingsOnContinuousNodeArray(addedNodesArray, arrayItemContext!);
248
- if (options.afterRender)
249
- options.afterRender(addedNodesArray, arrayValue);
250
- arrayItemContext = null;
251
- };
252
-
253
- const setDomNodeChildrenFromArrayMappingCb = (newArray: unknown[], changeList?: ArrayChange<unknown>[]) => {
254
- ignore(() => setDomNodeChildrenFromArrayMapping(
255
- targetNode, newArray, executeTemplateForArrayItem as never, options, activateBindingsCallback as never, changeList,
256
- ));
257
- bindingEvent.notify(targetNode, bindingEvent.childrenComplete);
258
- };
259
-
260
- const shouldHideDestroyed = (options.includeDestroyed === false);
261
-
262
- if (!shouldHideDestroyed && !options.beforeRemove && isObservableArray(arrayOrObservableArray)) {
263
- const observableArray = arrayOrObservableArray as ObservableArray<unknown>;
264
- const queuedChangeLists: ArrayChange<unknown>[][] = [];
265
- let isProcessing = false;
266
-
267
- function processArrayChange(changeList?: ArrayChange<unknown>[]): void {
268
- if (changeList) queuedChangeLists.push(changeList);
269
- if (isProcessing) return;
270
- isProcessing = true;
271
- try {
272
- if (queuedChangeLists.length === 0) {
273
- setDomNodeChildrenFromArrayMappingCb(observableArray.peek());
274
- } else {
275
- while (queuedChangeLists.length) {
276
- const cl = queuedChangeLists.shift()!;
277
- try {
278
- setDomNodeChildrenFromArrayMappingCb(observableArray.peek(), cl);
279
- } catch (e) {
280
- // allow processing to continue
281
- if (queuedChangeLists.length === 0) throw e;
282
- }
283
- }
284
- }
285
- } finally {
286
- isProcessing = false;
287
- }
288
- }
289
-
290
- const subscription = observableArray.subscribe(
291
- processArrayChange as (value: unknown) => void,
292
- 'arrayChange',
293
- );
294
- addDisposeCallback(targetNode, () => subscription.dispose());
295
-
296
- processArrayChange();
297
- return subscription;
298
- } else {
299
- const computed = new Computed<void>(() => {
300
- let unwrappedArray = unwrapObservable(arrayOrObservableArray) as unknown[] || [];
301
- if (!Array.isArray(unwrappedArray)) {
302
- unwrappedArray = [unwrappedArray];
303
- }
304
-
305
- if (shouldHideDestroyed) {
306
- unwrappedArray = (unwrappedArray as Record<string, unknown>[]).filter(
307
- item => item === undefined || item === null || !unwrapObservable(item._destroy),
308
- );
309
- }
310
- setDomNodeChildrenFromArrayMappingCb(unwrappedArray);
311
- });
312
-
313
- addDisposeCallback(targetNode, () => computed.dispose());
314
- return computed;
315
- }
316
- }
317
-
318
- // ---- template binding handler ----
319
-
320
- const cleanContainerDomDataKey = domDataNextKey();
321
-
322
- const templateHandler: BindingHandler = {
323
- init(element, valueAccessor) {
324
- const bindingValue = unwrapObservable(valueAccessor());
325
- if (typeof bindingValue === 'string' || (bindingValue && typeof bindingValue === 'object' && 'name' in (bindingValue as Record<string, unknown>))) {
326
- virtualEmptyNode(element);
327
- } else if (bindingValue && typeof bindingValue === 'object' && 'nodes' in (bindingValue as Record<string, unknown>)) {
328
- const nodes = (bindingValue as Record<string, unknown>).nodes as Node[] || [];
329
- if (isReadableSubscribable(nodes)) {
330
- throw new Error('The "nodes" option must be a plain, non-observable array.');
331
- }
332
-
333
- let container = nodes[0]?.parentNode as HTMLElement | undefined;
334
- if (!container || !domDataGet(container, cleanContainerDomDataKey)) {
335
- container = moveCleanedNodesToContainerElement(nodes);
336
- domDataSet(container, cleanContainerDomDataKey, true);
337
- }
338
-
339
- new AnonymousSource(element as Element).nodes(container);
340
- } else {
341
- const templateNodes = virtualChildNodes(element);
342
- if (templateNodes.length > 0) {
343
- const container = moveCleanedNodesToContainerElement(templateNodes);
344
- new AnonymousSource(element as Element).nodes(container);
345
- } else {
346
- throw new Error('Anonymous template defined, but no template content was provided');
347
- }
348
- }
349
- return { controlsDescendantBindings: true };
350
- },
351
-
352
- update(element, valueAccessor, allBindings, viewModel, bindingContext) {
353
- const value = valueAccessor();
354
- let options = unwrapObservable(value) as TemplateRenderOptions & Record<string, unknown>;
355
- let shouldDisplay = true;
356
- let templateComputed: { dispose(): void } | undefined;
357
- let template: unknown;
358
-
359
- if (typeof options === 'string') {
360
- template = value;
361
- options = {};
362
- } else {
363
- template = 'name' in options ? unwrapObservable(options.name) : element;
364
-
365
- if ('if' in options)
366
- shouldDisplay = !!unwrapObservable(options['if']);
367
- if (shouldDisplay && 'ifnot' in options)
368
- shouldDisplay = !unwrapObservable(options.ifnot);
369
- }
370
-
371
- if (shouldDisplay && !template) {
372
- shouldDisplay = false;
373
- }
374
-
375
- disposeOldComputed(element);
376
-
377
- if ('foreach' in options) {
378
- const dataArray = (shouldDisplay && options.foreach) || [];
379
- templateComputed = renderTemplateForEach(template, dataArray, options, element, bindingContext!);
380
- } else if (!shouldDisplay) {
381
- virtualEmptyNode(element);
382
- } else {
383
- let innerBindingContext = bindingContext!;
384
- if ('data' in options) {
385
- innerBindingContext = bindingContext!.createChildContext(options.data, {
386
- as: options.as,
387
- noChildContext: options.noChildContext,
388
- exportDependencies: true,
389
- });
390
- }
391
- templateComputed = renderTemplate(template, innerBindingContext, options, element);
392
- }
393
-
394
- storeNewComputed(element, templateComputed as Computed<void> | undefined);
395
- },
396
- };
397
-
398
- bindingHandlers['template'] = templateHandler;
399
- allowedVirtualElementBindings['template'] = true;
1
+ import { Computed } from './computed.js';
2
+ import { ignore } from './dependencyDetection.js';
3
+ import { BindingContext } from './bindingContext.js';
4
+ import { domDataGet, domDataSet, domDataNextKey } from './domData.js';
5
+ import { addDisposeCallback } from './domNodeDisposal.js';
6
+ import { bindingEvent } from './bindingEvent.js';
7
+ import { applyBindings, applyBindingsToDescendants } from './applyBindings.js';
8
+ import { instance as providerInstance } from './bindingProvider.js';
9
+ import type { BindingHandler } from './bindingProvider.js';
10
+ import { bindingHandlers } from './bindingProvider.js';
11
+ import { allowedVirtualElementBindings, virtualChildNodes, virtualEmptyNode, virtualSetChildren, virtualNextSibling } from './virtualElements.js';
12
+ import { isReadableSubscribable } from './subscribable.js';
13
+ import { isObservableArray, type ObservableArray } from './observableArray.js';
14
+ import { AnonymousSource } from './templateSources.js';
15
+ import { getTemplateEngine } from './templateEngine.js';
16
+ import type { TemplateEngine, TemplateRenderOptions } from './templateEngine.js';
17
+ import { setDomNodeChildrenFromArrayMapping } from './arrayToDomMapping.js';
18
+ import type { ArrayChange } from './compareArrays.js';
19
+ import { unmemoizeDomNodeAndDescendants } from './memoization.js';
20
+ import { ensureTemplateIsRewritten } from './templateRewriting.js';
21
+ import { unwrapObservable } from './utils.js';
22
+ import {
23
+ fixUpContinuousNodeArray,
24
+ replaceDomNodes,
25
+ moveCleanedNodesToContainerElement,
26
+ domNodeIsAttachedToDocument,
27
+ } from './utilsDom.js';
28
+
29
+ function invokeForEachNodeInContinuousRange(
30
+ firstNode: Node,
31
+ lastNode: Node,
32
+ action: (node: Node, nextInRange?: Node) => void,
33
+ ): void {
34
+ const firstOutOfRange = virtualNextSibling(lastNode);
35
+ let nextInQueue: Node | null = firstNode;
36
+ while (nextInQueue && nextInQueue !== firstOutOfRange) {
37
+ const node = nextInQueue;
38
+ nextInQueue = virtualNextSibling(node);
39
+ action(node, nextInQueue ?? undefined);
40
+ }
41
+ }
42
+
43
+ function activateBindingsOnContinuousNodeArray(
44
+ continuousNodeArray: Node[],
45
+ bindingContext: BindingContext,
46
+ ): void {
47
+ if (continuousNodeArray.length) {
48
+ let firstNode = continuousNodeArray[0];
49
+ let lastNode = continuousNodeArray[continuousNodeArray.length - 1];
50
+ const parentNode = firstNode.parentNode!;
51
+ const provider = providerInstance;
52
+ const preprocessNode = (provider as { preprocessNode?(node: Node): Node[] | void }).preprocessNode;
53
+
54
+ if (preprocessNode) {
55
+ invokeForEachNodeInContinuousRange(firstNode, lastNode, (node, nextNodeInRange) => {
56
+ const nodePreviousSibling = node.previousSibling;
57
+ const newNodes = preprocessNode.call(provider, node);
58
+ if (newNodes) {
59
+ if (node === firstNode)
60
+ firstNode = newNodes[0] || nextNodeInRange!;
61
+ if (node === lastNode)
62
+ lastNode = newNodes[newNodes.length - 1] || nodePreviousSibling!;
63
+ }
64
+ });
65
+
66
+ continuousNodeArray.length = 0;
67
+ if (!firstNode) return;
68
+ if (firstNode === lastNode) {
69
+ continuousNodeArray.push(firstNode);
70
+ } else {
71
+ continuousNodeArray.push(firstNode, lastNode);
72
+ fixUpContinuousNodeArray(continuousNodeArray, parentNode);
73
+ }
74
+ }
75
+
76
+ // Apply bindings before unmemoization — unmemoization may introduce new nodes
77
+ // that shouldn't be re-bound, whereas regular applyBindings won't add memoized nodes
78
+ invokeForEachNodeInContinuousRange(firstNode, lastNode, (node) => {
79
+ if (node.nodeType === 1 || node.nodeType === 8)
80
+ applyBindings(bindingContext, node);
81
+ });
82
+ invokeForEachNodeInContinuousRange(firstNode, lastNode, (node) => {
83
+ if (node.nodeType === 1 || node.nodeType === 8)
84
+ unmemoizeDomNodeAndDescendants(node, [bindingContext]);
85
+ });
86
+
87
+ fixUpContinuousNodeArray(continuousNodeArray, parentNode);
88
+ }
89
+ }
90
+
91
+ function getFirstNodeFromPossibleArray(nodeOrNodeArray: Node | Node[]): Node | null {
92
+ if ('nodeType' in nodeOrNodeArray && (nodeOrNodeArray as Node).nodeType) {
93
+ return nodeOrNodeArray as Node;
94
+ }
95
+ const arr = nodeOrNodeArray as Node[];
96
+ return arr.length > 0 ? arr[0] : null;
97
+ }
98
+
99
+ function executeTemplate(
100
+ targetNodeOrNodeArray: Node | Node[],
101
+ renderMode: string,
102
+ template: string | Node,
103
+ bindingContext: BindingContext,
104
+ options: TemplateRenderOptions,
105
+ ): Node[] {
106
+ options = options || {};
107
+ const firstTargetNode = targetNodeOrNodeArray && getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
108
+ const templateDocument = ((firstTargetNode || template) as Node)?.ownerDocument;
109
+ const templateEngineToUse: TemplateEngine = options.templateEngine || getTemplateEngine();
110
+ ensureTemplateIsRewritten(template, templateEngineToUse, templateDocument ?? undefined);
111
+ const renderedNodesArray = templateEngineToUse.renderTemplate(template, bindingContext, options, templateDocument ?? undefined);
112
+
113
+ if (typeof renderedNodesArray.length !== 'number' || (renderedNodesArray.length > 0 && typeof renderedNodesArray[0].nodeType !== 'number'))
114
+ throw new Error('Template engine must return an array of DOM nodes');
115
+
116
+ let haveAddedNodesToParent = false;
117
+ switch (renderMode) {
118
+ case 'replaceChildren':
119
+ virtualSetChildren(targetNodeOrNodeArray as Node, renderedNodesArray);
120
+ haveAddedNodesToParent = true;
121
+ break;
122
+ case 'replaceNode':
123
+ replaceDomNodes(targetNodeOrNodeArray, renderedNodesArray);
124
+ haveAddedNodesToParent = true;
125
+ break;
126
+ case 'ignoreTargetNode':
127
+ break;
128
+ default:
129
+ throw new Error('Unknown renderMode: ' + renderMode);
130
+ }
131
+
132
+ if (haveAddedNodesToParent) {
133
+ activateBindingsOnContinuousNodeArray(renderedNodesArray, bindingContext);
134
+ if (options.afterRender) {
135
+ ignore(() => options.afterRender!(renderedNodesArray, (bindingContext as Record<string, unknown>)[options.as || '$data']));
136
+ }
137
+ if (renderMode === 'replaceChildren') {
138
+ bindingEvent.notify(targetNodeOrNodeArray as Node, bindingEvent.childrenComplete);
139
+ }
140
+ }
141
+
142
+ return renderedNodesArray;
143
+ }
144
+
145
+ function resolveTemplateName(
146
+ template: unknown,
147
+ data: unknown,
148
+ context: BindingContext,
149
+ ): string | Node {
150
+ if (isReadableSubscribable(template)) {
151
+ return template.get() as string | Node;
152
+ } else if (typeof template === 'function') {
153
+ return (template as (data: unknown, context: BindingContext) => string | Node)(data, context);
154
+ } else {
155
+ return template as string | Node;
156
+ }
157
+ }
158
+
159
+ const templateComputedDomDataKey = domDataNextKey();
160
+
161
+ function disposeOldComputed(element: Node): void {
162
+ const oldComputed = domDataGet(element, templateComputedDomDataKey) as Computed<void> | undefined;
163
+ if (oldComputed && typeof oldComputed.dispose === 'function')
164
+ oldComputed.dispose();
165
+ }
166
+
167
+ function storeNewComputed(element: Node, newComputed: Computed<void> | { dispose(): void } | undefined): void {
168
+ domDataSet(element, templateComputedDomDataKey,
169
+ newComputed && (!('isActive' in newComputed) || (newComputed as Computed<void>).isActive()) ? newComputed : undefined);
170
+ }
171
+
172
+ export function renderTemplate(
173
+ template: unknown,
174
+ dataOrBindingContext: unknown,
175
+ options: TemplateRenderOptions,
176
+ targetNodeOrNodeArray: Node | Node[],
177
+ renderMode?: string,
178
+ ): Computed<void> {
179
+ options = options || {};
180
+ if ((options.templateEngine || getTemplateEngine()) == null)
181
+ throw new Error('Set a template engine before calling renderTemplate');
182
+ renderMode = renderMode || 'replaceChildren';
183
+
184
+ const firstTargetNode = getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
185
+ const whenToDispose = () => !firstTargetNode || !domNodeIsAttachedToDocument(firstTargetNode);
186
+ const activelyDisposeWhenNodeIsRemoved = (firstTargetNode && renderMode === 'replaceNode')
187
+ ? firstTargetNode.parentNode
188
+ : firstTargetNode;
189
+
190
+ let currentTargetNodeOrNodeArray = targetNodeOrNodeArray;
191
+
192
+ const computed = new Computed<void>(() => {
193
+ const bindingContext = (dataOrBindingContext instanceof BindingContext)
194
+ ? dataOrBindingContext
195
+ : new BindingContext(dataOrBindingContext, undefined, undefined, undefined, { exportDependencies: true });
196
+
197
+ const templateName = resolveTemplateName(template, bindingContext.$data, bindingContext);
198
+ const renderedNodesArray = executeTemplate(currentTargetNodeOrNodeArray, renderMode!, templateName, bindingContext, options);
199
+
200
+ if (renderMode === 'replaceNode') {
201
+ currentTargetNodeOrNodeArray = renderedNodesArray;
202
+ }
203
+ });
204
+
205
+ if (activelyDisposeWhenNodeIsRemoved) {
206
+ addDisposeCallback(activelyDisposeWhenNodeIsRemoved, () => computed.dispose());
207
+ }
208
+
209
+ // Also add a check to dispose when detached from DOM
210
+ const sub = computed.subscribe(() => {
211
+ if (whenToDispose()) {
212
+ computed.dispose();
213
+ sub.dispose();
214
+ }
215
+ });
216
+
217
+ return computed;
218
+ }
219
+
220
+ export function renderTemplateForEach(
221
+ template: unknown,
222
+ arrayOrObservableArray: unknown,
223
+ options: TemplateRenderOptions,
224
+ targetNode: Node,
225
+ parentBindingContext: BindingContext,
226
+ ): { dispose(): void } {
227
+ let arrayItemContext: BindingContext | null;
228
+ const asName = options.as;
229
+
230
+ const executeTemplateForArrayItem = (arrayValue: unknown, index: unknown) => {
231
+ arrayItemContext = parentBindingContext.createChildContext(arrayValue, {
232
+ as: asName,
233
+ noChildContext: options.noChildContext,
234
+ extend(context: BindingContext) {
235
+ context.$index = index;
236
+ if (asName) {
237
+ context[asName + 'Index'] = index;
238
+ }
239
+ },
240
+ });
241
+
242
+ const templateName = resolveTemplateName(template, arrayValue, arrayItemContext);
243
+ return executeTemplate(targetNode, 'ignoreTargetNode', templateName, arrayItemContext, options);
244
+ };
245
+
246
+ const activateBindingsCallback = (arrayValue: unknown, addedNodesArray: Node[]) => {
247
+ activateBindingsOnContinuousNodeArray(addedNodesArray, arrayItemContext!);
248
+ if (options.afterRender)
249
+ options.afterRender(addedNodesArray, arrayValue);
250
+ arrayItemContext = null;
251
+ };
252
+
253
+ const setDomNodeChildrenFromArrayMappingCb = (newArray: unknown[], changeList?: ArrayChange<unknown>[]) => {
254
+ ignore(() => setDomNodeChildrenFromArrayMapping(
255
+ targetNode, newArray, executeTemplateForArrayItem as never, options, activateBindingsCallback as never, changeList,
256
+ ));
257
+ bindingEvent.notify(targetNode, bindingEvent.childrenComplete);
258
+ };
259
+
260
+ const shouldHideDestroyed = (options.includeDestroyed === false);
261
+
262
+ if (!shouldHideDestroyed && !options.beforeRemove && isObservableArray(arrayOrObservableArray)) {
263
+ const observableArray = arrayOrObservableArray as ObservableArray<unknown>;
264
+ const queuedChangeLists: ArrayChange<unknown>[][] = [];
265
+ let isProcessing = false;
266
+
267
+ function processArrayChange(changeList?: ArrayChange<unknown>[]): void {
268
+ if (changeList) queuedChangeLists.push(changeList);
269
+ if (isProcessing) return;
270
+ isProcessing = true;
271
+ try {
272
+ if (queuedChangeLists.length === 0) {
273
+ setDomNodeChildrenFromArrayMappingCb(observableArray.peek());
274
+ } else {
275
+ while (queuedChangeLists.length) {
276
+ const cl = queuedChangeLists.shift()!;
277
+ try {
278
+ setDomNodeChildrenFromArrayMappingCb(observableArray.peek(), cl);
279
+ } catch (e) {
280
+ // allow processing to continue
281
+ if (queuedChangeLists.length === 0) throw e;
282
+ }
283
+ }
284
+ }
285
+ } finally {
286
+ isProcessing = false;
287
+ }
288
+ }
289
+
290
+ const subscription = observableArray.subscribe(
291
+ processArrayChange as (value: unknown) => void,
292
+ 'arrayChange',
293
+ );
294
+ addDisposeCallback(targetNode, () => subscription.dispose());
295
+
296
+ processArrayChange();
297
+ return subscription;
298
+ } else {
299
+ const computed = new Computed<void>(() => {
300
+ let unwrappedArray = unwrapObservable(arrayOrObservableArray) as unknown[] || [];
301
+ if (!Array.isArray(unwrappedArray)) {
302
+ unwrappedArray = [unwrappedArray];
303
+ }
304
+
305
+ if (shouldHideDestroyed) {
306
+ unwrappedArray = (unwrappedArray as Record<string, unknown>[]).filter(
307
+ item => item === undefined || item === null || !unwrapObservable(item._destroy),
308
+ );
309
+ }
310
+ setDomNodeChildrenFromArrayMappingCb(unwrappedArray);
311
+ });
312
+
313
+ addDisposeCallback(targetNode, () => computed.dispose());
314
+ return computed;
315
+ }
316
+ }
317
+
318
+ // ---- template binding handler ----
319
+
320
+ const cleanContainerDomDataKey = domDataNextKey();
321
+
322
+ const templateHandler: BindingHandler = {
323
+ init(element, valueAccessor) {
324
+ const bindingValue = unwrapObservable(valueAccessor());
325
+ if (typeof bindingValue === 'string' || (bindingValue && typeof bindingValue === 'object' && 'name' in (bindingValue as Record<string, unknown>))) {
326
+ virtualEmptyNode(element);
327
+ } else if (bindingValue && typeof bindingValue === 'object' && 'nodes' in (bindingValue as Record<string, unknown>)) {
328
+ const nodes = (bindingValue as Record<string, unknown>).nodes as Node[] || [];
329
+ if (isReadableSubscribable(nodes)) {
330
+ throw new Error('The "nodes" option must be a plain, non-observable array.');
331
+ }
332
+
333
+ let container = nodes[0]?.parentNode as HTMLElement | undefined;
334
+ if (!container || !domDataGet(container, cleanContainerDomDataKey)) {
335
+ container = moveCleanedNodesToContainerElement(nodes);
336
+ domDataSet(container, cleanContainerDomDataKey, true);
337
+ }
338
+
339
+ new AnonymousSource(element as Element).nodes(container);
340
+ } else {
341
+ const templateNodes = virtualChildNodes(element);
342
+ if (templateNodes.length > 0) {
343
+ const container = moveCleanedNodesToContainerElement(templateNodes);
344
+ new AnonymousSource(element as Element).nodes(container);
345
+ } else {
346
+ throw new Error('Anonymous template defined, but no template content was provided');
347
+ }
348
+ }
349
+ return { controlsDescendantBindings: true };
350
+ },
351
+
352
+ update(element, valueAccessor, allBindings, viewModel, bindingContext) {
353
+ const value = valueAccessor();
354
+ let options = unwrapObservable(value) as TemplateRenderOptions & Record<string, unknown>;
355
+ let shouldDisplay = true;
356
+ let templateComputed: { dispose(): void } | undefined;
357
+ let template: unknown;
358
+
359
+ if (typeof options === 'string') {
360
+ template = value;
361
+ options = {};
362
+ } else {
363
+ template = 'name' in options ? unwrapObservable(options.name) : element;
364
+
365
+ if ('if' in options)
366
+ shouldDisplay = !!unwrapObservable(options['if']);
367
+ if (shouldDisplay && 'ifnot' in options)
368
+ shouldDisplay = !unwrapObservable(options.ifnot);
369
+ }
370
+
371
+ if (shouldDisplay && !template) {
372
+ shouldDisplay = false;
373
+ }
374
+
375
+ disposeOldComputed(element);
376
+
377
+ if ('foreach' in options) {
378
+ const dataArray = (shouldDisplay && options.foreach) || [];
379
+ templateComputed = renderTemplateForEach(template, dataArray, options, element, bindingContext!);
380
+ } else if (!shouldDisplay) {
381
+ virtualEmptyNode(element);
382
+ } else {
383
+ let innerBindingContext = bindingContext!;
384
+ if ('data' in options) {
385
+ innerBindingContext = bindingContext!.createChildContext(options.data, {
386
+ as: options.as,
387
+ noChildContext: options.noChildContext,
388
+ exportDependencies: true,
389
+ });
390
+ }
391
+ templateComputed = renderTemplate(template, innerBindingContext, options, element);
392
+ }
393
+
394
+ storeNewComputed(element, templateComputed as Computed<void> | undefined);
395
+ },
396
+ };
397
+
398
+ bindingHandlers['template'] = templateHandler;
399
+ allowedVirtualElementBindings['template'] = true;