@cat-of-summer/st-script 1.0.2 → 1.0.4

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.
@@ -0,0 +1,825 @@
1
+ import { element, elements, expose, find, own } from '../_traits/hasInstanceSymbol.js';
2
+
3
+ export default class Mask {
4
+
5
+ static #SLOTS = { '0': /^[0-9]$/, 'a': /^\p{L}$/u, '*': /^[^\n]$/ };
6
+ static #CONFIG = ['target', 'mask'];
7
+ static #SELECTABLE = ['text', 'search', 'tel', 'url', 'password'];
8
+
9
+ static #unesc = str => str.replace(/\\(.)/g, '$1');
10
+ static #no_g = re => re.global ? new RegExp(re.source, re.flags.replace('g', '')) : re;
11
+
12
+ static #scan(str, from) {
13
+ let open = str[from], close = open == '{' ? '}' : ']', depth = 0;
14
+ for (let i = from; i < str.length; i++) {
15
+ let c = str[i];
16
+ if (c == '\\') { i++; continue; }
17
+ if (open == '[' && c == '{') {
18
+ if ((i = Mask.#scan(str, i)) < 0) return -1;
19
+ } else if (c == open) depth++;
20
+ else if (c == close && --depth == 0) return i;
21
+ }
22
+ return -1;
23
+ }
24
+
25
+ static #last_top(body, needle) {
26
+ let depth = 0, found = -1;
27
+ for (let i = 0; i < body.length; i++) {
28
+ if (body[i] == '\\') { i++; continue; }
29
+ if (body[i] == '{' || body[i] == '[') depth++;
30
+ else if (body[i] == '}' || body[i] == ']') depth--;
31
+ else if (depth == 0 && body.startsWith(needle, i)) found = i;
32
+ }
33
+ return found;
34
+ }
35
+
36
+ static #classify(body) {
37
+ let fail = () => {
38
+ console.warn('Некорректный блок маски', `{${body}}`);
39
+ return [...`{${body}}`].map(char => ({ type: 'literal', char }));
40
+ };
41
+
42
+ let semi = Mask.#last_top(body, ';');
43
+ if (semi > 0) {
44
+ let range = body.slice(semi + 1);
45
+ if (/^(\d+|\d*-\d*)$/.test(range) && range != '-') {
46
+ let [min, max] = /^\d+$/.test(range)
47
+ ? [+range, +range]
48
+ : range.split('-').map((n, i) => n === '' ? (i ? Infinity : 0) : +n);
49
+ return max < min ? fail()
50
+ : [{ type: 'repeat', children: Mask.compile(body.slice(0, semi)), min, max }];
51
+ }
52
+ }
53
+
54
+ if (body[0] == '{' && body.at(-1) == '}')
55
+ try {
56
+ return [{ type: 'slot', test: new RegExp(`^(?:${body.slice(1, -1)})$`, 'u') }];
57
+ } catch { return fail(); }
58
+
59
+ let arrow = Mask.#last_top(body, '=>');
60
+ if (arrow > 0) {
61
+ let from = Mask.#unesc(body.slice(0, arrow)), to = Mask.#unesc(body.slice(arrow + 2));
62
+ return from.length != 1 || !to ? fail() : [{ type: 'transform', from, to }];
63
+ }
64
+
65
+ return fail();
66
+ }
67
+
68
+ static compile(pattern) {
69
+ let nodes = [];
70
+
71
+ for (let i = 0; i < pattern.length; i++) {
72
+ let char = pattern[i], end;
73
+
74
+ if (char == '\\')
75
+ nodes.push({ type: 'literal', char: pattern[++i] ?? '\\' });
76
+ else if (char == '[' && (end = Mask.#scan(pattern, i)) >= 0) {
77
+ nodes.push({ type: 'optional', children: Mask.compile(pattern.slice(i + 1, end)) });
78
+ i = end;
79
+ } else if (char == '{' && (end = Mask.#scan(pattern, i)) >= 0) {
80
+ nodes.push(...Mask.#classify(pattern.slice(i + 1, end)));
81
+ i = end;
82
+ } else
83
+ nodes.push(Mask.#SLOTS[char] ? { type: 'slot', test: Mask.#SLOTS[char] } : { type: 'literal', char });
84
+ }
85
+
86
+ return nodes;
87
+ }
88
+
89
+ static #is_fixed(nodes) {
90
+ return nodes.every(node =>
91
+ node.type == 'literal' || node.type == 'slot'
92
+ || node.type == 'repeat' && node.min == node.max && Mask.#is_fixed(node.children));
93
+ }
94
+
95
+ static build(mask, base = {}) {
96
+ if (mask && typeof mask == 'object' && !Array.isArray(mask) && !(mask instanceof RegExp)
97
+ && mask.pattern == null && mask.filter == null)
98
+ return Object.entries(mask).flatMap(([key, m]) =>
99
+ Mask.build(m, base).map(def => ({ ...def, key })));
100
+
101
+ let defs = (Array.isArray(mask) ? mask : [mask]).map(m => {
102
+ if (typeof m == 'function') return { fn: m, base };
103
+ if (m instanceof RegExp) m = { filter: m };
104
+ if (typeof m == 'string') m = { pattern: m };
105
+
106
+ let nodes = m.pattern != null
107
+ ? Mask.compile(m.pattern)
108
+ : [{ type: 'repeat', min: 0, max: m.max_length ?? Infinity, greedy: true,
109
+ children: [{ type: 'slot', test: Mask.#no_g(m.filter) }] }];
110
+
111
+ return {
112
+ nodes,
113
+ fixed: m.pattern != null && Mask.#is_fixed(nodes),
114
+ valid: m.valid ? Mask.#no_g(m.valid) : (m.filter ? /./ : null),
115
+ filler: m.filler ?? base.filler,
116
+ before_char: m.before_char ?? base.before_char,
117
+ before_slot: m.before_slot ?? base.before_slot
118
+ };
119
+ });
120
+
121
+ defs.forEach((def, i) => def.key ??= i);
122
+ return defs;
123
+ }
124
+
125
+ static #filler(def, ordinal) {
126
+ let filler = def.filler ?? '_';
127
+ return filler[ordinal] ?? filler[filler.length - 1] ?? '_';
128
+ }
129
+
130
+ static #prepare(def, input_string, ctx) {
131
+ let chars = [...String(input_string ?? '')];
132
+ if (!def.before_char) return chars;
133
+
134
+ return chars.flatMap(char => {
135
+ let out = def.before_char(ctx?.input, { char });
136
+ if (out === false || out === '' || out === null) return [];
137
+ return typeof out == 'string' ? [...out] : [char];
138
+ });
139
+ }
140
+
141
+ static #takes(node, c, s) {
142
+ if (node.type == 'slot') return node.test.test(c);
143
+ if (node.type == 'transform') return node.from === c || s.input.slice(s.ip, s.ip + node.to.length).join('') === node.to;
144
+ if (node.type == 'repeat') return Mask.#consumes(node.children, c, s);
145
+ return false;
146
+ }
147
+
148
+ static #consumes(nodes, c, s, entry) {
149
+ for (let node of nodes) {
150
+ if (node.type == 'literal') {
151
+ if (!entry && node.char === c) return true;
152
+ continue;
153
+ }
154
+ if (node.type == 'optional' || node.type == 'repeat' && node.min == 0) {
155
+ if (Mask.#consumes(node.children, c, s, entry)) return true;
156
+ continue;
157
+ }
158
+ return Mask.#takes(node, c, s);
159
+ }
160
+ return entry ? nodes.some(node => node.type == 'literal' && node.char === c) : false;
161
+ }
162
+
163
+ static #accept(s, text, fmt_text, kind = 'char', ordinal = null) {
164
+ s.units.push({
165
+ kind, ordinal,
166
+ stream_start: s.stream.length, stream_end: s.stream.length + text.length,
167
+ fmt_start: s.formatted.length, fmt_end: s.formatted.length + fmt_text.length
168
+ });
169
+ s.stream += text;
170
+ if (kind == 'char') s.raw += text;
171
+ if (ordinal != null) s.cells[ordinal] = kind == 'char' ? text : null;
172
+ s.formatted += fmt_text;
173
+ }
174
+
175
+ static #stop(s) {
176
+ if (s.stop_fmt < 0) s.stop_fmt = s.formatted.length + s.tail.length;
177
+ }
178
+
179
+ static #walk(nodes, s, def) {
180
+ for (let i = 0; i < nodes.length; i++) {
181
+ let node = nodes[i];
182
+
183
+ if (node.type == 'literal') {
184
+ if (s.done) s.ph += node.char;
185
+ else if (s.ip < s.input.length) {
186
+ if (s.input[s.ip] === node.char) {
187
+ s.ip++;
188
+ s.consumed++;
189
+ Mask.#accept(s, node.char, node.char, 'literal');
190
+ } else
191
+ s.formatted += node.char;
192
+ } else s.tail += node.char;
193
+
194
+ } else if (node.type == 'slot') {
195
+ let ordinal = s.ordinal++, filler = Mask.#filler(def, ordinal);
196
+ if (s.done) {
197
+ s.ph_slots.push({ fmt: s.formatted.length + s.tail.length + s.ph.length, node });
198
+ s.ph += filler;
199
+ continue;
200
+ }
201
+ let no_fix = false;
202
+ for (;;) {
203
+ if (s.ip >= s.input.length) {
204
+ s.complete = false;
205
+ s.done = true;
206
+ Mask.#stop(s);
207
+ s.ph_slots.push({ fmt: s.formatted.length + s.tail.length, node });
208
+ s.ph += filler;
209
+ break;
210
+ }
211
+ let c = s.input[s.ip];
212
+ if (node.test.test(c)) {
213
+ if (def.before_slot && !no_fix) {
214
+ let out = def.before_slot(s.ctx?.input,
215
+ { char: c, slot: ordinal, cells: s.cells, raw: s.raw, node });
216
+ if (out === false) { s.ip++; continue; }
217
+ if (typeof out == 'string' && out !== c) {
218
+ s.input.splice(s.ip, 1, ...out);
219
+ no_fix = true;
220
+ continue;
221
+ }
222
+ }
223
+ Mask.#accept(s, c, c, 'char', ordinal);
224
+ } else if (c === filler) {
225
+ s.complete = false;
226
+ Mask.#accept(s, c, c, 'hole', ordinal);
227
+ } else { s.ip++; continue; }
228
+ s.ip++;
229
+ s.consumed++;
230
+ break;
231
+ }
232
+
233
+ } else if (node.type == 'transform') {
234
+ if (s.done) { s.ph += node.to; continue; }
235
+ for (;;) {
236
+ if (s.ip >= s.input.length) {
237
+ s.complete = false;
238
+ s.done = true;
239
+ Mask.#stop(s);
240
+ s.ph += node.to;
241
+ break;
242
+ }
243
+ if (s.input.slice(s.ip, s.ip + node.to.length).join('') === node.to)
244
+ s.ip += node.to.length, s.consumed += node.to.length;
245
+ else if (s.input[s.ip] === node.from)
246
+ s.ip++, s.consumed++;
247
+ else { s.ip++; continue; }
248
+ Mask.#accept(s, node.to, node.to);
249
+ break;
250
+ }
251
+
252
+ } else if (node.type == 'repeat') {
253
+ if (s.done) {
254
+ for (let k = 0; k < node.min; k++) Mask.#walk(node.children, s, def);
255
+ continue;
256
+ }
257
+ let count = 0;
258
+ while (count < node.max) {
259
+ if (s.ip >= s.input.length) {
260
+ if (count < node.min) {
261
+ s.complete = false;
262
+ s.done = true;
263
+ Mask.#stop(s);
264
+ for (let k = count; k < node.min; k++) Mask.#walk(node.children, s, def);
265
+ } else Mask.#stop(s);
266
+ break;
267
+ }
268
+ if (!Mask.#consumes(node.children, s.input[s.ip], s)) {
269
+ if (!node.greedy && count >= node.min) break;
270
+ s.ip++;
271
+ continue;
272
+ }
273
+ let before = s.ip;
274
+ Mask.#walk(node.children, s, def);
275
+ if (s.done) {
276
+ for (let k = count + 1; k < node.min; k++) Mask.#walk(node.children, s, def);
277
+ break;
278
+ }
279
+ if (s.ip === before) break;
280
+ count++;
281
+ }
282
+
283
+ } else if (node.type == 'optional') {
284
+ if (s.done) continue;
285
+ let rest = nodes.slice(i + 1), entered = false;
286
+ while (s.ip < s.input.length) {
287
+ let c = s.input[s.ip];
288
+ if (Mask.#consumes(node.children, c, s, true)) {
289
+ entered = true;
290
+ Mask.#walk(node.children, s, def);
291
+ break;
292
+ }
293
+ if (Mask.#consumes(rest, c, s)) break;
294
+ s.ip++;
295
+ }
296
+ if (!entered && s.ip >= s.input.length) Mask.#stop(s);
297
+ }
298
+ }
299
+ }
300
+
301
+ static run(def, input_string, ctx) {
302
+ let s = {
303
+ input: Mask.#prepare(def, input_string, ctx),
304
+ ctx,
305
+ ip: 0,
306
+ stream: '', raw: '', formatted: '', tail: '', ph: '',
307
+ ph_slots: [], units: [], cells: [],
308
+ consumed: 0, ordinal: 0,
309
+ complete: true, done: false, stop_fmt: -1
310
+ };
311
+
312
+ Mask.#walk(def.nodes, s, def);
313
+ if (s.stop_fmt < 0) s.stop_fmt = s.formatted.length;
314
+ if (def.valid) s.complete = s.complete && def.valid.test(s.raw);
315
+
316
+ return {
317
+ stream: s.stream, raw: s.raw, formatted: s.formatted, tail: s.tail,
318
+ ph: s.ph, ph_slots: s.ph_slots, complete: s.complete, consumed: s.consumed,
319
+ units: s.units, cells: s.cells, stop_fmt: s.stop_fmt
320
+ };
321
+ }
322
+
323
+ static run_all(defs, input_string, ctx = {}) {
324
+ let resolved = [];
325
+ ctx = { ...ctx, stream: String(input_string ?? '') };
326
+ for (let def of defs)
327
+ def.fn ? resolved.push(...Mask.build(def.fn(ctx), def.base).map(d => ({ ...d, key: def.key ?? d.key })))
328
+ : resolved.push(def);
329
+
330
+ let best = null;
331
+ for (let def of resolved) {
332
+ let result = Mask.run(def, input_string, ctx);
333
+ if (!best
334
+ || result.consumed > best.result.consumed
335
+ || result.consumed == best.result.consumed && result.complete && !best.result.complete)
336
+ best = { result, def, mask_id: def.key };
337
+ }
338
+ return best;
339
+ }
340
+
341
+ static render(result, placeholder) {
342
+ if (placeholder == 'always') return result.formatted + result.tail + result.ph;
343
+ if (placeholder === false) return result.formatted;
344
+ return result.formatted + result.tail;
345
+ }
346
+
347
+ static caret_for(result, stream_pos) {
348
+ for (let unit of result.units) {
349
+ if (unit.kind == 'literal') continue;
350
+ if (stream_pos <= unit.stream_start || stream_pos < unit.stream_end)
351
+ return unit.fmt_start;
352
+ }
353
+ return result.stop_fmt;
354
+ }
355
+
356
+ static #layout(def) {
357
+ let layout = Mask.run(def, ''), part = 0;
358
+ layout.slots = layout.ph_slots;
359
+ layout.parts = layout.slots.map((slot, i) =>
360
+ i && slot.fmt > layout.slots[i - 1].fmt + 1 ? ++part : part);
361
+ layout.template = Mask.render(layout, 'always');
362
+ return layout;
363
+ }
364
+
365
+ #params = {};
366
+ #methods = {};
367
+ #defs = null;
368
+ #states = new WeakMap();
369
+ #inputs = [];
370
+
371
+ static find = find;
372
+
373
+ get params() { return this.#params; }
374
+
375
+ get value() { return this.#inputs.map(input => input.value); }
376
+
377
+ clone(params) {
378
+ return new Mask({
379
+ ...this.#params,
380
+ ...this.#methods,
381
+ ...params,
382
+ parent: this
383
+ });
384
+ }
385
+
386
+ constructor(params) {
387
+ params = {
388
+ target: 'input[mask]',
389
+ mask: null,
390
+ filler: '_',
391
+ placeholder: true,
392
+ flow: true,
393
+ rewrite: false,
394
+ caret: true,
395
+
396
+ before_init: () => {},
397
+ on_init: () => {},
398
+ before_char: () => {},
399
+ before_slot: () => {},
400
+ before_input: () => {},
401
+ on_input: () => {},
402
+ before_paste: () => {},
403
+ on_paste: () => {},
404
+ on_accept: () => {},
405
+ on_complete: () => {},
406
+ on_incomplete: () => {},
407
+ on_mask_change: () => {},
408
+
409
+ ...params
410
+ };
411
+
412
+ for (let [key, value] of Object.entries(params))
413
+ if (typeof value == "function" && !Mask.#CONFIG.includes(key)) {
414
+ this[key] = value.bind(this);
415
+
416
+ this.#methods[key] = value;
417
+ } else
418
+ this.#params[key] = value;
419
+
420
+ this.before_init(this.#params);
421
+
422
+ if (this.#params.mask != null)
423
+ this.#defs = Mask.build(this.#params.mask, this.#base());
424
+
425
+ for (let input of elements(this.#params.target))
426
+ this.#bind(input);
427
+
428
+ this.on_init(this.#params);
429
+ }
430
+
431
+ raw(target = this.#only()) {
432
+ return this.#states.get(element(target))?.result?.raw ?? '';
433
+ }
434
+
435
+ state(target = this.#only()) {
436
+ let input = element(target), st = this.#states.get(input);
437
+ return st?.result ? this.#state_of(input, st) : null;
438
+ }
439
+
440
+ set(target, value) {
441
+ if (arguments.length < 2) [target, value] = [this.#only(), target];
442
+
443
+ for (let input of elements(target))
444
+ if (this.#states.has(input))
445
+ this.#reconcile(input, String(value ?? ''), { prefix: String(value ?? '') });
446
+ }
447
+
448
+ clear(target = this.#inputs) { this.set(target, ''); }
449
+
450
+ #only() {
451
+ if (this.#inputs.length != 1)
452
+ throw new Error(`Mask: маска привязана к ${this.#inputs.length} полям — укажите поле явно`);
453
+
454
+ return this.#inputs[0];
455
+ }
456
+
457
+ set_mask(mask, target = null) {
458
+ let defs = Mask.build(mask, this.#base());
459
+ if (!target) this.#defs = defs;
460
+
461
+ for (let input of (target ? elements(target) : this.#inputs)) {
462
+ let st = this.#states.get(input);
463
+ if (!st) continue;
464
+ st.defs = defs;
465
+ st.run = null;
466
+ this.#reconcile(input, st.stream, {});
467
+ }
468
+ }
469
+
470
+ #base() {
471
+ return {
472
+ filler: this.#params.filler,
473
+ before_char: this.before_char,
474
+ before_slot: this.before_slot
475
+ };
476
+ }
477
+
478
+ #bind(input) {
479
+ if (find(input)) throw new Error("Маска уже привязана к этому полю");
480
+ own(input, this);
481
+
482
+ if (!Mask.#SELECTABLE.includes(input.type))
483
+ console.warn(`Mask: поле type="${input.type}" не поддерживает управление кареткой — используйте type="text" или "tel"`, input);
484
+
485
+ let defs = this.#defs ?? (input.getAttribute('mask') ? Mask.build(input.getAttribute('mask'), this.#base()) : null);
486
+ if (!defs) {
487
+ console.warn('Mask: для поля не задана маска (ни в params.mask, ни в атрибуте mask)', input);
488
+ return;
489
+ }
490
+
491
+ let st = { defs, def: null, stream: '', result: null, mask_id: null, rendered: '', run: null, composing: false, handled: false };
492
+ this.#states.set(input, st);
493
+ this.#inputs.push(input);
494
+
495
+ expose(input, {
496
+ raw: () => this.raw(input),
497
+ state: () => this.state(input),
498
+ set: value => this.set(input, value),
499
+ clear: () => this.clear(input),
500
+ set_mask: mask => this.set_mask(mask, input)
501
+ });
502
+
503
+ let hide = () => this.#params.caret == 'hide'
504
+ && input.style.setProperty('caret-color', 'transparent', 'important');
505
+ hide();
506
+
507
+ input.addEventListener('beforeinput', event => this.#before(input, event));
508
+
509
+ if (this.#params.caret !== true) {
510
+ let pin = () => this.#pin(input);
511
+ for (let event of ['selectionchange', 'click', 'keyup', 'select'])
512
+ input.addEventListener(event, pin);
513
+ }
514
+
515
+ let refresh = () => {
516
+ if (st.handled) { st.handled = false; return; }
517
+ if (st.composing) return;
518
+ this.#refresh(input);
519
+ };
520
+ input.addEventListener('input', refresh);
521
+ input.addEventListener('change', refresh);
522
+
523
+ input.addEventListener('compositionstart', () => st.composing = true);
524
+ input.addEventListener('compositionend', () => { st.composing = false; this.#refresh(input); });
525
+
526
+ input.addEventListener('focus', () => {
527
+ hide();
528
+ this.#reconcile(input, st.stream, { prefix: st.stream, silent: true });
529
+ });
530
+ input.addEventListener('blur', () => { st.run = null; this.#reconcile(input, st.stream, { silent: true }); });
531
+
532
+ input.closest('form')?.addEventListener('reset', () => queueMicrotask(() => this.#refresh(input)));
533
+
534
+ this.#reconcile(input, input.value, { silent: true });
535
+ }
536
+
537
+ #before(input, event) {
538
+ let st = this.#states.get(input);
539
+ let type = event.inputType ?? 'insertText';
540
+
541
+ if (event.isComposing || type == 'insertCompositionText' || type == 'deleteCompositionText') {
542
+ st.composing = true;
543
+ return;
544
+ }
545
+
546
+ if (type == 'historyUndo' || type == 'historyRedo') return;
547
+
548
+ let start = input.selectionStart ?? 0, end = input.selectionEnd ?? start;
549
+
550
+ if (this.#params.caret !== true && st.result && !(start == 0 && end == input.value.length))
551
+ start = end = this.#tail_of(input, st, start);
552
+
553
+ event.preventDefault();
554
+ st.handled = true;
555
+
556
+ let is_delete = type.startsWith('delete');
557
+ let insert = '';
558
+
559
+ if (!is_delete) {
560
+ if (type == 'insertLineBreak' || type == 'insertParagraph') return;
561
+ insert = event.data ?? event.dataTransfer?.getData('text/plain') ?? '';
562
+
563
+ if (type == 'insertFromPaste') {
564
+ let out = this.before_paste(input, insert);
565
+ if (out === false) return;
566
+ if (typeof out == 'string') insert = out;
567
+ }
568
+ }
569
+
570
+ if (this.before_input(input, { type, insert, start, end }) === false) return;
571
+
572
+ this.#params.placeholder == 'always' && st.def?.fixed
573
+ ? this.#grid(input, type, start, end, is_delete ? '' : insert)
574
+ : this.#edit(input, start, end, is_delete ? '' : insert, type);
575
+
576
+ if (type == 'insertFromPaste') this.on_paste(input, this.#state_of(input, st));
577
+ }
578
+
579
+ #edit(input, fmt_start, fmt_end, insert, type) {
580
+ let st = this.#states.get(input);
581
+ let units = st.result?.units ?? [];
582
+ let del_start, del_end, unit;
583
+
584
+ if (fmt_start != fmt_end) {
585
+ let hit = units.filter(u => u.fmt_start < fmt_end && u.fmt_end > fmt_start);
586
+ del_start = hit.length ? hit[0].stream_start : this.#stream_pos(units, fmt_start);
587
+ del_end = hit.length ? hit.at(-1).stream_end : del_start;
588
+ } else if (!type.startsWith('delete'))
589
+ del_start = del_end = this.#stream_pos(units, fmt_start);
590
+ else {
591
+ if (type.includes('Forward'))
592
+ unit = units.find(u => u.fmt_end > fmt_start && u.kind != 'literal')
593
+ ?? units.find(u => u.fmt_end > fmt_start);
594
+ else {
595
+ let literal;
596
+ for (let u of units)
597
+ if (u.fmt_start < fmt_start) u.kind == 'literal' ? literal = u : unit = u;
598
+ unit ??= literal;
599
+ }
600
+ if (!unit) return;
601
+ del_start = unit.stream_start;
602
+ del_end = unit.stream_end;
603
+ }
604
+
605
+ let prefix = st.stream.slice(0, del_start) + insert;
606
+ this.#reconcile(input, prefix + st.stream.slice(del_end), { prefix });
607
+ }
608
+
609
+ #grid(input, type, fmt_start, fmt_end, insert) {
610
+ let st = this.#states.get(input), def = st.def;
611
+ let layout = def.layout ??= Mask.#layout(def);
612
+ let slots = layout.slots, parts = layout.parts, n = slots.length;
613
+ let flow = this.#params.flow, rewrite = this.#params.rewrite;
614
+
615
+ let cells = Array.from({ length: n }, (_, i) => st.result?.cells?.[i] ?? null);
616
+
617
+ let at = fmt => { let k = slots.findIndex(slot => slot.fmt >= fmt); return k < 0 ? n : k; };
618
+ let gap = i => layout.template.slice(slots[i - 1].fmt + 1, slots[i].fmt);
619
+ let k, anchor = null, restart = null;
620
+
621
+ if (fmt_start != fmt_end) {
622
+ k = at(fmt_start);
623
+ for (let i = k; i < n && slots[i].fmt < fmt_end; i++) cells[i] = null;
624
+ st.run = null;
625
+ } else if (!insert && type.startsWith('delete')) {
626
+ if (type.includes('Forward')) {
627
+ if ((k = at(fmt_start)) >= n) return;
628
+ let limit = parts[k];
629
+ while (k < n && cells[k] == null) k++;
630
+ if (k >= n || !flow && parts[k] != limit) return;
631
+ } else {
632
+ let edge = -1;
633
+ for (let i = 0; i < n; i++) if (slots[i].fmt < fmt_start) edge = i;
634
+ if (edge < 0) return;
635
+ k = edge;
636
+ while (k >= 0 && cells[k] == null) k--;
637
+ if (k < 0 || !flow && (parts[k] != parts[edge] || fmt_start > slots[edge].fmt + 1)) return;
638
+ }
639
+ cells[k] = null;
640
+ } else {
641
+ k = at(fmt_start);
642
+ if (k >= n && (k = cells.indexOf(null)) < 0) k = n;
643
+ anchor = this.#anchor_at(layout, k, fmt_start);
644
+
645
+ if (rewrite) {
646
+ let part = anchor ?? parts[Math.min(k, n - 1)];
647
+ if (st.run?.part !== part || st.run.k !== k || parts[k] !== part) restart = part;
648
+ }
649
+ }
650
+
651
+ anchor ??= k < n ? parts[k] : null;
652
+ let crossed = null;
653
+
654
+ for (let c of Mask.#prepare(def, insert, { input })) {
655
+ if (k >= n) {
656
+ if (restart == null) break;
657
+ k = parts.indexOf(restart);
658
+ }
659
+
660
+ if (!flow && parts[k] != anchor) {
661
+ if (gap(k).includes(c)) {
662
+ anchor = parts[k];
663
+ crossed = k;
664
+ restart = rewrite ? parts[k] : null;
665
+ continue;
666
+ }
667
+ if (restart == null) continue;
668
+ k = parts.indexOf(restart);
669
+ }
670
+
671
+ if (!slots[k].node.test.test(c)) {
672
+ let end = parts.lastIndexOf(parts[k]);
673
+ if (end + 1 < n && gap(end + 1).includes(c)) {
674
+ k = end + 1;
675
+ anchor = parts[k];
676
+ crossed = k;
677
+ restart = rewrite ? parts[k] : null;
678
+ }
679
+ continue;
680
+ }
681
+
682
+ if (restart != null) {
683
+ for (let i = 0; i < n; i++) if (parts[i] == restart) cells[i] = null;
684
+ k = parts.indexOf(restart);
685
+ anchor = restart;
686
+ restart = null;
687
+ }
688
+
689
+ cells[k++] = c;
690
+ }
691
+
692
+ let last = cells.reduce((acc, cell, i) => cell != null ? i : acc, -1);
693
+ let stream = cells.slice(0, last + 1).map((cell, i) => cell ?? Mask.#filler(def, i)).join('');
694
+
695
+ let pos = Math.min(Mask.run(def, stream.slice(0, k), { input }).stream.length, n);
696
+ let caret = pos < n ? slots[pos].fmt : slots[n - 1].fmt + 1;
697
+ if (!flow && insert && pos > 0 && pos < n && parts[pos] != parts[pos - 1])
698
+ caret = slots[pos - 1].fmt + 1;
699
+ if (crossed != null && k == crossed) caret = slots[crossed].fmt;
700
+
701
+ let kn = at(caret);
702
+ st.run = crossed != null ? null
703
+ : { part: this.#anchor_at(layout, kn, caret) ?? parts[Math.min(kn, n - 1)], k: kn };
704
+ this.#reconcile(input, stream, { caret_fmt: caret });
705
+ }
706
+
707
+ #pin(input) {
708
+ let st = this.#states.get(input);
709
+ if (document.activeElement !== input || !st?.result) return;
710
+
711
+ let start = input.selectionStart, end = input.selectionEnd;
712
+ if (start == null) return;
713
+
714
+ if (start !== end) {
715
+ if (start != 0 || end != input.value.length) input.setSelectionRange(0, input.value.length);
716
+ return;
717
+ }
718
+
719
+ if (start === st.caret) return;
720
+
721
+ let target = this.#tail_of(input, st, start);
722
+ if (start !== target) input.setSelectionRange(target, target);
723
+ st.caret = target;
724
+ }
725
+
726
+ #tail_of(input, st, fmt) {
727
+ let def = st.def;
728
+
729
+ if (this.#params.placeholder == 'always' && def?.fixed && !this.#params.flow) {
730
+ let layout = def.layout ??= Mask.#layout(def);
731
+ let { slots, parts } = layout;
732
+ let k = slots.findIndex(slot => slot.fmt >= fmt);
733
+ if (k < 0) k = slots.length - 1;
734
+
735
+ let part = this.#anchor_at(layout, k, fmt) ?? parts[k];
736
+ let first = parts.indexOf(part), last = parts.lastIndexOf(part);
737
+ for (let i = first; i <= last; i++)
738
+ if (st.result.cells?.[i] == null) return slots[i].fmt;
739
+
740
+ return slots[last].fmt + 1;
741
+ }
742
+
743
+ return Math.min(st.result.stop_fmt, input.value.length);
744
+ }
745
+
746
+ #anchor_at(layout, k, fmt) {
747
+ let { slots, parts } = layout;
748
+ return !this.#params.flow && k > 0 && k < slots.length
749
+ && parts[k] != parts[k - 1] && fmt == slots[k - 1].fmt + 1 ? parts[k - 1] : null;
750
+ }
751
+
752
+ #stream_pos(units, fmt) {
753
+ let pos = 0;
754
+ for (let unit of units)
755
+ if (unit.fmt_end <= fmt || unit.fmt_start < fmt) pos = unit.stream_end;
756
+ return pos;
757
+ }
758
+
759
+ #refresh(input) {
760
+ let st = this.#states.get(input);
761
+ if (input.value === st.rendered) return;
762
+
763
+ st.run = null;
764
+ let sel = input.selectionStart ?? input.value.length;
765
+ this.#reconcile(input, input.value, { prefix: input.value.slice(0, sel) });
766
+ }
767
+
768
+ #reconcile(input, stream_next, { prefix = null, caret_fmt = null, silent = false } = {}) {
769
+ let st = this.#states.get(input);
770
+ let best = Mask.run_all(st.defs, stream_next, { raw: st.result?.raw ?? '', value: input.value, input });
771
+ if (!best) return;
772
+
773
+ let { result, def, mask_id } = best;
774
+ let text = this.#text_for(input, result);
775
+
776
+ if (input.value !== text) input.value = text;
777
+ st.rendered = text;
778
+
779
+ if (caret_fmt == null && prefix != null && document.activeElement === input)
780
+ caret_fmt = Mask.caret_for(result, Mask.run(def, prefix, { input }).stream.length);
781
+ if (caret_fmt != null && document.activeElement === input) {
782
+ caret_fmt = Math.min(caret_fmt, text.length);
783
+ input.setSelectionRange(caret_fmt, caret_fmt);
784
+ st.caret = caret_fmt;
785
+ }
786
+
787
+ let prev = st.result, prev_id = st.mask_id;
788
+ st.result = result;
789
+ st.stream = result.stream;
790
+ st.def = def;
791
+ st.mask_id = mask_id;
792
+
793
+ input.setAttribute('mask_id', mask_id);
794
+ input.setAttribute('progress', result.raw.length);
795
+ input.setAttribute('is_complete', result.complete);
796
+
797
+ if (silent) return;
798
+
799
+ let state = this.#state_of(input, st);
800
+ this.on_input(input, state);
801
+ if (result.raw !== (prev?.raw ?? '')) this.on_accept(input, state);
802
+ if (result.complete && !prev?.complete) this.on_complete(input, state);
803
+ if (!result.complete && prev?.complete) this.on_incomplete(input, state);
804
+ if (prev && mask_id !== prev_id) this.on_mask_change(input, state);
805
+ }
806
+
807
+ #text_for(input, result) {
808
+ if (!result.stream) {
809
+ if (document.activeElement !== input) return '';
810
+ if (this.#params.placeholder == 'always') return Mask.render(result, 'always');
811
+ return this.#params.placeholder == false ? '' : Mask.render(result, true);
812
+ }
813
+ return Mask.render(result, this.#params.placeholder);
814
+ }
815
+
816
+ #state_of(input, st) {
817
+ return {
818
+ raw: st.result?.raw ?? '',
819
+ formatted: input.value,
820
+ complete: st.result?.complete ?? false,
821
+ mask_id: st.mask_id,
822
+ progress: st.result?.raw.length ?? 0
823
+ };
824
+ }
825
+ }