@directo-ui/astro 1.2.0 → 1.4.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 (45) hide show
  1. package/components.css +231 -0
  2. package/index.d.ts +47 -31
  3. package/index.js +46 -31
  4. package/package.json +5 -1
  5. package/src/close-icon.d.ts +2 -0
  6. package/src/close-icon.js +9 -0
  7. package/src/components/Alert.astro +2 -1
  8. package/src/components/Autocomplete.astro +107 -0
  9. package/src/components/Badge.astro +28 -13
  10. package/src/components/BottomSheet.astro +2 -1
  11. package/src/components/CellText.astro +17 -0
  12. package/src/components/Chip.astro +21 -0
  13. package/src/components/ChipGroup.astro +30 -0
  14. package/src/components/CloseButton.astro +18 -0
  15. package/src/components/DataTable.astro +168 -0
  16. package/src/components/DatePicker.astro +2 -1
  17. package/src/components/DateRangePicker.astro +107 -0
  18. package/src/components/Drawer.astro +41 -0
  19. package/src/components/Dropdown.astro +3 -2
  20. package/src/components/FieldLabel.astro +14 -0
  21. package/src/components/FileUpload.astro +153 -0
  22. package/src/components/FilterBar.astro +68 -0
  23. package/src/components/Modal.astro +4 -2
  24. package/src/components/MultiSelect.astro +2 -1
  25. package/src/components/Select.astro +2 -1
  26. package/src/components/Sidebar.astro +64 -0
  27. package/src/components/StatusTag.astro +4 -2
  28. package/src/components/Tabs.astro +60 -60
  29. package/src/components/TextField.astro +2 -1
  30. package/src/components/Textarea.astro +2 -1
  31. package/src/components/Timeline.astro +25 -0
  32. package/src/components/WariDateField.astro +2 -1
  33. package/src/components/WariDriverInbox.astro +74 -0
  34. package/src/components/WariSelect.astro +2 -1
  35. package/src/components/WariTimeField.astro +2 -1
  36. package/src/files.d.ts +27 -0
  37. package/src/files.js +52 -0
  38. package/src/modal.d.ts +3 -3
  39. package/src/modal.js +50 -39
  40. package/src/toast.d.ts +2 -0
  41. package/src/toast.js +18 -7
  42. package/src/wari/inbox.d.ts +13 -0
  43. package/src/wari/inbox.js +28 -0
  44. package/wari.d.ts +3 -0
  45. package/wari.js +2 -0
