@viewstem/ui 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/LICENSE +21 -0
  2. package/README.ko.md +47 -0
  3. package/README.md +60 -2
  4. package/dist/BASECOAT-LICENSE.md +21 -0
  5. package/dist/basecoat-contracts.d.ts +2 -0
  6. package/dist/basecoat-contracts.js +358 -0
  7. package/dist/basecoat-controllers.js +1612 -0
  8. package/dist/behaviors.d.ts +29 -0
  9. package/dist/behaviors.js +1475 -0
  10. package/dist/browser.d.ts +2 -0
  11. package/dist/browser.js +2 -0
  12. package/dist/catalog-meta.d.ts +26 -0
  13. package/dist/catalog-meta.js +130 -0
  14. package/dist/component-context.d.ts +7 -0
  15. package/dist/component-context.js +10 -0
  16. package/dist/components.d.ts +2 -0
  17. package/dist/components.js +536 -0
  18. package/dist/data-table.d.ts +2 -0
  19. package/dist/data-table.js +260 -0
  20. package/dist/date-calendar.d.ts +4 -0
  21. package/dist/date-calendar.js +512 -0
  22. package/dist/dynamic-catalog.d.ts +2 -0
  23. package/dist/dynamic-catalog.js +118 -0
  24. package/dist/form-scroll-families.d.ts +7 -0
  25. package/dist/form-scroll-families.js +895 -0
  26. package/dist/index.d.ts +1 -0
  27. package/dist/index.js +12 -0
  28. package/dist/markup-families.d.ts +10 -0
  29. package/dist/markup-families.js +492 -0
  30. package/dist/menus.d.ts +8 -0
  31. package/dist/menus.js +427 -0
  32. package/dist/shadcn.d.ts +13 -0
  33. package/dist/shadcn.js +8 -0
  34. package/dist/slider-values.d.ts +9 -0
  35. package/dist/slider-values.js +43 -0
  36. package/dist/slider.d.ts +2 -0
  37. package/dist/slider.js +148 -0
  38. package/dist/static-catalog.d.ts +2 -0
  39. package/dist/static-catalog.js +87 -0
  40. package/dist/style-scope.d.ts +2 -0
  41. package/dist/style-scope.js +3 -0
  42. package/dist/styles.css +9573 -0
  43. package/dist/styles.css.d.ts +1 -0
  44. package/dist/support.json +1 -0
  45. package/dist/widget-families.d.ts +6 -0
  46. package/dist/widget-families.js +739 -0
  47. package/package.json +59 -4
