@cat-of-summer/st-script 1.3.2 → 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.
- package/README.md +2 -0
- package/dist/app/datepicker.esm.min.js +30 -0
- package/dist/app/datepicker.esm.min.js.map +7 -0
- package/dist/app/datepicker.min.js +30 -0
- package/dist/app/datepicker.min.js.map +7 -0
- package/dist/app/form.esm.min.js +1 -1
- package/dist/app/form.esm.min.js.map +2 -2
- package/dist/app/form.min.js +1 -1
- package/dist/app/form.min.js.map +2 -2
- package/dist/cut.esm.min.js +2 -0
- package/dist/cut.esm.min.js.map +7 -0
- package/dist/cut.min.js +2 -0
- package/dist/cut.min.js.map +7 -0
- package/dist/toggle.esm.min.js +1 -1
- package/dist/toggle.esm.min.js.map +3 -3
- package/dist/toggle.min.js +1 -1
- package/dist/toggle.min.js.map +3 -3
- package/package.json +1 -1
- package/src/app/datepicker/_calendar.js +113 -0
- package/src/app/datepicker/index.js +312 -0
- package/src/app/form/index.js +3 -0
- package/src/cut/_engine.js +61 -0
- package/src/cut/index.js +167 -0
- package/src/index.js +1 -0
- package/src/toggle/index.js +158 -10
package/package.json
CHANGED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
// Календарное ядро datepicker: сетка месяца, выбор даты и диапазона, разбор и формат.
|
|
2
|
+
// Чистые функции без DOM — общее для st-app (app/datepicker) и для обёрток в других фреймворках.
|
|
3
|
+
//
|
|
4
|
+
// Дата везде — строка ISO 'YYYY-MM-DD': сравнивается как строка, не зависит от часового пояса.
|
|
5
|
+
// Месяц — число 1–12.
|
|
6
|
+
|
|
7
|
+
export const MONTHS = ['Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь',
|
|
8
|
+
'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'];
|
|
9
|
+
export const MONTHS_GENITIVE = ['января', 'февраля', 'марта', 'апреля', 'мая', 'июня',
|
|
10
|
+
'июля', 'августа', 'сентября', 'октября', 'ноября', 'декабря'];
|
|
11
|
+
export const WEEKDAYS = ['Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб', 'Вс'];
|
|
12
|
+
|
|
13
|
+
const pad = (n, len = 2) => String(n).padStart(len, '0');
|
|
14
|
+
|
|
15
|
+
export const days_in_month = (year, month) => new Date(Date.UTC(year, month, 0)).getUTCDate();
|
|
16
|
+
|
|
17
|
+
// Настоящая дата: 31.02 и 29.02 невисокосного года — нет.
|
|
18
|
+
export const valid = (year, month, day) =>
|
|
19
|
+
Number.isInteger(year) && Number.isInteger(month) && Number.isInteger(day)
|
|
20
|
+
&& year >= 1 && year <= 9999 && month >= 1 && month <= 12
|
|
21
|
+
&& day >= 1 && day <= days_in_month(year, month);
|
|
22
|
+
|
|
23
|
+
export const iso = (year, month, day) => `${pad(year, 4)}-${pad(month)}-${pad(day)}`;
|
|
24
|
+
|
|
25
|
+
export const parse_iso = (value) => {
|
|
26
|
+
let m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(String(value ?? '').trim());
|
|
27
|
+
if (!m) return null;
|
|
28
|
+
let [year, month, day] = m.slice(1).map(Number);
|
|
29
|
+
return valid(year, month, day) ? { year, month, day } : null;
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
export const today = (now = new Date()) => iso(now.getFullYear(), now.getMonth() + 1, now.getDate());
|
|
33
|
+
|
|
34
|
+
// 'ДД.ММ.ГГГГ' ↔ ISO. Неполная или несуществующая дата — null.
|
|
35
|
+
export const from_display = (value) => {
|
|
36
|
+
let m = /^(\d{2})\.(\d{2})\.(\d{4})$/.exec(String(value ?? '').trim());
|
|
37
|
+
if (!m) return null;
|
|
38
|
+
let [day, month, year] = m.slice(1).map(Number);
|
|
39
|
+
return valid(year, month, day) ? iso(year, month, day) : null;
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
export const to_display = (value) => {
|
|
43
|
+
let d = parse_iso(value);
|
|
44
|
+
return d ? `${pad(d.day)}.${pad(d.month)}.${pad(d.year, 4)}` : '';
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
// '18 октября 2026' — подпись дня для скринридера.
|
|
48
|
+
export const label = (value) => {
|
|
49
|
+
let d = parse_iso(value);
|
|
50
|
+
return d ? `${d.day} ${MONTHS_GENITIVE[d.month - 1]} ${d.year}` : '';
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
export const title = (year, month) => `${MONTHS[month - 1]} ${year}`;
|
|
54
|
+
|
|
55
|
+
export const shift = (year, month, delta) => {
|
|
56
|
+
let index = year * 12 + (month - 1) + delta;
|
|
57
|
+
return { year: Math.floor(index / 12), month: index % 12 + 1 };
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
// Пустые границы не ограничивают.
|
|
61
|
+
export const in_bounds = (value, min, max) => !(min && value < min) && !(max && value > max);
|
|
62
|
+
|
|
63
|
+
// Причина, по которой дату нельзя выбрать: 'invalid' | 'min' | 'max' | null.
|
|
64
|
+
export const problem = (value, min, max) => {
|
|
65
|
+
if (!parse_iso(value)) return 'invalid';
|
|
66
|
+
if (min && value < min) return 'min';
|
|
67
|
+
if (max && value > max) return 'max';
|
|
68
|
+
return null;
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
// Сетка месяца: 6 недель с понедельника, 42 ячейки; дни соседних месяцев помечены other.
|
|
72
|
+
export const month_grid = (year, month, { from = null, to = null, min = null, max = null, now = today() } = {}) => {
|
|
73
|
+
let first = (new Date(Date.UTC(year, month - 1, 1)).getUTCDay() + 6) % 7;
|
|
74
|
+
let cells = [];
|
|
75
|
+
|
|
76
|
+
for (let i = 0; i < 42; i++) {
|
|
77
|
+
let date = new Date(Date.UTC(year, month - 1, 1 - first + i));
|
|
78
|
+
let value = iso(date.getUTCFullYear(), date.getUTCMonth() + 1, date.getUTCDate());
|
|
79
|
+
let range = !!(from && to);
|
|
80
|
+
|
|
81
|
+
cells.push({
|
|
82
|
+
iso: value,
|
|
83
|
+
day: date.getUTCDate(),
|
|
84
|
+
label: label(value),
|
|
85
|
+
other: date.getUTCMonth() + 1 != month,
|
|
86
|
+
today: value == now,
|
|
87
|
+
disabled: !in_bounds(value, min, max),
|
|
88
|
+
selected: value == from || value == to,
|
|
89
|
+
in_range: range && value > from && value < to,
|
|
90
|
+
range_from: range && value == from,
|
|
91
|
+
range_to: range && value == to,
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
return cells;
|
|
96
|
+
};
|
|
97
|
+
|
|
98
|
+
// Следующий выбор по клику. Одиночная дата — заменяется. Диапазон: первый клик — начало,
|
|
99
|
+
// второй — конец (раньше начала — меняются местами), третий начинает заново.
|
|
100
|
+
export const choose = ({ from = null, to = null }, value, range = false) => {
|
|
101
|
+
if (!range || !from || to) return { from: value, to: null };
|
|
102
|
+
return value < from ? { from: value, to: from } : { from, to: value };
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
// Значение value: одиночная дата — 'YYYY-MM-DD', диапазон — 'YYYY-MM-DD/YYYY-MM-DD'
|
|
106
|
+
// (интервал ISO 8601). Пустые и несуществующие даты — null.
|
|
107
|
+
export const split = (value) => {
|
|
108
|
+
let [from, to] = String(value ?? '').split('/');
|
|
109
|
+
return { from: parse_iso(from) ? from.trim() : null, to: parse_iso(to) ? to.trim() : null };
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
export const join = ({ from, to }, range = false) =>
|
|
113
|
+
range ? (from || to ? `${from ?? ''}/${to ?? ''}` : '') : from ?? '';
|
|
@@ -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
|
+
};
|
package/src/app/form/index.js
CHANGED
|
@@ -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
|
+
};
|
package/src/cut/index.js
ADDED
|
@@ -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
|
+
}
|