@directo-ui/astro 1.1.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/files.js ADDED
@@ -0,0 +1,52 @@
1
+ // File selection rules shared by FileUpload in React, Angular and Astro (same file in the three packages).
2
+ /** 1536 → "1.5 KB". */
3
+ export function formatBytes(bytes) {
4
+ if (!Number.isFinite(bytes) || bytes < 1024)
5
+ return `${Math.max(0, Math.round(bytes || 0))} B`;
6
+ const units = ['KB', 'MB', 'GB'];
7
+ let value = bytes / 1024;
8
+ let unit = 0;
9
+ while (value >= 1024 && unit < units.length - 1) {
10
+ value /= 1024;
11
+ unit++;
12
+ }
13
+ return `${Number(value.toFixed(value < 10 ? 1 : 0))} ${units[unit]}`;
14
+ }
15
+ /** True when the file matches one of the accept rules (or there are none). */
16
+ export function acceptsFile(file, accept) {
17
+ const rules = accept?.toLowerCase().split(',').map(rule => rule.trim()).filter(Boolean) ?? [];
18
+ if (!rules.length)
19
+ return true;
20
+ const type = file.type.toLowerCase();
21
+ const name = file.name.toLowerCase();
22
+ return rules.some(rule => rule.startsWith('.') ? name.endsWith(rule)
23
+ : rule.endsWith('/*') ? type.startsWith(rule.slice(0, -1)) : type === rule);
24
+ }
25
+ const sameFile = (a, b) => a.name === b.name && a.size === b.size && a.lastModified === b.lastModified;
26
+ /**
27
+ * Adds `incoming` to the `current` selection: with multiple the files are appended (without duplicates),
28
+ * otherwise the first valid file replaces the selection. Returns the kept files and why the others were left out.
29
+ */
30
+ export function selectFiles(current, incoming, rules = {}) {
31
+ const rejections = [];
32
+ const files = rules.multiple ? [...current] : [];
33
+ const limit = rules.multiple ? (rules.maxFiles && rules.maxFiles > 0 ? Math.floor(rules.maxFiles) : Infinity) : 1;
34
+ for (const file of incoming) {
35
+ if (!acceptsFile(file, rules.accept)) {
36
+ rejections.push({ file, reason: 'type', message: `${file.name}: formato no admitido.` });
37
+ }
38
+ else if (rules.maxBytes !== undefined && file.size > rules.maxBytes) {
39
+ rejections.push({ file, reason: 'size', message: `${file.name}: supera el tamaño máximo (${formatBytes(rules.maxBytes)}).` });
40
+ }
41
+ else if (files.some(kept => sameFile(kept, file))) {
42
+ continue;
43
+ }
44
+ else if (files.length >= limit) {
45
+ rejections.push({ file, reason: 'count', message: `${file.name}: solo se permiten ${limit} archivo${limit === 1 ? '' : 's'}.` });
46
+ }
47
+ else {
48
+ files.push(file);
49
+ }
50
+ }
51
+ return { files, rejections };
52
+ }
package/src/modal.d.ts CHANGED
@@ -1,3 +1,3 @@
1
- export declare function initModals(root?: ParentNode): void;
2
- export declare function openModal(id: string, opener?: HTMLElement): void;
3
- export declare function closeModal(id: string): void;
1
+ export declare function initModals(root?: ParentNode | Event): void;
2
+ export declare function openModal(id: string, opener?: HTMLElement): void;
3
+ export declare function closeModal(id: string): void;
package/src/modal.js CHANGED
@@ -1,39 +1,50 @@
1
- /**
2
- * Wires native <dialog data-ds-modal> elements:
3
- * - any element with data-ds-open="<dialog id>" opens it as a modal,
4
- * - any [data-ds-close] inside closes it, as does a backdrop click or Escape,
5
- * - focus returns to the opener. Safe to call repeatedly.
6
- * @param {ParentNode} [root=document]
7
- */
8
- export function initModals(root = document) {
9
- root.querySelectorAll('[data-ds-open]:not([data-ds-ready])').forEach(trigger => {
10
- trigger.dataset.dsReady = '';
11
- trigger.setAttribute('aria-haspopup', 'dialog');
12
- trigger.addEventListener('click', () => openModal(trigger.dataset.dsOpen ?? '', trigger));
13
- });
14
- root.querySelectorAll('dialog[data-ds-modal]:not([data-ds-ready])').forEach(dialog => {
15
- dialog.dataset.dsReady = '';
16
- dialog.addEventListener('click', event => {
17
- const target = event.target;
18
- if (target === dialog || (target instanceof Element && target.closest('[data-ds-close]'))) dialog.close();
19
- });
20
- if (dialog.hasAttribute('data-ds-open-initially')) dialog.showModal();
21
- });
22
- }
23
-
24
- const openers = new WeakMap();
25
-
26
- /** @param {string} id @param {HTMLElement} [opener] */
27
- export function openModal(id, opener) {
28
- const dialog = document.getElementById(id);
29
- if (!(dialog instanceof HTMLDialogElement) || dialog.open) return;
30
- if (opener) openers.set(dialog, opener);
31
- dialog.showModal();
32
- dialog.addEventListener('close', () => openers.get(dialog)?.focus({ preventScroll: true }), { once: true });
33
- }
34
-
35
- /** @param {string} id */
36
- export function closeModal(id) {
37
- const dialog = document.getElementById(id);
38
- if (dialog instanceof HTMLDialogElement) dialog.close();
39
- }
1
+ /**
2
+ * Wires native <dialog data-ds-modal> elements:
3
+ * - any element with data-ds-open="<dialog id>" opens it as a modal,
4
+ * - any [data-ds-close] inside closes it, as does a backdrop click or Escape,
5
+ * - focus returns to the opener. Safe to call repeatedly.
6
+ * - data-ds-backdrop="static" keeps it open on backdrop clicks; data-ds-escape="false" ignores Escape.
7
+ * - the dialog emits ds-open and ds-close (bubbling CustomEvents) besides the native close event.
8
+ * @param {ParentNode | Event} [root=document]
9
+ */
10
+ export function initModals(root = document) {
11
+ // Also works as an event listener (astro:page-load passes an Event).
12
+ const scope = root && typeof root.querySelectorAll === 'function' ? root : document;
13
+ scope.querySelectorAll('[data-ds-open]:not([data-ds-ready])').forEach(trigger => {
14
+ trigger.dataset.dsReady = '';
15
+ trigger.setAttribute('aria-haspopup', 'dialog');
16
+ trigger.addEventListener('click', () => openModal(trigger.dataset.dsOpen ?? '', trigger));
17
+ });
18
+ scope.querySelectorAll('dialog[data-ds-modal]:not([data-ds-ready])').forEach(dialog => {
19
+ dialog.dataset.dsReady = '';
20
+ dialog.addEventListener('click', event => {
21
+ const target = event.target;
22
+ const backdrop = target === dialog && dialog.dataset.dsBackdrop !== 'static';
23
+ if (backdrop || (target instanceof Element && target.closest('[data-ds-close]'))) dialog.close();
24
+ });
25
+ dialog.addEventListener('cancel', event => { if (dialog.dataset.dsEscape === 'false') event.preventDefault(); });
26
+ dialog.addEventListener('close', () => dialog.dispatchEvent(new CustomEvent('ds-close', { bubbles: true })));
27
+ if (dialog.hasAttribute('data-ds-open-initially') && !dialog.open) {
28
+ dialog.showModal();
29
+ dialog.dispatchEvent(new CustomEvent('ds-open', { bubbles: true, detail: { opener: undefined } }));
30
+ }
31
+ });
32
+ }
33
+
34
+ const openers = new WeakMap();
35
+
36
+ /** @param {string} id @param {HTMLElement} [opener] */
37
+ export function openModal(id, opener) {
38
+ const dialog = document.getElementById(id);
39
+ if (!(dialog instanceof HTMLDialogElement) || dialog.open) return;
40
+ if (opener) openers.set(dialog, opener);
41
+ dialog.showModal();
42
+ dialog.dispatchEvent(new CustomEvent('ds-open', { bubbles: true, detail: { opener } }));
43
+ dialog.addEventListener('close', () => openers.get(dialog)?.focus({ preventScroll: true }), { once: true });
44
+ }
45
+
46
+ /** @param {string} id */
47
+ export function closeModal(id) {
48
+ const dialog = document.getElementById(id);
49
+ if (dialog instanceof HTMLDialogElement) dialog.close();
50
+ }
@@ -0,0 +1,14 @@
1
+ export type MotionSnapshot = Map<string, DOMRect>;
2
+ export declare function prefersReducedMotion(): boolean;
3
+ /** Positions of every [data-motion] element inside `root`, before a change. */
4
+ export declare function snapshot(root: Element | null | undefined): MotionSnapshot;
5
+ /**
6
+ * After the DOM changed: moved elements slide from their old position, new ones fade in (staggered).
7
+ * Nested [data-motion] elements only fade in; they already move with their parent.
8
+ */
9
+ export declare function animateFrom(root: Element | null | undefined, before: MotionSnapshot): void;
10
+ /**
11
+ * Fades an element out, then runs `remove` (your state change). The fade is cleared on the next frames, so an element that
12
+ * is reused for other content (for example a list keyed by index) shows up again.
13
+ */
14
+ export declare function leave(el: Element | null | undefined, remove: () => void): void;
@@ -0,0 +1,60 @@
1
+ // Generated from web/components/src/wari/motion.ts (same behaviour in React, Angular and Astro).
2
+ // Small FLIP helpers for the Wari route editor: elements marked with data-motion="key" slide to their new place when the
3
+ // list changes, new ones fade in and removed ones fade out first. Framework-free (same file in React, Angular and Astro).
4
+ // Respects prefers-reduced-motion.
5
+ const EASE = 'cubic-bezier(.2, .8, .2, 1)';
6
+ export function prefersReducedMotion() {
7
+ return typeof window === 'undefined' || typeof window.matchMedia !== 'function'
8
+ || window.matchMedia('(prefers-reduced-motion: reduce)').matches;
9
+ }
10
+ const canAnimate = (el) => typeof el.animate === 'function';
11
+ /** Positions of every [data-motion] element inside `root`, before a change. */
12
+ export function snapshot(root) {
13
+ const rects = new Map();
14
+ if (!root || prefersReducedMotion())
15
+ return rects;
16
+ root.querySelectorAll('[data-motion]').forEach(el => rects.set(el.dataset.motion, el.getBoundingClientRect()));
17
+ return rects;
18
+ }
19
+ /**
20
+ * After the DOM changed: moved elements slide from their old position, new ones fade in (staggered).
21
+ * Nested [data-motion] elements only fade in; they already move with their parent.
22
+ */
23
+ export function animateFrom(root, before) {
24
+ if (!root || before.size === 0 || prefersReducedMotion())
25
+ return;
26
+ let entering = 0;
27
+ root.querySelectorAll('[data-motion]').forEach(el => {
28
+ if (!canAnimate(el))
29
+ return;
30
+ const old = before.get(el.dataset.motion);
31
+ if (!old) {
32
+ el.animate([{ opacity: 0, transform: 'translateY(-6px) scale(.98)' }, { opacity: 1, transform: 'none' }], { duration: 240, easing: EASE, delay: Math.min(entering++, 6) * 35, fill: 'backwards' });
33
+ return;
34
+ }
35
+ if (el.parentElement?.closest('[data-motion]') && root.contains(el.parentElement.closest('[data-motion]')))
36
+ return;
37
+ const now = el.getBoundingClientRect();
38
+ const dx = old.left - now.left;
39
+ const dy = old.top - now.top;
40
+ if (Math.abs(dx) < 1 && Math.abs(dy) < 1)
41
+ return;
42
+ el.animate([{ transform: `translate(${dx}px, ${dy}px)` }, { transform: 'none' }], { duration: 280, easing: EASE });
43
+ });
44
+ }
45
+ /**
46
+ * Fades an element out, then runs `remove` (your state change). The fade is cleared on the next frames, so an element that
47
+ * is reused for other content (for example a list keyed by index) shows up again.
48
+ */
49
+ export function leave(el, remove) {
50
+ if (!el || !canAnimate(el) || prefersReducedMotion()) {
51
+ remove();
52
+ return;
53
+ }
54
+ const animation = el.animate([{ opacity: 1, transform: 'none' }, { opacity: 0, transform: 'translateX(12px) scale(.97)' }], { duration: 170, easing: 'ease-in', fill: 'forwards' });
55
+ const done = () => {
56
+ remove();
57
+ requestAnimationFrame(() => requestAnimationFrame(() => animation.cancel()));
58
+ };
59
+ animation.finished.then(done, done);
60
+ }
@@ -0,0 +1,10 @@
1
+ import type { WariRouteValue } from './route';
2
+ export interface WariRouteOptions {
3
+ title?: string; headingLevel?: 2 | 3 | 4; maxStops?: number; maxTolls?: number; showPassengers?: boolean; showTolls?: boolean;
4
+ disabled?: boolean; invertingLabel?: string; invertedMessage?: string; routePassengerNote?: string; inverting?: boolean; inverted?: boolean;
5
+ }
6
+ export declare const routeDefaults: Required<Omit<WariRouteOptions, 'inverting' | 'inverted'>>;
7
+ /** HTML interno de la tarjeta de ruta (el mismo que React y Angular). */
8
+ export declare function routeHtml(value: Partial<WariRouteValue> | null | undefined, options?: WariRouteOptions, baseId?: string): string;
9
+ /** Inicializa las tarjetas <WariRoute>. Idempotente. Cada tarjeta expone dsSetValue(ruta) y dsGetValue(). */
10
+ export declare function initWariRoute(scope?: ParentNode): void;
@@ -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
+ }