@cat-of-summer/st-script 1.7.0 → 1.8.0

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.
@@ -49,6 +49,12 @@ export default class Cookie {
49
49
  return null;
50
50
  }
51
51
 
52
+ // Проверяется наличие, а не get() === null: значение null тоже валидно (consent пишет именно его).
53
+ static has(name) {
54
+ name = encodeURIComponent(name) + '=';
55
+ return document.cookie.split(';').some(c => c.trim().startsWith(name));
56
+ }
57
+
52
58
  static delete(name, params = {}) {
53
59
  Cookie.set(name, '', {
54
60
  expires: 0,
@@ -65,11 +71,8 @@ export default class Cookie {
65
71
  ...params
66
72
  };
67
73
 
68
- // Проверяется наличие, а не get() === null: значение null тоже валидно (consent пишет именно его).
69
- let exists = () => document.cookie.split(';').some(c => c.trim().startsWith(encodeURIComponent(name) + '='));
70
-
71
74
  let interval = setInterval(() => {
72
- if (!exists()) {
75
+ if (!Cookie.has(name)) {
73
76
  Cookie.set(name, params.value, params);
74
77
 
75
78
  setTimeout(() => {
@@ -11,6 +11,8 @@ export default class Modal {
11
11
  #methods = {};
12
12
  #state = 'hidden';
13
13
  #pending_show = null;
14
+ // hide(), пришедший до конца анимации открытия: выполняется сразу после shown.
15
+ #pending_hide = null;
14
16
  // open(): промисы текущего показа и ждущие отложенного show().
15
17
  #resolvers = [];
16
18
  #waiting = [];
@@ -112,7 +114,11 @@ export default class Modal {
112
114
  ...params
113
115
  };
114
116
 
115
- let timeout;
117
+ // Таймеры раздельные: общий хэндл перезаписывался, и clearTimeout гасил не тот.
118
+ // pass_timer - конец анимации, auto_timer - auto_close, unlock_timer - снятие блокировки прокрутки.
119
+ let pass_timer, auto_timer, unlock_timer;
120
+ // Поколение прохода toggle(): кадры и таймер прерванного прохода видят, что устарели, и выходят.
121
+ let pass = 0;
116
122
  let body_inline_styles;
117
123
  let default_scroll_behavior;
118
124
  let locked = false;
@@ -246,19 +252,24 @@ export default class Modal {
246
252
  }, { signal });
247
253
 
248
254
  let toggle = (params) => {
255
+ let id = ++pass;
256
+
249
257
  params.before_func(params.data);
250
258
  this.#emit(params.hide ? 'hide' : 'show', params.data);
251
259
 
252
- clearTimeout(timeout);
260
+ clearTimeout(pass_timer);
253
261
 
254
262
  this.modal.style.display = 'flex';
255
263
 
256
264
  requestAnimationFrame(() => {
265
+ if (id !== pass) return;
257
266
  this.#state = params.process;
258
267
  this.modal.setAttribute('state', this.#state);
259
268
 
260
269
  requestAnimationFrame(() => {
261
- timeout = setTimeout(() => {
270
+ if (id !== pass) return;
271
+ pass_timer = setTimeout(() => {
272
+ if (id !== pass) return;
262
273
  this.#state = params.final;
263
274
  this.modal.setAttribute('state', this.#state);
264
275
 
@@ -281,6 +292,13 @@ export default class Modal {
281
292
  this.show(pending.data);
282
293
  }
283
294
 
295
+ // hide(), пришедший во время showing, выполняется после полного открытия.
296
+ if (!params.hide && this.#pending_hide) {
297
+ let pending = this.#pending_hide;
298
+ this.#pending_hide = null;
299
+ this.hide(pending.data);
300
+ }
301
+
284
302
  }, this.#params.duration * 1000);
285
303
  });
286
304
  });
@@ -288,6 +306,9 @@ export default class Modal {
288
306
  }
289
307
 
290
308
  this.show = (data = null) => {
309
+ // Побеждает последний вызов: show() отменяет отложенный hide(), окно остаётся открытым.
310
+ this.#pending_hide = null;
311
+
291
312
  if (this.#target == 'hidden' && this.#state != 'hidden' && !this.#params.allow_interrupt) {
292
313
  this.#pending_show = { data };
293
314
  return;
@@ -300,6 +321,8 @@ export default class Modal {
300
321
  Modal.#open = Modal.#open.filter(modal => modal !== this);
301
322
  Modal.#open.push(this);
302
323
  this.#target = 'shown';
324
+ // Прерванное закрытие не должно снять блокировку прокрутки у снова открытого окна.
325
+ clearTimeout(unlock_timer);
303
326
  this.#resolvers.push(...this.#waiting.splice(0));
304
327
 
305
328
  // Фокус запоминается только при показе с нуля, не при прерванном закрытии.
@@ -345,9 +368,9 @@ export default class Modal {
345
368
  }
346
369
 
347
370
  if (this.#params.auto_close > 0) {
348
- clearTimeout(timeout);
371
+ clearTimeout(auto_timer);
349
372
 
350
- timeout = setTimeout(() => {
373
+ auto_timer = setTimeout(() => {
351
374
  this.hide();
352
375
  }, this.#params.auto_close * 1000);
353
376
  }
@@ -360,12 +383,26 @@ export default class Modal {
360
383
  this.#waiting.splice(0).forEach(resolve => resolve(null));
361
384
  this.#pending_show = null;
362
385
 
386
+ // Окно ещё открывается (до первого кадра state остаётся прежним, затем showing):
387
+ // закрытие откладывается до shown, а не теряется. С allow_interrupt showing прерывается сразу.
388
+ if (
389
+ this.#target == 'shown' &&
390
+ this.#state != 'shown' &&
391
+ !(this.#params.allow_interrupt && this.#state == 'showing')
392
+ ) {
393
+ this.#pending_hide = { data };
394
+ return;
395
+ }
396
+
363
397
  if (
364
398
  this.#state == 'shown' ||
365
399
  (this.#params.allow_interrupt && this.#state == 'showing')
366
400
  ) {
367
401
  Modal.#open = Modal.#open.filter(modal => modal !== this);
368
402
  this.#target = 'hidden';
403
+ this.#pending_hide = null;
404
+ // Таймер auto_close от этого показа не должен закрыть следующий.
405
+ clearTimeout(auto_timer);
369
406
  // Esc и клик по оверлею передают событие — это не результат.
370
407
  this.#result = data instanceof Event ? null : data;
371
408
 
@@ -378,9 +415,9 @@ export default class Modal {
378
415
  data
379
416
  });
380
417
 
381
- clearTimeout(timeout);
418
+ clearTimeout(unlock_timer);
382
419
 
383
- timeout = setTimeout(unlock, this.#params.duration * 1000);
420
+ unlock_timer = setTimeout(unlock, this.#params.duration * 1000);
384
421
  }
385
422
  };
386
423
 
@@ -399,7 +436,10 @@ export default class Modal {
399
436
  };
400
437
 
401
438
  this.#teardown = () => {
402
- clearTimeout(timeout);
439
+ pass++;
440
+ clearTimeout(pass_timer);
441
+ clearTimeout(auto_timer);
442
+ clearTimeout(unlock_timer);
403
443
  unlock();
404
444
  };
405
445
 
@@ -434,6 +474,7 @@ export default class Modal {
434
474
  this.#teardown?.();
435
475
  Modal.#open = Modal.#open.filter(modal => modal !== this);
436
476
  this.#pending_show = null;
477
+ this.#pending_hide = null;
437
478
  [...this.#resolvers.splice(0), ...this.#waiting.splice(0)].forEach(resolve => resolve(null));
438
479
 
439
480
  disown(this.content, this);
@@ -15,6 +15,7 @@ export const RULES = {
15
15
  abbr: true, // сокращение — к следующему слову: «т. е.», «№ 5», «г. Москва»
16
16
  initials: true, // инициалы — к фамилии: «А. С. Пушкин», «Пушкин А. С.»
17
17
  last_word: true, // последнее слово прогона не остаётся на строке одно
18
+ last_word_min: 0, // last_word — только в прогонах от стольких слов; 0 — без порога
18
19
  max_chain: 14, // склеенная цепочка не длиннее стольких символов; 0 — без предела
19
20
  };
20
21
 
@@ -87,10 +88,12 @@ export function glue(parts, rules = RULES) {
87
88
 
88
89
  // join[w] — судьба промежутка перед куском w: true — клеить, false — нет, 'kept' — уже неразрывный
89
90
  let word = w => tokens[words[w]][0];
91
+ let last = words.length - 1;
92
+ let tail = rules.last_word && words.length >= rules.last_word_min;
90
93
  let join = words.map((_, w) => {
91
94
  if (!w) return false;
92
95
  if (UNBREAKABLE.test(tokens[words[w] - 1][0])) return 'kept';
93
- return rules.last_word && w == words.length - 1 || joins(word(w - 1), word(w), rules);
96
+ return tail && w == last || joins(word(w - 1), word(w), rules);
94
97
  });
95
98
 
96
99
  // Цепочка длиннее max_chain не влезет в узкую колонку. Справа налево: отпускается самая
@@ -121,6 +124,12 @@ export function glue(parts, rules = RULES) {
121
124
  }
122
125
  }
123
126
 
127
+ // last_word не забирает последнее место переноса: подпись «каждый год» должна уметь сложиться
128
+ // в две строки. Связи по другим правилам («в~доме», «2024~год») остаются.
129
+ if (tail && last > 0 && join[last] === true && !joins(word(last - 1), word(last), rules)
130
+ && join.slice(1, last).every(Boolean))
131
+ join[last] = false;
132
+
124
133
  join.forEach((glued, w) => {
125
134
  if (glued !== true) return;
126
135
  // промежуток целиком → один NBSP; символы-хвосты удаляются, длина частей может сократиться
@@ -142,11 +142,13 @@ export default class Typograf {
142
142
  own(el, this);
143
143
 
144
144
  // начальная обработка синхронно, если цель у экрана: без мигания сырого текста
145
- let st = { near: !this.#params.lazy || Typograf.#near(el), dirty: true };
145
+ // body и html всегда у экрана: при height: 100% их рамка уезжает при прокрутке, а содержимое — нет
146
+ let page = el === document.body || el === document.documentElement;
147
+ let st = { near: page || !this.#params.lazy || Typograf.#near(el), dirty: true };
146
148
  this.#states.set(el, st);
147
149
 
148
150
  if (!this.#params.live) this.#mo.observe(el, { childList: true, subtree: true, characterData: true });
149
- this.#io.observe(el);
151
+ if (!page) this.#io.observe(el);
150
152
  if (st.near) this.#apply(el);
151
153
  }
152
154