@@ -0,0 +1,17 @@
1
+ ---
2
+ interface Props {
3
+ /** Second, smaller line (district, user, time…). */
4
+ secondary?: string;
5
+ /** accent paints the second line purple (night times in Figma). */
6
+ tone?: 'default' | 'accent';
7
+ /** Strikes the main line (cancelled services). */
8
+ strike?: boolean;
9
+ class?: string;
10
+ }
11
+ /* Atom: two-line table cell. The default slot is the main line. */
12
+ const { secondary, tone = 'default', strike = false, class: className } = Astro.props;
13
+ ---
14
+ <span class:list={['ds-cell-text', className]} data-tone={tone === 'default' ? undefined : tone} data-strike={strike ? '' : undefined}>
15
+ <span class="ds-cell-text-primary"><slot /></span>
16
+ {secondary && <span class="ds-cell-text-secondary">{secondary}</span>}
17
+ </span>
@@ -0,0 +1,21 @@
1
+ ---
2
+ import type { HTMLAttributes } from 'astro/types';
3
+
4
+ interface Props extends Omit<HTMLAttributes<'button'>, 'type'> {
5
+ /** Renders a link with the chip look (for example to remove a filter on a server-rendered page). */
6
+ href?: string;
7
+ /** Toggle chip (aria-pressed). */
8
+ pressed?: boolean;
9
+ /** Shows × after the text: the whole chip removes something (give it an aria-label). */
10
+ removable?: boolean;
11
+ size?: 'sm' | 'md';
12
+ type?: 'button' | 'submit' | 'reset';
13
+ }
14
+
15
+ /* Atom: rounded button used for active filters (FilterBar) and quick options (DateRangePicker presets). */
16
+ const { href, pressed, removable = false, size = 'md', type = 'button', class: className, ...rest } = Astro.props;
17
+ const common = { class: ['ds-chip', className].filter(Boolean).join(' '), 'data-size': size === 'md' ? undefined : size };
18
+ ---
19
+ {href !== undefined
20
+ ? <a {...rest as HTMLAttributes<'a'>} {...common} href={href}><slot />{removable && <span class="ds-chip-remove" aria-hidden="true">×</span>}</a>
21
+ : <button {...rest} {...common} type={type} aria-pressed={pressed === undefined ? undefined : String(pressed)}><slot />{removable && <span class="ds-chip-remove" aria-hidden="true">×</span>}</button>}
@@ -0,0 +1,30 @@
1
+ ---
2
+ import Chip from './Chip.astro';
3
+
4
+ interface Props {
5
+ /** Accessible name of the group. */
6
+ label: string;
7
+ options: readonly { value: string; label: string; disabled?: boolean }[];
8
+ value?: string;
9
+ /** brand: blue outline chips that share the width. */
10
+ variant?: 'default' | 'brand';
11
+ size?: 'sm' | 'md';
12
+ class?: string;
13
+ [attribute: `data-${string}`]: unknown;
14
+ }
15
+ /* Atom group: one option at a time, built with Chip. Emits ds-change with the chosen value. */
16
+ const { label, options, value = options[0]?.value, variant = 'default', size = 'md', class: className, ...rest } = Astro.props;
17
+ ---
18
+ <div {...rest} role="group" aria-label={label} class:list={['ds-chip-group', className]} data-variant={variant} data-ds-chip-group>
19
+ {options.map(option => <Chip size={size} pressed={option.value === value} disabled={option.disabled} data-value={option.value}>{option.label}</Chip>)}
20
+ </div>
21
+
22
+ <script>
23
+ document.addEventListener('click', event => {
24
+ const chip = event.target instanceof Element ? event.target.closest<HTMLButtonElement>('[data-ds-chip-group] > .ds-chip') : null;
25
+ const group = chip?.parentElement;
26
+ if (!chip || !group || chip.getAttribute('aria-pressed') === 'true') return;
27
+ group.querySelectorAll('.ds-chip').forEach(item => item.setAttribute('aria-pressed', String(item === chip)));
28
+ group.dispatchEvent(new CustomEvent('ds-change', { bubbles: true, detail: chip.dataset.value }));
29
+ });
30
+ </script>
@@ -0,0 +1,18 @@
1
+ ---
2
+ import type { HTMLAttributes } from 'astro/types';
3
+ import { closeIconPath } from '../close-icon.js';
4
+
5
+ interface Props extends Omit<HTMLAttributes<'button'>, 'type'> {
6
+ /** Accessible name, for example "Cerrar alerta". */
7
+ label?: string;
8
+ /** xs 26px, sm 28px, md 32px, lg 40px. */
9
+ size?: 'xs' | 'sm' | 'md' | 'lg';
10
+ type?: 'button' | 'submit' | 'reset';
11
+ }
12
+
13
+ /* Atom: the × button of Alert, Toast, Modal, BottomSheet and Drawer. Extra attributes (data-ds-close…) pass through. */
14
+ const { label = 'Cerrar', size = 'md', type = 'button', class: className, ...rest } = Astro.props;
15
+ ---
16
+ <button aria-label={label} {...rest} type={type} data-size={size} class:list={['ds-close-button', className]}>
17
+ <svg viewBox="0 0 256 256" fill="currentColor" aria-hidden="true" focusable="false"><path d={closeIconPath} /></svg>
18
+ </button>
@@ -0,0 +1,168 @@
1
+ ---
2
+ import CellText from './CellText.astro';
3
+ import StatusTag from './StatusTag.astro';
4
+
5
+ type Row = Record<string, string | number | boolean | undefined>;
6
+ interface Column {
7
+ key: string; label: string; sortable?: boolean; align?: 'start' | 'center' | 'end';
8
+ /** Row key of a second, smaller line (district, user, time…): the cell becomes a CellText. */
9
+ secondaryKey?: string;
10
+ /** Paints the second line purple for these rows (night times). */
11
+ accent?: (row: Row) => boolean;
12
+ /** Strikes the main line for these rows (cancelled services). */
13
+ strike?: (row: Row) => boolean;
14
+ /** Row key of a status code: the cell becomes a StatusTag with a dot and the cell value as text. */
15
+ statusKey?: string;
16
+ }
17
+ type Direction = 'ascending' | 'descending';
18
+
19
+ interface Props {
20
+ caption: string;
21
+ columns: readonly Column[];
22
+ rows: readonly Row[];
23
+ loading?: boolean;
24
+ loadingMessage?: string;
25
+ emptyMessage?: string;
26
+ actionLabel?: string;
27
+ actionHref?: (row: Row) => string;
28
+ /** Column key whose value identifies each row (sent in ds-row-click). Defaults to "id". */
29
+ rowKey?: string;
30
+ /** Sorted on the server before rendering and shown in the header. */
31
+ defaultSort?: { key: string; direction: Direction };
32
+ /** Do not reorder rows in the browser: listen to ds-sort and sort on the server. */
33
+ manualSort?: boolean;
34
+ /** Rows respond to click, Enter and Space and emit ds-row-click. */
35
+ clickableRows?: boolean;
36
+ density?: 'comfortable' | 'compact';
37
+ stickyHeader?: boolean;
38
+ /** soft: light blue header and 60px rows without lines (Wari tables). */
39
+ variant?: 'default' | 'soft';
40
+ /** Rows shown at half opacity, for example cancelled services. */
41
+ rowMuted?: (row: Row) => boolean;
42
+ /** Totals bar under the table. */
43
+ summary?: readonly { label: string; value: string | number }[];
44
+ /** Maximum height of the scroll area (number = px). */
45
+ maxHeight?: number | string;
46
+ id?: string;
47
+ class?: string;
48
+ }
49
+
50
+ const {
51
+ caption, columns, rows, loading = false, loadingMessage = 'Cargando registros…', emptyMessage = 'No hay resultados.',
52
+ actionLabel = 'Ver detalle', actionHref, rowKey = 'id', defaultSort, manualSort = false, clickableRows = false,
53
+ density = 'comfortable', stickyHeader = false, variant = 'default', rowMuted, summary = [], maxHeight, id, class: className,
54
+ } = Astro.props;
55
+ const maxHeightValue = typeof maxHeight === 'number' ? `${maxHeight}px` : maxHeight;
56
+ const collator = new Intl.Collator('es', { numeric: true, sensitivity: 'base' });
57
+ const sortColumn = defaultSort && columns.find(column => column.key === defaultSort.key && column.sortable);
58
+ const shownRows = sortColumn && !manualSort ? [...rows].sort((left, right) => {
59
+ const a = left[sortColumn.key];
60
+ const b = right[sortColumn.key];
61
+ const order = typeof a === 'number' && typeof b === 'number' ? a - b : collator.compare(String(a ?? ''), String(b ?? ''));
62
+ return defaultSort!.direction === 'ascending' ? order : -order;
63
+ }) : rows;
64
+ const directionOf = (key: string) => sortColumn?.key === key ? defaultSort!.direction : undefined;
65
+ const arrow = (key: string) => directionOf(key) === 'ascending' ? '↑' : directionOf(key) === 'descending' ? '↓' : '↕';
66
+ ---
67
+ <directo-sortable-table id={id} class:list={['ds-data-table', className]} data-density={density}
68
+ data-variant={variant === 'default' ? undefined : variant} data-max-height={maxHeight === undefined ? undefined : ''}
69
+ style={maxHeightValue ? `--ds-table-max-height:${maxHeightValue}` : undefined}
70
+ data-sticky-header={stickyHeader || maxHeight !== undefined ? '' : undefined} data-manual-sort={manualSort ? '' : undefined}>
71
+ <div class="ds-data-scroll" role="region" aria-label={caption} tabindex="0">
72
+ <table aria-busy={loading}>
73
+ <caption>{caption}</caption>
74
+ <thead><tr>
75
+ {columns.map((column, index) => <th scope="col" data-align={column.align} aria-sort={column.sortable ? directionOf(column.key) : undefined}>
76
+ {column.sortable ? <button type="button" class="ds-sort-button" data-column={index} data-key={column.key}>{column.label} <span aria-hidden="true">{arrow(column.key)}</span></button> : column.label}
77
+ </th>)}
78
+ {actionHref && <th scope="col">Acciones</th>}
79
+ </tr></thead>
80
+ <tbody>
81
+ {loading || !rows.length
82
+ ? <tr><td colspan={Math.max(1, columns.length + Number(!!actionHref))}><span role="status">{loading ? loadingMessage : emptyMessage}</span></td></tr>
83
+ : shownRows.map((row, index) => <tr data-row data-muted={rowMuted?.(row) ? '' : undefined} data-index={index} data-key={row[rowKey] === undefined ? undefined : String(row[rowKey])}
84
+ tabindex={clickableRows ? 0 : undefined} data-clickable={clickableRows ? '' : undefined}>
85
+ {columns.map(column => <td data-align={column.align} data-number={typeof row[column.key] === 'number' ? '' : undefined}>
86
+ {column.statusKey ? <StatusTag status={String(row[column.statusKey] ?? '')} dot>{row[column.key]}</StatusTag>
87
+ : column.secondaryKey || column.accent || column.strike
88
+ ? <CellText secondary={row[column.secondaryKey ?? ''] === undefined ? undefined : String(row[column.secondaryKey ?? ''])}
89
+ tone={column.accent?.(row) ? 'accent' : 'default'} strike={column.strike?.(row)}>{row[column.key]}</CellText>
90
+ : row[column.key]}
91
+ </td>)}
92
+ {actionHref && <td><a href={actionHref(row)}>{actionLabel}</a></td>}
93
+ </tr>)}
94
+ </tbody>
95
+ </table>
96
+ </div>
97
+ {summary.length > 0 && <div class="ds-data-table-summary">{summary.map(item => <span>{item.label} {item.value}</span>)}</div>}
98
+ <slot name="pagination" />
99
+ </directo-sortable-table>
100
+
101
+ <script>
102
+ const collator = new Intl.Collator('es', { numeric: true, sensitivity: 'base' });
103
+ const interactive = 'a, button, input, select, textarea, label, [role="button"], [contenteditable="true"]';
104
+
105
+ class DirectoSortableTable extends HTMLElement {
106
+ connectedCallback() {
107
+ this.addEventListener('click', this.handleClick);
108
+ this.addEventListener('keydown', this.handleKey);
109
+ }
110
+ disconnectedCallback() {
111
+ this.removeEventListener('click', this.handleClick);
112
+ this.removeEventListener('keydown', this.handleKey);
113
+ }
114
+
115
+ private handleClick = (event: MouseEvent) => {
116
+ const target = event.target instanceof Element ? event.target : null;
117
+ const trigger = target?.closest<HTMLButtonElement>('button[data-column]');
118
+ if (trigger) { this.sort(trigger); return; }
119
+ const row = target?.closest<HTMLTableRowElement>('tr[data-clickable]');
120
+ if (!row || !this.contains(row)) return;
121
+ const inner = target?.closest(interactive);
122
+ if (inner && row.contains(inner)) return;
123
+ this.emitRow(row);
124
+ };
125
+
126
+ private handleKey = (event: KeyboardEvent) => {
127
+ const row = event.target instanceof HTMLTableRowElement && event.target.hasAttribute('data-clickable') ? event.target : null;
128
+ if (!row || (event.key !== 'Enter' && event.key !== ' ')) return;
129
+ event.preventDefault();
130
+ this.emitRow(row);
131
+ };
132
+
133
+ private emitRow(row: HTMLTableRowElement) {
134
+ this.dispatchEvent(new CustomEvent('ds-row-click', {
135
+ bubbles: true, detail: { key: row.dataset.key, index: Number(row.dataset.index), row },
136
+ }));
137
+ }
138
+
139
+ private sort(trigger: HTMLButtonElement) {
140
+ const body = this.querySelector('tbody');
141
+ const header = trigger.closest('th');
142
+ if (!body || !header) return;
143
+ const column = Number(trigger.dataset.column);
144
+ const direction = header.getAttribute('aria-sort') === 'ascending' ? 'descending' : 'ascending';
145
+ for (const th of this.querySelectorAll('th[aria-sort]')) {
146
+ th.removeAttribute('aria-sort');
147
+ const icon = th.querySelector('span');
148
+ if (icon) icon.textContent = '↕';
149
+ }
150
+ header.setAttribute('aria-sort', direction);
151
+ const icon = trigger.querySelector('span');
152
+ if (icon) icon.textContent = direction === 'ascending' ? '↑' : '↓';
153
+ this.dispatchEvent(new CustomEvent('ds-sort', { bubbles: true, detail: { key: trigger.dataset.key, column, direction } }));
154
+ if (this.hasAttribute('data-manual-sort')) return;
155
+ const rows = Array.from(body.querySelectorAll<HTMLTableRowElement>('tr[data-row]'));
156
+ rows.sort((left, right) => {
157
+ const a = left.cells[column];
158
+ const b = right.cells[column];
159
+ const x = (a.querySelector('.ds-cell-text-primary') ?? a).textContent?.trim() ?? '';
160
+ const y = (b.querySelector('.ds-cell-text-primary') ?? b).textContent?.trim() ?? '';
161
+ const order = a.hasAttribute('data-number') && b.hasAttribute('data-number') ? Number(x) - Number(y) : collator.compare(x, y);
162
+ return direction === 'ascending' ? order : -order;
163
+ });
164
+ body.append(...rows);
165
+ }
166
+ }
167
+ if (!customElements.get('directo-sortable-table')) customElements.define('directo-sortable-table', DirectoSortableTable);
168
+ </script>
@@ -1,4 +1,5 @@
1
1
  ---
