@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.
@@ -146,12 +146,150 @@ function setupSelect(root) {
146
146
  document.addEventListener('pointerdown', event => { if (isOpen() && !root.contains(event.target)) setOpen(false); });
147
147
  }
148
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"] }).
149
237
  function setupSwitches(root) {
150
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(); });
151
242
  root.addEventListener('change', event => {
152
- if (!event.target.matches('input[role="switch"]')) return;
153
- emit(root, [...root.querySelectorAll('input[role="switch"]:checked')].map(input => input.value));
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();
154
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);
155
293
  }
156
294
 
157
295
  function setupStepper(root) {
@@ -188,14 +326,18 @@ function setupTrip(root) {
188
326
  const services = JSON.parse(root.dataset.services || '[]');
189
327
  const [serviceSelect, paymentSelect] = root.querySelectorAll('[data-ds-wselect]');
190
328
  const [modes, extras] = root.querySelectorAll('[data-ds-wswitches]');
191
- const stepper = root.querySelector('[data-ds-wstepper]');
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]'));
192
331
  const read = () => {
193
332
  const activeModes = [...modes.querySelectorAll('input:checked')].map(input => input.value);
194
333
  return {
195
334
  service: serviceSelect.querySelector('[data-ds-value]').value,
196
335
  hourly: activeModes.includes('hourly'),
197
336
  delivery: activeModes.includes('delivery'),
198
- extras: [...extras.querySelectorAll('input:checked')].map(input => input.value),
337
+ extras: [...extras.querySelectorAll('input[role="switch"]:checked')].map(input => input.value),
338
+ extraQuantities: readQuantities(extras),
339
+ extraChoices: readChoices(extras),
340
+ extraFields: readFields(extras),
199
341
  vehicles: Number(stepper.querySelector('input').value),
200
342
  payment: paymentSelect.querySelector('[data-ds-value]').value,
201
343
  };
@@ -219,4 +361,10 @@ function setupTrip(root) {
219
361
  if (event.target === modes) renderMeta();
220
362
  emit(root, read());
221
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
+ }
222
370
  }
@@ -15,6 +15,32 @@ export interface WariOption {
15
15
  value: string;
16
16
  label: string;
17
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;
18
44
  }
19
45
  export interface WariTripAttributesValue {
20
46
  service: string;
@@ -22,6 +48,12 @@ export interface WariTripAttributesValue {
22
48
  delivery: boolean;
23
49
  /** Valores de los extras activos (por defecto: carseat, booster, carga). */
24
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>>;
25
57
  vehicles: number;
26
58
  payment: string;
27
59
  }
@@ -54,3 +86,22 @@ export declare function clampCount(value: number, min?: number, max?: number): n
54
86
  /** Type-ahead for select-only comboboxes: next enabled option whose label starts with `query`, after `from`. */
55
87
  export declare function typeaheadIndex(options: readonly WariOption[], query: string, from: number): number;
56
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;
package/src/wari/trip.js CHANGED
@@ -9,9 +9,22 @@ export const wariServices = [
9
9
  { value: 'van', label: 'Van', passengers: 7, luggage: 6, luggageAlt: 10, hourlyPrice: 140 },
10
10
  ];
11
11
  export const wariExtras = [
12
- { value: 'carseat', label: 'Carseat' },
13
- { value: 'booster', label: 'Booster' },
14
- { value: 'carga', label: 'Carga' },
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
+ },
15
28
  ];
16
29
  export const wariPaymentMethods = [
17
30
  { value: 'efectivo', label: 'Efectivo' },
@@ -19,7 +32,7 @@ export const wariPaymentMethods = [
19
32
  { value: 'vale', label: 'Vale corporativo' },
20
33
  ];
21
34
  export const defaultTripAttributes = {
22
- service: 'lite', hourly: false, delivery: false, extras: [], vehicles: 1, payment: 'efectivo',
35
+ service: 'lite', hourly: false, delivery: false, extras: [], extraQuantities: {}, extraChoices: {}, extraFields: {}, vehicles: 1, payment: 'efectivo',
23
36
  };
24
37
  export const formatSoles = (amount) => `S/${Number.isInteger(amount) ? amount : amount.toFixed(2)}`;
25
38
  /** Lo que muestra el diseño a la derecha de cada servicio, según "Por horas" y "Envíos". */
@@ -67,3 +80,50 @@ export function toggleExtra(extras, value, options = wariExtras) {
67
80
  set.add(value);
68
81
  return options.filter(option => set.has(option.value)).map(option => option.value);
69
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/wari.d.ts CHANGED
@@ -9,12 +9,18 @@ export { default as WariSwitchList } from './src/components/WariSwitchList.astro
9
9
  export { default as WariStepper } from './src/components/WariStepper.astro';
10
10
  export { default as WariServiceMeta } from './src/components/WariServiceMeta.astro';
11
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';
12
16
  export type { WariSelectOption } from './src/components/WariSelect.astro';
13
- export { clampCount, defaultTripAttributes, formatSoles, serviceMeta, toggleExtra, typeaheadIndex, wariExtras, wariPaymentMethods, wariServices } from './src/wari/trip';
14
- export type { WariService, WariOption, WariTripAttributesValue, ServiceMeta } from './src/wari/trip';
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';
15
19
  export { calendarWeeks, formatDisplayDate, formatDisplayTime, parseDisplayDate, parseDisplayTime, parseISODate, parseTime24, toISODate, todayISO } from './src/wari/datetime';
16
20
  export type { CalendarDay, TimeParts, Period } from './src/wari/datetime';
17
21
  export type { MultiSelectOption } from './src/components/MultiSelect.astro';
18
22
  export { wariStatuses, wariStatusLabel } from './src/wari/statuses';
19
23
  export type { WariStatus } from './src/wari/statuses';
20
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';
package/wari.js CHANGED
@@ -10,7 +10,12 @@ export { default as WariSwitchList } from './src/components/WariSwitchList.astro
10
10
  export { default as WariStepper } from './src/components/WariStepper.astro';
11
11
  export { default as WariServiceMeta } from './src/components/WariServiceMeta.astro';
12
12
  export { default as WariTripAttributes } from './src/components/WariTripAttributes.astro';
13
- export { clampCount, defaultTripAttributes, formatSoles, serviceMeta, toggleExtra, typeaheadIndex, wariExtras, wariPaymentMethods, wariServices } from './src/wari/trip.js';
13
+ export { default as WariClientSearch } from './src/components/WariClientSearch.astro';
14
+ export { default as WariClientDetails } from './src/components/WariClientDetails.astro';
15
+ export { default as WariRoute } from './src/components/WariRoute.astro';
16
+ export { default as WariPassengerField } from './src/components/WariPassengerField.astro';
17
+ export { clampCount, defaultTripAttributes, formatSoles, serviceMeta, syncExtraChoices, syncExtraFields, syncExtraQuantities, syncExtras, toggleExtra, typeaheadIndex, wariExtras, wariPaymentMethods, wariServices } from './src/wari/trip.js';
14
18
  export { calendarWeeks, formatDisplayDate, formatDisplayTime, parseDisplayDate, parseDisplayTime, parseISODate, parseTime24, toISODate, todayISO } from './src/wari/datetime.js';
15
19
  export { wariStatuses, wariStatusLabel } from './src/wari/statuses.js';
16
20
  export { filterOptions, normalizeSearch, selectionState, selectionSummary, toggleAll, toggleValue } from './src/wari/logic.js';
21
+ export { addStop, addToll, createStop, defaultRouteValue, emptyPassenger, invertRoute, moveStop, normalizeRoute, removeStop, removeToll, stopLabel, stopPlaceholder, tollsTotal, updateStop } from './src/wari/route.js';