@cat-of-summer/st-script 1.0.14 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/app/index.js CHANGED
@@ -1,11 +1,49 @@
1
1
  export default class App extends HTMLElement {
2
2
  static #boolean_attributes = new Set(['disabled', 'checked', 'readonly', 'required', 'selected', 'hidden', 'open', 'autofocus']);
3
- // Атрибут у них - только начальное значение: после действий пользователя браузер
3
+ // Атрибут у них — только начальное значение: после действий пользователя браузер
4
4
  // смотрит на свойство, поэтому привязка выставляет и его.
5
5
  static #live_properties = new Set(['checked', 'selected', 'value']);
6
6
  static #apps = new Map();
7
7
  static #instances = new Set();
8
8
  static #selectSync = new WeakMap();
9
+ // Классы, которые поставил #class: привязка class="{{ }}" переписывает атрибут целиком
10
+ // и возвращает их следом.
11
+ static #classSets = new WeakMap();
12
+ // Помощники шаблонов на все приложения: App.helpers({ … }).
13
+ static #globalHelpers = {};
14
+
15
+ // Значения, которые видны в шаблонах всех приложений, но не реактивны: форматтеры,
16
+ // фасады модулей. Методы не оборачиваются, их вызов ничего не перерисовывает.
17
+ static helpers(helpers = {}) {
18
+ Object.assign(App.#globalHelpers, helpers);
19
+ return App.#globalHelpers;
20
+ }
21
+
22
+ // Исходный объект под реактивной обёрткой. Вложенные значения не трогает.
23
+ static toRaw(value) {
24
+ return App.#raw(value);
25
+ }
26
+
27
+ // Глубокая копия данных без реактивных обёрток: массивы и простые объекты копируются,
28
+ // остальное (Date, File, Map…) идёт как есть.
29
+ static snapshot(value, seen = new WeakMap()) {
30
+ value = App.#raw(value);
31
+ if (value === null || typeof value !== 'object') return value;
32
+ if (seen.has(value)) return seen.get(value);
33
+ let proto = Object.getPrototypeOf(value);
34
+ if (Array.isArray(value)) {
35
+ let copy = [];
36
+ seen.set(value, copy);
37
+ value.forEach(item => copy.push(App.snapshot(item, seen)));
38
+ return copy;
39
+ }
40
+ if (proto !== Object.prototype && proto !== null) return value;
41
+ let copy = {};
42
+ seen.set(value, copy);
43
+ for (let key of Object.keys(value))
44
+ copy[key] = App.snapshot(value[key], seen);
45
+ return copy;
46
+ }
9
47
 
10
48
  static create(options) {
11
49
  let { app, setup = () => {}, template = ``, events = {} } = options;
@@ -30,6 +68,8 @@ export default class App extends HTMLElement {
30
68
  });
31
69
  if (baseConfig.events || options.events)
32
70
  merged.events = { ...baseConfig.events, ...options.events };
71
+ if (baseConfig.helpers || options.helpers)
72
+ merged.helpers = { ...baseConfig.helpers, ...options.helpers };
33
73
  return App.create(merged);
34
74
  }
35
75
 
@@ -55,6 +95,11 @@ export default class App extends HTMLElement {
55
95
  #appliedTemplate = '';
56
96
  #tornDown = false;
57
97
  #templated = false;
98
+ // helpers из конфига приложения.
99
+ #helpers = {};
100
+ // Эффекты по контексту строки #for (и всем его предкам): перенесённая строка
101
+ // перезапускает их с новыми переменными цикла, а не пересоздаётся.
102
+ #ctxEffects = new WeakMap();
58
103
 
59
104
  constructor() {
60
105
  super();
@@ -77,16 +122,35 @@ export default class App extends HTMLElement {
77
122
  binding.dispose?.();
78
123
 
79
124
  if (binding.effect) {
80
- this.#deps.forEach((effects, key) => {
81
- effects.delete(binding.effect);
82
- if (effects.size === 0)
83
- this.#deps.delete(key);
84
- });
125
+ this.#untrack(binding.effect);
85
126
  this.#updateQueue.delete(binding.effect);
127
+ this.#unregisterEffect(binding.effect);
86
128
  }
87
129
  });