@@ -0,0 +1,895 @@
1
+ import * as scrollArea from '@zag-js/scroll-area';
2
+ import { normalizeProps, spreadProps, VanillaMachine } from '@zag-js/vanilla';
3
+ import { uniqueId } from './behaviors.js';
4
+ import { emitFrom, readInputs } from './component-context.js';
5
+ import { styleScope } from './style-scope.js';
6
+ const propsOf = readInputs;
7
+ const part = (name) => `[data-vs-component="${name}"]`;
8
+ const find = (root, name) => root.querySelector(part(name));
9
+ const all = (root, name) => [...root.querySelectorAll(part(name))];
10
+ export const formScrollCatalog = {
11
+ 'MessageScroller.Provider': ['div', 'vs-ui-transparent'],
12
+ 'MessageScroller.Root': ['div', 'vs-message-scroller'],
13
+ 'MessageScroller.Viewport': ['div', 'vs-message-viewport'],
14
+ 'MessageScroller.Content': ['div', 'vs-message-content'],
15
+ 'MessageScroller.Item': ['div', 'vs-message-item'],
16
+ 'MessageScroller.Button': ['button', 'btn vs-message-scroll-button', { 'data-variant': 'secondary', 'data-size': 'icon-sm', 'data-active': 'false' }],
17
+ 'Questionnaire.Root': ['form', 'vs-questionnaire'],
18
+ 'Questionnaire.Actions': ['div', 'vs-questionnaire-actions'],
19
+ 'Questionnaire.Choice': ['label', 'vs-questionnaire-choice'],
20
+ 'Questionnaire.ChoiceDescription': ['span', 'vs-questionnaire-description'],
21
+ 'Questionnaire.Choices': ['div', 'vs-questionnaire-choices'],
22
+ 'Questionnaire.Description': ['p', 'vs-questionnaire-description'],
23
+ 'Questionnaire.Error': ['p', 'vs-questionnaire-error', { hidden: '' }],
24
+ 'Questionnaire.Input': ['input', 'input vs-questionnaire-input'],
25
+ 'Questionnaire.Item': ['fieldset', 'vs-questionnaire-item', { tabindex: '-1' }],
26
+ 'Questionnaire.Next': ['button', 'btn vs-questionnaire-next', { 'data-variant': 'primary' }],
27
+ 'Questionnaire.Previous': ['button', 'btn vs-questionnaire-previous', { 'data-variant': 'outline' }],
28
+ 'Questionnaire.Progress': ['div', 'vs-questionnaire-progress', { role: 'status' }],
29
+ 'Questionnaire.Skip': ['button', 'btn vs-questionnaire-skip', { 'data-variant': 'outline' }],
30
+ 'Questionnaire.Submit': ['button', 'btn vs-questionnaire-next', { 'data-variant': 'primary' }],
31
+ 'Questionnaire.Title': ['legend', 'vs-questionnaire-title'],
32
+ 'ScrollArea.Root': ['div', 'vs-scroll-area'],
33
+ 'ScrollArea.Scrollbar': ['div', 'vs-scrollbar-definition', { hidden: '' }],
34
+ 'Select.ScrollUpButton': ['div', 'vs-select-scroll-button', { 'data-direction': 'up', 'aria-hidden': 'true', hidden: '' }],
35
+ 'Select.ScrollDownButton': ['div', 'vs-select-scroll-button', { 'data-direction': 'down', 'aria-hidden': 'true', hidden: '' }],
36
+ };
37
+ export const formScrollPorts = {
38
+ 'MessageScroller.Provider': 'autoScroll defaultScrollPosition scrollEdgeThreshold scrollMargin scrollPreviousItemPeek',
39
+ 'MessageScroller.Viewport': 'preserveScrollOnPrepend',
40
+ 'MessageScroller.Content': 'spacerClassName',
41
+ 'MessageScroller.Item': 'messageId scrollAnchor',
42
+ 'MessageScroller.Button': 'direction behavior variant size type value',
43
+ 'Questionnaire.Root': 'defaultItem item items noValidate novalidate shortcuts',
44
+ 'Questionnaire.Choice': 'value checked defaultChecked',
45
+ 'Questionnaire.Input': 'type value defaultValue',
46
+ 'Questionnaire.Item': 'invalid multiple name required disabled',
47
+ 'Questionnaire.Next': 'type value variant size',
48
+ 'Questionnaire.Previous': 'type value variant size',
49
+ 'Questionnaire.Skip': 'type value variant size',
50
+ 'Questionnaire.Submit': 'type value variant size',
51
+ 'ScrollArea.Root': 'orientation type scrollHideDelay scrollbarXClasses scrollbarYClasses',
52
+ 'ScrollArea.Scrollbar': 'orientation forceMount',
53
+ };
54
+ export const formScrollEvents = {
55
+ 'Questionnaire.Root': 'itemChange submit reset',
56
+ 'Questionnaire.Item': 'statusChange',
57
+ };
58
+ export function formScrollHost(name, control) {
59
+ const doc = control.ownerDocument;
60
+ if (name === 'ScrollArea.Root') {
61
+ const viewport = styleScope.createElement(doc, 'div');
62
+ viewport.className = 'vs-scroll-area-viewport';
63
+ const content = styleScope.createElement(doc, 'div');
64
+ content.className = 'vs-scroll-area-content';
65
+ viewport.append(content);
66
+ control.append(viewport);
67
+ return content;
68
+ }
69
+ if (name === 'Questionnaire.Choice') {
70
+ const input = styleScope.createElement(doc, 'input');
71
+ input.className = 'vs-questionnaire-option-input';
72
+ const indicator = styleScope.createElement(doc, 'span');
73
+ indicator.className = 'vs-questionnaire-indicator';
74
+ indicator.setAttribute('aria-hidden', 'true');
75
+ const label = styleScope.createElement(doc, 'span');
76
+ label.className = 'vs-questionnaire-option-label';
77
+ control.append(input, indicator, label);
78
+ return label;
79
+ }
80
+ }
81
+ function showFallback(element, content, className, allowText = false) {
82
+ const inputs = propsOf(element);
83
+ let label = element.querySelector(`:scope > .${className}`);
84
+ const hasSlot = [...element.children].some(child => child !== label);
85
+ if (hasSlot || (allowText && typeof inputs.text === 'string')) {
86
+ label?.remove();
87
+ return;
88
+ }
89
+ if (!label) {
90
+ label = styleScope.createElement(element.ownerDocument, 'span');
91
+ label.className = className;
92
+ element.append(label);
93
+ }
94
+ label.textContent = content;
95
+ }
96
+ const question = 'Questionnaire.Item';
97
+ const questionChoice = 'Questionnaire.Choice';
98
+ const questionInput = 'Questionnaire.Input';
99
+ const navigation = ['Previous', 'Skip', 'Next', 'Submit'];
100
+ function questionnaire(form, send, signal) {
101
+ let inputs = {};
102
+ let activeName;
103
+ let pendingFocus;
104
+ let questions = [];
105
+ const state = new WeakMap();
106
+ const initialized = new WeakSet();
107
+ const freeAnswers = new WeakSet();
108
+ const previousValues = new WeakMap();
109
+ const controls = (node) => [...node.querySelectorAll(`input.vs-questionnaire-option-input, ${part(questionInput)}`)]
110
+ .filter(input => input.closest(part(question)) === node && !input.disabled);
111
+ const isChoice = (input) => input.classList.contains('vs-questionnaire-option-input');
112
+ const filled = (input) => isChoice(input) ? input.checked : freeAnswers.has(input);
113
+ const current = () => questions.findIndex(item => item.name === activeName);
114
+ const data = (node) => {
115
+ let item = state.get(node);
116
+ if (!item) {
117
+ item = { attempted: false, skipped: false };
118
+ state.set(node, item);
119
+ }
120
+ return item;
121
+ };
122
+ const status = (node) => data(node).skipped ? 'skipped' : controls(node).some(filled) ? 'answered' : 'unanswered';
123
+ const valid = (node) => {
124
+ const answer = status(node);
125
+ const item = propsOf(node);
126
+ return answer === 'skipped' ? item.required !== true : item.invalid !== true && answer === 'answered';
127
+ };
128
+ const focusInvalid = (node) => (controls(node).find(filled) ?? controls(node)[0] ?? node).focus({ preventScroll: true });
129
+ const move = (name, focus = 'item') => {
130
+ if (name !== activeName) {
131
+ activeName = name;
132
+ send('itemChange', { value: name });
133
+ }
134
+ paint();
135
+ const node = questions[current()]?.node;
136
+ if (node) {
137
+ if (focus === 'invalid')
138
+ focusInvalid(node);
139
+ else
140
+ node.focus({ preventScroll: true });
141
+ }
142
+ else
143
+ pendingFocus = name;
144
+ };
145
+ const validate = (node) => {
146
+ data(node).attempted = true;
147
+ if (!valid(node))
148
+ return false;
149
+ if (!form.noValidate) {
150
+ const invalid = controls(node).find(input => filled(input) && !input.validity.valid);
151
+ if (invalid) {
152
+ invalid.reportValidity();
153
+ return false;
154
+ }
155
+ }
156
+ return true;
157
+ };
158
+ const next = (submit) => {
159
+ const index = current();
160
+ const item = questions[index];
161
+ if (!item?.node)
162
+ return;
163
+ if (!validate(item.node)) {
164
+ paint();
165
+ focusInvalid(item.node);
166
+ return;
167
+ }
168
+ const following = questions[index + 1];
169
+ if (following)
170
+ move(following.name);
171
+ else if (submit)
172
+ form.requestSubmit();
173
+ };
174
+ const skip = () => {
175
+ const index = current();
176
+ const item = questions[index];
177
+ if (!item?.node || item.definition.required || propsOf(item.node).required === true)
178
+ return;
179
+ data(item.node).skipped = true;
180
+ for (const input of controls(item.node)) {
181
+ if (isChoice(input))
182
+ input.checked = false;
183
+ else
184
+ freeAnswers.delete(input);
185
+ }
186
+ paint();
187
+ const following = questions[index + 1];
188
+ if (following)
189
+ move(following.name);
190
+ else
191
+ form.requestSubmit();
192
+ };
193
+ const own = (element) => element.closest(part('Questionnaire.Root')) === form;
194
+ const answerChanged = (event) => {
195
+ const input = event.target;
196
+ if (!input?.matches?.(`.vs-questionnaire-option-input, ${part(questionInput)}`) || !own(input))
197
+ return;
198
+ const node = input.closest(part(question));
199
+ if (!node)
200
+ return;
201
+ if (!isChoice(input)) {
202
+ if (input.value.trim())
203
+ freeAnswers.add(input);
204
+ else
205
+ freeAnswers.delete(input);
206
+ }
207
+ if (filled(input)) {
208
+ data(node).skipped = false;
209
+ if (propsOf(node).multiple !== true) {
210
+ for (const sibling of controls(node))
211
+ if (sibling !== input) {
212
+ if (isChoice(sibling))
213
+ sibling.checked = false;
214
+ else
215
+ freeAnswers.delete(sibling);
216
+ }
217
+ }
218
+ }
219
+ paint();
220
+ };
221
+ form.addEventListener('change', answerChanged, { signal });
222
+ form.addEventListener('input', event => {
223
+ if (!event.target?.matches?.(part(questionInput)) || event.isComposing)
224
+ return;
225
+ answerChanged(event);
226
+ }, { signal });
227
+ form.addEventListener('compositionend', answerChanged, { signal });
228
+ form.addEventListener('click', event => {
229
+ const action = event.target?.closest('button[data-vs-component^="Questionnaire."]');
230
+ if (!action || !own(action) || event.defaultPrevented)
231
+ return;
232
+ const key = action.dataset.vsComponent?.slice('Questionnaire.'.length);
233
+ if (key === 'Previous') {
234
+ const previous = questions[current() - 1];
235
+ if (previous)
236
+ move(previous.name);
237
+ }
238
+ if (key === 'Next')
239
+ next(false);
240
+ if (key === 'Skip')
241
+ skip();
242
+ }, { signal });
243
+ form.addEventListener('submit', event => {
244
+ if (event.target !== form)
245
+ return;
246
+ const invalid = questions.find(item => item.node && !validate(item.node));
247
+ if (!invalid)
248
+ return;
249
+ event.preventDefault();
250
+ event.stopImmediatePropagation();
251
+ move(invalid.name, 'invalid');
252
+ }, { capture: true, signal });
253
+ form.addEventListener('reset', event => {
254
+ if (event.target !== form)
255
+ return;
256
+ queueMicrotask(() => {
257
+ if (signal.aborted || event.defaultPrevented)
258
+ return;
259
+ for (const { node } of questions)
260
+ if (node) {
261
+ data(node).skipped = false;
262
+ data(node).attempted = false;
263
+ for (const input of controls(node))
264
+ if (!isChoice(input)) {
265
+ if (input.value.trim() && (propsOf(node).multiple === true || !controls(node).some(other => other.checked)))
266
+ freeAnswers.add(input);
267
+ else
268
+ freeAnswers.delete(input);
269
+ }
270
+ }
271
+ const first = questions.find(item => item.name === inputs.defaultItem) ?? questions[0];
272
+ if (first)
273
+ move(first.name);
274
+ });
275
+ }, { signal });
276
+ form.addEventListener('keydown', event => {
277
+ const target = event.target;
278
+ const item = questions[current()]?.node;
279
+ if (!item || !own(target) || event.isComposing || event.defaultPrevented)
280
+ return;
281
+ const answers = controls(item);
282
+ if (event.key === 'Enter' && (event.metaKey || event.ctrlKey) && !event.altKey && !event.shiftKey) {
283
+ event.preventDefault();
284
+ if (!event.repeat)
285
+ next(true);
286
+ return;
287
+ }
288
+ if (event.metaKey || event.ctrlKey || event.altKey)
289
+ return;
290
+ const focused = answers.indexOf(target);
291
+ if (['ArrowDown', 'ArrowUp'].includes(event.key) && answers.length) {
292
+ const direction = event.key === 'ArrowDown' ? 1 : -1;
293
+ const selected = answers[focused];
294
+ const canMove = target === item || (selected && (isChoice(selected) || (!selected.value.trim() && ['email', 'password', 'search', 'tel', 'text', 'url'].includes(selected.type))));
295
+ const nextAnswer = focused < 0 ? answers.find(filled) ?? answers.at(direction > 0 ? 0 : -1)
296
+ : answers[(focused + direction + answers.length) % answers.length];
297
+ const nativeRadio = selected?.type === 'radio' && nextAnswer?.type === 'radio';
298
+ if (canMove && nextAnswer && nextAnswer !== target && !nativeRadio) {
299
+ event.preventDefault();
300
+ nextAnswer.focus();
301
+ if (nextAnswer.type === 'radio')
302
+ nextAnswer.click();
303
+ return;
304
+ }
305
+ }
306
+ if (event.key === 'Enter' && focused >= 0) {
307
+ event.preventDefault();
308
+ if (!event.repeat && filled(answers[focused]))
309
+ next(true);
310
+ return;
311
+ }
312
+ if ((focused < 0 || target.matches('[type=checkbox]')) && ['ArrowLeft', 'ArrowRight'].includes(event.key)) {
313
+ event.preventDefault();
314
+ if (event.repeat)
315
+ return;
316
+ if (event.key === 'ArrowLeft') {
317
+ const previous = questions[current() - 1];
318
+ if (previous)
319
+ move(previous.name);
320
+ }
321
+ else if (status(item) !== 'unanswered')
322
+ next(false);
323
+ return;
324
+ }
325
+ if (target.matches(part(questionInput)))
326
+ return;
327
+ const shortcut = answers.find(input => input.dataset.vsShortcut?.toLowerCase() === event.key.toLowerCase());
328
+ if (shortcut) {
329
+ event.preventDefault();
330
+ if (!event.repeat) {
331
+ shortcut.focus();
332
+ shortcut.click();
333
+ }
334
+ }
335
+ }, { signal });
336
+ function paint() {
337
+ const index = current();
338
+ const last = index === questions.length - 1 && index >= 0;
339
+ const currentItem = questions[index];
340
+ for (const { name, node, definition } of questions) {
341
+ if (!node)
342
+ continue;
343
+ node.hidden = name !== activeName || propsOf(node).hidden === true;
344
+ node.tabIndex = -1;
345
+ node.toggleAttribute('inert', node.hidden);
346
+ const currentState = data(node);
347
+ const itemStatus = status(node);
348
+ if (currentState.status !== undefined && currentState.status !== itemStatus)
349
+ emitFrom(node, 'statusChange', { value: itemStatus });
350
+ currentState.status = itemStatus;
351
+ node.dataset.status = itemStatus;
352
+ const invalid = !valid(node) && (propsOf(node).invalid === true || currentState.attempted);
353
+ node.toggleAttribute('data-invalid', invalid);
354
+ const description = find(node, 'Questionnaire.Description');
355
+ const error = find(node, 'Questionnaire.Error');
356
+ if (description)
357
+ description.id ||= uniqueId();
358
+ if (error) {
359
+ error.id ||= uniqueId();
360
+ error.hidden = !invalid || propsOf(error).hidden === true;
361
+ error.setAttribute('role', 'alert');
362
+ showFallback(error, definition.required ? 'Choose an answer to continue.' : 'Choose an answer or skip this question.', 'vs-questionnaire-fallback', true);
363
+ }
364
+ const descriptionIds = [propsOf(node)['aria-describedby'], description?.id, invalid && error?.id].filter(Boolean).join(' ');
365
+ if (descriptionIds)
366
+ node.setAttribute('aria-describedby', descriptionIds);
367
+ else
368
+ node.removeAttribute('aria-describedby');
369
+ const fields = controls(node);
370
+ if (!node.hidden) {
371
+ const keys = ['Meta+Enter', 'Control+Enter', fields.length && 'ArrowUp ArrowDown', index > 0 && 'ArrowLeft', !last && itemStatus !== 'unanswered' && 'ArrowRight'];
372
+ node.setAttribute('aria-keyshortcuts', keys.filter(Boolean).join(' '));
373
+ }
374
+ else
375
+ node.removeAttribute('aria-keyshortcuts');
376
+ for (const input of fields) {
377
+ if (isChoice(input)) {
378
+ const choice = input.parentElement;
379
+ choice.toggleAttribute('data-checked', input.checked);
380
+ choice.toggleAttribute('data-invalid', invalid);
381
+ input.name = itemStatus === 'skipped' ? '' : name;
382
+ }
383
+ else {
384
+ input.toggleAttribute('data-filled', input.value.trim() !== '');
385
+ if (itemStatus !== 'skipped' && filled(input))
386
+ input.name = name;
387
+ else
388
+ input.removeAttribute('name');
389
+ if (invalid)
390
+ input.setAttribute('aria-invalid', 'true');
391
+ else if (propsOf(input)['aria-invalid'] === undefined)
392
+ input.removeAttribute('aria-invalid');
393
+ }
394
+ }
395
+ }
396
+ for (const [action, visible] of [
397
+ ['Previous', index > 0], ['Skip', !!currentItem && !currentItem.definition.required], ['Next', questions.length > 1 && !last], ['Submit', last],
398
+ ])
399
+ for (const button of all(form, 'Questionnaire.' + action).filter(own)) {
400
+ const settings = propsOf(button);
401
+ button.hidden = !visible || settings.hidden === true;
402
+ button.toggleAttribute('inert', button.hidden);
403
+ button.type = action === 'Submit' && settings.type === undefined ? 'submit' : button.type;
404
+ if (settings.variant === 'default')
405
+ button.dataset.variant = 'primary';
406
+ showFallback(button, action, 'vs-questionnaire-fallback', true);
407
+ }
408
+ for (const progress of all(form, 'Questionnaire.Progress').filter(own)) {
409
+ showFallback(progress, questions.length ? `Question ${index + 1} of ${questions.length}` : '', 'vs-questionnaire-fallback', true);
410
+ }
411
+ }
412
+ return { sync(nextInputs) {
413
+ const previous = activeName;
414
+ const oldControlled = inputs.item;
415
+ inputs = nextInputs;
416
+ form.noValidate = inputs.noValidate !== false && inputs.novalidate !== false;
417
+ const nodes = all(form, question).filter(own);
418
+ const byName = new Map(nodes.map(node => [String(propsOf(node).name), node]));
419
+ const definitions = Array.isArray(inputs.items) ? inputs.items : nodes.map(node => ({
420
+ name: String(propsOf(node).name), required: propsOf(node).required === true, disabled: propsOf(node).disabled === true,
421
+ }));
422
+ questions = definitions.filter(definition => !definition.disabled && propsOf(byName.get(definition.name) ?? form).disabled !== true)
423
+ .map(definition => ({ name: definition.name, definition, node: byName.get(definition.name) }));
424
+ if (typeof inputs.item === 'string' && inputs.item !== oldControlled && questions.some(item => item.name === inputs.item))
425
+ activeName = inputs.item;
426
+ else if (!questions.some(item => item.name === activeName))
427
+ activeName = questions.find(item => item.name === inputs.defaultItem)?.name ?? questions[0]?.name;
428
+ for (const node of nodes) {
429
+ const entry = questions.find(item => item.node === node);
430
+ // Keep answers on the mounted controls while excluding inactive definitions from FormData.
431
+ node.disabled = !entry;
432
+ if (!entry) {
433
+ node.hidden = true;
434
+ node.inert = true;
435
+ continue;
436
+ }
437
+ const multiple = propsOf(node).multiple === true;
438
+ const shortcuts = inputs.shortcuts === 'numbers' ? '123456789' : inputs.shortcuts === 'letters' ? 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' : '';
439
+ let index = 0;
440
+ for (const choice of all(node, questionChoice)) {
441
+ const settings = propsOf(choice);
442
+ const input = choice.querySelector('.vs-questionnaire-option-input');
443
+ input.type = multiple ? 'checkbox' : 'radio';
444
+ input.name = entry.name;
445
+ input.value = String(settings.value ?? '');
446
+ const defined = entry.definition.choices?.find(candidate => candidate.value === settings.value);
447
+ input.disabled = settings.disabled === true || defined?.disabled === true;
448
+ choice.dataset.type = input.type;
449
+ choice.toggleAttribute('data-disabled', input.disabled);
450
+ if (!initialized.has(input)) {
451
+ initialized.add(input);
452
+ input.defaultChecked = settings.defaultChecked === true;
453
+ input.checked = input.defaultChecked;
454
+ }
455
+ if (typeof settings.checked === 'boolean' && settings.checked !== previousValues.get(input))
456
+ input.checked = settings.checked;
457
+ previousValues.set(input, settings.checked);
458
+ const logical = entry.definition.choices?.filter(choice => !choice.disabled).findIndex(candidate => candidate.value === settings.value);
459
+ const shortcut = !input.disabled ? shortcuts[logical !== undefined && logical >= 0 ? logical : index++] : undefined;
460
+ const old = choice.querySelector('.vs-questionnaire-shortcut');
461
+ if (shortcut) {
462
+ const badge = old ?? styleScope.createElement(form.ownerDocument, 'kbd');
463
+ badge.className = 'vs-questionnaire-shortcut';
464
+ badge.textContent = shortcut;
465
+ badge.setAttribute('aria-hidden', 'true');
466
+ if (!old)
467
+ choice.append(badge);
468
+ input.dataset.vsShortcut = shortcut;
469
+ input.setAttribute('aria-keyshortcuts', shortcut);
470
+ }
471
+ else {
472
+ old?.remove();
473
+ delete input.dataset.vsShortcut;
474
+ input.removeAttribute('aria-keyshortcuts');
475
+ }
476
+ }
477
+ for (const input of all(node, questionInput)) {
478
+ const settings = propsOf(input);
479
+ const initial = !initialized.has(input);
480
+ if (initial && typeof settings.defaultValue === 'string') {
481
+ input.defaultValue = settings.defaultValue;
482
+ if (settings.value === undefined)
483
+ input.value = settings.defaultValue;
484
+ }
485
+ if (initial || (settings.value !== undefined && settings.value !== previousValues.get(input))) {
486
+ if (input.value.trim() && (multiple || !controls(node).some(other => other !== input && filled(other))))
487
+ freeAnswers.add(input);
488
+ else
489
+ freeAnswers.delete(input);
490
+ }
491
+ initialized.add(input);
492
+ previousValues.set(input, settings.value);
493
+ }
494
+ }
495
+ paint();
496
+ const focus = questions[current()]?.node;
497
+ if (focus && (pendingFocus === activeName || (previous !== undefined && previous !== activeName))) {
498
+ pendingFocus = undefined;
499
+ focus.focus({ preventScroll: true });
500
+ }
501
+ } };
502
+ }
503
+ function messageScroller(root, signal) {
504
+ const win = root.ownerDocument.defaultView;
505
+ let viewport = null;
506
+ let content = null;
507
+ let bindings;
508
+ let sizeObserver;
509
+ let config = {};
510
+ let frame = 0;
511
+ let initial = true;
512
+ let pinnedToEnd = true;
513
+ let anchor;
514
+ let lastRow;
515
+ let lastMessageAnchor;
516
+ let activeMessageAnchor;
517
+ let tail;
518
+ const rows = () => content ? all(content, 'MessageScroller.Item') : [];
519
+ const threshold = () => typeof config.scrollEdgeThreshold === 'number' ? Math.max(0, config.scrollEdgeThreshold) : 8;
520
+ const atEnd = () => !viewport || viewport.scrollHeight - viewport.clientHeight - viewport.scrollTop <= threshold();
521
+ const setScroll = (position, behavior = 'instant') => viewport?.scrollTo({ top: position, behavior });
522
+ const locateAnchor = () => {
523
+ if (!viewport)
524
+ return;
525
+ const top = viewport.getBoundingClientRect().top;
526
+ const row = rows().find(row => row.getBoundingClientRect().bottom > top);
527
+ anchor = row ? { row, offset: row.getBoundingClientRect().top - top } : undefined;
528
+ };
529
+ function paint() {
530
+ if (!viewport)
531
+ return;
532
+ pinnedToEnd = atEnd();
533
+ const atStart = viewport.scrollTop <= threshold();
534
+ for (const button of all(root, 'MessageScroller.Button')) {
535
+ const options = propsOf(button);
536
+ const direction = options.direction === 'start' ? 'start' : 'end';
537
+ const active = direction === 'end' ? !pinnedToEnd : !atStart;
538
+ button.dataset.direction = direction;
539
+ button.dataset.active = String(active);
540
+ button.tabIndex = active ? (typeof options.tabindex === 'number' ? options.tabindex : 0) : -1;
541
+ if (active)
542
+ button.removeAttribute('aria-hidden');
543
+ else
544
+ button.setAttribute('aria-hidden', 'true');
545
+ if (!button.textContent?.trim() && !button.children.length && options['aria-label'] === undefined) {
546
+ button.setAttribute('aria-label', direction === 'end' ? 'Scroll to end' : 'Scroll to start');
547
+ button.dataset.vsScrollIcon = '';
548
+ }
549
+ else
550
+ delete button.dataset.vsScrollIcon;
551
+ if (options.variant === 'default')
552
+ button.dataset.variant = 'primary';
553
+ }
554
+ locateAnchor();
555
+ }
556
+ function anchorPosition(row) {
557
+ if (!viewport || !content)
558
+ return 0;
559
+ const margin = typeof config.scrollMargin === 'number' ? config.scrollMargin : 0;
560
+ const peek = typeof config.scrollPreviousItemPeek === 'number' ? config.scrollPreviousItemPeek : 64;
561
+ const bounds = viewport.getBoundingClientRect();
562
+ return row.getBoundingClientRect().top - bounds.top + viewport.scrollTop - margin - peek;
563
+ }
564
+ function resizeTail() {
565
+ const last = rows().at(-1);
566
+ if (!viewport || !content || !activeMessageAnchor || !content.contains(activeMessageAnchor) || !last) {
567
+ if (tail)
568
+ tail.hidden = true;
569
+ return;
570
+ }
571
+ if (!tail) {
572
+ tail = styleScope.createElement(root.ownerDocument, 'div');
573
+ tail.setAttribute('aria-hidden', 'true');
574
+ content.append(tail);
575
+ }
576
+ const bottom = last.getBoundingClientRect().bottom - viewport.getBoundingClientRect().top + viewport.scrollTop;
577
+ const gap = parseFloat(win.getComputedStyle(content).rowGap) || 0;
578
+ const height = Math.max(0, anchorPosition(activeMessageAnchor) + viewport.clientHeight - bottom - gap);
579
+ tail.className = ['vs-message-tail', propsOf(content).spacerClassName].filter(value => typeof value === 'string' && value).join(' ');
580
+ tail.hidden = height === 0;
581
+ tail.style.height = `${height}px`;
582
+ }
583
+ function positionAnchor(row) {
584
+ activeMessageAnchor = row;
585
+ resizeTail();
586
+ setScroll(anchorPosition(row));
587
+ }
588
+ function layout() {
589
+ frame = 0;
590
+ if (!viewport || !content || !viewport.clientHeight || signal.aborted)
591
+ return;
592
+ const items = rows();
593
+ if (items.length === 0) {
594
+ paint();
595
+ return;
596
+ }
597
+ const marked = [...items].reverse().find(row => propsOf(row).scrollAnchor === true);
598
+ if (!initial)
599
+ resizeTail();
600
+ if (initial) {
601
+ initial = false;
602
+ if (config.defaultScrollPosition === 'last-anchor' && marked)
603
+ positionAnchor(marked);
604
+ else if (config.defaultScrollPosition === 'start')
605
+ setScroll(0);
606
+ else
607
+ setScroll(viewport.scrollHeight);
608
+ }
609
+ else if (config.autoScroll === true && marked && lastRow !== items.at(-1) && marked !== lastMessageAnchor) {
610
+ positionAnchor(marked);
611
+ }
612
+ else if (config.autoScroll === true && pinnedToEnd) {
613
+ setScroll(viewport.scrollHeight);
614
+ }
615
+ else if (anchor?.row.isConnected && propsOf(viewport).preserveScrollOnPrepend !== false) {
616
+ const offset = anchor.row.getBoundingClientRect().top - viewport.getBoundingClientRect().top;
617
+ if (Math.abs(offset - anchor.offset) > 1)
618
+ setScroll(viewport.scrollTop + offset - anchor.offset);
619
+ }
620
+ lastRow = items.at(-1);
621
+ lastMessageAnchor = marked;
622
+ paint();
623
+ }
624
+ const schedule = () => { if (!frame && !signal.aborted)
625
+ frame = win.requestAnimationFrame(layout); };
626
+ root.addEventListener('click', event => {
627
+ const button = event.target?.closest(part('MessageScroller.Button'));
628
+ if (!button || !viewport || event.defaultPrevented)
629
+ return;
630
+ const options = propsOf(button);
631
+ const desired = options.behavior;
632
+ const behavior = desired === 'instant' || desired === 'auto' ? desired : 'smooth';
633
+ activeMessageAnchor = undefined;
634
+ resizeTail();
635
+ setScroll(options.direction === 'start' ? 0 : viewport.scrollHeight, behavior);
636
+ }, { signal });
637
+ return { sync() {
638
+ const provider = root.closest(part('MessageScroller.Provider'));
639
+ const nextConfig = provider ? propsOf(provider) : {};
640
+ if (nextConfig.defaultScrollPosition !== config.defaultScrollPosition)
641
+ initial = true;
642
+ config = nextConfig;
643
+ const nextViewport = find(root, 'MessageScroller.Viewport');
644
+ const nextContent = nextViewport && find(nextViewport, 'MessageScroller.Content');
645
+ if (nextViewport !== viewport || nextContent !== content) {
646
+ bindings?.abort();
647
+ sizeObserver?.disconnect();
648
+ viewport = nextViewport;
649
+ content = nextContent;
650
+ activeMessageAnchor = undefined;
651
+ tail = undefined;
652
+ initial = true;
653
+ if (viewport && content) {
654
+ bindings = new AbortController();
655
+ viewport.addEventListener('scroll', paint, { passive: true, signal: bindings.signal });
656
+ sizeObserver = new ResizeObserver(schedule);
657
+ sizeObserver.observe(viewport);
658
+ sizeObserver.observe(content);
659
+ }
660
+ }
661
+ schedule();
662
+ }, dispose() {
663
+ bindings?.abort();
664
+ sizeObserver?.disconnect();
665
+ win.cancelAnimationFrame(frame);
666
+ } };
667
+ }
668
+ function scrollContainer(root, send, signal) {
669
+ const doc = root.ownerDocument;
670
+ const win = doc.defaultView;
671
+ const viewport = root.querySelector('.vs-scroll-area-viewport');
672
+ const content = root.querySelector('.vs-scroll-area-content');
673
+ const corner = styleScope.createElement(doc, 'div');
674
+ corner.className = 'vs-scroll-area-corner';
675
+ root.append(corner);
676
+ const id = uniqueId();
677
+ let rootId = id;
678
+ let direction = root.matches(':dir(rtl)') ? 'rtl' : 'ltr';
679
+ const service = new VanillaMachine(scrollArea.machine, () => ({
680
+ id, dir: direction, ids: { root: rootId }, getRootNode: () => root.getRootNode(),
681
+ }));
682
+ const tracks = new Map();
683
+ const bindings = new Map();
684
+ let frame = 0;
685
+ let settings = {};
686
+ let started = false;
687
+ let hideTimer = 0;
688
+ function bind(element, props) {
689
+ bindings.set(element, spreadProps(element, props, id));
690
+ }
691
+ function paint() {
692
+ frame = 0;
693
+ if (signal.aborted || !started)
694
+ return;
695
+ const api = scrollArea.connect(service.service, normalizeProps);
696
+ bind(root, { ...api.getRootProps(), id: rootId, role: typeof settings.role === 'string' ? settings.role : undefined });
697
+ bind(viewport, {
698
+ ...api.getViewportProps(), tabindex: api.hasOverflowX || api.hasOverflowY ? 0 : undefined, role: undefined,
699
+ style: { overflowX: tracks.has('horizontal') ? 'auto' : 'hidden', overflowY: tracks.has('vertical') ? 'auto' : 'hidden' },
700
+ });
701
+ bind(content, api.getContentProps());
702
+ bind(corner, api.getCornerProps());
703
+ for (const [orientation, { track, thumb, marker }] of tracks) {
704
+ const trackProps = api.getScrollbarProps({ orientation });
705
+ const force = marker && propsOf(marker).forceMount === true;
706
+ track.hidden = !force && api.getScrollbarState({ orientation }).hidden;
707
+ bind(track, trackProps);
708
+ bind(thumb, api.getThumbProps({ orientation }));
709
+ }
710
+ }
711
+ const schedule = () => { if (!frame && !signal.aborted)
712
+ frame = win.requestAnimationFrame(paint); };
713
+ const unsubscribe = service.subscribe(schedule);
714
+ const hideDelay = () => typeof settings.scrollHideDelay === 'number' ? settings.scrollHideDelay : 600;
715
+ root.addEventListener('pointerenter', () => {
716
+ if (root.dataset.vsScrollMode !== 'hover')
717
+ return;
718
+ win.clearTimeout(hideTimer);
719
+ root.dataset.vsHovering = '';
720
+ }, { signal });
721
+ root.addEventListener('pointerleave', () => {
722
+ if (root.dataset.vsScrollMode !== 'hover')
723
+ return;
724
+ win.clearTimeout(hideTimer);
725
+ hideTimer = win.setTimeout(() => { delete root.dataset.vsHovering; }, hideDelay());
726
+ }, { signal });
727
+ const markScrolling = () => {
728
+ if (root.dataset.vsScrollMode === 'scroll') {
729
+ root.dataset.vsScrolling = '';
730
+ win.clearTimeout(hideTimer);
731
+ hideTimer = win.setTimeout(() => { delete root.dataset.vsScrolling; }, 100 + hideDelay());
732
+ }
733
+ send('scroll', { type: 'scroll' });
734
+ };
735
+ viewport.addEventListener('scroll', markScrolling, { signal, passive: true });
736
+ return { sync(inputs) {
737
+ const previousDir = direction;
738
+ const previousId = rootId;
739
+ settings = inputs;
740
+ rootId = typeof inputs.id === 'string' && inputs.id ? inputs.id : id;
741
+ direction = inputs.dir === 'rtl' || root.matches(':dir(rtl)') ? 'rtl' : 'ltr';
742
+ if (started && (direction !== previousDir || rootId !== previousId))
743
+ service.updateProps({ dir: direction, ids: { root: rootId } });
744
+ const mode = typeof inputs.type === 'string' ? inputs.type : 'hover';
745
+ if (mode !== root.dataset.vsScrollMode) {
746
+ win.clearTimeout(hideTimer);
747
+ root.dataset.vsScrollMode = mode;
748
+ delete root.dataset.vsScrolling;
749
+ root.toggleAttribute('data-vs-hovering', mode === 'hover' && root.matches(':hover'));
750
+ }
751
+ const requested = new Map();
752
+ if (inputs.orientation !== 'horizontal')
753
+ requested.set('vertical', undefined);
754
+ if (inputs.orientation === 'horizontal' || inputs.orientation === 'both')
755
+ requested.set('horizontal', undefined);
756
+ for (const marker of all(content, 'ScrollArea.Scrollbar')) {
757
+ marker.hidden = true;
758
+ const axis = propsOf(marker).orientation === 'horizontal' ? 'horizontal' : 'vertical';
759
+ requested.set(axis, marker);
760
+ }
761
+ for (const [orientation, track] of tracks)
762
+ if (!requested.has(orientation)) {
763
+ for (const node of [track.track, track.thumb]) {
764
+ bindings.get(node)?.();
765
+ bindings.delete(node);
766
+ }
767
+ track.track.remove();
768
+ tracks.delete(orientation);
769
+ }
770
+ for (const [orientation, marker] of requested) {
771
+ let entry = tracks.get(orientation);
772
+ if (!entry) {
773
+ const track = styleScope.createElement(doc, 'div');
774
+ const thumb = styleScope.createElement(doc, 'div');
775
+ thumb.className = 'vs-scroll-area-thumb';
776
+ track.append(thumb);
777
+ root.insertBefore(track, corner);
778
+ entry = { track, thumb };
779
+ tracks.set(orientation, entry);
780
+ }
781
+ if (marker)
782
+ entry.marker = marker;
783
+ else
784
+ delete entry.marker;
785
+ const classes = marker ? propsOf(marker).class : inputs[orientation === 'horizontal' ? 'scrollbarXClasses' : 'scrollbarYClasses'];
786
+ entry.track.className = ['vs-scroll-area-scrollbar', classes].filter(value => typeof value === 'string' && value).join(' ');
787
+ }
788
+ if (!started) {
789
+ started = true;
790
+ paint();
791
+ service.start();
792
+ }
793
+ schedule();
794
+ }, dispose() {
795
+ unsubscribe();
796
+ service.stop();
797
+ for (const dispose of bindings.values())
798
+ dispose();
799
+ bindings.clear();
800
+ win.cancelAnimationFrame(frame);
801
+ win.clearTimeout(hideTimer);
802
+ } };
803
+ }
804
+ function selectScroll(content, signal) {
805
+ const win = content.ownerDocument.defaultView;
806
+ let viewport = null;
807
+ let buttons = [];
808
+ let observer;
809
+ let frame = 0;
810
+ let timer = 0;
811
+ const stop = () => { win.clearTimeout(timer); timer = 0; };
812
+ const open = () => content.getAttribute('aria-hidden') === 'false';
813
+ function update() {
814
+ frame = 0;
815
+ if (!viewport)
816
+ return;
817
+ const scroll = viewport.scrollTop;
818
+ const max = viewport.scrollHeight - viewport.clientHeight;
819
+ for (const button of buttons)
820
+ button.hidden = !open() || (button.dataset.direction === 'up' ? scroll <= 1 : scroll >= max - 1);
821
+ }
822
+ const schedule = () => { if (!frame && !signal.aborted)
823
+ frame = win.requestAnimationFrame(update); };
824
+ function start(button) {
825
+ if (!viewport || timer || button.hidden || !open())
826
+ return;
827
+ const direction = button.dataset.direction === 'up' ? -1 : 1;
828
+ const tick = () => {
829
+ if (!viewport || button.hidden || !open()) {
830
+ stop();
831
+ return;
832
+ }
833
+ const before = viewport.scrollTop;
834
+ const row = viewport.querySelector('[role="option"].active, [role="option"][aria-selected="true"]')
835
+ ?? viewport.querySelector('[role="option"]');
836
+ viewport.scrollTop += (row?.offsetHeight || 24) * direction;
837
+ if (viewport.scrollTop === before) {
838
+ stop();
839
+ return;
840
+ }
841
+ schedule();
842
+ timer = win.setTimeout(tick, 50);
843
+ };
844
+ timer = win.setTimeout(tick, 50);
845
+ }
846
+ const target = (event) => event.target?.closest('.vs-select-scroll-button');
847
+ for (const type of ['pointerdown', 'pointermove'])
848
+ content.addEventListener(type, event => {
849
+ const button = target(event);
850
+ if (button) {
851
+ if (type === 'pointerdown')
852
+ event.preventDefault();
853
+ start(button);
854
+ }
855
+ }, { signal });
856
+ content.addEventListener('pointerout', event => {
857
+ const button = target(event);
858
+ if (button && !button.contains(event.relatedTarget))
859
+ stop();
860
+ }, { signal });
861
+ content.addEventListener('scroll', schedule, { capture: true, passive: true, signal });
862
+ const visibility = new MutationObserver(() => { if (!open())
863
+ stop(); schedule(); });
864
+ visibility.observe(content, { attributes: true, attributeFilter: ['aria-hidden'] });
865
+ return { sync() {
866
+ buttons = [...content.querySelectorAll('.vs-select-scroll-button')];
867
+ const next = content.querySelector('[role="listbox"]');
868
+ content.classList.toggle('vs-select-with-scroll', !!buttons.length);
869
+ if (viewport !== next) {
870
+ observer?.disconnect();
871
+ viewport = next;
872
+ if (viewport) {
873
+ observer = new ResizeObserver(schedule);
874
+ observer.observe(viewport);
875
+ observer.observe(content);
876
+ }
877
+ }
878
+ schedule();
879
+ }, dispose() {
880
+ stop();
881
+ visibility.disconnect();
882
+ observer?.disconnect();
883
+ win.cancelAnimationFrame(frame);
884
+ } };
885
+ }
886
+ export function formScrollBehavior(name, element, send, signal) {
887
+ if (name === 'Questionnaire.Root')
888
+ return questionnaire(element, send, signal);
889
+ if (name === 'MessageScroller.Root')
890
+ return messageScroller(element, signal);
891
+ if (name === 'ScrollArea.Root')
892
+ return scrollContainer(element, send, signal);
893
+ if (name === 'Select.Content')
894
+ return selectScroll(element, signal);
895
+ }