Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 | 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 19x 19x 19x 19x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 19x 19x 11x 11x 11x 11x 11x 11x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 23x 23x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 86x 86x 19x 19x 19x 19x 19x 19x 19x 19x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 1x 1x 2x 19x 19x 19x 19x 19x 19x 19x 19x 38x 38x 19x 19x 19x 19x 19x 19x 19x 19x 19x 2x 2x 2x 2x 19x 19x 19x 19x 19x 19x 43x 43x 19x 19x 42x 33x 33x 33x 33x 33x 42x 1x 1x 41x 41x 42x 41x 41x 41x 41x 41x 41x 41x 41x 42x 3x 3x 3x 3x 41x 42x 10x 10x 42x 19x 19x 19x 19x 19x 19x 32x 23x 23x 32x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 9x 1x 1x 1x 1x 1x 9x 8x 8x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 41x 41x 41x 5x 5x 5x 5x 5x 2x 5x 5x 3x 3x 3x 3x 8x 3x 3x 5x 2x 2x 41x 41x 19x 19x 19x 19x 19x 19x 19x 46x 46x 46x 46x 19x 19x 44x 9x 9x 35x 35x 10x 46x 46x 19x 19x 19x 19x 19x 19x 19x 5x 5x 5x 5x 5x 7x 1x 1x 1x 1x 1x 7x 6x 6x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 7x 5x 5x 5x 5x 5x 2x 5x 5x 5x 3x 5x 2x 2x 2x 2x 2x 2x 2x 3x 3x 2x 2x 2x 2x 2x 2x 2x 2x 5x 5x 5x 5x 5x 5x 19x 19x 19x 19x 19x 19x 16x 16x 16x 3x 3x 3x 3x 16x 16x 4x 4x 16x 19x 19x 19x 19x 19x 5x 5x 1x 1x 1x 1x 5x 5x 4x 4x 5x 5x 5x 5x 5x 5x 5x 19x 19x 19x 19x 19x 19x 5x 5x 5x 5x 2x 2x 2x 2x 2x 5x 5x 2x 2x 5x 19x 19x 19x 19x 19x 19x 19x 19x 19x 4x 4x 19x 19x 19x 19x 19x 19x 17x 17x 19x 19x 19x 19x 19x 19x 6x 6x 19x 19x 19x 19x 19x 19x 14x 14x 19x | import { ComputedRegistry } from '../reactive/createComputed.js';
import { StateFactory } from '../reactive/createState.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 { AvenxErrorCodes, formatMessage } from './AvenxError.js';
import { queueJob } from '../reactive/scheduler.js';
let currentMicrotaskPromise = null;
/**
* Processes data-ax-bind attributes on input, textarea, and select elements.
* Converts data-ax-bind="expr" to value="{{ expr }}" and event listener.
* @param {string} template - The template string.
* @returns {string} The processed template.
*/
function processBindDirectives(template) {
if (typeof template !== 'string') return template;
const tagRegex = /<(input|textarea|select)\b([^>]*?)>/gi;
return template.replace(tagRegex, (match, tagName, attrs) => {
const bindRegex = /\bdata-ax-bind\s*=\s*(?:"([^"]*)"|'([^']*)')/i;
const bindMatch = attrs.match(bindRegex);
if (!bindMatch) {
return match;
}
const bindExpr = (bindMatch[1] !== undefined ? bindMatch[1] : bindMatch[2]).trim();
let cleanAttrs = attrs.replace(bindRegex, '').trim();
let isSelfClosing = false;
if (cleanAttrs.endsWith('/')) {
isSelfClosing = true;
cleanAttrs = cleanAttrs.slice(0, -1).trim();
}
const eventName = tagName.toLowerCase() === 'select' ? 'change' : 'input';
const valueAttr = `value="{{ ${bindExpr} }}"`;
const eventAttr = `@${eventName}="${bindExpr} = event.target.value"`;
const suffix = isSelfClosing ? ' />' : '>';
return `<${tagName} ${cleanAttrs} ${valueAttr} ${eventAttr}`.trim().replace(/\s+/g, ' ') + suffix;
});
}
/**
* Base class for all Avenx components.
* Manages state, reactivity, rendering, and lifecycle.
*/
export class AvenxComponent {
/** @type {Element|null} @private */
#element = null;
/** @type {string} @private */
#template = '';
/** @type {Object} @private */
#methods = {};
/** @type {Object} @private */
#bridges = {};
/** @type {ComputedRegistry} @private */
#computed;
/** @type {TemplateRenderer} @private */
#renderer;
/** @type {DomPatcher} @private */
#patcher;
/** @type {ListManager} @private */
#listManager;
/** @type {EventBinder} @private */
#eventBinder;
/** @type {EventExecutor} @private */
#eventExecutor;
/** @type {DynamicEvaluator} @private */
#evaluator;
/** @type {LifecycleManager} @private */
#lifecycle;
/** @type {boolean} @private */
#isMounted = false;
/** @type {Set<string>} @private */
#evaluating = new Set();
/** @type {Object|null} @private */
#transcludedGroups = null;
/** @type {boolean} @private */
#updateQueued = false;
/** @type {Function} @private */
#updateJob = () => {
this.#updateQueued = false;
this.update();
};
/** @type {Promise|null} @private */
#lastUpdatedPromise = 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.
*/
constructor(initialState = {}, computed = {}, bridges = {}, template = '', methods = {}, props = {}) {
this.#template = processBindDirectives(template);
this.#bridges = bridges;
this.#computed = new ComputedRegistry(computed);
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);
/**
* The reactive state of the component.
* @type {Proxy}
*/
this.state = new StateFactory().create(initialState, {
computedKeys: this.#computed.keys(),
onChange: () => this.scheduleUpdate(),
getComputedValue: key => this.#evaluateComputed(key)
});
/**
* The reactive props of the component.
* @type {Proxy}
*/
this.props = new StateFactory().create(props, {
onChange: () => this.scheduleUpdate()
});
this.#methods = this.#evaluator.createMethodMap(
methods,
executableMethods => this.#createScope(executableMethods),
() => this.state
);
this.#eventExecutor = new EventExecutor((source, event) => this.#runEventHandler(source, event));
}
/**
* Creates a scope object for expression evaluation.
* @param {Object} [methods=this.#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 = {}) {
return { ...this.state, ...methods, ...this.#bridges, props: this.props, ...extras };
}
/**
* Evaluates a computed property.
* @param {string} key - The key of the computed property.
* @returns {any} The evaluated value.
* @private
*/
#evaluateComputed(key) {
if (this.#evaluating.has(key)) {
console.warn(formatMessage(AvenxErrorCodes.COMPUTED_CIRCULAR_DEPENDENCY, key));
return undefined;
}
this.#evaluating.add(key);
const expression = this.#computed.get(key);
try {
return this.#evaluator.evaluateExpression(expression, this.#createScope(), this.state);
} catch (error) {
console.warn(formatMessage(AvenxErrorCodes.COMPUTED_EVALUTION_FAILED, key, expression, error));
return undefined;
} finally {
this.#evaluating.delete(key);
}
}
/**
* Resolves an expression within the template.
* @param {string} expression - The expression to evaluate.
* @returns {any} The result of the evaluation.
* @private
*/
#resolveTemplateExpression(expression) {
return this.#evaluator.evaluateExpression(expression, this.#createScope(), this.state);
}
/**
* Runs an event handler.
* @param {string} source - The source code of the handler.
* @param {Event} event - The event object.
* @returns {any} The result of the execution.
* @private
*/
#runEventHandler(source, event) {
try {
return this.#evaluator.executeStatement(source, this.#createScope(this.#methods, { event }), this.state);
} catch (error) {
console.error(formatMessage(AvenxErrorCodes.EVENT_HANDLER_ERROR, source, error));
return undefined;
}
}
/**
* Renders the component template with current state.
* @returns {string} The rendered HTML string.
*/
render() {
return this.#renderer.render(this.#template, expression => this.#resolveTemplateExpression(expression));
}
update() {
if (!currentMicrotaskPromise) {
currentMicrotaskPromise = Promise.resolve();
Promise.resolve().then(() => {
currentMicrotaskPromise = null;
});
}
if (this.#lastUpdatedPromise === currentMicrotaskPromise) {
return;
}
this.#lastUpdatedPromise = currentMicrotaskPromise;
if (!this.#element) return;
this.#patcher.patch(this.#element, this.render());
// Fill slots with transcluded content
this.#fillSlots();
this.#listManager.process(this.#element, this.#createScope(), this.state);
this.#eventBinder.bind(this.#element, this.#eventExecutor);
if (this.#isMounted && this.#element?.dispatchEvent) {
this.#element.dispatchEvent(
new CustomEvent('avenx:update')
);
}
if (this.#isMounted && this.#methods.onUpdate) {
this.#methods.onUpdate();
}
}
/**
* Schedules an update to run asynchronously in a microtask.
* Deduplicates multiple calls to schedule.
*/
scheduleUpdate() {
if (this.#updateQueued) return;
this.#updateQueued = true;
queueJob(this.#updateJob);
}
/**
* Internal method to set the mount target.
* @param {Element} target - The target element.
* @private
*/
__setMountTarget(target) {
this.#element = target;
if (target) {
target.__avenx_comp_instance = this;
// Extract transcluded children
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);
}
});
// Clear the mount target's inner content
target.innerHTML = '';
}
}
/**
* Fills <slot> elements with transcluded child nodes.
* @private
*/
#fillSlots() {
if (!this.#element || !this.#transcludedGroups) return;
const slots = this.#getOwnSlots();
slots.forEach(slotEl => {
const name = slotEl.getAttribute('name');
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) {
// Clear default content of the slot
slotEl.innerHTML = '';
// Append the nodes
nodes.forEach(node => {
slotEl.appendChild(node);
});
slotEl.setAttribute('data-avenx-transcluded', 'true');
} else {
slotEl.removeAttribute('data-avenx-transcluded');
}
});
}
/**
* Retrieves slot elements belonging to this component (not nested inside child components).
* @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')) {
return false;
}
parent = parent.parentNode;
}
return true;
});
}
/**
* Updates the transcluded content when the parent template updates.
* @param {NodeList|Array} virtualChildNodes - The new virtual transcluded nodes from parent.
* @private
*/
__updateTranscludedContent(virtualChildNodes) {
const grouped = {
default: [],
named: {}
};
Array.from(virtualChildNodes || []).forEach(node => {
if (node.nodeType === 1 && node.hasAttribute('slot')) {
const name = node.getAttribute('slot');
if (!grouped.named[name]) {
grouped.named[name] = [];
}
grouped.named[name].push(node);
} else {
grouped.default.push(node);
}
});
this.#transcludedGroups = grouped;
// Patch the slots in the DOM recursively with new virtual transcluded children
if (this.#element) {
const slots = this.#getOwnSlots();
slots.forEach(slotEl => {
const name = slotEl.getAttribute('name');
const newChildren = name ? (grouped.named[name] || []) : (grouped.default || []);
const newSlotWrapper = slotEl.cloneNode(false);
newChildren.forEach(child => {
newSlotWrapper.appendChild(child.cloneNode(true));
});
const hasContent = newChildren.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) {
newSlotWrapper.setAttribute('data-avenx-transcluded', 'true');
} else {
newSlotWrapper.removeAttribute('data-avenx-transcluded');
// Restore default content from the template
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 = s.getAttribute('name');
return name ? (sName === name) : !sName;
});
if (defaultSlot) {
Array.from(defaultSlot.childNodes).forEach(child => {
newSlotWrapper.appendChild(child.cloneNode(true));
});
}
} catch (e) {
console.warn('[AvenxComponent] Failed to restore default slot content', e);
}
}
// Patch the slot element in-place
this.#patcher.patchElement(slotEl, newSlotWrapper);
});
}
}
/**
* Internal method called after the component is mounted to the DOM.
* @private
*/
__afterMount() {
this.#isMounted = true;
if (this.#element?.dispatchEvent) {
this.#element.dispatchEvent(
new CustomEvent('avenx:mount')
);
}
if (this.#methods.onMount) {
this.#methods.onMount();
}
}
/**
* Unmounts the component and triggers cleanup.
*/
unmount() {
this.#eventBinder.unbind(this.#element);
if (this.#element?.dispatchEvent) {
this.#element.dispatchEvent(
new CustomEvent('avenx:unmount')
);
}
if (this.#methods.onUnmount) {
this.#methods.onUnmount();
}
if (this.#element) {
this.#element.innerHTML = '';
}
this.#isMounted = false;
}
/**
* Updates the component's props and triggers an update if they changed.
* @param {Object} newProps - The new props to apply.
*/
setProps(newProps) {
let changed = false;
const currentProps = this.props;
for (const key of Object.keys(newProps)) {
if (currentProps[key] !== newProps[key]) {
currentProps[key] = newProps[key];
changed = true;
}
}
for (const key of Object.keys(currentProps)) {
if (!(key in newProps)) {
delete currentProps[key];
changed = true;
}
}
}
/**
* Evaluates an expression in the component's scope.
* @param {string} expression - The expression to evaluate.
* @param {Object} [extraScope={}] - Additional scope variables.
* @returns {any} The result of the evaluation.
* @protected
*/
_evaluate(expression, extraScope = {}) {
return this.#evaluator.evaluateExpression(expression, this.#createScope(this.#methods, extraScope), this.state);
}
/**
* @returns {Element|null} The component's root element.
* @protected
*/
_getElement() {
return this.#element;
}
/**
* @returns {Object} The bridges accessible to the component.
* @protected
*/
_getBridges() {
return this.#bridges;
}
/**
* Mounts the component to a target element.
* @param {Element|string} target - The target element or selector.
*/
mount(target) {
this.#lifecycle.mount(this, target);
}
}
|