88
130
  }
89
131
 
132
+ #untrack(effect) {
133
+ this.#deps.forEach((effects, key) => {
134
+ effects.delete(effect);
135
+ if (effects.size === 0)
136
+ this.#deps.delete(key);
137
+ });
138
+ }
139
+
140
+ #registerEffect(effect, ctx) {
141
+ for (let c = ctx; c; c = Object.getPrototypeOf(c)) {
142
+ let set = this.#ctxEffects.get(c);
143
+ if (!set)
144
+ this.#ctxEffects.set(c, set = new Set());
145
+ set.add(effect);
146
+ }
147
+ }
148
+
149
+ #unregisterEffect(effect) {
150
+ for (let c = effect.ctx; c; c = Object.getPrototypeOf(c))
151
+ this.#ctxEffects.get(c)?.delete(effect);
152
+ }
153
+
90
154
  get template() {
91
155
  return this.#template;
92
156
  }
@@ -452,7 +516,9 @@ export default class App extends HTMLElement {
452
516
  }
453
517
 
454
518
  #effect(fn) {
455
- let capturedLoopCtx = this.#loopContext ? { ...this.#loopContext } : null;
519
+ // Контекст цикла — по ссылке: перенесённая строка #for меняет в нём переменные,
520
+ // и перезапуск эффекта видит новые.
521
+ let capturedLoopCtx = this.#loopContext;
456
522
  let wrappedEffect = () => {
457
523
  // Стек, а не обнуление: вложенный эффект (#for внутри ветки #if) не должен
458
524
  // сбрасывать отслеживание внешнего.
@@ -469,6 +535,10 @@ export default class App extends HTMLElement {
469
535
  this.#activeEffect = prevEffect;
470
536
  }
471
537
  };
538
+ if (capturedLoopCtx) {
539
+ wrappedEffect.ctx = capturedLoopCtx;
540
+ this.#registerEffect(wrappedEffect, capturedLoopCtx);
541
+ }
472
542
  wrappedEffect();
473
543
  return wrappedEffect;
474
544
  }
