@directo-ui/astro 1.0.0 → 1.2.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.
Files changed (77) hide show
  1. package/README.md +16 -0
  2. package/components.css +661 -0
  3. package/index.d.ts +31 -31
  4. package/index.js +31 -31
  5. package/package.json +29 -7
  6. package/src/components/Accordion.astro +8 -8
  7. package/src/components/AccordionItem.astro +14 -14
  8. package/src/components/Alert.astro +42 -42
  9. package/src/components/Avatar.astro +21 -21
  10. package/src/components/Badge.astro +13 -13
  11. package/src/components/BottomSheet.astro +23 -23
  12. package/src/components/Breadcrumb.astro +18 -18
  13. package/src/components/Button.astro +31 -31
  14. package/src/components/Card.astro +25 -25
  15. package/src/components/Checkbox.astro +14 -14
  16. package/src/components/DatePicker.astro +25 -25
  17. package/src/components/Divider.astro +11 -11
  18. package/src/components/Dropdown.astro +71 -71
  19. package/src/components/EmptyState.astro +15 -15
  20. package/src/components/IconButton.astro +18 -18
  21. package/src/components/Modal.astro +34 -34
  22. package/src/components/MultiSelect.astro +108 -0
  23. package/src/components/Pagination.astro +30 -30
  24. package/src/components/Progress.astro +20 -20
  25. package/src/components/RadioGroup.astro +24 -24
  26. package/src/components/Select.astro +29 -29
  27. package/src/components/Skeleton.astro +13 -13
  28. package/src/components/Spinner.astro +17 -17
  29. package/src/components/StatusTag.astro +18 -0
  30. package/src/components/Switch.astro +13 -13
  31. package/src/components/Tabs.astro +60 -60
  32. package/src/components/TextField.astro +24 -24
  33. package/src/components/Textarea.astro +41 -41
  34. package/src/components/Toaster.astro +8 -8
  35. package/src/components/Tooltip.astro +31 -31
  36. package/src/components/WariClientDetails.astro +87 -0
  37. package/src/components/WariClientSearch.astro +88 -0
  38. package/src/components/WariDateField.astro +56 -0
  39. package/src/components/WariPassengerField.astro +84 -0
  40. package/src/components/WariRoute.astro +49 -0
  41. package/src/components/WariSchedule.astro +48 -0
  42. package/src/components/WariSelect.astro +76 -0
  43. package/src/components/WariServiceMeta.astro +19 -0
  44. package/src/components/WariStatusSelect.astro +20 -0
  45. package/src/components/WariStepper.astro +45 -0
  46. package/src/components/WariSwitchList.astro +111 -0
  47. package/src/components/WariTimeField.astro +50 -0
  48. package/src/components/WariTripAttributes.astro +60 -0
  49. package/src/modal.d.ts +3 -3
  50. package/src/modal.js +39 -39
  51. package/src/pagination.d.ts +2 -2
  52. package/src/pagination.js +16 -16
  53. package/src/toast.d.ts +9 -9
  54. package/src/toast.js +66 -66
  55. package/src/wari/datetime.d.ts +57 -0
  56. package/src/wari/datetime.js +151 -0
  57. package/src/wari/logic.d.ts +8 -0
  58. package/src/wari/logic.js +41 -0
  59. package/src/wari/motion.d.ts +14 -0
  60. package/src/wari/motion.js +60 -0
  61. package/src/wari/multiselect.d.ts +2 -0
  62. package/src/wari/multiselect.js +169 -0
  63. package/src/wari/pickers.d.ts +2 -0
  64. package/src/wari/pickers.js +369 -0
  65. package/src/wari/route-client.d.ts +10 -0
  66. package/src/wari/route-client.js +270 -0
  67. package/src/wari/route.d.ts +48 -0
  68. package/src/wari/route.js +71 -0
  69. package/src/wari/statuses.d.ts +14 -0
  70. package/src/wari/statuses.js +15 -0
  71. package/src/wari/trip-client.d.ts +4 -0
  72. package/src/wari/trip-client.js +370 -0
  73. package/src/wari/trip.d.ts +107 -0
  74. package/src/wari/trip.js +129 -0
  75. package/styles.css +3 -3
  76. package/wari.d.ts +26 -0
  77. package/wari.js +21 -0
