@groupteknology/vuno 0.4.0 → 0.6.1

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 (81) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +198 -0
  3. package/dist/module.json +1 -1
  4. package/dist/module.mjs +6 -0
  5. package/dist/runtime/app/assets/css/main.css +1 -1
  6. package/dist/runtime/app/components/App/App.d.vue.ts +33 -0
  7. package/dist/runtime/app/components/App/App.vue +127 -0
  8. package/dist/runtime/app/components/App/App.vue.d.ts +33 -0
  9. package/dist/runtime/app/components/App/AppContext.d.vue.ts +3 -0
  10. package/dist/runtime/app/components/App/AppContext.vue +7 -0
  11. package/dist/runtime/app/components/App/AppContext.vue.d.ts +3 -0
  12. package/dist/runtime/app/components/App/AppModal.d.vue.ts +38 -0
  13. package/dist/runtime/app/components/App/AppModal.vue +103 -0
  14. package/dist/runtime/app/components/App/AppModal.vue.d.ts +38 -0
  15. package/dist/runtime/app/components/App/AppOverlay.d.vue.ts +7 -0
  16. package/dist/runtime/app/components/App/AppOverlay.vue +33 -0
  17. package/dist/runtime/app/components/App/AppOverlay.vue.d.ts +7 -0
  18. package/dist/runtime/app/components/App/AppToast.d.vue.ts +11 -0
  19. package/dist/runtime/app/components/App/AppToast.vue +53 -0
  20. package/dist/runtime/app/components/App/AppToast.vue.d.ts +11 -0
  21. package/dist/runtime/app/components/App/AppToaster.d.vue.ts +11 -0
  22. package/dist/runtime/app/components/App/AppToaster.vue +49 -0
  23. package/dist/runtime/app/components/App/AppToaster.vue.d.ts +11 -0
  24. package/dist/runtime/app/components/Cell/CellBadge.d.vue.ts +5 -0
  25. package/dist/runtime/app/components/Cell/CellBadge.vue +24 -0
  26. package/dist/runtime/app/components/Cell/CellBadge.vue.d.ts +5 -0
  27. package/dist/runtime/app/components/Cell/CellBoolean.d.vue.ts +5 -0
  28. package/dist/runtime/app/components/Cell/CellBoolean.vue +21 -0
  29. package/dist/runtime/app/components/Cell/CellBoolean.vue.d.ts +5 -0
  30. package/dist/runtime/app/components/Cell/CellCurrency.d.vue.ts +5 -0
  31. package/dist/runtime/app/components/Cell/CellCurrency.vue +14 -0
  32. package/dist/runtime/app/components/Cell/CellCurrency.vue.d.ts +5 -0
  33. package/dist/runtime/app/components/Cell/CellDate.d.vue.ts +5 -0
  34. package/dist/runtime/app/components/Cell/CellDate.vue +19 -0
  35. package/dist/runtime/app/components/Cell/CellDate.vue.d.ts +5 -0
  36. package/dist/runtime/app/components/Cell/CellImage.d.vue.ts +5 -0
  37. package/dist/runtime/app/components/Cell/CellImage.vue +22 -0
  38. package/dist/runtime/app/components/Cell/CellImage.vue.d.ts +5 -0
  39. package/dist/runtime/app/components/Cell/CellNumber.d.vue.ts +5 -0
  40. package/dist/runtime/app/components/Cell/CellNumber.vue +15 -0
  41. package/dist/runtime/app/components/Cell/CellNumber.vue.d.ts +5 -0
  42. package/dist/runtime/app/components/Cell/CellText.d.vue.ts +5 -0
  43. package/dist/runtime/app/components/Cell/CellText.vue +13 -0
  44. package/dist/runtime/app/components/Cell/CellText.vue.d.ts +5 -0
  45. package/dist/runtime/app/components/Confirm/Confirm.vue +20 -13
  46. package/dist/runtime/app/components/Field/FieldArray.vue +68 -68
  47. package/dist/runtime/app/components/Field/FieldColor.vue +36 -36
  48. package/dist/runtime/app/components/Form/Form.vue +61 -49
  49. package/dist/runtime/app/components/Form/FormModal.vue +23 -15
  50. package/dist/runtime/app/components/Form/FormSection.vue +27 -27
  51. package/dist/runtime/app/components/Page/Page.vue +46 -46
  52. package/dist/runtime/app/components/State/EmptyState.vue +20 -20
  53. package/dist/runtime/app/components/State/FailureState.vue +21 -21
  54. package/dist/runtime/app/components/Table/Table.vue +286 -373
  55. package/dist/runtime/app/components/Table/TableCell.vue +24 -73
  56. package/dist/runtime/app/composables/useVunoConfirm.d.ts +15 -0
  57. package/dist/runtime/app/composables/useVunoConfirm.js +5 -0
  58. package/dist/runtime/app/composables/useVunoContext.d.ts +13 -0
  59. package/dist/runtime/app/composables/useVunoContext.js +9 -0
  60. package/dist/runtime/app/composables/useVunoModal.d.ts +21 -0
  61. package/dist/runtime/app/composables/useVunoModal.js +26 -0
  62. package/dist/runtime/app/composables/useVunoOverlay.d.ts +22 -0
  63. package/dist/runtime/app/composables/useVunoOverlay.js +10 -0
  64. package/dist/runtime/app/composables/useVunoTableQuery.js +3 -3
  65. package/dist/runtime/app/composables/useVunoTheme.js +2 -1
  66. package/dist/runtime/app/composables/useVunoToast.d.ts +28 -0
  67. package/dist/runtime/app/composables/useVunoToast.js +13 -0
  68. package/dist/runtime/app/internal/useVunoTable.d.ts +65 -0
  69. package/dist/runtime/app/internal/useVunoTable.js +161 -0
  70. package/dist/runtime/app/theme/index.js +69 -2
  71. package/dist/runtime/app/types/app.d.ts +83 -0
  72. package/dist/runtime/app/types/app.js +0 -0
  73. package/dist/runtime/app/types/confirm.d.ts +8 -0
  74. package/dist/runtime/app/types/index.d.ts +1 -0
  75. package/dist/runtime/app/types/table.d.ts +80 -13
  76. package/dist/runtime/app/types/theme.d.ts +12 -0
  77. package/dist/runtime/app/utils/column.d.ts +9 -0
  78. package/dist/runtime/app/utils/column.js +5 -0
  79. package/dist/runtime/app/utils/pagination.d.ts +12 -0
  80. package/dist/runtime/app/utils/pagination.js +6 -0
  81. package/package.json +6 -3