@@ -489,10 +559,17 @@ export default class App extends HTMLElement {
489
559
  #scopeProxy = null;
490
560
 
491
561
  get #scope() {
562
+ // Порядок поиска имени: свойства компонента и переменные цикла, helpers конфига,
563
+ // App.helpers, глобальные (window).
492
564
  return this.#scopeProxy ??= new Proxy(this, {
493
- has: (target, key) => typeof key === 'string' && key in target,
565
+ has: (target, key) => typeof key === 'string'
566
+ && (key in target || key in this.#helpers || key in App.#globalHelpers),
494
567
  get: (target, key) => {
495
568
  if (key === Symbol.unscopables) return undefined;
569
+ if (typeof key === 'string' && !(key in target)) {
570
+ if (key in this.#helpers) return this.#helpers[key];
571
+ if (key in App.#globalHelpers) return App.#globalHelpers[key];
572
+ }
496
573
  let value = Reflect.get(target, key);
497
574
  this.#warnNotReactive(key, value);
498
575
  // Вызов f() внутри with передаёт this = scope; методам прототипа (нативным
@@ -575,7 +652,7 @@ export default class App extends HTMLElement {
575
652
  let [eventName, ...modifiers] = attr.name.slice(1).split('.');
576
653
  let self = modifiers.includes('self');
577
654
  let statement = attr.value;
578
- let capturedLoopCtx = this.#loopContext ? { ...this.#loopContext } : null;
655
+ let capturedLoopCtx = this.#loopContext;
579
656
  let handler = (e) => {
580
657
  if (self && e.target !== element) return;
581
658
  if (capturedLoopCtx)
@@ -609,6 +686,30 @@ export default class App extends HTMLElement {
609
686
  this.#bindings.push({ type: 'show', element, effect });
610
687
  }
611
688
 
689
+ // #class="{ 'a b': cond }", массив или строка имён: классы ставятся поверх статического
690
+ // class и снимаются, когда условие ложно. Имена лежат литералами в разметке — их видит purge.
691
+ #bindClass(element, attr) {
692
+ let expr = attr.value;
693
+ let active = new Set();
694
+ App.#classSets.set(element, active);
695
+ let effect = this.#effect(() => {
696
+ let value = this.#evalExpression(expr);
697
+ let next = new Set();
698
+ let add = names => String(names).split(/\s+/).filter(Boolean).forEach(name => next.add(name));
699
+ if (Array.isArray(value))
700
+ value.forEach(names => names && add(names));
701
+ else if (value && typeof value === 'object')
702
+ Object.entries(value).forEach(([names, on]) => on && add(names));
703
+ else if (value)
704
+ add(value);
705
+ active.forEach(name => next.has(name) || element.classList.remove(name));
706
+ next.forEach(name => element.classList.add(name));
707
+ active.clear();
708
+ next.forEach(name => active.add(name));
709
+ });
710
+ this.#bindings.push({ type: 'class', element, effect });
711
+ }
712
+
612
713
  #bindModel(element, attr) {
613
714
  let prop = attr.value;
614
715
  let effect = this.#effect(() => {
@@ -626,14 +727,15 @@ export default class App extends HTMLElement {
626
727
  } else
627
728
  element.value = value == null ? '' : value;
628
729
  });
629
- let capturedLoopCtx = this.#loopContext ? { ...this.#loopContext } : null;
730
+ let capturedLoopCtx = this.#loopContext;
630
731
  let eventName = element.tagName === 'SELECT' ? 'change' : 'input';
631
732
  let handler = (e) => {
632
733
  let newValue;
633
734
  if (element.type === 'checkbox')
634
735
  newValue = element.checked;
736
+ // Пустое числовое поле — null, а не NaN из valueAsNumber.
635
737
  else if (element.type === 'number' || element.type === 'range')
636
- newValue = element.valueAsNumber;
738
+ newValue = element.value === '' ? null : element.valueAsNumber;
637
739
  else
638
740
  newValue = element.value;
639
741
  if (capturedLoopCtx)
@@ -700,15 +802,22 @@ export default class App extends HTMLElement {
700
802
  return this.#bindings.splice(before);
701
803
  }
702
804
 
805
+ // Контекст строки #for: переменные строки поверх контекста внешнего цикла (прототипом),
806
+ // так вложенная строка видит и свои, и внешние, а перенос внешней строки виден всем.
807
+ #loopScope(vars) {
808
+ return Object.assign(Object.create(this.#loopContext ?? null), vars);
809
+ }
810
+
703
811
  // Временно кладёт переменные цикла на компонент, чтобы их видели выражения.
704
- #withLoopVars(vars, fn) {
812
+ // ctx — контекст строки (#loopScope), он же становится текущим.
813
+ #withLoopVars(ctx, fn) {
705
814
  let saved = {};
706
- for (let key of Object.keys(vars)) {
815
+ for (let key in ctx) {
707
816
  saved[key] = this[key];
708
- this[key] = vars[key];
817
+ this[key] = ctx[key];
709
818
  }
710
819
  let previousLoopCtx = this.#loopContext;
711
- this.#loopContext = { ...previousLoopCtx, ...vars };
820
+ this.#loopContext = ctx;
712
821
  try {
713
822
  return fn();
714
823
  } finally {
@@ -722,6 +831,19 @@ export default class App extends HTMLElement {
722
831
  }
723
832
  }
724
833
 
834
+ // Перенос строки #for: новые переменные в её контексте и перезапуск всех эффектов
835
+ // строки, включая вложенные ветки и циклы. Зависимости собираются заново.
836
+ #moveRow(entry, vars) {
837
+ Object.assign(entry.ctx, vars);
838
+ let effects = [...(this.#ctxEffects.get(entry.ctx) ?? [])];
839
+ effects.forEach(effect => this.#untrack(effect));
840
+ // Перезапуск ветки #if может снять эффекты старой ветки — их уже не трогаем.
841
+ effects.forEach(effect => {
842
+ if (this.#ctxEffects.get(entry.ctx)?.has(effect))
843
+ effect();
844
+ });
845
+ }
846
+
725
847
  #bindLoop(element, attr) {
726
848
  let loopExpr = attr.value;
727
849
  let match = loopExpr.match(/^\s*(\w+)\s+in\s+(.+)$/);
@@ -740,7 +862,6 @@ export default class App extends HTMLElement {
740
862
  element.parentNode.insertBefore(anchor, element);
741
863
  let template = element.cloneNode(true);
742
864
  element.remove();
743
- let usesIndex = template.outerHTML.includes('$index');
744
865
  let rendered = new Map();
745
866
  let dispose = entry => {
746
867
  entry.node.remove();
@@ -758,21 +879,27 @@ export default class App extends HTMLElement {
758
879
  entries.forEach(({ value, key, index }) => {
759
880
  let vars = { [itemName]: value, $index: index };
760
881
  if (key !== undefined) vars.$key = key;
761
- let id = keyExpr ? this.#withLoopVars(vars, () => this.#evalExpression(keyExpr)) : Symbol();
882
+ let ctx = this.#loopScope(vars);
883
+ let id = keyExpr ? this.#withLoopVars(ctx, () => this.#evalExpression(keyExpr)) : Symbol();
762
884
  if (keyExpr && next.has(id))
763
885
  console.warn('Duplicate #key in #for:', loopExpr, id);
764
886
  let prev = rendered.get(id);
765
- // Узел переиспользуется, только если не изменились ни элемент, ни путь к нему:
766
- // эффекты строки отслеживают путь items.N.*, а не сам объект.
767
- if (prev && App.#raw(prev.value) === App.#raw(value) && (prev.index === index || !usesIndex && prev.key === key && !Array.isArray(collection))) {
887
+ // Строка с тем же ключом и тем же элементом не пересоздаётся, даже если сменила
888
+ // место: эффекты строки отслеживают путь items.N.*, поэтому они перезапускаются
889
+ // с новыми переменными цикла. Вложенные <st-app> при этом не пересоздаются.
890
+ if (prev && App.#raw(prev.value) === App.#raw(value)) {
768
891
  rendered.delete(id);
892
+ if (prev.value !== value || prev.index !== index || prev.key !== key) {
893
+ Object.assign(prev, { value, index, key });
894
+ this.#moveRow(prev, vars);
895
+ }
769
896
  next.set(id, prev);
770
897
  ordered.push(prev);
771
898
  return;
772
899
  }
773
900
  let node = template.cloneNode(true);
774
- let bindings = this.#withLoopVars(vars, () => this.#collectBindings(() => this.#processNode(node)));
775
- let entry = { node, bindings, value, index, key };
901
+ let bindings = this.#withLoopVars(ctx, () => this.#collectBindings(() => this.#processNode(node)));
902
+ let entry = { node, bindings, value, index, key, ctx };
776
903
  next.set(id, entry);
777
904
  ordered.push(entry);
778
905
  });
@@ -830,7 +957,10 @@ export default class App extends HTMLElement {
830
957
  element[attrName] = !falsy;
831
958
  } else {
832
959
  element.setAttribute(attrName, finalValue);
833
- // Сравнение - чтобы не сбрасывать курсор в поле при каждом проходе эффекта.
960
+ // Классы из #class атрибут не знает: возвращаем их после перезаписи.
961
+ if (attrName === 'class')
962
+ App.#classSets.get(element)?.forEach(name => element.classList.add(name));
963
+ // Сравнение — чтобы не сбрасывать курсор в поле при каждом проходе эффекта.
834
964
  if (live && element.value !== finalValue)
835
965
  element.value = finalValue;
836
966
  }
@@ -838,23 +968,34 @@ export default class App extends HTMLElement {
838
968
  this.#bindings.push({ type: 'attribute', element, attrName, effect });
839
969
  }
840
970
 
971
+ // Возвращает true, если потомков элемента обрабатывать не нужно.
841
972
  #processDirectives(element) {
842
973
  let attrs = Array.from(element.attributes);
974
+ // Структурные директивы — раньше остальных атрибутов, где бы ни стояли: иначе
975
+ // class="{{ }}" перед #for связался бы вне цикла и записал значение в шаблон строки.
976
+ let structural = attrs.find(attr => attr.name === '#pre' || attr.name === '#if' || attr.name === '#for');
977
+ if (structural?.name === '#pre') {
978
+ element.removeAttribute('#pre');
979
+ return true;
980
+ }
981
+ if (structural?.name === '#if') {
982
+ this.#bindConditional(element, structural);
983
+ return true;
984
+ }
985
+ if (structural?.name === '#for') {
986
+ this.#bindLoop(element, structural);
987
+ return true;
988
+ }
989
+ let skipChildren = false;
843
990
  for (let attr of attrs) {
844
- if (attr.name === '#if') {
845
- this.#bindConditional(element, attr);
846
- element.removeAttribute(attr.name);
847
- return true;
848
- }
849
- else if (attr.name === '#for') {
850
- this.#bindLoop(element, attr);
991
+ if (attr.name === '#html') {
992
+ this.#bindHtml(element, attr);
851
993
  element.removeAttribute(attr.name);
852
- return true;
994
+ skipChildren = true;
853
995
  }
854
- else if (attr.name === '#html') {
855
- this.#bindHtml(element, attr);
996
+ else if (attr.name === '#class') {
997
+ this.#bindClass(element, attr);
856
998
  element.removeAttribute(attr.name);
857
- return true;
858
999
  }
859
1000
  else if (attr.name === '#show') {
860
1001
  this.#bindShow(element, attr);
@@ -866,10 +1007,6 @@ export default class App extends HTMLElement {
866
1007
  }
867
1008
  else if (attr.name === '#once')
868
1009
  element.removeAttribute(attr.name);
869
- else if (attr.name === '#pre') {
870
- element.removeAttribute(attr.name);
871
- return true;
872
- }
873
1010
  else if (attr.name.startsWith('@')) {
874
1011
  this.#bindEvent(element, attr);
875
1012
  element.removeAttribute(attr.name);
@@ -877,7 +1014,7 @@ export default class App extends HTMLElement {
877
1014
  else if (/\{\{.+?\}\}/.test(attr.value))
878
1015
  this.#bindAttribute(element, attr);
879
1016
  }
880
- return false;
1017
+ return skipChildren;
881
1018
  }
882
1019
 
883
1020
  #processNode(node) {
@@ -912,8 +1049,9 @@ export default class App extends HTMLElement {
912
1049
  );
913
1050
  this.#template = prototype.template;
914
1051
  let config = prototype.config;
1052
+ this.#helpers = config.helpers ?? {};
915
1053
  let descriptors = Object.getOwnPropertyDescriptors(config);
916
- let skipKeys = new Set(['app', 'setup', 'template', 'events']);
1054
+ let skipKeys = new Set(['app', 'setup', 'template', 'events', 'helpers']);
917
1055
  Object.entries(descriptors).forEach(([key, descriptor]) => {
918
1056
  if (skipKeys.has(key)) return;
919
1057
  if (descriptor.get) {
package/src/core/index.js CHANGED
@@ -50,6 +50,57 @@ export default class Core {
50
50
  return `${hex.slice(0,8)}-${hex.slice(8,12)}-${hex.slice(12,16)}-${hex.slice(16,20)}-${hex.slice(20)}`;
51
51
  }
52
52
 
53
+ // Русское склонение по числу: plural(3, 'файл', 'файла', 'файлов') → 'файла'.
54
+ static plural(n, one, few, many) {
55
+ let abs = Math.abs(n), mod10 = abs % 10, mod100 = abs % 100;
56
+
57
+ if (mod10 === 1 && mod100 !== 11) return one;
58
+ if (mod10 >= 2 && mod10 <= 4 && (mod100 < 12 || mod100 > 14)) return few;
59
+ return many;
60
+ }
61
+
62
+ // Экранирование для вставки строки в HTML (#html, innerHTML).
63
+ static escape(text) {
64
+ return String(text ?? '').replace(/[&<>"']/g, ch => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[ch]);
65
+ }
66
+
67
+ // Текст в буфер обмена. Promise<boolean>. Вне защищённого контекста (http не на
68
+ // localhost) Clipboard API нет — копирование через скрытое поле и execCommand.
69
+ static async copy(text) {
70
+ text = String(text ?? '');
71
+
72
+ try {
73
+ await navigator.clipboard.writeText(text);
74
+ return true;
75
+ } catch {
76
+ let area = Object.assign(document.createElement('textarea'), { value: text, readOnly: true });
77
+ Object.assign(area.style, { position: 'fixed', top: '0', left: '0', opacity: '0' });
78
+
79
+ let active = document.activeElement;
80
+ document.body.append(area);
81
+ area.select();
82
+
83
+ let ok = false;
84
+ try { ok = document.execCommand('copy'); } catch {}
85
+
86
+ area.remove();
87
+ active?.focus?.({ preventScroll: true });
88
+ return ok;
89
+ }
90
+ }
91
+
92
+ // Отдать строку или Blob файлом: download('текст', 'key.txt').
93
+ static download(content, filename, type = 'text/plain') {
94
+ let blob = content instanceof Blob ? content : new Blob([content], { type });
95
+ let url = URL.createObjectURL(blob);
96
+ let link = Object.assign(document.createElement('a'), { href: url, download: filename, hidden: true });
97
+
98
+ document.body.append(link);
99
+ link.click();
100
+ link.remove();
101
+ setTimeout(() => URL.revokeObjectURL(url));
102
+ }
103
+
53
104
  static fetch(params) {
54
105
  if (params instanceof HTMLFormElement)
55
106
  params = {
@@ -11,6 +11,11 @@ export default class Modal {
11
11
  #methods = {};
12
12
  #state = 'hidden';
13
13
  #pending_show = null;
14
+ // open(): промисы текущего показа и ждущие отложенного show().
15
+ #resolvers = [];
16
+ #waiting = [];
17
+ #result = null;
18
+ #return_to = null;
14
19
  // Куда идёт окно. Меняется синхронно, а state — только в requestAnimationFrame,
15
20
  // поэтому show() сразу после hide() видит закрытие по #target.
16
21
  #target = 'hidden';
@@ -26,7 +31,8 @@ export default class Modal {
26
31
  Modal.#esc_bound = true;
27
32
  document.addEventListener('keydown', e => {
28
33
  if (e.code !== 'Escape' && e.keyCode !== 27) return;
29
- let top = Modal.#open[Modal.#open.length - 1];
34
+ // Неблокирующие окна (уведомления) не перекрывают Esc окну под ними.
35
+ let top = Modal.#open.filter(modal => modal.params.blocking).at(-1);
30
36
  if (top?.params.close_by_esc) top.hide(e);
31
37
  });
32
38
  }
@@ -34,6 +40,19 @@ export default class Modal {
34
40
  get state() {return this.#state;}
35
41
  get params() {return this.#params;}
36
42
 
43
+ // Показать окно и дождаться результата: промис разрешается значением из hide(value)
44
+ // после полного закрытия. Закрытие по Esc, оверлею или [action="close"] даёт null.
45
+ open(data = null) {
46
+ return new Promise(resolve => {
47
+ (this.#target == 'shown' ? this.#resolvers : this.#waiting).push(resolve);
48
+ this.show(data);
49
+ });
50
+ }
51
+
52
+ #emit(name, data) {
53
+ this.content?.dispatchEvent(new CustomEvent(`modal:${name}`, { bubbles: true, detail: { modal: this, data } }));
54
+ }
55
+
37
56
  clone(params) {
38
57
  let content = this.content.cloneNode(true);
39
58
  content.id = params.id ?? (content.id || 'modal').replace(/#+$/, '') + (params.suffix ?? '_copy');
@@ -66,6 +85,11 @@ export default class Modal {
66
85
 
67
86
  close_by_overlay: true,
68
87
  close_by_esc: true,
88
+ // После закрытия вернуть фокус элементу, который был активен до показа.
89
+ return_focus: true,
90
+ // false — окно не перекрывает страницу (уведомления): клики мимо контейнера
91
+ // уходят на страницу, прокрутка не блокируется, Esc его пропускает.
92
+ blocking: true,
69
93
  auto_close: -1,
70
94
 
71
95
  allow_interrupt: false,
@@ -148,13 +172,13 @@ export default class Modal {
148
172
  left: '0',
149
173
  right: '0',
150
174
  bottom: '0',
151
- overflowY: 'auto',
152
- overflowX: 'clip',
175
+ overflowY: this.#params.blocking ? 'auto' : 'visible',
176
+ overflowX: this.#params.blocking ? 'clip' : 'visible',
153
177
  display: 'flex',
154
178
  alignItems: 'flex-start',
155
179
  justifyContent: loc.includes('left') ? 'flex-start' : loc.includes('right') ? 'flex-end' : 'center',
156
180
  zIndex: ++this.#params.zIndex,
157
- pointerEvents: 'all',
181
+ pointerEvents: this.#params.blocking ? 'all' : 'none',
158
182
  transition: 'inherit'
159
183
  });
160
184
 
@@ -204,7 +228,8 @@ export default class Modal {
204
228
 
205
229
  let toggle = (params) => {
206
230
  params.before_func(params.data);
207
-
231
+ this.#emit(params.hide ? 'hide' : 'show', params.data);
232
+
208
233
  clearTimeout(timeout);
209
234
 
210
235
  this.modal.style.display = 'flex';
@@ -221,6 +246,14 @@ export default class Modal {
221
246
  if (params.hide) this.modal.style.display = 'none';
222
247
 
223
248
  params.after_func(params.data);
249
+ this.#emit(params.final, params.data);
250
+
251
+ if (params.hide) {
252
+ this.#restoreFocus();
253
+ let result = this.#result;
254
+ this.#result = null;
255
+ this.#resolvers.splice(0).forEach(resolve => resolve(result));
256
+ }
224
257
 
225
258
  // show(), пришедший во время hiding, выполняется после полного закрытия.
226
259
  if (params.hide && this.#pending_show) {
@@ -248,6 +281,13 @@ export default class Modal {
248
281
  Modal.#open = Modal.#open.filter(modal => modal !== this);
249
282
  Modal.#open.push(this);
250
283
  this.#target = 'shown';
284
+ this.#resolvers.push(...this.#waiting.splice(0));
285
+
286
+ // Фокус запоминается только при показе с нуля, не при прерванном закрытии.
287
+ if (this.#state == 'hidden') {
288
+ let active = document.activeElement;
289
+ this.#return_to = active && active !== document.body && !this.modal.contains(active) ? active : null;
290
+ }
251
291
 
252
292
  toggle({
253
293
  before_func: this.before_show,
@@ -258,7 +298,7 @@ export default class Modal {
258
298
  data
259
299
  });
260
300
 
261
- if (this.#params.overlay_scroll_lock && this.overlay) {
301
+ if (this.#params.overlay_scroll_lock && this.overlay && this.#params.blocking) {
262
302
  default_scroll_behavior = document.documentElement.style.scrollBehavior;
263
303
 
264
304
  body_inline_styles = document.body.style;
@@ -293,6 +333,9 @@ export default class Modal {
293
333
  };
294
334
 
295
335
  this.hide = (data = null) => {
336
+ // Отложенный show() отменён: ждущие его open() получают null.
337
+ if (this.#pending_show)
338
+ this.#waiting.splice(0).forEach(resolve => resolve(null));
296
339
  this.#pending_show = null;
297
340
 
298
341
  if (
@@ -301,6 +344,8 @@ export default class Modal {
301
344
  ) {
302
345
  Modal.#open = Modal.#open.filter(modal => modal !== this);
303
346
  this.#target = 'hidden';
347
+ // Esc и клик по оверлею передают событие — это не результат.
348
+ this.#result = data instanceof Event ? null : data;
304
349
 
305
350
  toggle({
306
351
  before_func: this.before_hide,
@@ -336,4 +381,15 @@ export default class Modal {
336
381
 
337
382
  this.on_init(this.#params);
338
383
  }
384
+
385
+ // Фокус возвращается, только если он остался в окне или ушёл на body: пользователь,
386
+ // успевший перейти в другое место, его не теряет.
387
+ #restoreFocus() {
388
+ let target = this.#return_to;
389
+ this.#return_to = null;
390
+ if (!this.#params.return_focus || !target?.isConnected) return;
391
+ let active = document.activeElement;
392
+ if (active && active !== document.body && !this.modal.contains(active)) return;
393
+ target.focus?.({ preventScroll: true });
394
+ }
339
395
  }