@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,270 @@
1
+ // Markup and client behaviour for <WariRoute> (same HTML as the React and Angular versions). Safe to call many times.
2
+ // The card emits a bubbling "ds-change" CustomEvent with the whole route { stops, passenger, tolls } and "ds-invert" with the
3
+ // inverted route. Set aria-busy="true" on the card while your app recalculates; removing it shows the success notice.
4
+ import {
5
+ addStop, addToll, emptyPassenger, invertRoute, moveStop, normalizeRoute, removeStop, removeToll, stopLabel, stopPlaceholder, updateStop,
6
+ } from './route.js';
7
+ import { formatSoles } from './trip.js';
8
+ import { animateFrom, leave, snapshot } from './motion.js';
9
+
10
+ const svg = (size, body, extra = '') => `<svg width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"${extra}>${body}</svg>`;
11
+ const icons = {
12
+ route: svg(24, '<path d="M6 5h9.5a3.5 3.5 0 0 1 0 7h-7a3.5 3.5 0 0 0 0 7H17"/><circle cx="19" cy="19" r="2" fill="currentColor" stroke="none"/>'),
13
+ plus: svg(16, '<path d="M12 5v14M5 12h14"/>'),
14
+ swap: svg(16, '<path d="M4 9a8 8 0 0 1 14-3l2 2M20 4v4h-4M20 15a8 8 0 0 1-14 3l-2-2M4 20v-4h4"/>'),
15
+ handle: svg(18, '<path d="M5 7h14M5 12h14M5 17h14"/>'),
16
+ close: svg(18, '<path d="M6 6l12 12M18 6 6 18"/>'),
17
+ circle: svg(16, '<circle cx="12" cy="12" r="7.5"/>', ' style="stroke-width:2.4"'),
18
+ square: svg(16, '<rect x="4.5" y="4.5" width="15" height="15" rx="1.5"/>', ' style="stroke-width:2.4"'),
19
+ userPlus: svg(16, '<circle cx="10" cy="8" r="3.5"/><path d="M3.5 20c.8-3.5 3.3-5.5 6.5-5.5s5.7 2 6.5 5.5M18 8v6M15 11h6"/>'),
20
+ user: svg(16, '<circle cx="12" cy="8" r="3.5"/><path d="M5 20c.8-3.5 3.6-5.5 7-5.5s6.2 2 7 5.5"/>'),
21
+ phone: svg(16, '<path d="M5 3.5h3.2l1.6 4-2 1.3a10.5 10.5 0 0 0 5.4 5.4l1.3-2 4 1.6V17a2 2 0 0 1-2 2A15.5 15.5 0 0 1 3 5.5a2 2 0 0 1 2-2Z"/>'),
22
+ plusCircle: svg(16, '<circle cx="12" cy="12" r="9.5" fill="currentColor" stroke="none"/><path d="M12 7.5v9M7.5 12h9" stroke="#fff" stroke-width="2.2"/>'),
23
+ clearCircle: svg(16, '<circle cx="12" cy="12" r="9.5" fill="currentColor" stroke="none"/><path d="m9 9 6 6M15 9l-6 6" stroke="#fff" stroke-width="2"/>'),
24
+ };
25
+
26
+ const esc = value => String(value ?? '').replace(/[&<>"']/g, ch => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[ch]);
27
+ const attr = (name, value) => (value === undefined || value === null || value === false ? '' : value === true ? ` ${name}` : ` ${name}="${esc(value)}"`);
28
+
29
+ /** Default texts and limits. */
30
+ export const routeDefaults = {
31
+ title: 'Ruta', headingLevel: 3, maxStops: 10, maxTolls: 5, showPassengers: true, showTolls: true, disabled: false,
32
+ invertingLabel: 'Invirtiendo direcciones...', invertedMessage: 'Direcciones invertidas con éxito',
33
+ routePassengerNote: 'Este pasajero será el registrado para todas las direcciones de la ruta.',
34
+ };
35
+
36
+ function passengerHtml(passenger, scope, stop, disabled) {
37
+ return `<div class="ds-wroute-passenger" role="group" aria-label="${esc(`Pasajero: ${scope}`)}" data-passenger="${stop}">`
38
+ + `<label>${icons.user}<input class="ds-wroute-input" type="text" autocomplete="name" placeholder="Nombre del pasajero" aria-label="Nombre del pasajero" data-field="name" value="${esc(passenger.name)}"${attr('disabled', disabled)}></label>`
39
+ + `<label>${icons.phone}<input class="ds-wroute-input" type="tel" autocomplete="tel" inputmode="tel" placeholder="Ingresa el número del pasajero" aria-label="Número del pasajero" data-field="phone" value="${esc(passenger.phone)}"${attr('disabled', disabled)}></label>`
40
+ + `<button type="button" class="ds-wroute-clear" aria-label="${esc(`Quitar pasajero: ${scope}`)}" data-action="passenger-remove"${attr('disabled', disabled)}>${icons.clearCircle}</button>`
41
+ + '</div>';
42
+ }
43
+
44
+ /**
45
+ * Inner HTML of the card (everything inside <section class="ds-wcard ds-wroute">). Used by WariRoute.astro on the server and
46
+ * by the client after each structural change.
47
+ */
48
+ export function routeHtml(value, options = {}, baseId = 'ds-wroute') {
49
+ const o = { ...routeDefaults, ...options };
50
+ const route = normalizeRoute(value);
51
+ const dis = Boolean(o.disabled);
52
+ const busy = Boolean(o.inverting);
53
+ let html = `<header class="ds-wcard-header">${icons.route}<span class="ds-wcard-title" role="heading" aria-level="${o.headingLevel}" id="${baseId}-title">${esc(o.title)}</span>`;
54
+ if (o.showPassengers && !route.passenger && !busy) {
55
+ html += `<button type="button" class="ds-wroute-pill" data-motion="pill" data-action="route-passenger"${attr('disabled', dis)}>${icons.plus}Añadir pasajero (ruta completa)</button>`;
56
+ }
57
+ html += `<span class="ds-wroute-header-spacer"></span><button type="button" class="ds-wroute-link" data-action="invert"${attr('disabled', dis || busy)}>${icons.swap}Invertir</button></header>`;
58
+ if (busy) {
59
+ return `${html}<div class="ds-wroute-status" role="status" data-motion="status"><div class="ds-wclient-progress" role="progressbar" aria-label="${esc(o.invertingLabel)}"></div>${esc(o.invertingLabel)}</div>`;
60
+ }
61
+ if (o.inverted) html += `<p class="ds-wroute-success" role="status">${esc(o.invertedMessage)}</p>`;
62
+ if (route.passenger) {
63
+ html += `<div class="ds-wroute-passenger-block" data-motion="route-passenger">${passengerHtml(route.passenger, 'ruta completa', -1, dis)}<p class="ds-wroute-info">${esc(o.routePassengerNote)}</p></div>`;
64
+ }
65
+ html += '<ol class="ds-wroute-stops" aria-label="Paradas">';
66
+ route.stops.forEach((stop, index) => {
67
+ const name = stopLabel(index);
68
+ html += `<li class="ds-wroute-stop" data-stop="${esc(stop.id)}" data-motion="stop:${esc(stop.id)}" data-index="${index}">`
69
+ + `<button type="button" class="ds-wroute-handle"${attr('draggable', dis ? 'false' : 'true')} aria-label="${esc(`Mover ${name}`)}" aria-describedby="${baseId}-move-hint"${attr('disabled', dis)}>${icons.handle}</button>`
70
+ + '<div class="ds-wroute-stop-box"><div class="ds-wroute-stop-main">'
71
+ + `<label class="ds-wroute-address">${index === 0 ? icons.circle : icons.square}<input class="ds-wroute-input" type="text" autocomplete="off" placeholder="${esc(stopPlaceholder(index))}" aria-label="${esc(`Dirección: ${name}`)}" data-field="address" value="${esc(stop.address)}"${attr('disabled', dis)}></label>`
72
+ + `<span class="ds-wroute-zone"><strong>Zona</strong>${esc(stop.zone || 'Sin definir')}</span>`
73
+ + (stop.price != null ? `<span class="ds-wroute-price">${esc(formatSoles(stop.price))}</span>` : '')
74
+ + '</div><div class="ds-wroute-stop-extra">'
75
+ + `<input class="ds-wroute-input ds-wroute-input-sm" type="text" autocomplete="off" placeholder="Escribe la referencia" aria-label="${esc(`Referencia: ${name}`)}" data-field="reference" value="${esc(stop.reference)}"${attr('disabled', dis)}>`
76
+ + (o.showPassengers && !stop.passenger ? `<button type="button" class="ds-wroute-stop-passenger" aria-label="${esc(`Añadir pasajero: ${name}`)}" data-action="stop-passenger"${attr('disabled', dis)}>${icons.userPlus}Añadir Pasajero</button>` : '')
77
+ + '</div>'
78
+ + (stop.passenger ? `<div class="ds-wroute-stop-passenger-wrap" data-motion="passenger:${esc(stop.id)}">${passengerHtml(stop.passenger, name, index, dis)}</div>` : '')
79
+ + `</div><button type="button" class="ds-wroute-remove" aria-label="${esc(`${route.stops.length > 2 ? 'Quitar' : 'Vaciar'} ${name}`)}" data-action="stop-remove"${attr('disabled', dis)}>${icons.close}</button></li>`;
80
+ });
81
+ html += `</ol><span id="${baseId}-move-hint" class="ds-wvisually-hidden">Arrastra o usa las flechas arriba y abajo para cambiar el orden.</span>`;
82
+ html += `<button type="button" class="ds-wroute-add" data-motion="add" data-action="stop-add"${attr('disabled', dis || route.stops.length >= o.maxStops)}>${icons.plusCircle}Agregar destino</button>`;
83
+ if (o.showTolls) {
84
+ html += '<div class="ds-wroute-tolls" role="group" aria-label="Peajes" data-motion="tolls">';
85
+ route.tolls.forEach((toll, index) => {
86
+ html += `<div class="ds-wroute-toll" data-toll="${index}" data-motion="toll:${index}"><label for="${baseId}-toll-${index}">Peaje ${index + 1}</label>`
87
+ + `<input id="${baseId}-toll-${index}" class="ds-wroute-input" type="text" inputmode="decimal" placeholder="S/ 0.00" data-field="toll" value="${esc(toll)}"${attr('disabled', dis)}>`
88
+ + (route.tolls.length > 1 ? `<button type="button" class="ds-wroute-clear" aria-label="Quitar peaje ${index + 1}" data-action="toll-remove"${attr('disabled', dis)}>${icons.close}</button>` : '')
89
+ + '</div>';
90
+ });
91
+ html += `<button type="button" class="ds-wroute-toll-add" data-action="toll-add"${attr('disabled', dis || route.tolls.length >= o.maxTolls)}>${icons.plusCircle}Agregar peaje</button></div>`;
92
+ }
93
+ return html;
94
+ }
95
+
96
+ export function initWariRoute(scope = document) {
97
+ scope.querySelectorAll('[data-ds-wroute]:not([data-ds-ready])').forEach(setupRoute);
98
+ }
99
+
100
+ function readOptions(root) {
101
+ const d = root.dataset;
102
+ return {
103
+ title: d.title ?? routeDefaults.title,
104
+ headingLevel: Number(d.headingLevel) || routeDefaults.headingLevel,
105
+ maxStops: Number(d.maxStops) || routeDefaults.maxStops,
106
+ maxTolls: Number(d.maxTolls) || routeDefaults.maxTolls,
107
+ showPassengers: d.showPassengers !== 'false',
108
+ showTolls: d.showTolls !== 'false',
109
+ disabled: d.disabled === 'true',
110
+ invertingLabel: d.invertingLabel ?? routeDefaults.invertingLabel,
111
+ invertedMessage: d.invertedMessage ?? routeDefaults.invertedMessage,
112
+ routePassengerNote: d.routePassengerNote ?? routeDefaults.routePassengerNote,
113
+ };
114
+ }
115
+
116
+ function setupRoute(root) {
117
+ root.dataset.dsReady = '';
118
+ const baseId = root.dataset.baseId || `ds-wroute-${Math.random().toString(36).slice(2, 9)}`;
119
+ const hidden = root.querySelector('input[type="hidden"][data-ds-value]');
120
+ let route;
121
+ try { route = normalizeRoute(JSON.parse(root.dataset.value || 'null')); } catch { route = normalizeRoute(null); }
122
+ let inverted = false;
123
+ let successTimer;
124
+ let dragFrom = null;
125
+ const content = root.querySelector('[data-ds-route-content]') ?? root;
126
+
127
+ const render = focusSelector => {
128
+ const before = snapshot(content);
129
+ content.innerHTML = routeHtml(route, { ...readOptions(root), inverting: root.getAttribute('aria-busy') === 'true', inverted }, baseId);
130
+ animateFrom(content, before);
131
+ if (focusSelector) content.querySelector(focusSelector)?.focus();
132
+ };
133
+ const leaveThen = (button, change) => leave(button.closest('[data-motion]'), change);
134
+ const emit = () => {
135
+ if (hidden) hidden.value = JSON.stringify(route);
136
+ root.dispatchEvent(new CustomEvent('ds-change', { detail: route, bubbles: true }));
137
+ };
138
+ const set = (next, focusSelector) => { route = next; render(focusSelector); emit(); };
139
+ const showSuccess = show => {
140
+ clearTimeout(successTimer);
141
+ inverted = show;
142
+ if (show) successTimer = setTimeout(() => { inverted = false; root.querySelector('.ds-wroute-success')?.remove(); }, 3000);
143
+ };
144
+ const indexOf = element => Number(element.closest('[data-index]')?.dataset.index ?? -1);
145
+
146
+ /** Lets your app replace the route (e.g. after geocoding sets zone and price): card.dsSetValue(route). */
147
+ root.dsSetValue = value => { route = normalizeRoute(value); render(); if (hidden) hidden.value = JSON.stringify(route); };
148
+ root.dsGetValue = () => route;
149
+
150
+ // Typing updates the value without re-rendering (keeps focus and caret).
151
+ root.addEventListener('input', event => {
152
+ const input = event.target;
153
+ const field = input.dataset?.field;
154
+ if (!field) return;
155
+ if (field === 'toll') {
156
+ const index = Number(input.closest('[data-toll]').dataset.toll);
157
+ route = { ...route, tolls: route.tolls.map((toll, i) => (i === index ? input.value : toll)) };
158
+ } else if (field === 'name' || field === 'phone') {
159
+ const stop = Number(input.closest('[data-passenger]').dataset.passenger);
160
+ const current = stop < 0 ? route.passenger : route.stops[stop].passenger;
161
+ const passenger = { ...emptyPassenger(), ...current, [field]: input.value };
162
+ route = stop < 0 ? { ...route, passenger } : { ...route, stops: updateStop(route.stops, stop, { passenger }) };
163
+ } else {
164
+ route = { ...route, stops: updateStop(route.stops, indexOf(input), { [field]: input.value }) };
165
+ }
166
+ emit();
167
+ });
168
+
169
+ root.addEventListener('click', async event => {
170
+ const button = event.target.closest?.('[data-action]');
171
+ if (!button || button.disabled || !root.contains(button)) return;
172
+ const index = indexOf(button);
173
+ const o = readOptions(root);
174
+ switch (button.dataset.action) {
175
+ case 'route-passenger': set({ ...route, passenger: emptyPassenger() }, '[data-passenger="-1"] input'); break;
176
+ case 'stop-passenger': set({ ...route, stops: updateStop(route.stops, index, { passenger: emptyPassenger() }) }, `[data-passenger="${index}"] input`); break;
177
+ case 'passenger-remove': {
178
+ const stop = Number(button.closest('[data-passenger]').dataset.passenger);
179
+ leaveThen(button, () => {
180
+ if (stop < 0) set({ ...route, passenger: null }, '.ds-wroute-pill');
181
+ else set({ ...route, stops: updateStop(route.stops, stop, { passenger: null }) }, `[data-index="${stop}"] .ds-wroute-stop-passenger`);
182
+ });
183
+ break;
184
+ }
185
+ case 'stop-remove': {
186
+ const stops = removeStop(route.stops, index);
187
+ const change = () => set({ ...route, stops }, `[data-index="${Math.min(index, stops.length - 1)}"] input[data-field="address"]`);
188
+ if (route.stops.length > 2) leaveThen(button, change); else change();
189
+ break;
190
+ }
191
+ case 'stop-add': {
192
+ const stops = addStop(route.stops, o.maxStops);
193
+ set({ ...route, stops }, `[data-index="${stops.length - 1}"] input[data-field="address"]`);
194
+ break;
195
+ }
196
+ case 'toll-add': {
197
+ const tolls = addToll(route.tolls, o.maxTolls);
198
+ set({ ...route, tolls }, `[data-toll="${tolls.length - 1}"] input`);
199
+ break;
200
+ }
201
+ case 'toll-remove': {
202
+ const toll = Number(button.closest('[data-toll]').dataset.toll);
203
+ leaveThen(button, () => set({ ...route, tolls: removeToll(route.tolls, toll) }, '.ds-wroute-toll-add'));
204
+ break;
205
+ }
206
+ case 'invert': {
207
+ const next = invertRoute(route);
208
+ showSuccess(false);
209
+ root.dispatchEvent(new CustomEvent('ds-invert', { detail: next, bubbles: true }));
210
+ route = next;
211
+ emit();
212
+ const delay = Number(root.dataset.invertDelay) || 0;
213
+ if (delay > 0) {
214
+ root.setAttribute('aria-busy', 'true');
215
+ setTimeout(() => root.removeAttribute('aria-busy'), delay);
216
+ } else if (root.getAttribute('aria-busy') !== 'true') {
217
+ showSuccess(true);
218
+ render('.ds-wroute-link');
219
+ }
220
+ break;
221
+ }
222
+ }
223
+ });
224
+
225
+ root.addEventListener('keydown', event => {
226
+ const handle = event.target.closest?.('.ds-wroute-handle');
227
+ if (!handle) return;
228
+ const index = indexOf(handle);
229
+ const to = event.key === 'ArrowUp' ? index - 1 : event.key === 'ArrowDown' ? index + 1 : -1;
230
+ if (to < 0 || to >= route.stops.length) return;
231
+ event.preventDefault();
232
+ const id = route.stops[index].id;
233
+ set({ ...route, stops: moveStop(route.stops, index, to) }, `[data-stop="${CSS.escape(id)}"] .ds-wroute-handle`);
234
+ });
235
+
236
+ root.addEventListener('dragstart', event => {
237
+ const handle = event.target.closest?.('.ds-wroute-handle');
238
+ if (!handle) return;
239
+ dragFrom = indexOf(handle);
240
+ handle.closest('li').dataset.dragging = 'true';
241
+ event.dataTransfer.effectAllowed = 'move';
242
+ event.dataTransfer.setData('text/plain', route.stops[dragFrom].id);
243
+ });
244
+ root.addEventListener('dragover', event => {
245
+ const li = event.target.closest?.('.ds-wroute-stop');
246
+ if (dragFrom === null || !li) return;
247
+ event.preventDefault();
248
+ content.querySelectorAll('[data-drop]').forEach(el => el.removeAttribute('data-drop'));
249
+ if (indexOf(li) !== dragFrom) li.dataset.drop = 'true';
250
+ });
251
+ root.addEventListener('drop', event => {
252
+ const li = event.target.closest?.('.ds-wroute-stop');
253
+ if (dragFrom === null || !li) return;
254
+ event.preventDefault();
255
+ const from = dragFrom;
256
+ dragFrom = null;
257
+ set({ ...route, stops: moveStop(route.stops, from, indexOf(li)) });
258
+ });
259
+ root.addEventListener('dragend', () => {
260
+ dragFrom = null;
261
+ content.querySelectorAll('[data-drop], [data-dragging]').forEach(el => { el.removeAttribute('data-drop'); el.removeAttribute('data-dragging'); });
262
+ });
263
+
264
+ // aria-busy="true" from your app (or invertDelay) shows "Invirtiendo direcciones..."; removing it shows the success notice.
265
+ new MutationObserver(() => {
266
+ const busy = root.getAttribute('aria-busy') === 'true';
267
+ if (!busy && content.querySelector('.ds-wroute-status')) showSuccess(true);
268
+ render(busy ? undefined : '.ds-wroute-link');
269
+ }).observe(root, { attributes: true, attributeFilter: ['aria-busy', 'data-disabled'] });
270
+ }
@@ -0,0 +1,48 @@
1
+ export interface WariPassenger {
2
+ name: string;
3
+ phone: string;
4
+ }
5
+ export interface WariRouteStop {
6
+ /** Identificador estable (para reordenar sin perder el foco ni el texto). */
7
+ id: string;
8
+ address: string;
9
+ reference: string;
10
+ /** Zona calculada por tu app al elegir la dirección; sin zona se muestra "Sin definir". */
11
+ zone?: string;
12
+ /** Tarifa de la parada en soles; sin precio no se muestra. */
13
+ price?: number;
14
+ /** Pasajero solo de esta parada ("Añadir Pasajero" en la parada); null = sin pasajero propio. */
15
+ passenger?: WariPassenger | null;
16
+ }
17
+ export interface WariRouteValue {
18
+ /** La primera parada es el origen; las demás, destinos. */
19
+ stops: WariRouteStop[];
20
+ /** Pasajero para toda la ruta ("Añadir pasajero (ruta completa)"); null = sin pasajero. */
21
+ passenger: WariPassenger | null;
22
+ /** Montos de los peajes, como texto (p. ej. ['4.50', '']). */
23
+ tolls: string[];
24
+ }
25
+ export declare function createStop(partial?: Partial<WariRouteStop>): WariRouteStop;
26
+ /** Ruta vacía: origen, un destino y un peaje sin monto. */
27
+ export declare function defaultRouteValue(): WariRouteValue;
28
+ export declare const emptyPassenger: () => WariPassenger;
29
+ /** Mueve una parada de `from` a `to` (índices); fuera de rango no cambia nada. */
30
+ export declare function moveStop(stops: readonly WariRouteStop[], from: number, to: number): WariRouteStop[];
31
+ /** "Invertir": el último destino pasa a ser el origen y viceversa. */
32
+ export declare function invertRoute(value: WariRouteValue): WariRouteValue;
33
+ /** Agrega un destino al final, sin pasar de `maxStops`. */
34
+ export declare function addStop(stops: readonly WariRouteStop[], maxStops?: number): WariRouteStop[];
35
+ /** Quita una parada; con solo dos (origen y un destino) la vacía en lugar de quitarla. */
36
+ export declare function removeStop(stops: readonly WariRouteStop[], index: number): WariRouteStop[];
37
+ export declare function updateStop(stops: readonly WariRouteStop[], index: number, patch: Partial<WariRouteStop>): WariRouteStop[];
38
+ /** Agrega un peaje vacío, sin pasar de `maxTolls`. */
39
+ export declare function addToll(tolls: readonly string[], maxTolls?: number): string[];
40
+ /** Quita un peaje; el primero nunca se quita (se vacía). */
41
+ export declare function removeToll(tolls: readonly string[], index: number): string[];
42
+ /** Suma de los peajes válidos (acepta coma o punto decimal). */
43
+ export declare function tollsTotal(tolls: readonly string[]): number;
44
+ export declare function stopPlaceholder(index: number): string;
45
+ /** Nombre accesible de una parada: "Origen" o "Destino 1", "Destino 2"… */
46
+ export declare function stopLabel(index: number): string;
47
+ /** Acepta valores parciales o de versiones anteriores y los completa. */
48
+ export declare function normalizeRoute(value: Partial<WariRouteValue> | null | undefined): WariRouteValue;
@@ -0,0 +1,71 @@
1
+ // Generated from web/components/src/wari/route.ts (same behaviour in React, Angular and Astro).
2
+ // Data and pure helpers for the Wari route editor ("Rutas"). No framework code, easy to test.
3
+ let nextStop = 0;
4
+ export function createStop(partial = {}) {
5
+ nextStop += 1;
6
+ return { id: `stop-${Date.now().toString(36)}-${nextStop}`, address: '', reference: '', passenger: null, ...partial };
7
+ }
8
+ /** Ruta vacía: origen, un destino y un peaje sin monto. */
9
+ export function defaultRouteValue() {
10
+ return { stops: [createStop(), createStop()], passenger: null, tolls: [''] };
11
+ }
12
+ export const emptyPassenger = () => ({ name: '', phone: '' });
13
+ /** Mueve una parada de `from` a `to` (índices); fuera de rango no cambia nada. */
14
+ export function moveStop(stops, from, to) {
15
+ if (from === to || from < 0 || to < 0 || from >= stops.length || to >= stops.length)
16
+ return [...stops];
17
+ const next = [...stops];
18
+ const [moved] = next.splice(from, 1);
19
+ next.splice(to, 0, moved);
20
+ return next;
21
+ }
22
+ /** "Invertir": el último destino pasa a ser el origen y viceversa. */
23
+ export function invertRoute(value) {
24
+ return { ...value, stops: [...value.stops].reverse() };
25
+ }
26
+ /** Agrega un destino al final, sin pasar de `maxStops`. */
27
+ export function addStop(stops, maxStops = 10) {
28
+ return stops.length >= maxStops ? [...stops] : [...stops, createStop()];
29
+ }
30
+ /** Quita una parada; con solo dos (origen y un destino) la vacía en lugar de quitarla. */
31
+ export function removeStop(stops, index) {
32
+ if (index < 0 || index >= stops.length)
33
+ return [...stops];
34
+ if (stops.length <= 2)
35
+ return stops.map((stop, i) => (i === index ? { ...stop, address: '', reference: '', zone: undefined, price: undefined, passenger: null } : stop));
36
+ return stops.filter((_, i) => i !== index);
37
+ }
38
+ export function updateStop(stops, index, patch) {
39
+ return stops.map((stop, i) => (i === index ? { ...stop, ...patch } : stop));
40
+ }
41
+ /** Agrega un peaje vacío, sin pasar de `maxTolls`. */
42
+ export function addToll(tolls, maxTolls = 5) {
43
+ return tolls.length >= maxTolls ? [...tolls] : [...tolls, ''];
44
+ }
45
+ /** Quita un peaje; el primero nunca se quita (se vacía). */
46
+ export function removeToll(tolls, index) {
47
+ if (tolls.length <= 1)
48
+ return [''];
49
+ return tolls.filter((_, i) => i !== index);
50
+ }
51
+ /** Suma de los peajes válidos (acepta coma o punto decimal). */
52
+ export function tollsTotal(tolls) {
53
+ return tolls.reduce((sum, toll) => {
54
+ const amount = Number(toll.replace(',', '.'));
55
+ return Number.isFinite(amount) && amount > 0 ? sum + amount : sum;
56
+ }, 0);
57
+ }
58
+ export function stopPlaceholder(index) {
59
+ return index === 0 ? '¿Dónde recogemos al cliente?' : '¿A dónde lo llevamos?';
60
+ }
61
+ /** Nombre accesible de una parada: "Origen" o "Destino 1", "Destino 2"… */
62
+ export function stopLabel(index) {
63
+ return index === 0 ? 'Origen' : `Destino ${index}`;
64
+ }
65
+ /** Acepta valores parciales o de versiones anteriores y los completa. */
66
+ export function normalizeRoute(value) {
67
+ const stops = value?.stops?.length ? value.stops.map(stop => ({ passenger: null, ...stop })) : defaultRouteValue().stops;
68
+ while (stops.length < 2)
69
+ stops.push(createStop());
70
+ return { stops, passenger: value?.passenger ?? null, tolls: value?.tolls?.length ? [...value.tolls] : [''] };
71
+ }
@@ -0,0 +1,14 @@
1
+ export declare const wariStatuses: readonly [
2
+ { value: 'libre'; label: 'Libre' },
3
+ { value: 'aceptado'; label: 'Aceptado' },
4
+ { value: 'contacto'; label: 'Contacto' },
5
+ { value: 'inicio'; label: 'Inició' },
6
+ { value: 'llego'; label: 'Llegó' },
7
+ { value: 'terminado'; label: 'Terminado' },
8
+ { value: 'preasignado'; label: 'Preasignado' },
9
+ { value: 'anulado-operador'; label: 'Anulado Operador' },
10
+ { value: 'anulado-usuario'; label: 'Anulado Usuario' },
11
+ { value: 'empalmado'; label: 'Empalmado' },
12
+ ];
13
+ export type WariStatus = (typeof wariStatuses)[number]['value'];
14
+ export declare function wariStatusLabel(status: WariStatus | string): string;
@@ -0,0 +1,15 @@
1
+ /** Estados de un servicio en Wari, en el orden en que aparecen en Figma. */
2
+ export const wariStatuses = [
3
+ { value: 'libre', label: 'Libre' },
4
+ { value: 'aceptado', label: 'Aceptado' },
5
+ { value: 'contacto', label: 'Contacto' },
6
+ { value: 'inicio', label: 'Inició' },
7
+ { value: 'llego', label: 'Llegó' },
8
+ { value: 'terminado', label: 'Terminado' },
9
+ { value: 'preasignado', label: 'Preasignado' },
10
+ { value: 'anulado-operador', label: 'Anulado Operador' },
11
+ { value: 'anulado-usuario', label: 'Anulado Usuario' },
12
+ { value: 'empalmado', label: 'Empalmado' },
13
+ ];
14
+
15
+ export const wariStatusLabel = status => wariStatuses.find(item => item.value === status)?.label ?? status;
@@ -0,0 +1,4 @@
1
+ import type { WariService } from './trip';
2
+ /** Inicializa selectores, interruptores, contadores y tarjetas de atributos de Wari. Idempotente. */
3
+ export declare function initWariTripFields(scope?: ParentNode): void;
4
+ export declare function serviceMetaHtml(service: WariService, mode: { hourly: boolean; delivery: boolean }): { html: string; label: string };