@@ -0,0 +1,370 @@
1
+ // Client behaviour for <WariSelect>, <WariSwitchList>, <WariStepper> and <WariTripAttributes>. Safe to call many times.
2
+ // Each piece emits a bubbling "ds-change" CustomEvent with its value; <WariTripAttributes> stops those and emits its own
3
+ // "ds-change" with the whole object { service, hourly, delivery, extras, vehicles, payment }.
4
+ import { clampCount, serviceMeta, typeaheadIndex } from './trip.js';
5
+
6
+ const emit = (element, detail) => element.dispatchEvent(new CustomEvent('ds-change', { detail, bubbles: true }));
7
+ const userSvg = '<svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="8" r="4" fill="currentColor"/><path d="M4.5 20.5c1-4 4-6 7.5-6s6.5 2 7.5 6" fill="currentColor"/></svg>';
8
+ const bagSvg = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><rect x="2.5" y="8.5" width="19" height="11" rx="2" fill="currentColor" stroke="none"/><path d="M9 8.5V6.5h6v2"/></svg>';
9
+ const luggageSvg = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><rect x="6" y="7" width="12" height="13" rx="2" fill="currentColor" stroke="none"/><path d="M9.5 7V4.5h5V7M9 22v-2M15 22v-2"/></svg>';
10
+
11
+ /** Same markup as WariServiceMeta.astro, for re-rendering when "Por horas" / "Envíos" change. */
12
+ export function serviceMetaHtml(service, mode) {
13
+ const meta = serviceMeta(service, mode);
14
+ let html = '';
15
+ if (meta.delivery) html += '<span class="ds-wmeta-badge">Envío</span>';
16
+ if (meta.price) html += `<span class="ds-wmeta-item">${meta.price}</span>`;
17
+ if (meta.capacity) {
18
+ html += `<span class="ds-wmeta-item">${userSvg}${meta.capacity.passengers}</span><span class="ds-wmeta-item">${luggageSvg}${meta.capacity.luggage}</span>`;
19
+ if (meta.capacity.luggageAlt != null) html += `<span class="ds-wmeta-item">o ${bagSvg}${meta.capacity.luggageAlt}</span>`;
20
+ }
21
+ return { html, label: meta.label };
22
+ }
23
+
24
+ export function initWariTripFields(scope = document) {
25
+ scope.querySelectorAll('[data-ds-wselect]:not([data-ds-ready])').forEach(setupSelect);
26
+ scope.querySelectorAll('[data-ds-wswitches]:not([data-ds-ready])').forEach(setupSwitches);
27
+ scope.querySelectorAll('[data-ds-wstepper]:not([data-ds-ready])').forEach(setupStepper);
28
+ scope.querySelectorAll('[data-ds-wtrip]:not([data-ds-ready])').forEach(setupTrip);
29
+ }
30
+
31
+ function setupSelect(root) {
32
+ root.dataset.dsReady = '';
33
+ const combo = root.querySelector('[role="combobox"]');
34
+ const list = root.querySelector('[role="listbox"]');
35
+ const valueText = root.querySelector('.ds-wselect-value');
36
+ const valueMeta = root.querySelector('[data-ds-value-meta]');
37
+ const hidden = root.querySelector('[data-ds-value]');
38
+ const label = root.querySelector('label');
39
+ const rows = () => [...list.querySelectorAll('[role="option"]')];
40
+ const options = () => rows().map(li => ({ value: li.dataset.value, label: li.dataset.label, disabled: li.getAttribute('aria-disabled') === 'true' }));
41
+ let active = 0;
42
+ let typed = { text: '', at: 0 };
43
+ const isOpen = () => !list.hidden;
44
+ const disabled = () => combo.getAttribute('aria-disabled') === 'true';
45
+ const selectedIndex = () => rows().findIndex(li => li.getAttribute('aria-selected') === 'true');
46
+ const enabled = index => { const li = rows()[index]; return !!li && li.getAttribute('aria-disabled') !== 'true'; };
47
+ const move = (from, delta) => {
48
+ const count = rows().length;
49
+ let index = from;
50
+ for (let i = 0; i < count; i++) {
51
+ index = Math.min(count - 1, Math.max(0, index + delta));
52
+ if (enabled(index)) return index;
53
+ if (index === 0 || index === count - 1) break;
54
+ }
55
+ return from;
56
+ };
57
+ const setActive = index => {
58
+ active = Math.max(0, index);
59
+ rows().forEach((li, i) => { li.dataset.active = String(i === active); });
60
+ const current = rows()[active];
61
+ if (current) { combo.setAttribute('aria-activedescendant', current.id); current.scrollIntoView?.({ block: 'nearest' }); }
62
+ };
63
+ const setOpen = (open, index = 0) => {
64
+ if (open && disabled()) return;
65
+ list.hidden = !open;
66
+ root.dataset.open = String(open);
67
+ combo.setAttribute('aria-expanded', String(open));
68
+ if (open) setActive(index); else combo.removeAttribute('aria-activedescendant');
69
+ };
70
+ /** Copies the chosen option into the closed field (text + detail). Also used when the trip card re-renders details. */
71
+ root.dsSyncValue = () => {
72
+ const li = rows()[selectedIndex()];
73
+ valueText.firstChild.textContent = li ? li.dataset.label : root.dataset.placeholder || '';
74
+ valueText.dataset.placeholder = String(!li);
75
+ const hiddenLabel = valueText.querySelector('.ds-wvisually-hidden');
76
+ const metaLabel = li?.dataset.metaLabel;
77
+ if (hiddenLabel) hiddenLabel.textContent = metaLabel ? `, ${metaLabel}` : '';
78
+ if (valueMeta) valueMeta.innerHTML = li?.querySelector('.ds-wmeta')?.outerHTML ?? '';
79
+ };
80
+ const commit = index => {
81
+ const li = rows()[index];
82
+ if (!li || !enabled(index) || li.dataset.value === hidden.value) return;
83
+ rows().forEach((row, i) => row.setAttribute('aria-selected', String(i === index)));
84
+ hidden.value = li.dataset.value;
85
+ root.dsSyncValue();
86
+ emit(root, li.dataset.value);
87
+ };
88
+
89
+ label?.addEventListener('click', () => combo.focus());
90
+ combo.addEventListener('click', () => (isOpen() ? setOpen(false) : setOpen(true, Math.max(0, selectedIndex()))));
91
+ combo.addEventListener('keydown', event => {
92
+ if (disabled()) return;
93
+ const start = Math.max(0, selectedIndex());
94
+ const open = isOpen();
95
+ switch (event.key) {
96
+ case 'ArrowDown':
97
+ case 'ArrowUp':
98
+ event.preventDefault();
99
+ if (!open) setOpen(true, start); else setActive(move(active, event.key === 'ArrowDown' ? 1 : -1));
100
+ return;
101
+ case 'Home':
102
+ event.preventDefault();
103
+ setOpen(true, move(-1, 1));
104
+ return;
105
+ case 'End':
106
+ event.preventDefault();
107
+ setOpen(true, move(rows().length, -1));
108
+ return;
109
+ case 'PageDown':
110
+ case 'PageUp':
111
+ if (open) { event.preventDefault(); setActive(move(active, event.key === 'PageDown' ? 10 : -10)); }
112
+ return;
113
+ case 'Enter':
114
+ case ' ':
115
+ event.preventDefault();
116
+ if (!open) setOpen(true, start); else { commit(active); setOpen(false); }
117
+ return;
118
+ case 'Escape':
119
+ if (open) { event.preventDefault(); setOpen(false); }
120
+ return;
121
+ case 'Tab':
122
+ if (open) { commit(active); setOpen(false); }
123
+ return;
124
+ }
125
+ if (event.key.length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey) {
126
+ const now = Date.now();
127
+ typed = { text: now - typed.at < 600 ? typed.text + event.key : event.key, at: now };
128
+ const from = open ? active : start;
129
+ const index = typeaheadIndex(options(), typed.text, typed.text.length > 1 ? from - 1 : from);
130
+ if (index >= 0) { if (open) setActive(index); else setOpen(true, index); }
131
+ }
132
+ });
133
+ list.addEventListener('mousedown', event => event.preventDefault());
134
+ list.addEventListener('mousemove', event => {
135
+ const index = rows().indexOf(event.target.closest('[role="option"]'));
136
+ if (index >= 0 && index !== active && enabled(index)) setActive(index);
137
+ });
138
+ list.addEventListener('click', event => {
139
+ const index = rows().indexOf(event.target.closest('[role="option"]'));
140
+ if (index < 0 || !enabled(index)) return;
141
+ commit(index);
142
+ setOpen(false);
143
+ combo.focus();
144
+ });
145
+ root.addEventListener('focusout', event => { if (isOpen() && event.relatedTarget && !root.contains(event.relatedTarget)) setOpen(false); });
146
+ document.addEventListener('pointerdown', event => { if (isOpen() && !root.contains(event.target)) setOpen(false); });
147
+ }
148
+
149
+ /** Cantidades de los extras activos: contador (Booster) o número de unidades (Carseat), p. ej. { booster: 2, carseat: 1 }. */
150
+ function readQuantities(root) {
151
+ const result = {};
152
+ // In the extras' order, like syncExtras in React and Angular.
153
+ root.querySelectorAll('[data-ds-quantity], [data-ds-units]').forEach(element => {
154
+ if (element.dataset.dsUnits) {
155
+ const count = element.querySelectorAll(':scope > .ds-wswitch-unit').length;
156
+ if (count) result[element.dataset.dsUnits] = count;
157
+ return;
158
+ }
159
+ const input = element.querySelector('input');
160
+ if (!input.disabled) result[element.dataset.dsQuantity] = Number(input.value);
161
+ });
162
+ return result;
163
+ }
164
+
165
+ /** Opción de cada unidad de los extras activos con choices, p. ej. { carseat: ['0-2', '3-5'] }. */
166
+ function readChoices(root) {
167
+ const result = {};
168
+ root.querySelectorAll('[data-ds-units]').forEach(group => {
169
+ const units = [...group.querySelectorAll(':scope > .ds-wswitch-unit [data-ds-value]')].map(input => input.value);
170
+ if (units.length) result[group.dataset.dsUnits] = units;
171
+ });
172
+ return result;
173
+ }
174
+
175
+ /** Texto de los campos de los extras activos con fields, p. ej. { carga: { weight: '20', value: '' } }. */
176
+ function readFields(root) {
177
+ const result = {};
178
+ root.querySelectorAll('[data-ds-fields]').forEach(group => {
179
+ const inputs = [...group.querySelectorAll('input[data-field]')];
180
+ if (inputs.some(input => input.disabled)) return;
181
+ result[group.dataset.dsFields] = Object.fromEntries(inputs.map(input => [input.dataset.field, input.value]));
182
+ });
183
+ return result;
184
+ }
185
+
186
+ /** A cloned row needs its own ids (WariSelect label, listbox and options) and matching references. */
187
+ function uniquifyIds(node) {
188
+ const suffix = Math.random().toString(36).slice(2, 7);
189
+ const map = new Map();
190
+ node.querySelectorAll('[id]').forEach(element => {
191
+ const next = `${element.id}-${suffix}`;
192
+ map.set(element.id, next);
193
+ element.id = next;
194
+ });
195
+ const refs = ['for', 'aria-labelledby', 'aria-controls', 'aria-describedby', 'aria-activedescendant'];
196
+ node.querySelectorAll('*').forEach(element => {
197
+ for (const attribute of refs) {
198
+ const value = element.getAttribute(attribute);
199
+ if (value) element.setAttribute(attribute, value.split(/\s+/).map(id => map.get(id) ?? id).join(' '));
200
+ }
201
+ });
202
+ }
203
+
204
+ /** Numbers the rows ("Carseat 1", "Carseat 2") and shows the trash / + buttons like Figma. */
205
+ function renderUnits(group) {
206
+ const rows = [...group.querySelectorAll(':scope > .ds-wswitch-unit')];
207
+ const label = group.dataset.label;
208
+ const max = Number(group.dataset.max || 1);
209
+ rows.forEach((row, index) => {
210
+ const name = `${label} ${index + 1}`;
211
+ row.querySelector('[role="combobox"]')?.setAttribute('aria-label', name);
212
+ row.querySelector('[role="listbox"]')?.setAttribute('aria-label', name);
213
+ const remove = row.querySelector('[data-ds-unit-remove]');
214
+ const add = row.querySelector('[data-ds-unit-add]');
215
+ remove.setAttribute('aria-label', `Quitar ${name}`);
216
+ remove.hidden = rows.length < 2;
217
+ add.hidden = index !== rows.length - 1 || rows.length >= max;
218
+ });
219
+ }
220
+
221
+ function addUnit(group) {
222
+ const template = group.querySelector(':scope > template[data-ds-unit-template]');
223
+ const row = template.content.firstElementChild.cloneNode(true);
224
+ uniquifyIds(row);
225
+ group.insertBefore(row, template);
226
+ initWariTripFields(row);
227
+ renderUnits(group);
228
+ return row;
229
+ }
230
+
231
+ const focusLastUnit = group => {
232
+ const combos = group.querySelectorAll('[role="combobox"]');
233
+ combos[combos.length - 1]?.focus();
234
+ };
235
+
236
+ // Emits "ds-change" (valores activos, string[]), "ds-quantities" ({ booster: 2 }) and "ds-choices" ({ carseat: ["0-2"] }).
237
+ function setupSwitches(root) {
238
+ root.dataset.dsReady = '';
239
+ const emitQuantities = () => root.dispatchEvent(new CustomEvent('ds-quantities', { detail: readQuantities(root), bubbles: true }));
240
+ const emitFields = () => root.dispatchEvent(new CustomEvent('ds-fields', { detail: readFields(root), bubbles: true }));
241
+ root.addEventListener('input', event => { if (event.target.matches('input[data-field]')) emitFields(); });
242
+ root.addEventListener('change', event => {
243
+ const input = event.target;
244
+ if (!input.matches('input[role="switch"]')) return;
245
+ const panel = input.getAttribute('aria-controls') ? document.getElementById(input.getAttribute('aria-controls')) : null;
246
+ let quantityChanged = false;
247
+ if (panel) {
248
+ panel.hidden = !input.checked;
249
+ input.setAttribute('aria-expanded', String(input.checked));
250
+ const group = panel.querySelector('[data-ds-units]');
251
+ if (group) {
252
+ // On: one unit with the first option (same as syncExtraChoices). Off: no units, so nothing is submitted.
253
+ group.querySelectorAll(':scope > .ds-wswitch-unit').forEach(row => row.remove());
254
+ if (input.checked) addUnit(group);
255
+ quantityChanged = true;
256
+ }
257
+ // Fields: enabled and empty when on; disabled (so nothing is submitted) when off.
258
+ panel.querySelectorAll('input[data-field]').forEach(field => {
259
+ field.disabled = !input.checked;
260
+ field.value = '';
261
+ });
262
+ if (panel.querySelector('[data-ds-fields]')) emitFields();
263
+ const stepper = panel.querySelector('[data-ds-quantity]');
264
+ if (stepper) {
265
+ const count = stepper.querySelector('input');
266
+ count.disabled = !input.checked;
267
+ // A freshly activated extra starts at 1 (same as syncExtraQuantities).
268
+ if (input.checked) count.value = '1';
269
+ count.dispatchEvent(new Event('blur'));
270
+ stepper.querySelectorAll('.ds-wstepper-button').forEach(button => { if (!input.checked) button.disabled = true; });
271
+ quantityChanged = true;
272
+ }
273
+ }
274
+ emit(root, [...root.querySelectorAll('input[role="switch"]:checked')].map(item => item.value));
275
+ if (quantityChanged) emitQuantities();
276
+ });
277
+ const emitChoices = () => root.dispatchEvent(new CustomEvent('ds-choices', { detail: readChoices(root), bubbles: true }));
278
+ root.addEventListener('click', event => {
279
+ const button = event.target.closest('[data-ds-unit-add], [data-ds-unit-remove]');
280
+ if (!button || button.disabled) return;
281
+ const group = button.closest('[data-ds-units]');
282
+ if (button.matches('[data-ds-unit-add]')) addUnit(group);
283
+ else { button.closest('.ds-wswitch-unit').remove(); renderUnits(group); }
284
+ focusLastUnit(group);
285
+ emitChoices();
286
+ });
287
+ // The pieces' own events stay inside: outside only "ds-change" (active values), "ds-quantities" and "ds-choices" are seen.
288
+ root.addEventListener('ds-change', event => {
289
+ if (event.target === root) return;
290
+ event.stopPropagation();
291
+ if (event.target.closest('[data-ds-units]')) emitChoices(); else emitQuantities();
292
+ }, true);
293
+ }
294
+
295
+ function setupStepper(root) {
296
+ root.dataset.dsReady = '';
297
+ const input = root.querySelector('input');
298
+ const [minus, plus] = root.querySelectorAll('.ds-wstepper-button');
299
+ const min = Number(root.dataset.min ?? 1);
300
+ const max = Number(root.dataset.max ?? 99);
301
+ let value = clampCount(Number(input.value), min, max);
302
+ const set = next => {
303
+ const clamped = clampCount(next, min, max);
304
+ input.value = String(clamped);
305
+ input.setAttribute('aria-valuenow', String(clamped));
306
+ minus.disabled = input.disabled || clamped <= min;
307
+ plus.disabled = input.disabled || clamped >= max;
308
+ if (clamped === value) return;
309
+ value = clamped;
310
+ emit(root, clamped);
311
+ };
312
+ minus.addEventListener('click', () => set(value - 1));
313
+ plus.addEventListener('click', () => set(value + 1));
314
+ input.addEventListener('input', () => { input.value = input.value.replace(/\D/g, ''); });
315
+ input.addEventListener('blur', () => set(input.value.trim() ? Number(input.value) : value));
316
+ input.addEventListener('keydown', event => {
317
+ const moves = { ArrowUp: value + 1, ArrowDown: value - 1, PageUp: value + 10, PageDown: value - 10, Home: min, End: max };
318
+ if (event.key in moves) { event.preventDefault(); set(moves[event.key]); }
319
+ if (event.key === 'Enter') { event.preventDefault(); set(input.value.trim() ? Number(input.value) : value); }
320
+ });
321
+ }
322
+
323
+ function setupTrip(root) {
324
+ root.dataset.dsReady = '';
325
+ initWariTripFields(root);
326
+ const services = JSON.parse(root.dataset.services || '[]');
327
+ const [serviceSelect, paymentSelect] = root.querySelectorAll('[data-ds-wselect]');
328
+ const [modes, extras] = root.querySelectorAll('[data-ds-wswitches]');
329
+ // The vehicles stepper (extras may contain their own quantity steppers).
330
+ const stepper = [...root.querySelectorAll('[data-ds-wstepper]')].find(item => !item.closest('[data-ds-wswitches]'));
331
+ const read = () => {
332
+ const activeModes = [...modes.querySelectorAll('input:checked')].map(input => input.value);
333
+ return {
334
+ service: serviceSelect.querySelector('[data-ds-value]').value,
335
+ hourly: activeModes.includes('hourly'),
336
+ delivery: activeModes.includes('delivery'),
337
+ extras: [...extras.querySelectorAll('input[role="switch"]:checked')].map(input => input.value),
338
+ extraQuantities: readQuantities(extras),
339
+ extraChoices: readChoices(extras),
340
+ extraFields: readFields(extras),
341
+ vehicles: Number(stepper.querySelector('input').value),
342
+ payment: paymentSelect.querySelector('[data-ds-value]').value,
343
+ };
344
+ };
345
+ const renderMeta = () => {
346
+ const value = read();
347
+ serviceSelect.querySelectorAll('[role="option"]').forEach(li => {
348
+ const service = services.find(item => item.value === li.dataset.value);
349
+ if (!service) return;
350
+ const meta = serviceMetaHtml(service, value);
351
+ li.querySelector('.ds-wmeta').innerHTML = meta.html;
352
+ li.dataset.metaLabel = meta.label;
353
+ li.setAttribute('aria-label', `${service.label}, ${meta.label}`);
354
+ });
355
+ serviceSelect.dsSyncValue?.();
356
+ };
357
+ // Capture phase: the pieces' own events never reach listeners on the card (or above); only the full object does.
358
+ root.addEventListener('ds-change', event => {
359
+ if (event.target === root) return;
360
+ event.stopPropagation();
361
+ if (event.target === modes) renderMeta();
362
+ emit(root, read());
363
+ }, true);
364
+ for (const type of ['ds-quantities', 'ds-choices', 'ds-fields']) {
365
+ root.addEventListener(type, event => {
366
+ event.stopPropagation();
367
+ emit(root, read());
368
+ }, true);
369
+ }
370
+ }
@@ -0,0 +1,107 @@
1
+ export interface WariService {
2
+ value: string;
3
+ label: string;
4
+ /** Pasajeros. */
5
+ passengers: number;
6
+ /** Maletas. */
7
+ luggage: number;
8
+ /** Capacidad alternativa que muestra el diseño tras "o" (XL: 4 o 6, Van: 6 o 10). */
9
+ luggageAlt?: number;
10
+ /** Tarifa por horas desde la que se cobra (se muestra como "Desde S/80"). */
11
+ hourlyPrice?: number;
12
+ disabled?: boolean;
13
+ }
14
+ export interface WariOption {
15
+ value: string;
16
+ label: string;
17
+ disabled?: boolean;
18
+ /** Extras: texto que aparece al activarlo (p. ej. "Para niños de 4 hasta 12 años"). */
19
+ description?: string;
20
+ /** Extras: aviso oscuro que aparece al activarlo (p. ej. "Solicítalo con al menos 2 horas de anticipación…"). */
21
+ note?: string;
22
+ /** Extras: cantidad máxima; si se indica, al activarlo aparece un contador de 1 a este número. */
23
+ maxQuantity?: number;
24
+ /**
25
+ * Extras: opciones de cada unidad (p. ej. edades del Carseat). Con `choices`, en lugar del contador cada unidad
26
+ * se elige en una lista; se agregan con + hasta `maxQuantity` y se quitan con la papelera.
27
+ */
28
+ choices?: {
29
+ value: string;
30
+ label: string;
31
+ }[];
32
+ /** Extras: campos de texto que aparecen al activarlo (p. ej. peso y valor de la Carga). */
33
+ fields?: WariExtraField[];
34
+ }
35
+ export interface WariExtraField {
36
+ /** Clave del valor (p. ej. 'weight'). */
37
+ name: string;
38
+ /** Nombre accesible del campo (el placeholder desaparece al escribir y no sirve como etiqueta). */
39
+ label: string;
40
+ placeholder?: string;
41
+ inputMode?: 'text' | 'decimal' | 'numeric';
42
+ /** Ancho fijo (p. ej. '96px'); sin ancho, el campo ocupa el espacio restante. */
43
+ width?: string;
44
+ }
45
+ export interface WariTripAttributesValue {
46
+ service: string;
47
+ hourly: boolean;
48
+ delivery: boolean;
49
+ /** Valores de los extras activos (por defecto: carseat, booster, carga). */
50
+ extras: string[];
51
+ /** Cantidad de cada extra activo que tiene `maxQuantity` (p. ej. { booster: 2 }). */
52
+ extraQuantities: Record<string, number>;
53
+ /** Opción de cada unidad de los extras activos con `choices` (p. ej. { carseat: ['0-2', '3-5'] }). */
54
+ extraChoices: Record<string, string[]>;
55
+ /** Texto de los campos de los extras activos con `fields` (p. ej. { carga: { weight: '20', value: '150' } }). */
56
+ extraFields: Record<string, Record<string, string>>;
57
+ vehicles: number;
58
+ payment: string;
59
+ }
60
+ /** Servicios del diseño de Figma. Reemplázalos con los datos de tu API. */
61
+ export declare const wariServices: WariService[];
62
+ export declare const wariExtras: WariOption[];
63
+ export declare const wariPaymentMethods: WariOption[];
64
+ export declare const defaultTripAttributes: WariTripAttributesValue;
65
+ export interface ServiceMeta {
66
+ /** Mostrar la insignia "Envío". */
67
+ delivery: boolean;
68
+ /** "Desde S/80" cuando el viaje es por horas. */
69
+ price: string | null;
70
+ /** Capacidad cuando no es por horas ni envío. */
71
+ capacity: {
72
+ passengers: number;
73
+ luggage: number;
74
+ luggageAlt?: number;
75
+ } | null;
76
+ /** Texto completo para lectores de pantalla. */
77
+ label: string;
78
+ }
79
+ export declare const formatSoles: (amount: number) => string;
80
+ /** Lo que muestra el diseño a la derecha de cada servicio, según "Por horas" y "Envíos". */
81
+ export declare function serviceMeta(service: WariService, mode: {
82
+ hourly: boolean;
83
+ delivery: boolean;
84
+ }): ServiceMeta;
85
+ export declare function clampCount(value: number, min?: number, max?: number): number;
86
+ /** Type-ahead for select-only comboboxes: next enabled option whose label starts with `query`, after `from`. */
87
+ export declare function typeaheadIndex(options: readonly WariOption[], query: string, from: number): number;
88
+ export declare function toggleExtra(extras: readonly string[], value: string, options?: readonly WariOption[]): string[];
89
+ /** Cantidades solo de los extras activos con `maxQuantity`; un extra recién activado empieza en 1. */
90
+ export declare function syncExtraQuantities(extras: readonly string[], quantities: Readonly<Record<string, number>>, options?: readonly WariOption[]): Record<string, number>;
91
+ /**
92
+ * Opciones por unidad solo de los extras activos con `choices`: un extra recién activado empieza con una unidad
93
+ * (la primera opción), se descartan valores que ya no existen y nunca hay más de `maxQuantity` unidades.
94
+ */
95
+ export declare function syncExtraChoices(extras: readonly string[], choices: Readonly<Record<string, readonly string[]>>, options?: readonly WariOption[]): Record<string, string[]>;
96
+ /** Texto de los campos solo de los extras activos con `fields`; un extra recién activado empieza con los campos vacíos. */
97
+ export declare function syncExtraFields(extras: readonly string[], fields: Readonly<Record<string, Readonly<Record<string, string>>>>, options?: readonly WariOption[]): Record<string, Record<string, string>>;
98
+ export interface WariExtrasState {
99
+ extraQuantities: Record<string, number>;
100
+ extraChoices: Record<string, string[]>;
101
+ extraFields: Record<string, Record<string, string>>;
102
+ }
103
+ /**
104
+ * Cantidades, opciones y campos coherentes con los extras activos. La cantidad de un extra con `choices` es su número
105
+ * de unidades; los extras inactivos no guardan nada.
106
+ */
107
+ export declare function syncExtras(extras: readonly string[], current?: Partial<WariExtrasState>, options?: readonly WariOption[]): WariExtrasState;
@@ -0,0 +1,129 @@
1
+ // Generated from web/components/src/wari/trip.ts (same behaviour in React, Angular and Astro).
2
+ // Data and pure helpers for "Atributos del viaje" (no framework code, easy to test).
3
+ /** Servicios del diseño de Figma. Reemplázalos con los datos de tu API. */
4
+ export const wariServices = [
5
+ { value: 'lite', label: 'Lite', passengers: 4, luggage: 1, hourlyPrice: 80 },
6
+ { value: 'comfort', label: 'Comfort', passengers: 4, luggage: 2, hourlyPrice: 90 },
7
+ { value: 'comfort-xl', label: 'Comfort XL', passengers: 4, luggage: 2, hourlyPrice: 90 },
8
+ { value: 'xl', label: 'XL', passengers: 4, luggage: 4, luggageAlt: 6, hourlyPrice: 90 },
9
+ { value: 'van', label: 'Van', passengers: 7, luggage: 6, luggageAlt: 10, hourlyPrice: 140 },
10
+ ];
11
+ export const wariExtras = [
12
+ {
13
+ value: 'carseat', label: 'Carseat', maxQuantity: 2,
14
+ choices: [{ value: '0-2', label: '0-2 años' }, { value: '3-5', label: '3-5 años' }, { value: '6-10', label: '6-10 años' }],
15
+ note: 'Solicítalo con al menos 2 horas de anticipación a la hora programada.',
16
+ },
17
+ {
18
+ value: 'booster', label: 'Booster', description: 'Para niños de 4 hasta 12 años', maxQuantity: 2,
19
+ note: 'Solicítalo con al menos 2 horas de anticipación a la hora programada.',
20
+ },
21
+ {
22
+ value: 'carga', label: 'Carga',
23
+ fields: [
24
+ { name: 'weight', label: 'Peso aproximado', placeholder: 'Peso aprox.', inputMode: 'decimal', width: '96px' },
25
+ { name: 'value', label: 'Valor estimado en soles', placeholder: 'S/Valor est.', inputMode: 'decimal' },
26
+ ],
27
+ },
28
+ ];
29
+ export const wariPaymentMethods = [
30
+ { value: 'efectivo', label: 'Efectivo' },
31
+ { value: 'tarjeta', label: 'Tarjeta' },
32
+ { value: 'vale', label: 'Vale corporativo' },
33
+ ];
34
+ export const defaultTripAttributes = {
35
+ service: 'lite', hourly: false, delivery: false, extras: [], extraQuantities: {}, extraChoices: {}, extraFields: {}, vehicles: 1, payment: 'efectivo',
36
+ };
37
+ export const formatSoles = (amount) => `S/${Number.isInteger(amount) ? amount : amount.toFixed(2)}`;
38
+ /** Lo que muestra el diseño a la derecha de cada servicio, según "Por horas" y "Envíos". */
39
+ export function serviceMeta(service, mode) {
40
+ const price = mode.hourly && service.hourlyPrice != null ? `Desde ${formatSoles(service.hourlyPrice)}` : null;
41
+ const capacity = !mode.hourly && !mode.delivery
42
+ ? { passengers: service.passengers, luggage: service.luggage, luggageAlt: service.luggageAlt }
43
+ : null;
44
+ const parts = [];
45
+ if (mode.delivery)
46
+ parts.push('envío');
47
+ if (price)
48
+ parts.push(price.toLowerCase());
49
+ if (capacity) {
50
+ parts.push(`${capacity.passengers} pasajeros`);
51
+ parts.push(capacity.luggageAlt != null ? `${capacity.luggage} o ${capacity.luggageAlt} maletas` : `${capacity.luggage} ${capacity.luggage === 1 ? 'maleta' : 'maletas'}`);
52
+ }
53
+ return { delivery: mode.delivery, price, capacity, label: parts.join(', ') };
54
+ }
55
+ export function clampCount(value, min = 1, max = 99) {
56
+ if (!Number.isFinite(value))
57
+ return min;
58
+ return Math.min(max, Math.max(min, Math.round(value)));
59
+ }
60
+ /** Type-ahead for select-only comboboxes: next enabled option whose label starts with `query`, after `from`. */
61
+ export function typeaheadIndex(options, query, from) {
62
+ const needle = query.normalize('NFD').replace(/\p{Diacritic}/gu, '').toLowerCase();
63
+ if (!needle)
64
+ return -1;
65
+ const count = options.length;
66
+ for (let step = 1; step <= count; step++) {
67
+ const index = (from + step + count) % count;
68
+ const option = options[index];
69
+ const label = option.label.normalize('NFD').replace(/\p{Diacritic}/gu, '').toLowerCase();
70
+ if (!option.disabled && label.startsWith(needle))
71
+ return index;
72
+ }
73
+ return -1;
74
+ }
75
+ export function toggleExtra(extras, value, options = wariExtras) {
76
+ const set = new Set(extras);
77
+ if (set.has(value))
78
+ set.delete(value);
79
+ else
80
+ set.add(value);
81
+ return options.filter(option => set.has(option.value)).map(option => option.value);
82
+ }
83
+ /** Cantidades solo de los extras activos con `maxQuantity`; un extra recién activado empieza en 1. */
84
+ export function syncExtraQuantities(extras, quantities, options = wariExtras) {
85
+ const result = {};
86
+ for (const option of options) {
87
+ if (!option.maxQuantity || !extras.includes(option.value))
88
+ continue;
89
+ result[option.value] = clampCount(quantities[option.value] ?? 1, 1, option.maxQuantity);
90
+ }
91
+ return result;
92
+ }
93
+ /**
94
+ * Opciones por unidad solo de los extras activos con `choices`: un extra recién activado empieza con una unidad
95
+ * (la primera opción), se descartan valores que ya no existen y nunca hay más de `maxQuantity` unidades.
96
+ */
97
+ export function syncExtraChoices(extras, choices, options = wariExtras) {
98
+ const result = {};
99
+ for (const option of options) {
100
+ if (!option.choices?.length || !extras.includes(option.value))
101
+ continue;
102
+ const valid = (choices[option.value] ?? []).filter(value => option.choices.some(choice => choice.value === value));
103
+ const max = option.maxQuantity ?? 1;
104
+ result[option.value] = (valid.length ? valid : [option.choices[0].value]).slice(0, Math.max(1, max));
105
+ }
106
+ return result;
107
+ }
108
+ /** Texto de los campos solo de los extras activos con `fields`; un extra recién activado empieza con los campos vacíos. */
109
+ export function syncExtraFields(extras, fields, options = wariExtras) {
110
+ const result = {};
111
+ for (const option of options) {
112
+ if (!option.fields?.length || !extras.includes(option.value))
113
+ continue;
114
+ result[option.value] = Object.fromEntries(option.fields.map(field => [field.name, fields[option.value]?.[field.name] ?? '']));
115
+ }
116
+ return result;
117
+ }
118
+ /**
119
+ * Cantidades, opciones y campos coherentes con los extras activos. La cantidad de un extra con `choices` es su número
120
+ * de unidades; los extras inactivos no guardan nada.
121
+ */
122
+ export function syncExtras(extras, current = {}, options = wariExtras) {
123
+ const extraChoices = syncExtraChoices(extras, current.extraChoices ?? {}, options);
124
+ const extraQuantities = syncExtraQuantities(extras, current.extraQuantities ?? {}, options);
125
+ for (const [value, units] of Object.entries(extraChoices))
126
+ extraQuantities[value] = units.length;
127
+ const extraFields = syncExtraFields(extras, current.extraFields ?? {}, options);
128
+ return { extraQuantities, extraChoices, extraFields };
129
+ }
package/styles.css CHANGED
@@ -1,3 +1,3 @@
1
- /* @directo-ui/astro: design tokens + component styles (generated copies, run `pnpm build`). */
2
- @import "./tokens.css";
3
- @import "./components.css";
1
+ /* @directo-ui/astro: design tokens + component styles (generated copies, run `pnpm build`). */
2
+ @import "./tokens.css";
3
+ @import "./components.css";
package/wari.d.ts ADDED
@@ -0,0 +1,26 @@
1
+ export { default as StatusTag } from './src/components/StatusTag.astro';
2
+ export { default as MultiSelect } from './src/components/MultiSelect.astro';
3
+ export { default as WariStatusSelect } from './src/components/WariStatusSelect.astro';
4
+ export { default as WariDateField } from './src/components/WariDateField.astro';
5
+ export { default as WariTimeField } from './src/components/WariTimeField.astro';
6
+ export { default as WariSchedule } from './src/components/WariSchedule.astro';
7
+ export { default as WariSelect } from './src/components/WariSelect.astro';
8
+ export { default as WariSwitchList } from './src/components/WariSwitchList.astro';
9
+ export { default as WariStepper } from './src/components/WariStepper.astro';
10
+ export { default as WariServiceMeta } from './src/components/WariServiceMeta.astro';
11
+ export { default as WariTripAttributes } from './src/components/WariTripAttributes.astro';
12
+ export { default as WariClientSearch } from './src/components/WariClientSearch.astro';
13
+ export { default as WariClientDetails } from './src/components/WariClientDetails.astro';
14
+ export { default as WariRoute } from './src/components/WariRoute.astro';
15
+ export { default as WariPassengerField } from './src/components/WariPassengerField.astro';
16
+ export type { WariSelectOption } from './src/components/WariSelect.astro';
17
+ export { clampCount, defaultTripAttributes, formatSoles, serviceMeta, syncExtraChoices, syncExtraFields, syncExtraQuantities, syncExtras, toggleExtra, typeaheadIndex, wariExtras, wariPaymentMethods, wariServices } from './src/wari/trip';
18
+ export type { WariService, WariOption, WariExtraField, WariExtrasState, WariTripAttributesValue, ServiceMeta } from './src/wari/trip';
19
+ export { calendarWeeks, formatDisplayDate, formatDisplayTime, parseDisplayDate, parseDisplayTime, parseISODate, parseTime24, toISODate, todayISO } from './src/wari/datetime';
20
+ export type { CalendarDay, TimeParts, Period } from './src/wari/datetime';
21
+ export type { MultiSelectOption } from './src/components/MultiSelect.astro';
22
+ export { wariStatuses, wariStatusLabel } from './src/wari/statuses';
23
+ export type { WariStatus } from './src/wari/statuses';
24
+ export * from './src/wari/logic';
25
+ export { addStop, addToll, createStop, defaultRouteValue, emptyPassenger, invertRoute, moveStop, normalizeRoute, removeStop, removeToll, stopLabel, stopPlaceholder, tollsTotal, updateStop } from './src/wari/route';
26
+ export type { WariPassenger, WariRouteStop, WariRouteValue } from './src/wari/route';