-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib_core_runtime_AvenxComponent.js.html
More file actions
1971 lines (1706 loc) · 72.6 KB
/
Copy pathlib_core_runtime_AvenxComponent.js.html
File metadata and controls
1971 lines (1706 loc) · 72.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JSDoc: Source: lib/core/runtime/AvenxComponent.js</title>
<script src="scripts/prettify/prettify.js"> </script>
<script src="scripts/prettify/lang-css.js"> </script>
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
<link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css">
</head>
<body>
<div id="main">
<h1 class="page-title">Source: lib/core/runtime/AvenxComponent.js</h1>
<section>
<article>
<pre class="prettyprint source linenums"><code>import { ComputedRegistry } from '../reactive/createComputed.js';
import { styleMountManager } from './StyleMountManager.js';
import { TemplateRenderer } from '../renderer/renderTemplate.js';
import { DomPatcher } from '../renderer/domPatch.js';
import { EventBinder } from '../events/bindEvents.js';
import { EventExecutor } from '../events/eventExecutor.js';
import { DynamicEvaluator } from '../security/evaluator.js';
import { LifecycleManager } from './lifecycle.js';
import { ListManager } from '../renderer/listManager.js';
import { DeferManager } from '../renderer/deferManager.js';
import { AvenxError, AvenxErrorCodes, formatMessage } from './AvenxError.js';
import { logger } from './AvenxLogger.js';
import { queueJob, nextTick as schedulerNextTick } from '../reactive/scheduler.js';
import { AvenxSandbox } from '../security/sandbox.js';
import { AvenxWatcher } from '../reactive/watcher.js';
import { Resource } from '../reactive/Resource.js';
import { ProxyHandlerFactory, RAW_SYMBOL } from '../reactive/proxyHandler.js';
import { processBindDirectives } from '../utils/templateUtils.js';
import { profile } from '../utils/profiler.js';
import { parseValidationRules, validateValue, getFieldName, updateValidationState } from '../validation/validator.js';
export const RESERVED_INSTANCE_KEYS = [
'mount',
'unmount',
'update',
'destroy',
'scheduleUpdate',
'onBeforeMount',
'onMount',
'onBeforeUpdate',
'onUpdate',
'onUnmount',
'onActivate',
'onDeactivate',
'onErrorCaptured',
];
const globalMixins = [];
let componentUid = 0;
/**
* Base class for all Avenx components.
* Manages state, reactivity, rendering, and lifecycle.
*/
export class AvenxComponent {
/** @type {Element|null} */
#element = null;
/** @type {string} */
#template = '';
/** @type {object} */
#methods = {};
/** @type {object} */
#bridges = {};
/** @type {ComputedRegistry} */
#computed;
/** @type {TemplateRenderer} */
#renderer;
/** @type {DomPatcher} */
#patcher;
/** @type {ListManager} */
#listManager;
/** @type {DeferManager} */
#deferManager;
/** @type {EventBinder} */
#eventBinder;
/** @type {EventExecutor} */
#eventExecutor;
/** @type {DynamicEvaluator} */
#evaluator;
/** @type {LifecycleManager} */
#lifecycle;
/** @type {boolean} */
#isMounted = false;
/** @type {boolean} */
#isUpdating = false;
/** @type {Set<string>} */
#evaluating = new Set();
/** @type {object | null} */
#transcludedGroups = null;
/** @type {boolean} */
#updateQueued = false;
/** @type {Function} */
#updateJob = () => {
this.#updateQueued = false;
this.update();
};
/** @type {boolean} */
#isUnmounting = false;
/** @type {Promise<void>|null} */
#unmountPromise = null;
/** @type {boolean} */
#isUnmounted = false;
/** @type {Record<string, Element>} */
#refsCache = {};
/** @type {boolean} */
#refsDirty = false;
/** @type {boolean} */
#isBeforeMounting = false;
/** @type {Object<string, object>} */
#resources = {};
/** @type {Error|null} */
#componentError = null;
/**
* @param {object} [initialState] - The initial state of the component.
* @param {object} [computed] - Computed properties definitions.
* @param {object} [bridges] - External bridges accessible to the component.
* @param {string} [template] - The HTML template string.
* @param {object} [methods] - Component methods.
* @param {object} [props] - Component properties.
* @param {object} [styles] - Component CSS variables.
* @param {object} [resources] - Reactive resources.
*/
constructor(initialState = {}, computed = {}, bridges = {}, template = '', methods = {}, props = {}, styles = {}, resources = {}) {
this.uid = componentUid++;
this.#updateJob.id = this.uid;
/** @type {AvenxComponent|null} */
this.$parent = null;
// Merge global mixins options
const mergedState = {};
const mergedComputed = {};
const mergedMethods = {};
const mergedProps = {};
const mergedStyles = {};
for (const mixin of globalMixins) {
const mixinState = typeof mixin.state === 'function' ? mixin.state.call(this) : mixin.state;
if (mixinState && typeof mixinState === 'object') {
Object.assign(mergedState, mixinState);
}
const mixinData = typeof mixin.data === 'function' ? mixin.data.call(this) : mixin.data;
if (mixinData && typeof mixinData === 'object') {
Object.assign(mergedState, mixinData);
}
if (mixin.computed && typeof mixin.computed === 'object') {
Object.assign(mergedComputed, mixin.computed);
}
if (mixin.methods && typeof mixin.methods === 'object') {
Object.assign(mergedMethods, mixin.methods);
}
if (mixin.props && typeof mixin.props === 'object') {
Object.assign(mergedProps, mixin.props);
}
if (mixin.styles && typeof mixin.styles === 'object') {
Object.assign(mergedStyles, mixin.styles);
}
}
Object.assign(mergedState, initialState);
Object.assign(mergedComputed, computed);
Object.assign(mergedMethods, methods);
Object.assign(mergedProps, props);
Object.assign(mergedStyles, styles);
this._mixinProps = {};
const reservedKeys = ['state', 'data', 'methods', 'computed', 'props', 'styles', 'onBeforeMount', 'onMount', 'onBeforeUpdate', 'onUpdate', 'onUnmount', 'onActivate', 'onDeactivate', 'onErrorCaptured'];
for (const mixin of globalMixins) {
for (const key of Object.keys(mixin)) {
if (!reservedKeys.includes(key)) {
let value = mixin[key];
if (typeof value === 'function') {
value = value.bind(this);
}
if (!(key in this)) {
this[key] = value;
}
this._mixinProps[key] = value;
}
}
}
this.#template = processBindDirectives(template);
this.#bridges = bridges;
this.#computed = new ComputedRegistry(mergedComputed);
this.#renderer = new TemplateRenderer();
this.#patcher = new DomPatcher();
this.#eventBinder = new EventBinder();
this.#evaluator = new DynamicEvaluator();
this.#lifecycle = new LifecycleManager();
this.#listManager = new ListManager(this.#evaluator, this.#renderer, this.#eventBinder, this.constructor.name);
this.#deferManager = new DeferManager(this.#evaluator, this.#renderer, this.#eventBinder, this.constructor.name);
/** @type {AvenxWatcher[]} */
this._watchers = [];
this._stateHandler = new ProxyHandlerFactory({
computedKeys: this.#computed.keys(),
onChange: () => this.scheduleUpdate(),
instance: this,
getComputedValue: (key) => {
if (this.#evaluating.has(key)) {
logger.warn(formatMessage(AvenxErrorCodes.COMPUTED_CIRCULAR_DEPENDENCY, key), this.$logContext);
return undefined;
}
this.#evaluating.add(key);
const definition = this.#computed.get(key);
try {
if (typeof definition === 'function') {
return definition.call(this);
}
return this.#evaluator.evaluateExpression(
definition,
this.#createScope(),
this.state
);
} catch (error) {
if (error && error.code === AvenxErrorCodes.STATE_MUTATION_IN_UPDATE) {
throw error;
}
logger.warn(formatMessage(AvenxErrorCodes.COMPUTED_EVALUTION_FAILED, key, definition, error), this.$logContext);
return undefined;
} finally {
this.#evaluating.delete(key);
}
},
});
this.state = new Proxy(mergedState, this._stateHandler.create());
this._propsHandler = new ProxyHandlerFactory({
onChange: () => this.scheduleUpdate(),
});
this.props = new Proxy(mergedProps, this._propsHandler.create());
this._stylesHandler = new ProxyHandlerFactory({
onChange: () => this.scheduleUpdate(),
});
this.styles = new Proxy(mergedStyles, this._stylesHandler.create());
this.#methods = this.#evaluator.createMethodMap(
mergedMethods,
(executableMethods) => this.#createScope(executableMethods),
() => this.state,
);
for (const [name, fn] of Object.entries(this.#methods)) {
if (RESERVED_INSTANCE_KEYS.includes(name)) {
logger.warn(
formatMessage(
AvenxErrorCodes.COMPONENT_METHOD_RESERVED_KEY_COLLISION,
name,
this.constructor && this.constructor.name !== 'AvenxComponent' && this.constructor.name !== 'Object'
? this.constructor.name
: 'Component'
),
this.$logContext
);
}
if (!(name in this)) {
this[name] = fn;
}
}
const activeResources = typeof resources === 'object' && resources !== null ? resources : {};
for (const [name, resDef] of Object.entries(activeResources)) {
const handler = typeof resDef === 'object' && resDef !== null ? resDef.handler : resDef;
const pollInterval = typeof resDef === 'object' && resDef !== null ? resDef.pollInterval : 0;
let handlerFn = typeof handler === 'function' ? handler : null;
if (!handlerFn) {
const cleanHandler = typeof handler === 'string' && handler.trim().startsWith('return') ? handler : `return ${handler}`;
handlerFn = this.#evaluator.createMethodMap(
{ [name]: cleanHandler },
() => ({
...this.#createScope(),
setTimeout: typeof setTimeout !== 'undefined' ? setTimeout : undefined,
clearTimeout: typeof clearTimeout !== 'undefined' ? clearTimeout : undefined,
setInterval: typeof setInterval !== 'undefined' ? setInterval : undefined,
clearInterval: typeof clearInterval !== 'undefined' ? clearInterval : undefined,
fetch: typeof fetch !== 'undefined' ? fetch : undefined,
Promise: typeof Promise !== 'undefined' ? Promise : undefined,
}),
() => this.state
)[name];
}
this.#resources[name] = new Resource(name, handlerFn, this, { pollInterval });
Object.defineProperty(this, name, {
get: () => this.#resources[name].read(),
enumerable: true,
configurable: true
});
}
// Process declarative watch options from mixins and initialState options
const mergedWatch = {};
for (const mixin of globalMixins) {
if (mixin.watch && typeof mixin.watch === 'object') {
Object.assign(mergedWatch, mixin.watch);
}
}
const optionWatch =
initialState && typeof initialState === 'object' && initialState.watch && typeof initialState.watch === 'object'
? initialState.watch
: null;
if (optionWatch) {
Object.assign(mergedWatch, optionWatch);
}
for (const [key, handler] of Object.entries(mergedWatch)) {
if (typeof handler === 'function') {
this.$watch(key, handler);
} else if (typeof handler === 'object' && handler !== null && typeof handler.handler === 'function') {
const { handler: fn, ...watchOpts } = handler;
this.$watch(key, fn, watchOpts);
} else if (typeof handler === 'string' && typeof this[handler] === 'function') {
this.$watch(key, this[handler]);
}
}
/** @type {boolean} */
this._isFirstRender = true;
this.#eventExecutor = new EventExecutor((source, event, slotScope) => this.#runEventHandler(source, event, slotScope));
this.#eventExecutor.validate = (el) => this.$validateElement(el);
if (typeof process !== 'undefined' && process.env && process.env.NODE_ENV !== 'production') {
let initialized = false;
const originalProto = Object.getPrototypeOf(this);
const protoProxy = new Proxy(originalProto, {
getPrototypeOf(target) {
return target;
},
set(target, key, value, receiver) {
if (initialized && typeof key === 'string' && !key.startsWith('$') && !key.startsWith('_') && key !== 'renderWatcher') {
const hasKey = (key in receiver);
if (!hasKey) {
const compName = receiver.constructor?.name || 'Component';
console.warn(
`[Avenx Warning] Direct assignment to "this.${key} = ${value}" on component <${compName}> is non-reactive and will not trigger DOM updates. Declare "${key}" in <state> instead.`
);
}
}
return Reflect.set(target, key, value, receiver);
}
});
Object.setPrototypeOf(this, protoProxy);
Promise.resolve().then(() => {
initialized = true;
});
}
}
/**
* Evaluates validation rules for an element and updates this.state.$validation.
* @param {Element} el - The element to validate.
* @returns {string[]} Validation errors for the field.
*/
$validateElement(el) {
if (!el || typeof el.getAttribute !== 'function' || !el.hasAttribute('data-ax-validate')) {
return [];
}
const ruleStr = el.getAttribute('data-ax-validate');
const rules = parseValidationRules(ruleStr);
const fieldName = getFieldName(el);
let value = el.value;
if (el.type === 'checkbox') {
value = el.checked;
}
let customMessages = {};
if (el.hasAttribute('data-ax-validate-messages')) {
try {
customMessages = JSON.parse(el.getAttribute('data-ax-validate-messages'));
} catch {
// Ignored
}
}
const errors = validateValue(value, rules, { state: this.state, customMessages });
updateValidationState(this.state, fieldName, errors);
return errors;
}
/**
* Programmatically registers a watcher on a reactive expression/function.
* @param {Function} getter - Evaluation function returning the value to watch.
* @param {Function} callback - Triggered when the value changes.
* @param {object} [options] - Config options.
* @returns {AvenxWatcher}
*/
watch(getter, callback, options = {}) {
const watcher = new AvenxWatcher(getter, callback, options);
if (this.#isUnmounted) {
watcher.teardown();
return watcher;
}
this._watchers.push(watcher);
return watcher;
}
/**
* Returns component context metadata for diagnostic logging.
* @returns {{ componentName: string, fileName: string|null, component: AvenxComponent }}
*/
get $logContext() {
return {
componentName: this.constructor && this.constructor.name !== 'AvenxComponent' && this.constructor.name !== 'Object' ? this.constructor.name : (this.name || 'Component'),
fileName: this.__filename || (this.options && this.options.__filename) || null,
component: this,
};
}
/**
* Getter for the component's root element.
* @returns {Element|null}
*/
get $element() {
return this.#element;
}
/**
* Getter for component reference elements marked with data-ax-ref.
* Lazily resolves references if marked dirty.
* @returns {Record<string, Element>}
*/
get $refs() {
if (this.#refsDirty) {
this.#collectRefs();
}
return this.#refsCache;
}
/**
* Slot helpers for checking whether the parent provided content for a slot.
* Available after mount target setup populates `#transcludedGroups`.
* @returns {object}
*/
get $slots() {
const groups = this.#transcludedGroups;
return {
/**
* @param {string} [slotName] Named slot, or `default` / empty for the default slot.
* @returns {boolean}
*/
has(slotName = 'default') {
if (!groups) return false;
const name = !slotName || slotName === 'default' ? null : slotName;
if (!name) {
return Array.isArray(groups.default) && groups.default.length > 0;
}
const nodes = groups.named?.[name];
return Array.isArray(nodes) && nodes.length > 0;
},
};
}
/**
* KeepAlive invalidation API for clearing cached components.
* @returns {object}
*/
get $keepAlive() {
return {
clear: (componentName) => {
if (this.$app && typeof this.$app.clearKeepAliveCache === 'function') {
return this.$app.clearKeepAliveCache(componentName);
}
return false;
},
};
}
/**
* Helper method to clear cached KeepAlive component instances.
* @param {string} [pageName] - Optional component or page name to clear from cache.
* @returns {boolean} True if cache entries were evicted, false otherwise.
*/
clearKeepAliveCache(pageName) {
if (this.$app && typeof this.$app.clearKeepAliveCache === 'function') {
return this.$app.clearKeepAliveCache(pageName);
}
return false;
}
/**
* Emits a custom event up to parent components with unified bubble options.
* @param {string} eventName - Name of the event to emit.
* @param {object} [detail] - Event details payload.
* @param {object} [options] - Optional custom event options.
*/
emit(eventName, detail = {}, options = {}) {
const event = new CustomEvent(eventName, {
detail,
bubbles: options.bubbles !== undefined ? options.bubbles : true,
cancelable: options.cancelable !== undefined ? options.cancelable : true,
...options
});
if (this.$element) {
this.$element.dispatchEvent(event);
}
}
/**
* Emits a custom event to the parent component.
* @param {string} eventName - Name of the event to emit.
* @param {object} [detail] - Event details.
*/
$emit(eventName, detail = {}) {
this.emit(eventName, detail, { composed: true });
}
/**
* Reactively listens to changes in specific state values or getters.
* @param {string|Function|Array<string|Function>} source - State property key string, getter function, or array of sources.
* @param {Function} callback - Triggered when the value changes.
* @param {object} [options] - Config options.
* @param {boolean} [options.immediate] - Run callback immediately on watcher creation.
* @param {boolean} [options.deep] - Deeply watch nested properties.
* @returns {AvenxWatcher}
*/
$watch(source, callback, options = {}) {
const resolveSource = (src) => {
if (typeof src === 'string') {
return () => {
const segments = src.split('.');
let val = this.state;
for (const seg of segments) {
if (val === null || val === undefined) return undefined;
val = val[seg];
}
return val;
};
} else if (typeof src === 'function') {
return () => src.call(this);
} else {
throw new Error('source element must be a string or a function');
}
};
let getter;
if (Array.isArray(source)) {
getter = source.map((src) => resolveSource(src));
} else if (typeof source === 'string' || typeof source === 'function') {
getter = resolveSource(source);
} else {
throw new Error('source must be a string, function, or array of sources');
}
const watcher = new AvenxWatcher(getter, callback, options);
if (this.#isUnmounted) {
watcher.teardown();
return watcher;
}
this._watchers.push(watcher);
return watcher;
}
/**
* Creates a scope object for expression evaluation.
* @param {object} [methods] - Methods to include in the scope.
* @param {object} [extras] - Additional variables to include.
* @returns {object} The combined scope.
* @private
*/
#createScope(methods = this.#methods, extras = {}) {
const injected = {};
const injectOption =
this.inject ||
(typeof this.constructor.inject === 'function' ? this.constructor.inject() : this.constructor.inject);
if (injectOption) {
const resolvedOption = typeof injectOption === 'function' ? injectOption.call(this) : injectOption;
let keys = [];
if (Array.isArray(resolvedOption)) {
keys = resolvedOption;
} else if (resolvedOption && typeof resolvedOption === 'object') {
keys = Object.keys(resolvedOption);
}
for (const key of keys) {
if (key in this) {
injected[key] = this[key];
}
}
}
const scope = {
state: this.state,
...this._mixinProps,
...this.state,
...methods,
...this.#bridges,
props: this.props,
styles: this.styles,
$route: this.$route,
$emit: (eventName, detail) => this.$emit(eventName, detail),
$watch: (source, callback, options) => this.$watch(source, callback, options),
$nextTick: (callback) => this.$nextTick(callback),
...injected,
...extras,
};
if (this.#resources) {
for (const key of Object.keys(this.#resources)) {
if (!(key in scope)) {
Object.defineProperty(scope, key, {
get: () => this.#resources[key].read(),
enumerable: true,
configurable: true,
});
}
}
}
return scope;
}
/**
* Resolves an expression within the template.
* @param {string} expression - The expression to evaluate.
* @param {object} [extraScope] - Additional scope variables.
* @returns {any} The result of the evaluation.
* @private
*/
#resolveTemplateExpression(expression, extraScope = {}) {
return this.#evaluator.evaluateExpression(expression, this.#createScope(this.#methods, extraScope), this.state);
}
/**
* Runs an event handler.
* @param {string | Function} compiledFnOrSource - The source code of the handler or its compiled function.
* @param {Event} event - The event object.
* @param {object|null} [slotScope] - Optional slot scope variables.
* @returns {any} The result of the execution.
* @private
*/
#runEventHandler(compiledFnOrSource, event, slotScope = null) {
try {
if (typeof compiledFnOrSource === 'function') {
const scope = this.#createScope(this.#methods, { event, ...slotScope });
const sandbox = AvenxSandbox.createProxy(scope, this.state, true);
const args = scope.args || [];
return compiledFnOrSource(sandbox, this.#methods, event, args);
}
return this.#evaluator.executeStatement(compiledFnOrSource, this.#createScope(this.#methods, { event, ...slotScope }), this.state);
} catch (error) {
const sourceStr = typeof compiledFnOrSource === 'function' ? (compiledFnOrSource.source || compiledFnOrSource.toString()) : compiledFnOrSource;
logger.error(formatMessage(AvenxErrorCodes.EVENT_HANDLER_ERROR, sourceStr, error), this.$logContext);
this.#reportError(error, sourceStr);
return undefined;
}
}
/**
* Renders the component template with current state.
* @returns {string} The rendered HTML string.
*/
render() {
const enableProfiling = !!(this.$app?.enableProfiling || (typeof window !== 'undefined' && window.__avenx_enable_profiling));
return profile(enableProfiling, this.constructor.name, 'render', () => {
return this.#renderer.render(this.#template, (expression) => this.#resolveTemplateExpression(expression));
});
}
/**
* Triggers a synchronous DOM patch update and registers event/list bindings.
*/
update() {
if (!this.renderWatcher) {
this.renderWatcher = new AvenxWatcher(
() => this.runUpdate(),
() => this.scheduleUpdate(),
{ lazy: true, name: `${this.constructor.name}#render` },
);
}
this.renderWatcher.evaluate();
}
/**
* Performs the actual update/render of the component.
*/
runUpdate() {
if (!this.#element) return;
if (this.#componentError) {
this.#handleComponentError(this.#componentError);
return;
}
this.#isUpdating = true;
try {
if (this.#isMounted) {
this.#triggerLifecycle('onBeforeUpdate');
}
this.__updateProvidedState();
this.#patcher.patch(this.#element, this.render(), (expression, slotScope) => this.#resolveTemplateExpression(expression, slotScope), this.$app);
// Fill slots with transcluded content.
this.#fillSlots();
this.#listManager.process(this.#element, this.#createScope(), this.state, this.$app);
this.#deferManager.process(this.#element, this.#createScope(), this.state, this.$app);
this.#eventBinder.bind(this.#element, this.#eventExecutor);
this.#refsDirty = true;
this.#syncSelectElements();
if (this.#isMounted && this.#element?.dispatchEvent) {
this.#element.dispatchEvent(new CustomEvent('avenx:update'));
}
if (this.#isMounted) {
this.#resolveRefs();
this.#triggerLifecycle('onUpdate');
}
this.__notifyInjectingChildren();
} catch (error) {
if (error instanceof Promise) {
this.#suspend(error);
return;
}
if (error && error.code === AvenxErrorCodes.STATE_MUTATION_IN_UPDATE) {
throw error;
}
this.#handleComponentError(error);
} finally {
this.#isUpdating = false;
this.#validateFormElements();
}
}
/**
* Validates all form input elements in the component that have data-ax-validate.
* @private
*/
#validateFormElements() {
if (!this.$element || typeof this.$element.querySelectorAll !== 'function') return;
const elements = Array.from(this.$element.querySelectorAll('[data-ax-validate]'));
if (this.$element.hasAttribute && this.$element.hasAttribute('data-ax-validate')) {
elements.unshift(this.$element);
}
for (const el of elements) {
this.$validateElement(el);
}
}
/**
* Executes a callback (or resolves a Promise) after the current reactive
* update cycle has finished flushing pending DOM updates.
* @param {Function} [callback] - Optional callback to run after the flush.
* @returns {Promise<void>|void} A promise resolving after the flush, if no callback was given.
*/
$nextTick(callback) {
return schedulerNextTick(callback);
}
/**
* Alias for {@link AvenxComponent#$nextTick}.
* @param {Function} [callback] - Optional callback to run after the flush.
* @returns {Promise<void>|void}
*/
nextTick(callback) {
return this.$nextTick(callback);
}
/**
* Schedules an update to run asynchronously in a microtask.
*/
scheduleUpdate() {
if (this.#isUpdating) {
throw new AvenxError(AvenxErrorCodes.STATE_MUTATION_IN_UPDATE);
}
if (this.renderWatcher) {
this.renderWatcher.dirty = true;
}
if (this.#isBeforeMounting) {
return;
}
if (this.#updateQueued) return;
this.#updateQueued = true;
queueJob(this.#updateJob);
}
/**
* Internal method to set the mount target.
* @param {Element} target - The target element.
* @param {boolean} [isRestore] - Whether the component is being restored from keep-alive.
* @private
*/
__setMountTarget(target, isRestore = false) {
this.#element = target;
this.#isUnmounted = false;
if (target) {
target.__avenx_comp_instance = this;
this.__initProvide();
this.__initInjection();
if (isRestore) {
return;
}
const children = Array.from(target.childNodes);
this.#transcludedGroups = {
default: [],
named: {},
};
children.forEach((child) => {
if (child.nodeType === 1 && child.hasAttribute('slot')) {
const name = child.getAttribute('slot');
if (!this.#transcludedGroups.named[name]) {
this.#transcludedGroups.named[name] = [];
}
this.#transcludedGroups.named[name].push(child);
} else {
this.#transcludedGroups.default.push(child);
}
});
target.innerHTML = '';
}
}
/**
* Resolves the current name of a slot element.
* Dynamic slot names are evaluated during template rendering, so the
* rendered name attribute contains the value used for transclusion.
* @param {Element} slotEl - The slot element.
* @returns {string|null} The resolved slot name.
* @private
*/
#resolveSlotName(slotEl) {
const name = slotEl.getAttribute('name');
return name && name.trim() ? name.trim() : null;
}
/**
* Retrieves default children of a slot by parsing the rendered template.
* @param {string|null} name - The name of the slot.
* @returns {Node[]} Cloned child nodes.
* @private
*/
#getDefaultSlotChildren(name) {
try {
const parser = new DOMParser();
const doc = parser.parseFromString(this.render(), 'text/html');
const rootDoc = doc.body || doc;
const defaultSlot = Array.from(rootDoc.querySelectorAll('slot')).find((s) => {
const sName = this.#resolveSlotName(s);
return name ? sName === name : !sName;
});
if (defaultSlot) {
return Array.from(defaultSlot.childNodes).map((child) => child.cloneNode(true));
}
} catch (e) {
logger.warn(
formatMessage(AvenxErrorCodes.COMPONENT_RESTORE_SLOT_CONTENT_FAILED, e.message || e),
this.$logContext
);
}
return [];
}
/**
* Fills <slot> elements with transcluded child nodes.
* Supports both static and dynamically rendered slot names.
* @private
*/
#fillSlots() {
if (!this.#element || !this.#transcludedGroups) return;
const slots = this.#getOwnSlots();
slots.forEach((slotEl) => {
const name = this.#resolveSlotName(slotEl);
const nodes = name ? this.#transcludedGroups.named[name] || [] : this.#transcludedGroups.default || [];
const hasContent = nodes.some((node) => {
if (node.nodeType === 1 && node.nodeName !== '!--' && node.nodeName !== '#comment') return true;
if (node.nodeType === 3 && node.textContent.trim().length > 0) return true;
return false;
});
if (hasContent) {
slotEl.innerHTML = '';
const templateEl = nodes.find(
(node) => node.nodeType === 1 && node.tagName.toLowerCase() === 'template' && node.hasAttribute('data-slot-props')
);
if (templateEl) {
const renderedNodes = this.#renderScopedSlot(slotEl, templateEl);
renderedNodes.forEach((node) => {
slotEl.appendChild(node);
});
} else {
nodes.forEach((node) => {
slotEl.appendChild(node);
});
}
slotEl.setAttribute('data-avenx-transcluded', 'true');
} else {
slotEl.removeAttribute('data-avenx-transcluded');
slotEl.innerHTML = '';
this.#getDefaultSlotChildren(name).forEach((child) => {
slotEl.appendChild(child);
});
}
});
}
/**
* Retrieves slot elements belonging to this component.
* @returns {Element[]}
* @private
*/
#getOwnSlots() {
if (!this.#element) return [];
const slots = this.#element.querySelectorAll('slot');
const root = this.#element;
return Array.from(slots).filter((slot) => {
let parent = slot.parentNode;
while (parent && parent !== root) {
if (
parent.hasAttribute &&
(parent.hasAttribute('data-avenx-comp') || parent.hasAttribute('data-avenx-comp-dynamic'))