package/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 Diego Otayza
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Diego Otayza
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -68,6 +68,14 @@ const definition = {
68
68
 
69
69
  Cada uno declara sus propios props mediante una unión discriminada por `type`, así que el editor te avisa si a un `slug` le falta el `source` o si le pasas un `placeholder` a un `file`.
70
70
 
71
+ ### Campos obligatorios
72
+
73
+ `required: true` hace tres cosas: pinta el asterisco en la etiqueta, pone el atributo `required` en el input —que es lo que anuncia el campo como obligatorio a un lector de pantalla y lo que permite estilar `:invalid`— y nada más. **Quien decide si el valor vale es el esquema.**
74
+
75
+ El `<form>` lleva `novalidate`, así que el navegador no valida por su cuenta. Sin eso convivirían dos validaciones y ganaría la del navegador: cortaría el envío antes de que el esquema llegase a ejecutarse, y el usuario vería un globo del navegador, en su idioma y fuera del tema, en lugar del mensaje que tú escribiste.
76
+
77
+ Conviene saberlo si vienes de Nuxt UI a secas: `UFormField` con `required` solo pinta el asterisco y no toca el input. Los campos de vuno sí lo propagan, a propósito y por accesibilidad, y por eso el `novalidate` es necesario y no una preferencia.
78
+
71
79
  ### Campos repetibles
72
80
 
73
81
  `type: 'array'` repite un grupo de campos y genera rutas anidadas (`variants.0.sku`) que coinciden con las que produce la validación, de modo que cada campo muestra su propio error. Admite anidamiento.
@@ -106,6 +114,87 @@ El slot `footer` recibe `formId`, necesario para enviar desde un botón propio:
106
114
  <VFormModal v-model:open="open" v-model:state="state" :definition="definition" :schema="schema" title="Nuevo producto" close-on-submit @submit="guardar" />
107
115
  ```
108
116
 
117
+ ### Un componente por formulario
118
+
119
+ Un formulario largo no vive en la página. Se declara en su propio componente, que contiene **la definición, el esquema y los textos**, y nada más.
120
+
121
+ Es la práctica recomendada y no es una cuestión de orden: el mismo formulario acaba abriéndose desde más de un sitio —la lista, la ficha, un atajo— y en el momento en que lleva dentro el guardado, ya no se puede reutilizar sin arrastrar consecuencias que no son suyas.
122
+
123
+ La regla que lo resume: **el componente decide cómo es el formulario; quien lo usa decide qué pasa al enviarlo.**
124
+
125
+ ```vue
126
+ <!-- app/components/Product/ProductForm.vue -->
127
+ <script setup lang="ts">
128
+ import type { VunoFormDefinition } from '@groupteknology/vuno'
129
+ import * as z from 'zod'
130
+
131
+ const props = defineProps<{
132
+ /** La fila en edición. Sin ella, el formulario es de alta. */
133
+ product?: null | Product
134
+ loading?: boolean
135
+ }>()
136
+
137
+ const emit = defineEmits<{ submit: [] }>()
138
+
139
+ const open = defineModel<boolean>('open', { default: false })
140
+ const state = defineModel<ProductFormState>('state', { required: true })
141
+
142
+ // Lo propio del formulario: su forma, sus reglas y sus textos.
143
+ const schema = z.object({ sku: z.string().min(1, 'El SKU es requerido') })
144
+
145
+ const title = computed(() => (props.product ? `Editar ${props.product.sku}` : 'Nuevo producto'))
146
+
147
+ const definition = {
148
+ layout: 'tabs',
149
+ sections: [/* ... */],
150
+ } satisfies VunoFormDefinition
151
+ </script>
152
+
153
+ <template>
154
+ <VFormModal
155
+ v-model:open="open"
156
+ v-model:state="state"
157
+ :definition="definition"
158
+ :loading="props.loading"
159
+ :schema="schema"
160
+ :title="title"
161
+ @submit="emit('submit')"
162
+ />
163
+ </template>
164
+ ```
165
+
166
+ Y la página queda sin saber nada de los campos:
167
+
168
+ ```vue
169
+ <ProductForm
170
+ v-model:open="formOpen"
171
+ v-model:state="state"
172
+ :loading="isSaving"
173
+ :product="editing"
174
+ @submit="submit"
175
+ />
176
+ ```
177
+
178
+ #### Qué expone
179
+
180
+ | | |
181
+ |---|---|
182
+ | `v-model:state` | El estado del formulario. Obligatorio: lo posee quien lo usa, no el formulario. |
183
+ | `v-model:open` | Solo si es modal. |
184
+ | `:loading` | Si se está guardando, para bloquear el botón. |
185
+ | La fila en edición | Un prop —`product`, `brand`, lo que sea— que vale `null` en el alta. De él salen el título y la etiqueta del botón. |
186
+ | `@submit` | Significa «el usuario confirmó», nada más. Sin datos: ya están en `state`. |
187
+
188
+ No es casualidad que encaje: son exactamente `state`, `formOpen`, `isSaving`, `editing` y `submit` de `useVunoCrud`.
189
+
190
+ #### Qué se queda fuera
191
+
192
+ La petición, la mutación, invalidar la caché, los avisos y cerrar el modal al terminar. Todo eso es consecuencia del envío, y la consecuencia cambia según desde dónde se abra el formulario.
193
+
194
+ Si el componente hace el `$fetch` dentro, el síntoma llega pronto: en cuanto haga falta abrirlo desde otra pantalla con otro destino, hay que copiarlo o llenarlo de condicionales.
195
+
196
+ El estado tampoco se queda dentro. Si el formulario declara su propio `ref` en vez de recibir `v-model:state`, quien lo usa no ve lo que el usuario escribió y el guardado envía el estado inicial: falla en silencio y lejos de la causa.
197
+
109
198
  ## Una pantalla de mantenimiento entera
110
199
 
111
200
  `useVunoCrud` resuelve el ciclo completo: listar, dar de alta o editar en un modal, borrar con confirmación, invalidar la caché y avisar. Está construido sobre [TanStack Query](https://tanstack.com/query).
@@ -241,6 +330,78 @@ const { data, status } = await useFetch('/api/products', {
241
330
 
242
331
  Con `url: true` los filtros, la página, la búsqueda y el orden viajan en la query string: el enlace es compartible y recargar conserva la vista.
243
332
 
333
+ ### Tipos de columna
334
+
335
+ `text` · `number` · `currency` · `date` · `badge` · `boolean` · `image` · `actions` · `custom`
336
+
337
+ Cada uno declara sus propios props en una unión discriminada por `type`, igual que los campos. `key` es la ruta del valor en la fila y admite anidado: `key: 'proveedor.nombre'`.
338
+
339
+ ```ts
340
+ const definition = {
341
+ searchable: false, // el endpoint no busca: no se pinta la barra
342
+ paginated: false, // ni pagina: el pie dice cuántos hay y nada más
343
+ columns: [
344
+ { key: 'sku', label: 'SKU', type: 'text', sortable: true },
345
+ { key: 'price', label: 'Precio', type: 'currency', currency: 'EUR', align: 'end' },
346
+ { key: 'createdAt', label: 'Alta', type: 'date' },
347
+ ],
348
+ } satisfies VunoTableDefinition<Product>
349
+ ```
350
+
351
+ #### Traducir un valor a una etiqueta
352
+
353
+ La columna `badge` tiene `map`, que convierte el valor crudo que llega del servidor en la etiqueta y el color que ve el usuario. Es lo que evita enseñar `user` o `published` en pantalla:
354
+
355
+ ```ts
356
+ {
357
+ key: 'role',
358
+ label: 'Rol',
359
+ type: 'badge',
360
+ map: {
361
+ user: { color: 'neutral', label: 'Usuario' },
362
+ admin: { color: 'primary', label: 'Administrador' },
363
+ },
364
+ }
365
+ ```
366
+
367
+ Un valor sin entrada en el `map` se pinta tal cual, con el `color` de la columna o `neutral`. Es deliberado: si el servidor empieza a mandar un estado nuevo, verás el valor crudo en pantalla en lugar de una celda vacía que esconde que hay algo sin contemplar.
368
+
369
+ #### Calcular el valor desde la fila
370
+
371
+ Cuando lo que se muestra no está en una sola clave, o hay que derivarlo, toda columna acepta `value`:
372
+
373
+ ```ts
374
+ { key: 'role', label: 'Rol', type: 'text', value: (row) => traducirRol(row.role) }
375
+ { key: 'total', label: 'Total', type: 'currency', value: (row) => row.precio * row.unidades }
376
+ { key: 'autor', label: 'Autor', type: 'text', value: (row) => `${row.nombre} ${row.apellido}` }
377
+ ```
378
+
379
+ Recibe la fila entera y está tipada: con `VunoTableDefinition<Product>`, `row` es un `Product`.
380
+
381
+ **Sustituye de dónde sale el valor, no cómo se pinta.** Lo que devuelve sigue pasando por el formato de su tipo de columna, así que se combina con todo lo demás: en una columna `currency` se formatea como moneda, en una `date` como fecha, y en un `badge` pasa por su `map`.
382
+
383
+ ```ts
384
+ // Deriva el valor, y el `map` lo traduce después.
385
+ { key: 'estado', type: 'badge', value: (row) => (row.stock > 0 ? 'disponible' : 'agotado'), map: { agotado: { color: 'error', label: 'Agotado' }, disponible: { color: 'success', label: 'Disponible' } } }
386
+ ```
387
+
388
+ `key` sigue haciendo falta: nombra la columna para el orden y para el slot `cell-<key>`.
389
+
390
+ Y un aviso al ordenar: `sortable` ordena **en servidor por `key`**, y el servidor no conoce esta función. Si el valor mostrado no se deriva de `key` de forma monótona —un nombre completo compuesto de dos campos, por ejemplo— el orden no coincidirá con lo que se ve. Para eso, ordena por la clave que de verdad manda o deja la columna sin `sortable`.
391
+
392
+ `map` es solo de `badge`. Para traducir en otro tipo de columna, o para componer algo que no es una etiqueta, está `type: 'custom'` con su slot:
393
+
394
+ ```vue
395
+ <VTable :definition="definition" :data="rows">
396
+ <template #cell-stock="{ row, value }">
397
+ <span class="tabular-nums">{{ value }} uds.</span>
398
+ <UBadge v-if="row.stock === 0" color="error" label="Agotado" />
399
+ </template>
400
+ </VTable>
401
+ ```
402
+
403
+ El slot se llama `cell-<key>` y recibe `value` —el valor de esa columna, ya resuelto por su `key`— y `row` entera, directa y sin envolver.
404
+
244
405
  ### Una tabla vacía no es una que falló
245
406
 
246
407
  Son dos estados distintos y se pintan distinto. Sin separarlos, una consulta que falla se normaliza a lista vacía (`data ?? []`) y la tabla dice «No hay resultados»: afirma que no hay nada cuando lo cierto es que no se pudo saber.
@@ -251,6 +412,10 @@ const failure = computed(() => isError.value
251
412
  : undefined)
252
413
  ```
253
414
 
415
+ Con `useVunoCrud` no hace falta escribirlo: el objeto lo construye él, y el título y la pista se declaran en `messages` con `listFailed` y `listFailedHint`.
416
+
417
+ Si vienes de componerlo a mano, cuenta con un efecto lateral: si tu proyecto tiene un test que sujeta esta invariante buscando el objeto en la pantalla, se pondrá **rojo** al mudar los textos, porque ahí ya no hay ningún `retry:` que encontrar. No es una regresión —la garantía sigue, solo que ahora la sostiene el tipo `VunoTableFailure`, cuyo `retry` es obligatorio y comprueba el typecheck— pero el test tiene que mirar otra cosa.
418
+
254
419
  El reintento va **dentro** del objeto para que no se pueda pintar un error sin ofrecer salida. Mientras hay fallo, la tabla no muestra filas ni paginación. El estado vacío se declara en la definición (`empty: { title, hint, icon }`) y tiene un slot `empty-actions` donde encaja el «crear el primero».
255
420
 
256
421
  Los dos estados existen además como componentes sueltos, para las pantallas que no son una tabla:
@@ -278,6 +443,39 @@ Tipos de columna: `text` · `number` · `currency` · `date` · `boolean` · `ba
278
443
 
279
444
  No se cierra solo cuando recibe `loading`: así se espera a que la acción termine contra la API y se cierra desde fuera.
280
445
 
446
+ ## Modales del proyecto
447
+
448
+ Un modal por componente, en `components/modal/`, abierto por su clave:
449
+
450
+ ```
451
+ app/components/modal/ModalProduct.vue -> open('product')
452
+ app/components/modal/ModalInvoice.vue -> open('invoice')
453
+ ```
454
+
455
+ ```ts
456
+ const modal = useVunoModal()
457
+
458
+ const guardado = await modal.open<boolean>('product', { sku: row.sku })
459
+ ```
460
+
461
+ No hay que registrarlo ni colocarlo en ninguna plantilla: el módulo marca esa carpeta como global, así que la clave **es** el nombre del componente y un modal que existe se puede abrir.
462
+
463
+ El componente recibe `open` y los props que le pases, y resuelve la promesa emitiendo `close` con su resultado:
464
+
465
+ ```vue
466
+ <script setup lang="ts">
467
+ const emit = defineEmits<{ close: [guardado: boolean] }>()
468
+ const open = defineModel<boolean>('open', { default: false })
469
+
470
+ function guardar() {
471
+ open.value = false
472
+ emit('close', true)
473
+ }
474
+ </script>
475
+ ```
476
+
477
+ Se pinta en `<VApp>` y no en la pantalla que lo abrió, así que navegar no lo desmonta a medias ni deja la promesa colgada. Cerrarlo con Escape o pulsando fuera resuelve sin valor.
478
+
281
479
  ## Composables
282
480
 
283
481
  | Composable | Para qué |
package/dist/module.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "vuno",
3
3
  "configKey": "vuno",
4
- "version": "0.4.0",
4
+ "version": "0.6.1",
5
5
  "builder": {
6
6
  "@nuxt/module-builder": "1.0.3",
7
7
  "unbuild": "unknown"
package/dist/module.mjs CHANGED
@@ -20,6 +20,12 @@ const module$1 = defineNuxtModule({
20
20
  pathPrefix: false,
21
21
  prefix: options.prefix
22
22
  });
23
+ nuxt.hook("components:extend", (components) => {
24
+ for (const component of components) {
25
+ const path = component.filePath.split("\\").join("/");
26
+ if (path.includes("/components/modal/")) component.global = true;
27
+ }
28
+ });
23
29
  addImportsDir(resolver.resolve("./runtime/app/composables"));
24
30
  nuxt.options.css.push(resolver.resolve("./runtime/app/assets/css/main.css"));
25
31
  }
@@ -1 +1 @@
1
- @import "tailwindcss";@import "@nuxt/ui";@source "../../**/*";
1
+ @import "tailwindcss";@import "@nuxt/ui";@source "../../**/*";:root{--vuno-modal-duration:180ms;--vuno-modal-ease:cubic-bezier(0.32,0.72,0,1);--vuno-backdrop:rgba(0,0,0,.5)}dialog{opacity:0;transform:scale(.97) translateY(.5rem);transition:opacity var(--vuno-modal-duration) var(--vuno-modal-ease),transform var(--vuno-modal-duration) var(--vuno-modal-ease),display var(--vuno-modal-duration) allow-discrete,overlay var(--vuno-modal-duration) allow-discrete}dialog[open]{opacity:1;transform:scale(1) translateY(0)}@starting-style{dialog[open]{opacity:0;transform:scale(.97) translateY(.5rem)}}dialog::backdrop{background-color:transparent;transition:background-color var(--vuno-modal-duration) var(--vuno-modal-ease),display var(--vuno-modal-duration) allow-discrete,overlay var(--vuno-modal-duration) allow-discrete}dialog[open]::backdrop{background-color:var(--vuno-backdrop)}@starting-style{dialog[open]::backdrop{background-color:transparent}}dialog.vuno-overlay-behind::backdrop,dialog.vuno-overlay-behind[open]::backdrop{background-color:transparent}@media (prefers-reduced-motion:reduce){dialog,dialog::backdrop{transition-duration:1ms}dialog{transform:none}}
@@ -0,0 +1,33 @@
1
+ import { type Component } from 'vue';
2
+ import type { VunoAlertRequest, VunoConfirmRequest, VunoNotifyRequest } from '#vuno/types/app';
3
+ /**
4
+ * Monta un componente y espera a que emita `close`.
5
+ *
6
+ * Cerrar con Escape o pulsando fuera cuenta como cerrar sin resultado: un
7
+ * `update:open` en falso resuelve igual, porque si no la promesa se quedaría
8
+ * esperando para siempre a un diálogo que ya no está en pantalla.
9
+ */
10
+ declare function open<TResult = unknown>(component: Component, props?: Record<string, unknown>): Promise<TResult | undefined>;
11
+ declare function closeAll(): void;
12
+ declare function dismiss(id: number): void;
13
+ declare function notify(request: VunoNotifyRequest): number;
14
+ declare var __VLS_1: {};
15
+ type __VLS_Slots = {} & {
16
+ default?: (props: typeof __VLS_1) => any;
17
+ };
18
+ declare const __VLS_base: import("vue").DefineComponent<{}, {
19
+ alert: (request: VunoAlertRequest) => Promise<void>;
20
+ closeAll: typeof closeAll;
21
+ confirm: (request: VunoConfirmRequest) => Promise<boolean>;
22
+ dismiss: typeof dismiss;
23
+ notify: typeof notify;
24
+ open: typeof open;
25
+ }, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").PublicProps, Readonly<{}> & Readonly<{}>, {}, {}, {}, {}, string, import("vue").ComponentProvideOptions, true, {}, any>;
26
+ declare const __VLS_export: __VLS_WithSlots<typeof __VLS_base, __VLS_Slots>;
27
+ declare const _default: typeof __VLS_export;
28
+ export default _default;
29
+ type __VLS_WithSlots<T, S> = T & {
30
+ new (): {
31
+ $slots: S;
32
+ };
33
+ };
@@ -0,0 +1,127 @@
1
+ <script setup>
2
+ import { onBeforeUnmount, provide, reactive, shallowReactive } from "vue";
3
+ import Confirm from "#vuno/components/Confirm/Confirm.vue";
4
+ import { vunoContextInjectionKey } from "#vuno/composables/useVunoContext";
5
+ import AppOverlay from "./AppOverlay.vue";
6
+ import AppToaster from "./AppToaster.vue";
7
+ const overlays = reactive([]);
8
+ const notifications = shallowReactive([]);
9
+ let nextId = 0;
10
+ const EXIT_MS = 220;
11
+ function removeOverlay(id) {
12
+ const index = overlays.findIndex((entry) => entry.id === id);
13
+ if (index !== -1) overlays.splice(index, 1);
14
+ }
15
+ function dismissOverlay(id) {
16
+ const entry = overlays.find((item) => item.id === id);
17
+ if (entry) entry.open = false;
18
+ setTimeout(() => removeOverlay(id), EXIT_MS);
19
+ }
20
+ function open(component, props = {}) {
21
+ return new Promise((resolve) => {
22
+ const id = nextId++;
23
+ let settled = false;
24
+ const settle = (value) => {
25
+ if (settled) return;
26
+ settled = true;
27
+ resolve(value);
28
+ dismissOverlay(id);
29
+ };
30
+ overlays.push({
31
+ id,
32
+ component,
33
+ listeners: {
34
+ close: (value) => settle(value),
35
+ /**
36
+ * Se aplaza una microtarea porque lo normal dentro del modal
37
+ * es cerrar y luego emitir el resultado:
38
+ *
39
+ * ```ts
40
+ * open.value = false
41
+ * emit('close', true)
42
+ * ```
43
+ *
44
+ * Resolver aquí en el acto se quedaría con el primero de los
45
+ * dos y devolvería `undefined` habiendo un resultado. Con el
46
+ * aplazamiento, un `close` síncrono llega antes y gana; si no
47
+ * llega ninguno —Escape, pulsar fuera—, resuelve sin valor.
48
+ */
49
+ "update:open": (value) => {
50
+ if (!value) queueMicrotask(() => settle(void 0));
51
+ }
52
+ },
53
+ open: true,
54
+ props: { ...props }
55
+ });
56
+ });
57
+ }
58
+ function askConfirm(request, dismissed) {
59
+ return new Promise((resolve) => {
60
+ const id = nextId++;
61
+ let settled = false;
62
+ const settle = (value) => {
63
+ if (settled) return;
64
+ settled = true;
65
+ resolve(value);
66
+ dismissOverlay(id);
67
+ };
68
+ overlays.push({
69
+ id,
70
+ component: Confirm,
71
+ listeners: {
72
+ cancel: () => settle(false),
73
+ confirm: () => settle(true),
74
+ // Escape o pulsar fuera: en una confirmación es que no, y en
75
+ // una alerta es que ya se enteró.
76
+ "update:open": (value) => {
77
+ if (!value) settle(dismissed);
78
+ }
79
+ },
80
+ open: true,
81
+ props: { ...request }
82
+ });
83
+ });
84
+ }
85
+ const confirm = (request) => askConfirm(request, false);
86
+ const alert = async (request) => {
87
+ await askConfirm({ ...request, alert: true }, true);
88
+ };
89
+ function closeAll() {
90
+ for (const entry of [...overlays]) (entry.listeners.cancel ?? entry.listeners.close)?.();
91
+ }
92
+ const timers = /* @__PURE__ */ new Map();
93
+ function dismiss(id) {
94
+ const timer = timers.get(id);
95
+ if (timer) {
96
+ clearTimeout(timer);
97
+ timers.delete(id);
98
+ }
99
+ const index = notifications.findIndex((entry) => entry.id === id);
100
+ if (index !== -1) notifications.splice(index, 1);
101
+ }
102
+ function notify(request) {
103
+ const id = nextId++;
104
+ const duration = request.duration ?? 5e3;
105
+ notifications.push({ ...request, id, color: request.color ?? "neutral", duration });
106
+ if (duration > 0) timers.set(id, setTimeout(() => dismiss(id), duration));
107
+ return id;
108
+ }
109
+ onBeforeUnmount(() => {
110
+ for (const timer of timers.values()) clearTimeout(timer);
111
+ timers.clear();
112
+ });
113
+ const context = { alert, closeAll, confirm, dismiss, notifications, notify, open, overlays };
114
+ provide(vunoContextInjectionKey, context);
115
+ defineExpose({ alert, closeAll, confirm, dismiss, notify, open });
116
+ </script>
117
+
118
+ <template>
119
+ <slot />
120
+
121
+ <AppOverlay :overlays="overlays" />
122
+
123
+ <AppToaster
124
+ :notifications="notifications"
125
+ @dismiss="dismiss"
126
+ />
127
+ </template>
@@ -0,0 +1,33 @@
1
+ import { type Component } from 'vue';
2
+ import type { VunoAlertRequest, VunoConfirmRequest, VunoNotifyRequest } from '#vuno/types/app';
3
+ /**
4
+ * Monta un componente y espera a que emita `close`.
5
+ *
6
+ * Cerrar con Escape o pulsando fuera cuenta como cerrar sin resultado: un
7
+ * `update:open` en falso resuelve igual, porque si no la promesa se quedaría
8
+ * esperando para siempre a un diálogo que ya no está en pantalla.
9
+ */
10
+ declare function open<TResult = unknown>(component: Component, props?: Record<string, unknown>): Promise<TResult | undefined>;
11
+ declare function closeAll(): void;
12
+ declare function dismiss(id: number): void;
13
+ declare function notify(request: VunoNotifyRequest): number;
14
+ declare var __VLS_1: {};
15
+ type __VLS_Slots = {} & {
16
+ default?: (props: typeof __VLS_1) => any;
17
+ };
18
+ declare const __VLS_base: import("vue").DefineComponent<{}, {
19
+ alert: (request: VunoAlertRequest) => Promise<void>;
20
+ closeAll: typeof closeAll;
21
+ confirm: (request: VunoConfirmRequest) => Promise<boolean>;
22
+ dismiss: typeof dismiss;
23
+ notify: typeof notify;
24
+ open: typeof open;
25
+ }, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").PublicProps, Readonly<{}> & Readonly<{}>, {}, {}, {}, {}, string, import("vue").ComponentProvideOptions, true, {}, any>;
26
+ declare const __VLS_export: __VLS_WithSlots<typeof __VLS_base, __VLS_Slots>;
27
+ declare const _default: typeof __VLS_export;
28
+ export default _default;
29
+ type __VLS_WithSlots<T, S> = T & {
30
+ new (): {
31
+ $slots: S;
32
+ };
33
+ };
@@ -0,0 +1,3 @@
1
+ declare const __VLS_export: import("vue").DefineComponent<{}, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").PublicProps, Readonly<{}> & Readonly<{}>, {}, {}, {}, {}, string, import("vue").ComponentProvideOptions, true, {}, any>;
2
+ declare const _default: typeof __VLS_export;
3
+ export default _default;
@@ -0,0 +1,7 @@
1
+ <script setup lang="ts"></script>
2
+
3
+ <template>
4
+ <div>
5
+ <!-- -->
6
+ </div>
7
+ </template>
@@ -0,0 +1,3 @@
1
+ declare const __VLS_export: import("vue").DefineComponent<{}, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").PublicProps, Readonly<{}> & Readonly<{}>, {}, {}, {}, {}, string, import("vue").ComponentProvideOptions, true, {}, any>;
2
+ declare const _default: typeof __VLS_export;
3
+ export default _default;
@@ -0,0 +1,38 @@
1
+ import type { VunoFieldSlots } from '#vuno/types/field';
2
+ type __VLS_Props = {
3
+ description?: string;
4
+ /** Cerrar con Escape o pulsando el fondo. */
5
+ dismissible?: boolean;
6
+ title?: string;
7
+ ui?: VunoFieldSlots;
8
+ };
9
+ type __VLS_Slots = {
10
+ body?: () => unknown;
11
+ default?: () => unknown;
12
+ footer?: () => unknown;
13
+ header?: () => unknown;
14
+ };
15
+ type __VLS_ModelProps = {
16
+ 'open'?: boolean;
17
+ };
18
+ type __VLS_PublicProps = __VLS_Props & __VLS_ModelProps;
19
+ declare const __VLS_base: import("vue").DefineComponent<__VLS_PublicProps, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {
20
+ close: () => any;
21
+ "update:open": (value: boolean) => any;
22
+ }, string, import("vue").PublicProps, Readonly<__VLS_PublicProps> & Readonly<{
23
+ onClose?: (() => any) | undefined;
24
+ "onUpdate:open"?: ((value: boolean) => any) | undefined;
25
+ }>, {
26
+ description: string;
27
+ title: string;
28
+ ui: VunoFieldSlots;
29
+ dismissible: boolean;
30
+ }, {}, {}, {}, string, import("vue").ComponentProvideOptions, false, {}, any>;
31
+ declare const __VLS_export: __VLS_WithSlots<typeof __VLS_base, __VLS_Slots>;
32
+ declare const _default: typeof __VLS_export;
33
+ export default _default;
34
+ type __VLS_WithSlots<T, S> = T & {
35
+ new (): {
36
+ $slots: S;
37
+ };
38
+ };
@@ -0,0 +1,103 @@
1
+ <script setup>
2
+ import { onBeforeUnmount, useTemplateRef, watch } from "vue";
3
+ import { useVunoTheme } from "#vuno/composables/useVunoTheme";
4
+ const props = defineProps({
5
+ description: { type: String, required: false, default: void 0 },
6
+ dismissible: { type: Boolean, required: false, default: true },
7
+ title: { type: String, required: false, default: void 0 },
8
+ ui: { type: Object, required: false, default: void 0 }
9
+ });
10
+ const emit = defineEmits(["close"]);
11
+ const open = defineModel("open", { type: Boolean, ...{ default: false } });
12
+ defineSlots();
13
+ const ui = useVunoTheme("appModal", () => props.ui);
14
+ const dialog = useTemplateRef("dialog");
15
+ function lockScroll(locked) {
16
+ if (typeof document === "undefined") return;
17
+ document.body.style.overflow = locked ? "hidden" : "";
18
+ }
19
+ watch(
20
+ [open, dialog],
21
+ ([value, element]) => {
22
+ if (!element) return;
23
+ if (value && !element.open) {
24
+ element.showModal();
25
+ lockScroll(true);
26
+ return;
27
+ }
28
+ if (!value && element.open) {
29
+ element.close();
30
+ lockScroll(false);
31
+ }
32
+ },
33
+ { immediate: true }
34
+ );
35
+ onBeforeUnmount(() => lockScroll(false));
36
+ function requestClose() {
37
+ open.value = false;
38
+ lockScroll(false);
39
+ emit("close");
40
+ }
41
+ function onCancel(event) {
42
+ event.preventDefault();
43
+ if (props.dismissible) requestClose();
44
+ }
45
+ function onClick(event) {
46
+ if (!props.dismissible) return;
47
+ const element = dialog.value;
48
+ if (!element || event.target !== element) return;
49
+ const box = element.getBoundingClientRect();
50
+ const inside = event.clientX >= box.left && event.clientX <= box.right && event.clientY >= box.top && event.clientY <= box.bottom;
51
+ if (!inside) requestClose();
52
+ }
53
+ </script>
54
+
55
+ <template>
56
+ <dialog
57
+ ref="dialog"
58
+ :aria-describedby="props.description ? 'vuno-modal-description' : void 0"
59
+ :aria-labelledby="props.title ? 'vuno-modal-title' : void 0"
60
+ :class="ui.root"
61
+ @cancel="onCancel"
62
+ @click="onClick"
63
+ @close="open = false"
64
+ >
65
+ <div :class="ui.content">
66
+ <slot name="header">
67
+ <div
68
+ v-if="props.title || props.description"
69
+ :class="ui.header"
70
+ >
71
+ <h2
72
+ v-if="props.title"
73
+ id="vuno-modal-title"
74
+ :class="ui.title"
75
+ >
76
+ {{ props.title }}
77
+ </h2>
78
+
79
+ <p
80
+ v-if="props.description"
81
+ id="vuno-modal-description"
82
+ :class="ui.description"
83
+ >
84
+ {{ props.description }}
85
+ </p>
86
+ </div>
87
+ </slot>
88
+
89
+ <div :class="ui.body">
90
+ <slot name="body">
91
+ <slot />
92
+ </slot>
93
+ </div>
94
+
95
+ <div
96
+ v-if="$slots.footer"
97
+ :class="ui.footer"
98
+ >
99
+ <slot name="footer" />
100
+ </div>
101
+ </div>
102
+ </dialog>
103
+ </template>