@cat-of-summer/st-script 1.3.1 → 1.4.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.
@@ -0,0 +1,312 @@
1
+ import Mask from '../../mask/index.js';
2
+ import {
3
+ WEEKDAYS, month_grid, choose, title, shift, today, parse_iso, from_display, to_display,
4
+ problem, split, join,
5
+ } from './_calendar.js';
6
+
7
+ // Маска поля: дата набирается целыми группами, как в нативном input type=date.
8
+ const MASK = {
9
+ mask: '{dd:00}.{mm:00}.{yyyy:0000}',
10
+ placeholder: 'always',
11
+ edit: 'whole',
12
+ align: 'right',
13
+ pad: '0',
14
+ validate: false,
15
+ groups: {
16
+ dd: { filler: 'ДД', min: 1, max: 31 },
17
+ mm: { filler: 'ММ', min: 1, max: 12 },
18
+ yyyy: { filler: 'ГГГГ', min: 1 },
19
+ },
20
+ };
21
+
22
+ const ICON = '<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true"><rect x="3.5" y="5" width="17" height="15.5" rx="2"/><path d="M3.5 10h17M8 3v4M16 3v4"/></svg>';
23
+
24
+ // Календарь: поле с маской ДД.ММ.ГГГГ (или два — для диапазона), кнопка и всплывающая сетка
25
+ // месяца; inline — только сетка с кнопками "Сбросить" и "Выбрать". В форму уходит ISO из
26
+ // скрытых полей: name — одиночная дата, name_from и name_to — диапазон.
27
+ // Регистрация — App.create(datepicker); Mask входит в бандл, App — нет.
28
+ export default {
29
+ app: 'datepicker',
30
+
31
+ name: '',
32
+ range: false,
33
+ inline: false,
34
+ required: false,
35
+ // ISO 'YYYY-MM-DD'; диапазон — 'YYYY-MM-DD/YYYY-MM-DD'. Меняется при выборе.
36
+ value: '',
37
+ min: '',
38
+ max: '',
39
+ // id первого поля — для <label for>.
40
+ inputId: '',
41
+
42
+ messages: {
43
+ required: 'Заполните поле',
44
+ incomplete: 'Введите дату полностью',
45
+ invalid: 'Такой даты нет',
46
+ min: 'Дата не раньше {date}',
47
+ max: 'Дата не позже {date}',
48
+ order: 'Конец периода раньше начала',
49
+ },
50
+
51
+ // Выбор в сетке. В inline-режиме и на середине диапазона он ещё не значение.
52
+ from: null,
53
+ to: null,
54
+ year: 0,
55
+ month: 0,
56
+ is_open: false,
57
+ invalid: false,
58
+ days: [],
59
+ weekdays: WEEKDAYS,
60
+
61
+ get caption() {
62
+ return this.year ? title(this.year, this.month) : '';
63
+ },
64
+
65
+ template: `
66
+ <div class="datepicker" #class="{ 'datepicker--range': range, 'datepicker--inline': inline, 'datepicker--open': is_open, 'datepicker--invalid': invalid }">
67
+ <div class="datepicker__field" #show="!inline">
68
+ <input class="datepicker__input" datepicker-from type="text" inputmode="numeric" autocomplete="off" id="{{ inputId }}" required="{{ required }}">
69
+ <span class="datepicker__dash" #show="range" aria-hidden="true">—</span>
70
+ <input class="datepicker__input" datepicker-to type="text" inputmode="numeric" autocomplete="off" aria-label="Конец периода" #show="range" required="{{ required && range }}">
71
+ <button class="datepicker__toggle" type="button" aria-label="Открыть календарь" aria-haspopup="dialog" aria-expanded="{{ is_open }}" @click="toggle()">${ICON}</button>
72
+ </div>
73
+ <input type="hidden" datepicker-value="from" name="{{ name ? (range ? name + '_from' : name) : '' }}">
74
+ <input type="hidden" datepicker-value="to" name="{{ name && range ? name + '_to' : '' }}" disabled="{{ !range }}">
75
+ <div class="datepicker__popup" role="dialog" aria-label="Выбор даты" hidden="{{ !inline && !is_open }}">
76
+ <div class="datepicker__nav">
77
+ <button class="datepicker__prev" type="button" aria-label="Предыдущий месяц" @click="go(-1)">‹</button>
78
+ <span class="datepicker__caption" aria-live="polite">{{ caption }}</span>
79
+ <button class="datepicker__next" type="button" aria-label="Следующий месяц" @click="go(1)">›</button>
80
+ </div>
81
+ <div class="datepicker__grid">
82
+ <span class="datepicker__weekday" aria-hidden="true" #for="day in weekdays">{{ day }}</span>
83
+ <button class="datepicker__day" type="button" #for="cell in days" #key="$index"
84
+ #class="{ 'datepicker__day--other': cell.other, 'datepicker__day--today': cell.today, 'datepicker__day--selected': cell.selected, 'datepicker__day--in-range': cell.in_range, 'datepicker__day--range-from': cell.range_from, 'datepicker__day--range-to': cell.range_to }"
85
+ disabled="{{ cell.disabled }}" aria-pressed="{{ cell.selected }}" aria-label="{{ cell.label }}"
86
+ @click="pick(cell.iso)">{{ cell.day }}</button>
87
+ </div>
88
+ <div class="datepicker__buttons" #show="inline">
89
+ <button class="datepicker__reset" type="button" @click="clear()">Сбросить</button>
90
+ <button class="datepicker__apply" type="button" @click="apply()">Выбрать</button>
91
+ </div>
92
+ </div>
93
+ </div>`,
94
+
95
+ setup() {
96
+ // Свой массив на экземпляр: значение из конфига общее для всех <st-app app="datepicker">.
97
+ this.days = Array.from({ length: 42 }, () => ({
98
+ iso: '', day: 0, label: '', other: false, today: false, disabled: false,
99
+ selected: false, in_range: false, range_from: false, range_to: false,
100
+ }));
101
+ },
102
+
103
+ events: {
104
+ rendered: function() {
105
+ const self = this;
106
+
107
+ self._abort?.abort();
108
+ self._abort = new AbortController();
109
+ const signal = self._abort.signal;
110
+
111
+ self._inputs = [self.querySelector('[datepicker-from]'), self.querySelector('[datepicker-to]')];
112
+ self._hidden = [self.querySelector('[datepicker-value="from"]'), self.querySelector('[datepicker-value="to"]')];
113
+ self._mask = new Mask({ target: self._inputs, ...MASK });
114
+ self._initial = self.value;
115
+
116
+ for (const input of self._inputs) {
117
+ input.addEventListener('input', () => self._typed(), { signal });
118
+ input.addEventListener('blur', () => { self.invalid = !self._valid(); }, { signal });
119
+ input.addEventListener('invalid', () => { self.invalid = true; }, { signal });
120
+ }
121
+
122
+ self.addEventListener('keydown', e => {
123
+ if (e.key == 'Escape' && self.is_open) {
124
+ self.close();
125
+ self.querySelector('.datepicker__toggle')?.focus();
126
+ }
127
+ }, { signal });
128
+
129
+ // Слушатель на document снимается сам, когда календарь пропал из DOM.
130
+ document.addEventListener('click', e => {
131
+ if (!self.isConnected) return self._abort.abort();
132
+ if (self.is_open && !e.composedPath().includes(self)) self.close();
133
+ }, { signal });
134
+
135
+ // Нативный reset не трогает скрытые поля (их value — атрибут), а маска чистит видимые
136
+ // в своей микрозадаче: начальное значение возвращаем следующей задачей, после неё.
137
+ self.closest('form')?.addEventListener('reset', () => setTimeout(() => {
138
+ self._load(self._initial);
139
+ self.invalid = false;
140
+ }), { signal });
141
+
142
+ // Значение из кода или атрибута :value; своё _write совпадает с _value и пропускается.
143
+ if (!self._watching) self._watching = self.watch('value', value => {
144
+ if (value !== self._value) self._load(value);
145
+ });
146
+
147
+ self._load(self.value);
148
+ }
149
+ },
150
+
151
+ // Перечитать значение из скрытых полей: после form.fill() или записи value из кода.
152
+ refresh() {
153
+ let [from, to] = this._hidden.map(input => input.value);
154
+ this._load(this.range ? join({ from, to }, true) : from);
155
+ },
156
+
157
+ open() {
158
+ if (this.inline || this.is_open) return;
159
+ this._view(this.from);
160
+ this.is_open = true;
161
+ this.dispatchEvent('datepicker:open', null, { bubbles: true });
162
+ },
163
+
164
+ close() {
165
+ if (this.inline || !this.is_open) return;
166
+ this.is_open = false;
167
+ // Незаконченный диапазон не остаётся висеть в сетке.
168
+ this._select(split(this._value));
169
+ this.dispatchEvent('datepicker:close', null, { bubbles: true });
170
+ },
171
+
172
+ toggle() {
173
+ this.is_open ? this.close() : this.open();
174
+ },
175
+
176
+ go(delta) {
177
+ let { year, month } = shift(this.year, this.month, delta);
178
+ this.year = year;
179
+ this.month = month;
180
+ this._paint();
181
+ },
182
+
183
+ pick(date) {
184
+ let next = choose({ from: this.from, to: this.to }, date, this.range);
185
+ this._select(next);
186
+ if (this.inline || (this.range && !next.to)) return;
187
+ this._commit();
188
+ this.close();
189
+ },
190
+
191
+ apply() {
192
+ this._commit();
193
+ },
194
+
195
+ clear() {
196
+ this._select({ from: null, to: null });
197
+ this._commit();
198
+ this.close();
199
+ },
200
+
201
+ // Значение → сетка, поля и скрытые поля, без событий изменения.
202
+ _load(value) {
203
+ let { from, to } = split(value);
204
+ if (!this.range) to = null;
205
+ this._select({ from, to });
206
+ this._view(from);
207
+ this._write({ from, to });
208
+ this._emitted = this._value;
209
+ this._check();
210
+ },
211
+
212
+ _select({ from, to }) {
213
+ this.from = from;
214
+ this.to = to;
215
+ this._paint();
216
+ },
217
+
218
+ // Выбор → значение: поля, скрытые поля, value и события, как от пользователя.
219
+ _commit() {
220
+ let parts = { from: this.from, to: this.range ? this.to : null };
221
+ this._write(parts);
222
+ this._check();
223
+ this.invalid = !this._valid();
224
+ this._emit(parts);
225
+ },
226
+
227
+ _write({ from, to }, visible = true) {
228
+ this._value = join({ from, to }, this.range);
229
+ this.value = this._value;
230
+ this._hidden[0].value = from ?? '';
231
+ this._hidden[1].value = to ?? '';
232
+ if (!visible) return;
233
+
234
+ this._silent = true;
235
+ this._inputs.forEach((input, i) => this._mask.set(input, to_display(i ? to : from).replace(/\D/g, '')));
236
+ this._silent = false;
237
+ },
238
+
239
+ // События — только когда значение правда сменилось: набор по цифре даёт input на каждую.
240
+ _emit(parts) {
241
+ if (this._emitted === this._value) return;
242
+ this._emitted = this._value;
243
+
244
+ for (const input of this._hidden.filter(input => !input.disabled)) {
245
+ input.dispatchEvent(new Event('input', { bubbles: true }));
246
+ input.dispatchEvent(new Event('change', { bubbles: true }));
247
+ }
248
+ this.dispatchEvent('datepicker:change', { ...parts, value: this._value }, { bubbles: true });
249
+ },
250
+
251
+ // Набор с клавиатуры: полная и существующая дата в границах становится значением сразу.
252
+ _typed() {
253
+ if (this._silent) return;
254
+
255
+ let [from, to] = this._inputs.map(input => from_display(input.value));
256
+ if (from && problem(from, this.min, this.max)) from = null;
257
+ if (to && problem(to, this.min, this.max)) to = null;
258
+ if (!this.range) to = null;
259
+
260
+ this._write({ from, to }, false);
261
+ this._select({ from, to });
262
+ this._view(to ?? from);
263
+ this._check();
264
+ if (this.invalid) this.invalid = !this._valid();
265
+ this._emit({ from, to });
266
+ },
267
+
268
+ // Сообщения проверки на видимые поля: их видит форма и reportValidity().
269
+ _check() {
270
+ let [first, second] = this._inputs;
271
+ first.setCustomValidity(this._problem(first));
272
+ second.setCustomValidity(this.range ? this._problem(second) : '');
273
+
274
+ if (this.range && !first.validationMessage && !second.validationMessage) {
275
+ let [from, to] = this._inputs.map(input => from_display(input.value));
276
+ if (from && to && to < from) second.setCustomValidity(this.messages.order);
277
+ }
278
+ },
279
+
280
+ _problem(input) {
281
+ let state = this._mask.state(input);
282
+ if (!state || state.empty) return this.required ? this.messages.required : '';
283
+ if (!state.complete) return this.messages.incomplete;
284
+
285
+ let date = from_display(input.value);
286
+ let reason = date ? problem(date, this.min, this.max) : 'invalid';
287
+ if (!reason) return '';
288
+ return this.messages[reason].replace('{date}', to_display(reason == 'min' ? this.min : this.max));
289
+ },
290
+
291
+ _valid() {
292
+ return this._inputs.every(input => !input.validationMessage);
293
+ },
294
+
295
+ // Месяц на экране: месяц даты, иначе сегодняшний, прижатый к min/max.
296
+ _view(date) {
297
+ let now = today();
298
+ if (this.min && now < this.min) now = this.min;
299
+ if (this.max && now > this.max) now = this.max;
300
+ let { year, month } = parse_iso(date) ?? parse_iso(now);
301
+ this.year = year;
302
+ this.month = month;
303
+ this._paint();
304
+ },
305
+
306
+ // Ячейки правятся на месте: #for с #key="$index" переиспользует кнопки, фокус не теряется.
307
+ _paint() {
308
+ if (!this.year || this.days.length != 42) return;
309
+ let grid = month_grid(this.year, this.month, { from: this.from, to: this.to, min: this.min, max: this.max });
310
+ grid.forEach((cell, i) => Object.assign(this.days[i], cell));
311
+ },
312
+ };
@@ -128,6 +128,9 @@ export default {
128
128
  get form() {
129
129
  return this._form;
130
130
  },
131
+ get is_done() {
132
+ return !!this.form?.hidden && !!this.querySelector('[form-done]');
133
+ },
131
134
  fields(name = null) {
132
135
  if (!name)
133
136
  return Array.from(this.form.elements);
@@ -0,0 +1,61 @@
1
+ // Фигура с вырезами: путь из Figma → путь под реальный размер элемента. Чистые функции без DOM.
2
+ //
3
+ // Значение атрибута — "ширина высота | d": размер фрейма в px макета и путь Figma как есть
4
+ // (абсолютные M L H V C S Q Z). Кривые — скругления углов в пару px — заменяются отрезком
5
+ // до конечной точки.
6
+
7
+ export const parse = (value) => {
8
+ let [size, d] = String(value ?? '').split('|');
9
+ let [w, h] = (size ?? '').trim().split(/\s+/).map(Number);
10
+ if (!(w > 0 && h > 0) || !d) return null;
11
+
12
+ let points = [], x = 0, y = 0;
13
+
14
+ for (let [, cmd, args] of d.matchAll(/([MLHVZCSQ])([^MLHVZCSQ]*)/gi)) {
15
+ let nums = (args.match(/-?\d*\.?\d+(?:e-?\d+)?/gi) || []).map(Number);
16
+ switch (cmd.toUpperCase()) {
17
+ case 'M':
18
+ case 'L':
19
+ for (let i = 0; i + 1 < nums.length; i += 2) points.push([x = nums[i], y = nums[i + 1]]);
20
+ break;
21
+ case 'H':
22
+ for (let n of nums) points.push([x = n, y]);
23
+ break;
24
+ case 'V':
25
+ for (let n of nums) points.push([x, y = n]);
26
+ break;
27
+ case 'C':
28
+ for (let i = 0; i + 5 < nums.length; i += 6) points.push([x = nums[i + 4], y = nums[i + 5]]);
29
+ break;
30
+ case 'S':
31
+ case 'Q':
32
+ for (let i = 0; i + 3 < nums.length; i += 4) points.push([x = nums[i + 2], y = nums[i + 3]]);
33
+ break;
34
+ }
35
+ }
36
+
37
+ return points.length > 2 ? { w, h, points } : null;
38
+ };
39
+
40
+ // Каждая точка привязывается к ближнему краю: x левее середины фрейма считается от левого
41
+ // края, правее — от правого; так же по y. Вырезы сохраняют размер, прямые участки тянутся
42
+ // под реальный размер. k — px экрана на px макета (rem / scale): вырезы масштабируются
43
+ // вместе с вёрсткой на rem.
44
+ export const build = (shape, width, height, k = 1) => 'M' + shape.points.map(([x, y]) => {
45
+ let px = x <= shape.w / 2 ? x * k : width - (shape.w - x) * k;
46
+ let py = y <= shape.h / 2 ? y * k : height - (shape.h - y) * k;
47
+ return `${+px.toFixed(2)} ${+py.toFixed(2)}`;
48
+ }).join('L') + 'Z';
49
+
50
+ // Фигура для ширины окна: самый широкий брейкпоинт, чей min не больше width и для которого
51
+ // задана своя фигура; иначе — base. variants: { base, md: shape, … }, breakpoints: { md: 768, … }.
52
+ export const pick = (variants, breakpoints, width) => {
53
+ let best = variants.base, min = -1;
54
+ for (let [bp, shape] of Object.entries(variants)) {
55
+ let from = breakpoints[bp];
56
+ if (bp == 'base' || !shape || from == null || from > width || from < min) continue;
57
+ best = shape;
58
+ min = from;
59
+ }
60
+ return best;
61
+ };
@@ -0,0 +1,167 @@
1
+ import { elements, find, own, disown } from '../_traits/hasInstanceSymbol.js';
2
+ import { parse, build, pick } from './_engine.js';
3
+
4
+ const NS = 'http://www.w3.org/2000/svg';
5
+ const CALLBACKS = ['before_init', 'on_init', 'on_draw'];
6
+
7
+ // Фигуры с вырезанными углами по путям из Figma. Внутрь элемента первым ребёнком кладётся
8
+ // <svg class="cut-shape"><path/></svg> — фон и обводка (цвета задаёт CSS, st-style [cut]), — а сам
9
+ // элемент клипается тем же путём. Форма пересчитывается при смене размера элемента, брейкпоинта
10
+ // и атрибутов.
11
+ export default class Cut {
12
+
13
+ static #CONFIG = ['target'];
14
+
15
+ #params = {};
16
+ #methods = {};
17
+ #shapes = new Map();
18
+ #pending = new Set();
19
+ #frame = 0;
20
+ #abort = new AbortController();
21
+ #ro = new ResizeObserver(entries => this.#schedule(entries.map(e => e.target)));
22
+ #mo = new MutationObserver(records => {
23
+ for (let { target } of records) this.#read(target);
24
+ this.#schedule(records.map(r => r.target));
25
+ });
26
+
27
+ static find = find;
28
+
29
+ get params() { return this.#params; }
30
+
31
+ get elements() { return [...this.#shapes.keys()]; }
32
+
33
+ clone(params) {
34
+ return new Cut({ ...this.#params, ...this.#methods, ...params, parent: this });
35
+ }
36
+
37
+ constructor(params) {
38
+ params = {
39
+ target: '[cut]',
40
+ attribute: 'cut',
41
+ // Шкала st-style по умолчанию: фигура для брейкпоинта — атрибут cut-<ключ>, действует от min и шире.
42
+ breakpoints: { xs: 360, sm: 576, md: 768, lp: 1024, lg: 1280, dt: 1536, xl: 1920 },
43
+ // px макета в 1rem: координаты переводятся в rem и масштабируются вместе с вёрсткой.
44
+ // 0 — без масштаба, 1px макета = 1px экрана.
45
+ scale: 10,
46
+ ...Object.fromEntries(CALLBACKS.map(k => [k, () => {}])),
47
+ ...params
48
+ };
49
+
50
+ for (let [key, value] of Object.entries(params))
51
+ if (typeof value == 'function' && !Cut.#CONFIG.includes(key)) {
52
+ this[key] = value.bind(this);
53
+ this.#methods[key] = value;
54
+ } else
55
+ this.#params[key] = value;
56
+
57
+ this.before_init(this.#params);
58
+
59
+ let signal = this.#abort.signal, redraw = () => this.#schedule(this.elements);
60
+ for (let min of Object.values(this.#params.breakpoints))
61
+ matchMedia(`(min-width: ${min}px)`).addEventListener('change', redraw, { signal });
62
+
63
+ for (let el of elements(this.#params.target)) this.#bind(el);
64
+
65
+ this.on_init(this.#params);
66
+ }
67
+
68
+ #names() {
69
+ let a = this.#params.attribute;
70
+ return [a, ...Object.keys(this.#params.breakpoints).map(bp => `${a}-${bp}`)];
71
+ }
72
+
73
+ #bind(el) {
74
+ if (this.#shapes.has(el)) return;
75
+ let owner = find(el);
76
+ if (owner instanceof Cut && owner !== this) return;
77
+
78
+ own(el, this);
79
+
80
+ let svg = document.createElementNS(NS, 'svg');
81
+ let path = document.createElementNS(NS, 'path');
82
+ svg.classList.add('cut-shape');
83
+ svg.setAttribute('aria-hidden', 'true');
84
+ svg.setAttribute('preserveAspectRatio', 'none');
85
+ svg.append(path);
86
+ el.prepend(svg);
87
+
88
+ this.#shapes.set(el, { svg, path, clip: el.style.clipPath, variants: {} });
89
+ this.#read(el);
90
+ this.#draw(el);
91
+
92
+ this.#ro.observe(el);
93
+ this.#mo.observe(el, { attributes: true, attributeFilter: this.#names() });
94
+ }
95
+
96
+ #read(el) {
97
+ let data = this.#shapes.get(el);
98
+ if (!data) return;
99
+ let a = this.#params.attribute;
100
+ data.variants = { base: parse(el.getAttribute(a)) };
101
+ for (let bp of Object.keys(this.#params.breakpoints))
102
+ if (el.hasAttribute(`${a}-${bp}`)) data.variants[bp] = parse(el.getAttribute(`${a}-${bp}`));
103
+ }
104
+
105
+ // Пересчёт пачкой в кадре: ResizeObserver и смена брейкпоинта приходят на много элементов сразу.
106
+ #schedule(list) {
107
+ for (let el of list) this.#pending.add(el);
108
+ this.#frame ||= requestAnimationFrame(() => {
109
+ this.#frame = 0;
110
+ let batch = [...this.#pending];
111
+ this.#pending.clear();
112
+ batch.forEach(el => this.#draw(el));
113
+ });
114
+ }
115
+
116
+ #draw(el) {
117
+ let data = this.#shapes.get(el);
118
+ if (!data) return;
119
+
120
+ let shape = pick(data.variants, this.#params.breakpoints, innerWidth);
121
+ let { width, height } = el.getBoundingClientRect();
122
+ if (!shape || !width || !height) {
123
+ data.path.removeAttribute('d');
124
+ el.style.clipPath = data.clip;
125
+ return;
126
+ }
127
+
128
+ let scale = this.#params.scale;
129
+ let k = scale ? parseFloat(getComputedStyle(document.documentElement).fontSize) / scale : 1;
130
+ let d = build(shape, width, height, k);
131
+
132
+ data.path.setAttribute('d', d);
133
+ data.svg.setAttribute('viewBox', `0 0 ${width} ${height}`);
134
+ el.style.clipPath = `path("${d}")`;
135
+
136
+ this.on_draw(el, d);
137
+ }
138
+
139
+ // Перечитать атрибуты и перерисовать; новые элементы под target — взять под управление.
140
+ refresh(target = this.#params.target) {
141
+ for (let el of elements(target)) {
142
+ if (!this.#shapes.has(el)) { this.#bind(el); continue; }
143
+ this.#read(el);
144
+ this.#draw(el);
145
+ }
146
+ return this;
147
+ }
148
+
149
+ // Разобрать: снять наблюдатели и слушатели, убрать svg, вернуть прежний clip-path.
150
+ destroy() {
151
+ this.#abort.abort();
152
+ this.#ro.disconnect();
153
+ this.#mo.disconnect();
154
+ cancelAnimationFrame(this.#frame);
155
+ this.#frame = 0;
156
+ this.#pending.clear();
157
+
158
+ for (let [el, { svg, clip }] of this.#shapes) {
159
+ svg.remove();
160
+ el.style.clipPath = clip;
161
+ if (!el.getAttribute('style')) el.removeAttribute('style');
162
+ disown(el, this);
163
+ }
164
+
165
+ this.#shapes.clear();
166
+ }
167
+ }
package/src/index.js CHANGED
@@ -14,3 +14,4 @@ export { default as Toggle } from './toggle/index.js';
14
14
  export { default as Typograf } from './typograf/index.js';
15
15
  export { default as Uploader } from './uploader/index.js';
16
16
  export { default as Validator } from './validator/index.js';
17
+ export { default as Cut } from './cut/index.js';
@@ -212,6 +212,12 @@ function stop(s) {
212
212
  if (s.stop_fmt < 0) s.stop_fmt = s.formatted.length + s.tail.length;
213
213
  }
214
214
 
215
+ // Символ входа отброшен: не подошёл узлу, на котором стоит разбор. slot - номер слота, если отказал слот
216
+ function skip(s, slot = null) {
217
+ s.rejected.push({ at: s.ip, slot });
218
+ s.ip++;
219
+ }
220
+
215
221
  function exhaust(s) {
216
222
  s.complete = false;
217
223
  s.done = true;
@@ -262,7 +268,7 @@ function walk(nodes, s, def) {
262
268
  if (def.before_slot && !no_fix) {
263
269
  let out = def.before_slot(s.ctx?.input,
264
270
  { char: c, slot: ordinal, cells: s.cells, raw: s.raw, node });
265
- if (out === false) { s.ip++; continue; }
271
+ if (out === false) { skip(s, ordinal); continue; }
266
272
  if (typeof out == 'string' && out !== c) {
267
273
  s.input.splice(s.ip, 1, ...out);
268
274
  no_fix = true;
@@ -270,10 +276,10 @@ function walk(nodes, s, def) {
270
276
  }
271
277
  }
272
278
  accept(s, c, c, 'char', ordinal, group);
273
- } else if (c === fill) {
279
+ } else if (c === fill && s.ctx?.holes !== false) {
274
280
  s.complete = false;
275
281
  accept(s, c, c, 'hole', ordinal, group);
276
- } else { s.ip++; continue; }
282
+ } else { skip(s, ordinal); continue; }
277
283
  s.ip++;
278
284
  s.consumed++;
279
285
  break;
@@ -291,7 +297,7 @@ function walk(nodes, s, def) {
291
297
  s.ip += node.to.length, s.consumed += node.to.length;
292
298
  else if (s.input[s.ip] === node.from)
293
299
  s.ip++, s.consumed++;
294
- else { s.ip++; continue; }
300
+ else { skip(s); continue; }
295
301
  if (!s.diverged) s.lead++;
296
302
  accept(s, node.to, node.to);
297
303
  break;
@@ -313,7 +319,7 @@ function walk(nodes, s, def) {
313
319
  }
314
320
  if (!consumes(node.children, s.input[s.ip], s)) {
315
321
  if (!node.greedy && count >= node.min) break;
316
- s.ip++;
322
+ skip(s);
317
323
  continue;
318
324
  }
319
325
  let before = s.ip;
@@ -337,7 +343,7 @@ function walk(nodes, s, def) {
337
343
  break;
338
344
  }
339
345
  if (consumes(rest, c, s)) break;
340
- s.ip++;
346
+ skip(s);
341
347
  }
342
348
  if (!entered && s.ip >= s.input.length) stop(s);
343
349
  }
@@ -418,20 +424,38 @@ export function run(def, input_string, ctx) {
418
424
  ph_slots: [], units: [], cells: [],
419
425
  groups: Object.fromEntries((def.names ?? []).map(name => [name, ''])), local: {},
420
426
  consumed: 0, lead: 0, diverged: false, ordinal: 0,
421
- complete: true, done: false, stop_fmt: -1
427
+ complete: true, done: false, stop_fmt: -1, rejected: []
422
428
  };
423
429
 
424
430
  walk(def.nodes, s, def);
425
431
  if (s.stop_fmt < 0) s.stop_fmt = s.formatted.length;
426
432
  if (def.valid) s.complete = s.complete && def.valid.test(s.raw);
427
433
 
434
+ // Почему отброшен символ: 'full' - шаблон кончился раньше ввода, 'literal' - разделитель
435
+ // шаблона не на своём месте (пробел, дефис), 'slot' - не подошёл позиции
436
+ let seps = def.seps ??= separators(def.nodes);
437
+ let rejected = s.rejected.map(({ at, slot }) =>
438
+ ({ at, char: s.input[at], slot, reason: seps.has(s.input[at]) ? 'literal' : 'slot' }));
439
+ for (let at = s.ip; at < s.input.length; at++)
440
+ rejected.push({ at, char: s.input[at], slot: null, reason: 'full' });
441
+
428
442
  return {
429
443
  stream: s.stream, raw: s.raw, formatted: s.formatted, tail: s.tail,
430
444
  ph: s.ph, ph_slots: s.ph_slots, complete: s.complete, consumed: s.consumed,
431
- lead: s.lead, units: s.units, cells: s.cells, groups: s.groups, stop_fmt: s.stop_fmt
445
+ lead: s.lead, units: s.units, cells: s.cells, groups: s.groups, stop_fmt: s.stop_fmt,
446
+ rejected
432
447
  };
433
448
  }
434
449
 
450
+ // Разделители шаблона - литералы, не входящие в код маски (SIGNIFICANT)
451
+ function separators(nodes, set = new Set()) {
452
+ for (let node of nodes) {
453
+ if (node.type == 'literal' && !SIGNIFICANT.test(node.char)) set.add(node.char);
454
+ if (node.children) separators(node.children, set);
455
+ }
456
+ return set;
457
+ }
458
+
435
459
  export function run_all(defs, input_string, ctx = {}) {
436
460
  let resolved = [];
437
461
  ctx = { ...ctx, stream: String(input_string ?? '') };