@cat-of-summer/st-script 1.0.9 → 1.0.11
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.
- package/README.md +50 -49
- package/dist/app.esm.min.js +1 -1
- package/dist/app.esm.min.js.map +3 -3
- package/dist/app.min.js +1 -1
- package/dist/app.min.js.map +3 -3
- package/dist/cookie.esm.min.js +1 -1
- package/dist/cookie.esm.min.js.map +2 -2
- package/dist/cookie.min.js +1 -1
- package/dist/cookie.min.js.map +2 -2
- package/dist/modal.esm.min.js +1 -1
- package/dist/modal.esm.min.js.map +3 -3
- package/dist/modal.min.js +1 -1
- package/dist/modal.min.js.map +3 -3
- package/dist/route.esm.min.js +1 -1
- package/dist/route.esm.min.js.map +3 -3
- package/dist/route.min.js +1 -1
- package/dist/route.min.js.map +3 -3
- package/dist/uploader.esm.min.js +1 -1
- package/dist/uploader.esm.min.js.map +3 -3
- package/dist/uploader.min.js +1 -1
- package/dist/uploader.min.js.map +3 -3
- package/package.json +1 -1
- package/src/app/index.js +246 -146
- package/src/cookie/index.js +9 -0
- package/src/modal/index.js +46 -7
- package/src/route/index.js +86 -3
- package/src/uploader/index.js +9 -8
package/src/app/index.js
CHANGED
|
@@ -2,6 +2,7 @@ export default class App extends HTMLElement {
|
|
|
2
2
|
static #boolean_attributes = new Set(['disabled', 'checked', 'readonly', 'required', 'selected', 'hidden', 'open', 'autofocus']);
|
|
3
3
|
static #apps = new Map();
|
|
4
4
|
static #instances = new Set();
|
|
5
|
+
static #selectSync = new WeakMap();
|
|
5
6
|
|
|
6
7
|
static create(options) {
|
|
7
8
|
let { app, setup = () => {}, template = ``, events = {} } = options;
|
|
@@ -19,7 +20,11 @@ export default class App extends HTMLElement {
|
|
|
19
20
|
if (!base)
|
|
20
21
|
throw new Error(`Application "${app}" not found!`);
|
|
21
22
|
let baseConfig = base.config;
|
|
22
|
-
|
|
23
|
+
// Через дескрипторы, а не spread: spread вычисляет геттеры и замораживает их значения.
|
|
24
|
+
let merged = Object.defineProperties({}, {
|
|
25
|
+
...Object.getOwnPropertyDescriptors(baseConfig),
|
|
26
|
+
...Object.getOwnPropertyDescriptors(options)
|
|
27
|
+
});
|
|
23
28
|
if (baseConfig.events || options.events)
|
|
24
29
|
merged.events = { ...baseConfig.events, ...options.events };
|
|
25
30
|
return App.create(merged);
|
|
@@ -41,6 +46,8 @@ export default class App extends HTMLElement {
|
|
|
41
46
|
#pendingFlush = false;
|
|
42
47
|
#methodWrappers = new Map();
|
|
43
48
|
#renderToken = 0;
|
|
49
|
+
#appliedTemplate = '';
|
|
50
|
+
#tornDown = false;
|
|
44
51
|
|
|
45
52
|
constructor() {
|
|
46
53
|
super();
|
|
@@ -57,7 +64,8 @@ export default class App extends HTMLElement {
|
|
|
57
64
|
binding.element.removeEventListener(eventName, binding.handler);
|
|
58
65
|
} else if (binding.type === 'attrSync' && binding.unwatch)
|
|
59
66
|
binding.unwatch();
|
|
60
|
-
|
|
67
|
+
binding.dispose?.();
|
|
68
|
+
|
|
61
69
|
if (binding.effect) {
|
|
62
70
|
this.#deps.forEach((effects, key) => {
|
|
63
71
|
effects.delete(binding.effect);
|
|
@@ -87,7 +95,13 @@ export default class App extends HTMLElement {
|
|
|
87
95
|
|
|
88
96
|
addEventListener(type, listener, options) {
|
|
89
97
|
if ((type === 'setup' || type === 'rendered') && this.#rendered) {
|
|
90
|
-
queueMicrotask(() =>
|
|
98
|
+
queueMicrotask(() => {
|
|
99
|
+
let event = new CustomEvent(type);
|
|
100
|
+
if (typeof listener === 'function')
|
|
101
|
+
listener.call(this, event);
|
|
102
|
+
else
|
|
103
|
+
listener?.handleEvent?.(event);
|
|
104
|
+
});
|
|
91
105
|
return;
|
|
92
106
|
}
|
|
93
107
|
super.addEventListener(type, listener, options);
|
|
@@ -103,6 +117,7 @@ export default class App extends HTMLElement {
|
|
|
103
117
|
|
|
104
118
|
applyTemplate(template = '') {
|
|
105
119
|
let tplContent = template || this.#template;
|
|
120
|
+
this.#appliedTemplate = tplContent;
|
|
106
121
|
this.#cleanupBindings(this.#bindings);
|
|
107
122
|
this.#bindings = [];
|
|
108
123
|
this.innerHTML = '';
|
|
@@ -336,13 +351,28 @@ export default class App extends HTMLElement {
|
|
|
336
351
|
return true;
|
|
337
352
|
}
|
|
338
353
|
|
|
354
|
+
static #raw(value) {
|
|
355
|
+
return value !== null && typeof value === 'object' ? value.__raw ?? value : value;
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
// Один прокси на пару «объект + путь»: items.indexOf(item) и сравнение по ссылке
|
|
359
|
+
// работают. Путь входит в ключ, потому что зависимости отслеживаются по пути.
|
|
360
|
+
#proxyCache = new WeakMap();
|
|
361
|
+
|
|
339
362
|
#createReactiveProxy(obj, path = []) {
|
|
340
363
|
if (obj === null || typeof obj !== 'object' || obj.__isReactive)
|
|
341
364
|
return obj;
|
|
365
|
+
let pathKey = path.join('.');
|
|
366
|
+
let byPath = this.#proxyCache.get(obj);
|
|
367
|
+
if (!byPath)
|
|
368
|
+
this.#proxyCache.set(obj, byPath = new Map());
|
|
369
|
+
if (byPath.has(pathKey))
|
|
370
|
+
return byPath.get(pathKey);
|
|
342
371
|
let $this = this;
|
|
343
372
|
let proxy = new Proxy(obj, {
|
|
344
373
|
get(target, prop, receiver) {
|
|
345
374
|
if (prop === '__isReactive') return true;
|
|
375
|
+
if (prop === '__raw') return target;
|
|
346
376
|
const pathSegment = typeof prop === 'symbol' ? '<symbol>' : prop;
|
|
347
377
|
let fullPath = [...path, pathSegment].join('.');
|
|
348
378
|
$this.#track(fullPath);
|
|
@@ -373,6 +403,7 @@ export default class App extends HTMLElement {
|
|
|
373
403
|
return result;
|
|
374
404
|
}
|
|
375
405
|
});
|
|
406
|
+
byPath.set(pathKey, proxy);
|
|
376
407
|
return proxy;
|
|
377
408
|
}
|
|
378
409
|
|
|
@@ -381,6 +412,10 @@ export default class App extends HTMLElement {
|
|
|
381
412
|
return new Proxy(fn, {
|
|
382
413
|
apply(target, thisArg, args) {
|
|
383
414
|
let result = Reflect.apply(target, $this, args);
|
|
415
|
+
// Вызов из выражения шаблона (форматтер в {{ }}) не перерисовывает
|
|
416
|
+
// читателей метода: иначе каждый рендер порождает лишний проход flush.
|
|
417
|
+
if ($this.#activeEffect)
|
|
418
|
+
return result;
|
|
384
419
|
if (result instanceof Promise)
|
|
385
420
|
return result.then(r => {
|
|
386
421
|
$this.#trigger(key);
|
|
@@ -395,36 +430,58 @@ export default class App extends HTMLElement {
|
|
|
395
430
|
#effect(fn) {
|
|
396
431
|
let capturedLoopCtx = this.#loopContext ? { ...this.#loopContext } : null;
|
|
397
432
|
let wrappedEffect = () => {
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
for (let key of Object.keys(capturedLoopCtx)) {
|
|
402
|
-
savedValues[key] = this[key];
|
|
403
|
-
this[key] = capturedLoopCtx[key];
|
|
404
|
-
}
|
|
405
|
-
}
|
|
433
|
+
// Стек, а не обнуление: вложенный эффект (#for внутри ветки #if) не должен
|
|
434
|
+
// сбрасывать отслеживание внешнего.
|
|
435
|
+
let prevEffect = this.#activeEffect;
|
|
406
436
|
this.#activeEffect = wrappedEffect;
|
|
407
437
|
try {
|
|
408
|
-
|
|
438
|
+
// Контекст цикла восстанавливается целиком, включая #loopContext: привязки,
|
|
439
|
+
// созданные при перезапуске (ветка #if внутри строки), видят переменные строки.
|
|
440
|
+
if (capturedLoopCtx)
|
|
441
|
+
this.#withLoopVars(capturedLoopCtx, fn);
|
|
442
|
+
else
|
|
443
|
+
fn();
|
|
409
444
|
} finally {
|
|
410
|
-
this.#activeEffect =
|
|
411
|
-
if (savedValues) {
|
|
412
|
-
for (let key of Object.keys(savedValues)) {
|
|
413
|
-
if (savedValues[key] !== undefined)
|
|
414
|
-
this[key] = savedValues[key];
|
|
415
|
-
else
|
|
416
|
-
delete this[key];
|
|
417
|
-
}
|
|
418
|
-
}
|
|
445
|
+
this.#activeEffect = prevEffect;
|
|
419
446
|
}
|
|
420
447
|
};
|
|
421
448
|
wrappedEffect();
|
|
422
449
|
return wrappedEffect;
|
|
423
450
|
}
|
|
424
451
|
|
|
452
|
+
static #compiled = new Map();
|
|
453
|
+
|
|
454
|
+
static #compile(body) {
|
|
455
|
+
let fn = App.#compiled.get(body);
|
|
456
|
+
if (!fn) {
|
|
457
|
+
fn = new Function('$s', '$event', '$__v', `with($s) { ${body} }`);
|
|
458
|
+
App.#compiled.set(body, fn);
|
|
459
|
+
}
|
|
460
|
+
return fn;
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
// Scope для with: свойства компонента без Element.prototype[Symbol.unscopables],
|
|
464
|
+
// иначе методы remove(), append() и т. п. в шаблоне не видны.
|
|
465
|
+
#scopeProxy = null;
|
|
466
|
+
|
|
467
|
+
get #scope() {
|
|
468
|
+
return this.#scopeProxy ??= new Proxy(this, {
|
|
469
|
+
has: (target, key) => typeof key === 'string' && key in target,
|
|
470
|
+
get: (target, key) => {
|
|
471
|
+
if (key === Symbol.unscopables) return undefined;
|
|
472
|
+
let value = Reflect.get(target, key);
|
|
473
|
+
// Вызов f() внутри with передаёт this = scope; методам прототипа (нативным
|
|
474
|
+
// и с приватными полями) нужен сам элемент.
|
|
475
|
+
return typeof value === 'function' && !Object.hasOwn(target, key)
|
|
476
|
+
? value.bind(target) : value;
|
|
477
|
+
},
|
|
478
|
+
set: (target, key, value) => Reflect.set(target, key, value)
|
|
479
|
+
});
|
|
480
|
+
}
|
|
481
|
+
|
|
425
482
|
#evalExpression(expr) {
|
|
426
483
|
try {
|
|
427
|
-
return
|
|
484
|
+
return App.#compile(`return (${expr});`).call(this, this.#scope);
|
|
428
485
|
} catch (e) {
|
|
429
486
|
console.warn('Expression evaluation error:', expr, e);
|
|
430
487
|
return undefined;
|
|
@@ -433,12 +490,20 @@ export default class App extends HTMLElement {
|
|
|
433
490
|
|
|
434
491
|
#execStatement(statement, event = null) {
|
|
435
492
|
try {
|
|
436
|
-
return
|
|
493
|
+
return App.#compile(statement).call(this, this.#scope, event);
|
|
437
494
|
} catch (e) {
|
|
438
495
|
console.error('Statement execution error:', statement, e);
|
|
439
496
|
}
|
|
440
497
|
}
|
|
441
498
|
|
|
499
|
+
#assign(prop, value) {
|
|
500
|
+
try {
|
|
501
|
+
App.#compile(`${prop} = $__v;`).call(this, this.#scope, null, value);
|
|
502
|
+
} catch (e) {
|
|
503
|
+
console.error('Model binding error:', prop, e);
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
|
|
442
507
|
#processTextInterpolation(textNode) {
|
|
443
508
|
let originalText = textNode.nodeValue;
|
|
444
509
|
let parts = [];
|
|
@@ -471,26 +536,25 @@ export default class App extends HTMLElement {
|
|
|
471
536
|
let statement = attr.value;
|
|
472
537
|
let capturedLoopCtx = this.#loopContext ? { ...this.#loopContext } : null;
|
|
473
538
|
let handler = (e) => {
|
|
474
|
-
if (capturedLoopCtx)
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
savedValues[key] = this[key];
|
|
478
|
-
this[key] = capturedLoopCtx[key];
|
|
479
|
-
}
|
|
480
|
-
this.#execStatement(statement, e);
|
|
481
|
-
for (let key of Object.keys(savedValues)) {
|
|
482
|
-
if (savedValues[key] !== undefined)
|
|
483
|
-
this[key] = savedValues[key];
|
|
484
|
-
else
|
|
485
|
-
delete this[key];
|
|
486
|
-
}
|
|
487
|
-
} else
|
|
539
|
+
if (capturedLoopCtx)
|
|
540
|
+
this.#withLoopVars(capturedLoopCtx, () => this.#execStatement(statement, e));
|
|
541
|
+
else
|
|
488
542
|
this.#execStatement(statement, e);
|
|
489
543
|
};
|
|
490
544
|
element.addEventListener(eventName, handler);
|
|
491
545
|
this.#bindings.push({ type: 'event', element, eventName, handler });
|
|
492
546
|
}
|
|
493
547
|
|
|
548
|
+
// Сырой HTML без обработки директив внутри. Только для доверенной разметки.
|
|
549
|
+
#bindHtml(element, attr) {
|
|
550
|
+
let expr = attr.value;
|
|
551
|
+
let effect = this.#effect(() => {
|
|
552
|
+
let value = this.#evalExpression(expr);
|
|
553
|
+
element.innerHTML = value == null ? '' : String(value);
|
|
554
|
+
});
|
|
555
|
+
this.#bindings.push({ type: 'html', element, effect });
|
|
556
|
+
}
|
|
557
|
+
|
|
494
558
|
#bindShow(element, attr) {
|
|
495
559
|
let expr = attr.value;
|
|
496
560
|
let effect = this.#effect(() => {
|
|
@@ -511,9 +575,13 @@ export default class App extends HTMLElement {
|
|
|
511
575
|
element.checked = !!value;
|
|
512
576
|
else if (element.tagName === 'INPUT' && element.type === 'radio')
|
|
513
577
|
element.checked = element.value === value;
|
|
514
|
-
else if (element.tagName === 'SELECT')
|
|
515
|
-
|
|
516
|
-
|
|
578
|
+
else if (element.tagName === 'SELECT') {
|
|
579
|
+
// Опции из #for появляются позже эффекта: ставим значение ещё раз после них.
|
|
580
|
+
let sync = () => { element.value = value; };
|
|
581
|
+
App.#selectSync.set(element, sync);
|
|
582
|
+
sync();
|
|
583
|
+
queueMicrotask(sync);
|
|
584
|
+
} else
|
|
517
585
|
element.value = value == null ? '' : value;
|
|
518
586
|
});
|
|
519
587
|
let capturedLoopCtx = this.#loopContext ? { ...this.#loopContext } : null;
|
|
@@ -526,30 +594,10 @@ export default class App extends HTMLElement {
|
|
|
526
594
|
newValue = element.valueAsNumber;
|
|
527
595
|
else
|
|
528
596
|
newValue = element.value;
|
|
529
|
-
if (capturedLoopCtx)
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
this[key] = capturedLoopCtx[key];
|
|
534
|
-
}
|
|
535
|
-
try {
|
|
536
|
-
new Function('value', `with(this) { ${prop} = value; }`).call(this, newValue);
|
|
537
|
-
} catch (e) {
|
|
538
|
-
console.error('Model binding error:', prop, e);
|
|
539
|
-
}
|
|
540
|
-
for (let key of Object.keys(savedValues)) {
|
|
541
|
-
if (savedValues[key] !== undefined)
|
|
542
|
-
this[key] = savedValues[key];
|
|
543
|
-
else
|
|
544
|
-
delete this[key];
|
|
545
|
-
}
|
|
546
|
-
} else {
|
|
547
|
-
try {
|
|
548
|
-
new Function('value', `with(this) { ${prop} = value; }`).call(this, newValue);
|
|
549
|
-
} catch (e) {
|
|
550
|
-
console.error('Model binding error:', prop, e);
|
|
551
|
-
}
|
|
552
|
-
}
|
|
597
|
+
if (capturedLoopCtx)
|
|
598
|
+
this.#withLoopVars(capturedLoopCtx, () => this.#assign(prop, newValue));
|
|
599
|
+
else
|
|
600
|
+
this.#assign(prop, newValue);
|
|
553
601
|
};
|
|
554
602
|
element.addEventListener(eventName, handler);
|
|
555
603
|
this.#bindings.push({ type: 'model', element, effect, handler });
|
|
@@ -559,56 +607,77 @@ export default class App extends HTMLElement {
|
|
|
559
607
|
let expr = attr.value;
|
|
560
608
|
let placeholder = document.createComment(`if: ${expr}`);
|
|
561
609
|
element.parentNode.insertBefore(placeholder, element);
|
|
562
|
-
|
|
610
|
+
element.removeAttribute(attr.name);
|
|
611
|
+
// Ветка хранит чистый шаблон и собирается заново при каждом показе:
|
|
612
|
+
// привязки скрытой ветки сняты, её прежний узел мёртв.
|
|
613
|
+
let chain = [{ expr, template: element.cloneNode(true) }];
|
|
563
614
|
let nextSibling = element.nextElementSibling;
|
|
564
615
|
while (nextSibling) {
|
|
565
616
|
if (nextSibling.hasAttribute('#else-if')) {
|
|
566
617
|
let elseIfExpr = nextSibling.getAttribute('#else-if');
|
|
567
|
-
chain.push({ expr: elseIfExpr, element: nextSibling, bindings: [], processed: false });
|
|
568
618
|
nextSibling.removeAttribute('#else-if');
|
|
619
|
+
chain.push({ expr: elseIfExpr, template: nextSibling.cloneNode(true) });
|
|
569
620
|
let next = nextSibling.nextElementSibling;
|
|
570
621
|
nextSibling.remove();
|
|
571
622
|
nextSibling = next;
|
|
572
623
|
} else if (nextSibling.hasAttribute('#else')) {
|
|
573
|
-
chain.push({ expr: 'true', element: nextSibling, bindings: [], processed: false });
|
|
574
624
|
nextSibling.removeAttribute('#else');
|
|
625
|
+
chain.push({ expr: 'true', template: nextSibling.cloneNode(true) });
|
|
575
626
|
nextSibling.remove();
|
|
576
627
|
break;
|
|
577
628
|
} else
|
|
578
629
|
break;
|
|
579
630
|
}
|
|
580
|
-
element.removeAttribute(attr.name);
|
|
581
631
|
element.remove();
|
|
582
|
-
let
|
|
632
|
+
let current = { branch: null, node: null, bindings: [] };
|
|
633
|
+
let hide = () => {
|
|
634
|
+
current.node?.remove();
|
|
635
|
+
this.#cleanupBindings(current.bindings);
|
|
636
|
+
current.node = null;
|
|
637
|
+
current.bindings = [];
|
|
638
|
+
};
|
|
583
639
|
let effect = this.#effect(() => {
|
|
584
|
-
let matchedBranch = null;
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
if (currentBranch) {
|
|
594
|
-
if (currentBranch.element && currentBranch.element.parentNode)
|
|
595
|
-
currentBranch.element.remove();
|
|
596
|
-
this.#cleanupBindings(currentBranch.bindings);
|
|
597
|
-
currentBranch.bindings = [];
|
|
598
|
-
}
|
|
599
|
-
if (matchedBranch) {
|
|
600
|
-
placeholder.parentNode.insertBefore(matchedBranch.element, placeholder.nextSibling);
|
|
601
|
-
if (!matchedBranch.processed) {
|
|
602
|
-
let bindingsLengthBefore = this.#bindings.length;
|
|
603
|
-
this.#processNode(matchedBranch.element);
|
|
604
|
-
matchedBranch.bindings = this.#bindings.slice(bindingsLengthBefore);
|
|
605
|
-
matchedBranch.processed = true;
|
|
606
|
-
}
|
|
607
|
-
}
|
|
608
|
-
currentBranch = matchedBranch;
|
|
609
|
-
}
|
|
640
|
+
let matchedBranch = chain.find(branch => this.#evalExpression(branch.expr)) ?? null;
|
|
641
|
+
if (current.branch === matchedBranch) return;
|
|
642
|
+
hide();
|
|
643
|
+
current.branch = matchedBranch;
|
|
644
|
+
if (!matchedBranch) return;
|
|
645
|
+
let node = matchedBranch.template.cloneNode(true);
|
|
646
|
+
placeholder.parentNode.insertBefore(node, placeholder.nextSibling);
|
|
647
|
+
current.bindings = this.#collectBindings(() => this.#processNode(node));
|
|
648
|
+
current.node = node;
|
|
610
649
|
});
|
|
611
|
-
this.#bindings.push({ type: 'conditional', placeholder,
|
|
650
|
+
this.#bindings.push({ type: 'conditional', placeholder, effect, dispose: hide });
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
// Привязки, созданные внутри fn, забираются из общего списка: ими владеет
|
|
654
|
+
// вызывающий (ветка #if, строка #for) и снимает их вместе со своим узлом.
|
|
655
|
+
#collectBindings(fn) {
|
|
656
|
+
let before = this.#bindings.length;
|
|
657
|
+
fn();
|
|
658
|
+
return this.#bindings.splice(before);
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
// Временно кладёт переменные цикла на компонент, чтобы их видели выражения.
|
|
662
|
+
#withLoopVars(vars, fn) {
|
|
663
|
+
let saved = {};
|
|
664
|
+
for (let key of Object.keys(vars)) {
|
|
665
|
+
saved[key] = this[key];
|
|
666
|
+
this[key] = vars[key];
|
|
667
|
+
}
|
|
668
|
+
let previousLoopCtx = this.#loopContext;
|
|
669
|
+
this.#loopContext = { ...previousLoopCtx, ...vars };
|
|
670
|
+
try {
|
|
671
|
+
return fn();
|
|
672
|
+
} finally {
|
|
673
|
+
this.#loopContext = previousLoopCtx;
|
|
674
|
+
for (let key of Object.keys(saved)) {
|
|
675
|
+
if (saved[key] !== undefined)
|
|
676
|
+
this[key] = saved[key];
|
|
677
|
+
else
|
|
678
|
+
delete this[key];
|
|
679
|
+
}
|
|
680
|
+
}
|
|
612
681
|
}
|
|
613
682
|
|
|
614
683
|
#bindLoop(element, attr) {
|
|
@@ -620,64 +689,67 @@ export default class App extends HTMLElement {
|
|
|
620
689
|
}
|
|
621
690
|
let itemName = match[1];
|
|
622
691
|
let collectionExpr = match[2];
|
|
623
|
-
let
|
|
624
|
-
let nextSibling = element.nextSibling;
|
|
692
|
+
let keyExpr = element.getAttribute('#key');
|
|
625
693
|
element.removeAttribute(attr.name);
|
|
694
|
+
element.removeAttribute('#key');
|
|
695
|
+
// Якорь вместо запомненного родителя: на верхнем уровне шаблона родитель —
|
|
696
|
+
// DocumentFragment, который после монтирования пуст.
|
|
697
|
+
let anchor = document.createComment(`for: ${loopExpr}`);
|
|
698
|
+
element.parentNode.insertBefore(anchor, element);
|
|
626
699
|
let template = element.cloneNode(true);
|
|
627
700
|
element.remove();
|
|
628
|
-
let
|
|
701
|
+
let usesIndex = template.outerHTML.includes('$index');
|
|
702
|
+
let rendered = new Map();
|
|
703
|
+
let dispose = entry => {
|
|
704
|
+
entry.node.remove();
|
|
705
|
+
this.#cleanupBindings(entry.bindings);
|
|
706
|
+
};
|
|
629
707
|
let effect = this.#effect(() => {
|
|
630
708
|
let collection = this.#evalExpression(collectionExpr);
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
item.node.remove();
|
|
634
|
-
this.#cleanupBindings(item.bindings);
|
|
635
|
-
});
|
|
636
|
-
renderedItems = [];
|
|
637
|
-
let entries;
|
|
638
|
-
if (Array.isArray(collection)) {
|
|
709
|
+
let entries = [];
|
|
710
|
+
if (Array.isArray(collection))
|
|
639
711
|
entries = collection.map((value, index) => ({ value, key: undefined, index }));
|
|
640
|
-
|
|
712
|
+
else if (collection !== null && typeof collection === 'object')
|
|
641
713
|
entries = Object.entries(collection).map(([key, value], index) => ({ value, key, index }));
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
}
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
let
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
let
|
|
660
|
-
this.#processNode(
|
|
661
|
-
let
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
this[itemName] = originalItem;
|
|
665
|
-
else
|
|
666
|
-
delete this[itemName];
|
|
667
|
-
if (originalIndex !== undefined)
|
|
668
|
-
this.$index = originalIndex;
|
|
669
|
-
else
|
|
670
|
-
delete this.$index;
|
|
671
|
-
if (originalKey !== undefined)
|
|
672
|
-
this.$key = originalKey;
|
|
673
|
-
else
|
|
674
|
-
delete this.$key;
|
|
675
|
-
fragment.appendChild(clone);
|
|
676
|
-
renderedItems.push({ node: clone, bindings: itemBindings });
|
|
714
|
+
let next = new Map();
|
|
715
|
+
let ordered = [];
|
|
716
|
+
entries.forEach(({ value, key, index }) => {
|
|
717
|
+
let vars = { [itemName]: value, $index: index };
|
|
718
|
+
if (key !== undefined) vars.$key = key;
|
|
719
|
+
let id = keyExpr ? this.#withLoopVars(vars, () => this.#evalExpression(keyExpr)) : Symbol();
|
|
720
|
+
if (keyExpr && next.has(id))
|
|
721
|
+
console.warn('Duplicate #key in #for:', loopExpr, id);
|
|
722
|
+
let prev = rendered.get(id);
|
|
723
|
+
// Узел переиспользуется, только если не изменились ни элемент, ни путь к нему:
|
|
724
|
+
// эффекты строки отслеживают путь items.N.*, а не сам объект.
|
|
725
|
+
if (prev && App.#raw(prev.value) === App.#raw(value) && (prev.index === index || !usesIndex && prev.key === key && !Array.isArray(collection))) {
|
|
726
|
+
rendered.delete(id);
|
|
727
|
+
next.set(id, prev);
|
|
728
|
+
ordered.push(prev);
|
|
729
|
+
return;
|
|
730
|
+
}
|
|
731
|
+
let node = template.cloneNode(true);
|
|
732
|
+
let bindings = this.#withLoopVars(vars, () => this.#collectBindings(() => this.#processNode(node)));
|
|
733
|
+
let entry = { node, bindings, value, index, key };
|
|
734
|
+
next.set(id, entry);
|
|
735
|
+
ordered.push(entry);
|
|
677
736
|
});
|
|
678
|
-
|
|
737
|
+
rendered.forEach(dispose);
|
|
738
|
+
rendered = next;
|
|
739
|
+
let ref = anchor;
|
|
740
|
+
for (let i = ordered.length - 1; i >= 0; i--) {
|
|
741
|
+
let node = ordered[i].node;
|
|
742
|
+
if (node.nextSibling !== ref)
|
|
743
|
+
anchor.parentNode.insertBefore(node, ref);
|
|
744
|
+
ref = node;
|
|
745
|
+
}
|
|
746
|
+
let select = anchor.parentNode?.closest?.('select');
|
|
747
|
+
if (select) App.#selectSync.get(select)?.();
|
|
679
748
|
});
|
|
680
|
-
this.#bindings.push({ type: 'loop',
|
|
749
|
+
this.#bindings.push({ type: 'loop', anchor, template, effect, dispose: () => {
|
|
750
|
+
rendered.forEach(dispose);
|
|
751
|
+
rendered.clear();
|
|
752
|
+
} });
|
|
681
753
|
}
|
|
682
754
|
|
|
683
755
|
#bindAttribute(element, attr) {
|
|
@@ -729,6 +801,11 @@ export default class App extends HTMLElement {
|
|
|
729
801
|
element.removeAttribute(attr.name);
|
|
730
802
|
return true;
|
|
731
803
|
}
|
|
804
|
+
else if (attr.name === '#html') {
|
|
805
|
+
this.#bindHtml(element, attr);
|
|
806
|
+
element.removeAttribute(attr.name);
|
|
807
|
+
return true;
|
|
808
|
+
}
|
|
732
809
|
else if (attr.name === '#show') {
|
|
733
810
|
this.#bindShow(element, attr);
|
|
734
811
|
element.removeAttribute(attr.name);
|
|
@@ -932,6 +1009,11 @@ export default class App extends HTMLElement {
|
|
|
932
1009
|
connectedCallback() {
|
|
933
1010
|
App.#instances.add(this);
|
|
934
1011
|
if (this.#booted === true) {
|
|
1012
|
+
// Вернули в DOM после полной очистки — привязки сняты, собираем заново.
|
|
1013
|
+
if (this.#tornDown) {
|
|
1014
|
+
this.#tornDown = false;
|
|
1015
|
+
this.applyTemplate(this.#appliedTemplate);
|
|
1016
|
+
}
|
|
935
1017
|
if (!this.#attrObserver) {
|
|
936
1018
|
this.#attrObserver = new MutationObserver(mutations => {
|
|
937
1019
|
for (let m of mutations) {
|
|
@@ -1000,6 +1082,16 @@ export default class App extends HTMLElement {
|
|
|
1000
1082
|
}
|
|
1001
1083
|
|
|
1002
1084
|
disconnectedCallback() {
|
|
1085
|
+
// Очистка откладывается: перенос узла (append в другой контейнер, Modal)
|
|
1086
|
+
// вызывает disconnected и connected в одной задаче, и привязки должны выжить.
|
|
1087
|
+
queueMicrotask(() => {
|
|
1088
|
+
if (!this.isConnected)
|
|
1089
|
+
this.#teardown();
|
|
1090
|
+
});
|
|
1091
|
+
}
|
|
1092
|
+
|
|
1093
|
+
#teardown() {
|
|
1094
|
+
this.#tornDown = true;
|
|
1003
1095
|
if (this.#attrObserver) {
|
|
1004
1096
|
this.#attrObserver.disconnect();
|
|
1005
1097
|
this.#attrObserver = null;
|
|
@@ -1026,7 +1118,15 @@ export default class App extends HTMLElement {
|
|
|
1026
1118
|
App.#instances.delete(this);
|
|
1027
1119
|
}
|
|
1028
1120
|
|
|
1029
|
-
|
|
1121
|
+
// Нативная сигнатура (name, force) сохраняется: на неё полагается сторонний код.
|
|
1122
|
+
// Строковые аргументы — старый режим, он же cycleAttribute.
|
|
1123
|
+
toggleAttribute(name, ...args) {
|
|
1124
|
+
if (args.length <= 1 && (args[0] === undefined || typeof args[0] === 'boolean'))
|
|
1125
|
+
return super.toggleAttribute(name, ...args);
|
|
1126
|
+
return this.cycleAttribute(name, ...args);
|
|
1127
|
+
}
|
|
1128
|
+
|
|
1129
|
+
cycleAttribute(name, value_1 = '', value_2 = '') {
|
|
1030
1130
|
let value = this.getAttribute(name);
|
|
1031
1131
|
|
|
1032
1132
|
this[
|
package/src/cookie/index.js
CHANGED
|
@@ -7,6 +7,15 @@ export default class Cookie {
|
|
|
7
7
|
...params
|
|
8
8
|
};
|
|
9
9
|
|
|
10
|
+
// «Бессрочно»: браузеры всё равно режут срок, Chrome — до 400 дней.
|
|
11
|
+
if (params.expires === Infinity)
|
|
12
|
+
params.expires = 400 * 24 * 3600;
|
|
13
|
+
|
|
14
|
+
// get() разбирает JSON, поэтому не-строки пишутся через JSON.stringify.
|
|
15
|
+
// Строки остаются как есть: их читает и сервер.
|
|
16
|
+
if (typeof value !== 'string')
|
|
17
|
+
value = JSON.stringify(value);
|
|
18
|
+
|
|
10
19
|
if (!(params.expires instanceof Date)) {
|
|
11
20
|
let expires = params.expires;
|
|
12
21
|
|