2
+ import FieldLabel from './FieldLabel.astro';
2
3
  import type { HTMLAttributes } from 'astro/types';
3
4
 
4
5
  interface Props extends Omit<HTMLAttributes<'input'>, 'type'> {
@@ -16,7 +17,7 @@ const fieldId = id ?? `ds-field-${Math.random().toString(36).slice(2, 9)}`;
16
17
  const hintId = supportingText ? `${fieldId}-hint` : undefined;
17
18
  ---
18
19
  <div class="ds-input" data-error={String(error)} data-disabled={String(Boolean(disabled))}>
19
- {label && <label for={fieldId}>{label}{required && <span class="ds-input-required" aria-hidden="true">*</span>}</label>}
20
+ {label && <FieldLabel for={fieldId} required={required}>{label}</FieldLabel>}
20
21
  <div class="ds-input-shell">
21
22
  <input {...rest} id={fieldId} type="date" disabled={disabled} required={required}
22
23
  aria-invalid={error ? 'true' : undefined} aria-describedby={hintId} />
@@ -0,0 +1,107 @@
1
+ ---
2
+ import FieldLabel from './FieldLabel.astro';
3
+ import Chip from './Chip.astro';
4
+ import TextField from './TextField.astro';
5
+
6
+ interface Props {
7
+ id: string;
8
+ label?: string;
9
+ startLabel?: string;
10
+ endLabel?: string;
11
+ start?: string;
12
+ end?: string;
13
+ startName?: string;
14
+ endName?: string;
15
+ min?: string;
16
+ max?: string;
17
+ required?: boolean;
18
+ disabled?: boolean;
19
+ /** Your own error message (server validation). The picker also warns when the end is before the start. */
20
+ error?: string;
21
+ /** Quick ranges shown as buttons. */
22
+ presets?: readonly { label: string; range: { start: string; end: string } }[];
23
+ class?: string;
24
+ }
25
+ const {
26
+ id, label = 'Rango de fechas', startLabel = 'Desde', endLabel = 'Hasta', start = '', end = '', startName, endName, min, max,
27
+ required = false, disabled = false, error, presets = [], class: className,
28
+ } = Astro.props;
29
+ const startMax = end && (!max || end < max) ? end : max;
30
+ const endMin = start && (!min || start > min) ? start : min;
31
+ const orderMessage = 'La fecha final no puede ser anterior a la inicial.';
32
+ const message = error ?? (start && end && end < start ? orderMessage : '');
33
+ ---
34
+ <directo-date-range data-message={orderMessage}>
35
+ <fieldset id={id} class:list={['ds-date-range', className]} data-min={min} data-max={max} disabled={disabled}
36
+ data-error={error} aria-describedby={`${id}-error`}>
37
+ <FieldLabel as="legend" required={required}>{label}</FieldLabel>
38
+ {presets.length > 0 && <div class="ds-date-range-presets">
39
+ {presets.map(preset => <Chip data-start={preset.range.start} data-end={preset.range.end}
40
+ pressed={preset.range.start === start && preset.range.end === end}>{preset.label}</Chip>)}
41
+ </div>}
42
+ <div class="ds-date-range-fields">
43
+ <TextField id={`${id}-start`} label={startLabel} type="date" name={startName} value={start} min={min} max={startMax}
44
+ required={required} error={!!message} />
45
+ <TextField id={`${id}-end`} label={endLabel} type="date" name={endName} value={end} min={endMin} max={max}
46
+ required={required} error={!!message} />
47
+ </div>
48
+ <p id={`${id}-error`} class="ds-date-range-error" role="status">{message}</p>
49
+ </fieldset>
50
+ </directo-date-range>
51
+
52
+ <script>
53
+ class DirectoDateRange extends HTMLElement {
54
+ connectedCallback() {
55
+ this.addEventListener('input', this.sync);
56
+ this.addEventListener('click', this.preset);
57
+ }
58
+ disconnectedCallback() {
59
+ this.removeEventListener('input', this.sync);
60
+ this.removeEventListener('click', this.preset);
61
+ }
62
+
63
+ /** Current range (YYYY-MM-DD). */
64
+ get dsValue() {
65
+ const [start, end] = this.querySelectorAll<HTMLInputElement>('input[type="date"]');
66
+ return { start: start?.value ?? '', end: end?.value ?? '' };
67
+ }
68
+
69
+ /** Sets both dates and emits ds-change (and ds-complete when valid). */
70
+ dsSetValue(range: { start: string; end: string }) {
71
+ const [start, end] = this.querySelectorAll<HTMLInputElement>('input[type="date"]');
72
+ if (!start || !end) return;
73
+ start.value = range.start;
74
+ end.value = range.end;
75
+ this.sync();
76
+ }
77
+
78
+ private preset = (event: MouseEvent) => {
79
+ const button = event.target instanceof Element ? event.target.closest<HTMLButtonElement>('button[data-start]') : null;
80
+ if (button) this.dsSetValue({ start: button.dataset.start ?? '', end: button.dataset.end ?? '' });
81
+ };
82
+
83
+ private sync = () => {
84
+ const fields = this.querySelector('fieldset');
85
+ const [start, end] = this.querySelectorAll<HTMLInputElement>('input[type="date"]');
86
+ if (!fields || !start || !end) return;
87
+ const { min = '', max = '' } = fields.dataset;
88
+ start.max = end.value && (!max || end.value < max) ? end.value : max;
89
+ end.min = start.value && (!min || start.value > min) ? start.value : min;
90
+ const reversed = !!start.value && !!end.value && end.value < start.value;
91
+ const message = reversed ? this.dataset.message ?? '' : fields.dataset.error ?? '';
92
+ const status = this.querySelector('.ds-date-range-error');
93
+ if (status) status.textContent = message;
94
+ for (const input of [start, end]) {
95
+ input.closest('.ds-input')?.setAttribute('data-error', String(!!message));
96
+ if (message) input.setAttribute('aria-invalid', 'true'); else input.removeAttribute('aria-invalid');
97
+ }
98
+ for (const button of this.querySelectorAll<HTMLButtonElement>('button[data-start]')) {
99
+ button.setAttribute('aria-pressed', String(button.dataset.start === start.value && button.dataset.end === end.value));
100
+ }
101
+ const value = { start: start.value, end: end.value };
102
+ this.dispatchEvent(new CustomEvent('ds-change', { bubbles: true, detail: value }));
103
+ if (value.start && value.end && !reversed) this.dispatchEvent(new CustomEvent('ds-complete', { bubbles: true, detail: value }));
104
+ };
105
+ }
106
+ if (!customElements.get('directo-date-range')) customElements.define('directo-date-range', DirectoDateRange);
107
+ </script>
@@ -0,0 +1,41 @@
1
+ ---
2
+ import CloseButton from './CloseButton.astro';
3
+ interface Props {
4
+ id: string;
5
+ title: string;
6
+ description?: string;
7
+ side?: 'start' | 'end';
8
+ /** Width: sm 360px, md 440px, lg 640px. */
9
+ size?: 'sm' | 'md' | 'lg';
10
+ /** Opens when the page loads. */
11
+ open?: boolean;
12
+ closeOnBackdrop?: boolean;
13
+ closeOnEscape?: boolean;
14
+ closeLabel?: string;
15
+ class?: string;
16
+ }
17
+ const {
18
+ id, title, description, side = 'end', size = 'md', open = false, closeOnBackdrop = true, closeOnEscape = true,
19
+ closeLabel = 'Cerrar panel', class: className,
20
+ } = Astro.props;
21
+ ---
22
+ <dialog id={id} class:list={['ds-drawer', className]} data-side={side} data-size={size} data-ds-modal
23
+ data-ds-open-initially={open ? '' : undefined} data-ds-backdrop={closeOnBackdrop ? undefined : 'static'}
24
+ data-ds-escape={closeOnEscape ? undefined : 'false'}
25
+ aria-labelledby={`${id}-title`} aria-describedby={description ? `${id}-description` : undefined}>
26
+ <header class="ds-drawer-header">
27
+ <div>
28
+ <h2 id={`${id}-title`}>{title}</h2>
29
+ {description && <p class="ds-drawer-description" id={`${id}-description`}>{description}</p>}
30
+ </div>
31
+ <CloseButton class="ds-sheet-close" size="lg" label={closeLabel} data-ds-close />
32
+ </header>
33
+ <div class="ds-drawer-body"><slot /></div>
34
+ {Astro.slots.has('footer') && <footer class="ds-drawer-footer"><slot name="footer" /></footer>}
35
+ </dialog>
36
+
37
+ <script>
38
+ import { initModals } from '../modal.js';
39
+ initModals();
40
+ document.addEventListener('astro:page-load', () => initModals());
41
+ </script>
@@ -1,4 +1,5 @@
1
1
  ---
2
+ import Button from './Button.astro';
2
3
  export interface MenuItem { id: string; label: string; href?: string; disabled?: boolean; danger?: boolean; divider?: boolean; shortcut?: string }
3
4
  interface Props {
4
5
  label: string;
@@ -11,9 +12,9 @@ const { label, items, variant = 'secondary', align = 'start' } = Astro.props;
11
12
  const id = `ds-menu-${Math.random().toString(36).slice(2, 9)}`;
12
13
  ---
13
14
  <div class="ds-menu" data-align={align} data-ds-menu>
14
- <button type="button" class="ds-button" data-variant={variant} data-size="md" aria-haspopup="menu" aria-expanded="false" aria-controls={id}>
15
+ <Button variant={variant} aria-haspopup="menu" aria-expanded="false" aria-controls={id}>
15
16
  {label}<span aria-hidden="true" style="font-size:10px">▼</span>
16
- </button>
17
+ </Button>
17
18
  <div class="ds-dropdown" role="menu" id={id} aria-label={label} hidden>
18
19
  {items.map(item => item.divider
19
20
  ? <div class="ds-dropdown-separator" role="separator" />
@@ -0,0 +1,14 @@
1
+ ---
2
+ import type { HTMLAttributes } from 'astro/types';
3
+
4
+ interface Props extends HTMLAttributes<'label'> {
5
+ /** Adds the red asterisk (hidden from screen readers: the field itself is marked required). */
6
+ required?: boolean;
7
+ /** Use legend inside a fieldset. */
8
+ as?: 'label' | 'legend';
9
+ }
10
+
11
+ /* Atom: label of every form field with the required mark. */
12
+ const { required = false, as: Tag = 'label', ...rest } = Astro.props;
13
+ ---
14
+ <Tag {...rest}><slot />{required && <span class="ds-input-required" aria-hidden="true">*</span>}</Tag>
@@ -0,0 +1,153 @@
1
+ ---
2
+ import FieldLabel from './FieldLabel.astro';
3
+ interface Props {
4
+ id: string;
5
+ label: string;
6
+ name?: string;
7
+ accept?: string;
8
+ multiple?: boolean;
9
+ /** Maximum size of each file, in bytes. */
10
+ maxBytes?: number;
11
+ /** Maximum number of files (with multiple). */
12
+ maxFiles?: number;
13
+ required?: boolean;
14
+ disabled?: boolean;
15
+ supportingText?: string;
16
+ /** Allows dropping files onto the component. */
17
+ dropzone?: boolean;
18
+ class?: string;
19
+ }
20
+ const {
21
+ id, label, name, accept, multiple = false, maxBytes, maxFiles, required = false, disabled = false, supportingText,
22
+ dropzone = true, class: className,
23
+ } = Astro.props;
24
+ const describedBy = [supportingText ? `${id}-hint` : '', `${id}-error`].filter(Boolean).join(' ');
25
+ ---
26
+ <directo-file-picker class:list={['ds-file-upload', className]} data-max-bytes={maxBytes} data-max-files={maxFiles}
27
+ data-dropzone={dropzone ? '' : undefined} data-disabled={disabled ? '' : undefined} data-required={required ? '' : undefined}>
28
+ <FieldLabel for={id} required={required}>{label}</FieldLabel>
29
+ {supportingText && <small id={`${id}-hint`}>{supportingText}</small>}
30
+ <input id={id} type="file" name={name} accept={accept} multiple={multiple} required={required} disabled={disabled}
31
+ aria-describedby={describedBy} />
32
+ <div id={`${id}-error`} role="status"></div>
33
+ <ul hidden></ul>
34
+ </directo-file-picker>
35
+
36
+ <script>
37
+ import { formatBytes, selectFiles } from '../files.js';
38
+
39
+ class DirectoFilePicker extends HTMLElement {
40
+ private files: File[] = [];
41
+ private urls: string[] = [];
42
+
43
+ connectedCallback() {
44
+ this.addEventListener('change', this.select);
45
+ this.addEventListener('dragover', this.dragOver);
46
+ this.addEventListener('dragleave', this.dragLeave);
47
+ this.addEventListener('drop', this.drop);
48
+ }
49
+
50
+ disconnectedCallback() {
51
+ this.removeEventListener('change', this.select);
52
+ this.removeEventListener('dragover', this.dragOver);
53
+ this.removeEventListener('dragleave', this.dragLeave);
54
+ this.removeEventListener('drop', this.drop);
55
+ this.releasePreviews();
56
+ }
57
+
58
+ /** Files currently kept by the component. */
59
+ get dsFiles(): readonly File[] { return this.files; }
60
+
61
+ private get input() { return this.querySelector<HTMLInputElement>('input[type="file"]'); }
62
+ private get canDrop() { return this.hasAttribute('data-dropzone') && !this.input?.disabled; }
63
+
64
+ private dragOver = (event: DragEvent) => {
65
+ if (!this.canDrop) return;
66
+ event.preventDefault();
67
+ this.setAttribute('data-dragging', '');
68
+ };
69
+
70
+ private dragLeave = (event: DragEvent) => {
71
+ if (!this.contains(event.relatedTarget as Node | null)) this.removeAttribute('data-dragging');
72
+ };
73
+
74
+ private drop = (event: DragEvent) => {
75
+ if (!this.canDrop) return;
76
+ event.preventDefault();
77
+ this.removeAttribute('data-dragging');
78
+ this.add(Array.from(event.dataTransfer?.files ?? []));
79
+ };
80
+
81
+ private select = (event: Event) => {
82
+ if (event.target !== this.input) return;
83
+ this.add(Array.from(this.input?.files ?? []));
84
+ };
85
+
86
+ private add(incoming: File[]) {
87
+ const input = this.input;
88
+ if (!input) return;
89
+ const number = (value?: string) => value === undefined || value === '' ? undefined : Number(value);
90
+ const result = selectFiles(this.files, incoming, {
91
+ accept: input.accept, multiple: input.multiple,
92
+ maxBytes: number(this.dataset.maxBytes), maxFiles: number(this.dataset.maxFiles),
93
+ });
94
+ this.renderFiles(result.files, result.rejections.map(rejection => rejection.message).join(' '));
95
+ if (result.rejections.length) {
96
+ this.dispatchEvent(new CustomEvent('ds-reject', { bubbles: true, detail: result.rejections }));
97
+ }
98
+ }
99
+
100
+ private releasePreviews() {
101
+ this.urls.forEach(url => URL.revokeObjectURL(url));
102
+ this.urls = [];
103
+ }
104
+
105
+ private renderFiles(files: File[], error = '') {
106
+ const input = this.input;
107
+ const status = this.querySelector('[role="status"]');
108
+ const list = this.querySelector('ul');
109
+ if (!input || !status || !list) return;
110
+ const changed = files.length !== this.files.length || files.some((file, index) => file !== this.files[index]);
111
+ this.files = files;
112
+ const transfer = new DataTransfer();
113
+ files.forEach(file => transfer.items.add(file));
114
+ input.files = transfer.files;
115
+ input.required = this.hasAttribute('data-required') && !files.length;
116
+ if (error) input.setAttribute('aria-invalid', 'true'); else input.removeAttribute('aria-invalid');
117
+ this.releasePreviews();
118
+ status.textContent = error;
119
+ list.hidden = !files.length;
120
+ list.replaceChildren(...files.map((file, index) => {
121
+ const item = document.createElement('li');
122
+ if (file.type.startsWith('image/')) {
123
+ const image = document.createElement('img');
124
+ image.src = URL.createObjectURL(file);
125
+ image.alt = '';
126
+ this.urls.push(image.src);
127
+ item.append(image);
128
+ }
129
+ const name = document.createElement('span');
130
+ name.textContent = file.name;
131
+ const size = document.createElement('small');
132
+ size.textContent = formatBytes(file.size);
133
+ const button = document.createElement('button');
134
+ button.type = 'button';
135
+ button.className = 'ds-button';
136
+ button.dataset.variant = 'text';
137
+ button.dataset.size = 'sm';
138
+ button.disabled = input.disabled;
139
+ button.textContent = 'Quitar';
140
+ button.setAttribute('aria-label', 'Quitar ' + file.name);
141
+ button.addEventListener('click', () => {
142
+ this.renderFiles(files.filter((_, position) => position !== index));
143
+ this.dispatchEvent(new CustomEvent('ds-remove', { bubbles: true, detail: file }));
144
+ input.focus();
145
+ });
146
+ item.append(name, size, button);
147
+ return item;
148
+ }));
149
+ if (changed) this.dispatchEvent(new CustomEvent('ds-change', { bubbles: true, detail: files }));
150
+ }
151
+ }
152
+ if (!customElements.get('directo-file-picker')) customElements.define('directo-file-picker', DirectoFilePicker);
153
+ </script>