@dotrino/nav 0.2.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 seyacat
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 ADDED
@@ -0,0 +1,108 @@
1
+ # @dotrino/nav
2
+
3
+ Navegación **"volver"** unificada para todo el ecosistema [Dotrino](https://dotrino.com).
4
+
5
+ Resuelve un problema real: en iOS / PWA standalone no había forma de volver a
6
+ `dotrino.com`, y cada app inventaba (o no) su propio botón atrás. Este paquete
7
+ unifica el **botón físico de volver de Android**, el **gesto de volver de iOS** y
8
+ el **botón atrás del navegador** con un **chevron de UI**, y aplica la misma
9
+ cascada en todas las apps:
10
+
11
+ ```
12
+ modal abierto → ciérralo
13
+ historial de pestañas → vuelve a la vista anterior
14
+ sin historial interno → página anterior del navegador
15
+ sin página anterior → dotrino.com
16
+ ```
17
+
18
+ Sin JS de terceros, sin cookies, autohosteado (Shadow DOM). Funciona en apps
19
+ Vue y vanilla.
20
+
21
+ ## Por qué un paquete y no copiar el código
22
+
23
+ El chevron es trivial; lo que **no** lo es —y por eso se centraliza— es la
24
+ lógica de `popstate`: el botón físico de Android/iOS en una PWA no dispara un
25
+ evento propio, sino `popstate`. Para interceptarlo hay que mantener un
26
+ **centinela de history** (`pushState` base + uno por capa) y contar entradas
27
+ para no salirse de la app antes de tiempo ni quedar atrapado. Reimplementado por
28
+ app, son 15 variantes con bugs sutiles distintos. Aquí está en un solo lugar y
29
+ testeado (`npm test`, Playwright).
30
+
31
+ ## Dos piezas
32
+
33
+ ### 1. Controlador `createBackNav()`
34
+
35
+ ```js
36
+ import { createBackNav } from '@dotrino/nav'
37
+
38
+ const nav = createBackNav({ home: 'https://dotrino.com' }) // crea e instala el singleton
39
+
40
+ // Modal: empuja una capa; onClose define cómo cerrarlo.
41
+ const layer = nav.open(() => { mostrarModal.value = false })
42
+ // …y al cerrarlo desde su propio botón X / backdrop:
43
+ layer.close()
44
+
45
+ // Pestaña/vista: deja "miga" para volver a la anterior.
46
+ nav.open(() => setTab(tabAnterior))
47
+
48
+ // Routing real (opcional): refleja una URL/path enlazable mientras la capa
49
+ // esté abierta. Al cerrar (volver físico o layer.close()) el navegador
50
+ // restaura la URL anterior automáticamente.
51
+ const vista = nav.open(() => cerrarVista(), { url: '/que-es' })
52
+ ```
53
+
54
+ API: `open(onClose, opts?) → { close(), active }` —con `opts.url` opcional para
55
+ **routing real** (URL enlazable/indexable por capa; sin `url` = modal clásico que
56
+ no toca la barra de direcciones)—, `back()` (volver programático, idéntico al
57
+ físico), `size()`, `home`, `destroy()`. `getBackNav()` devuelve el controlador
58
+ activo.
59
+
60
+ > Routing real en GitHub Pages: para que un deep-link a `/que-es` cargue, genera
61
+ > una página estática real (p. ej. copia `index.html` → `que-es.html`, que Pages
62
+ > sirve con 200) y, al arrancar, deriva la vista inicial de `location.pathname`.
63
+
64
+ ### 2. Web Component `<dotrino-back>` (el chevron)
65
+
66
+ ```html
67
+ <!-- vanilla -->
68
+ <script type="module" src=".../@dotrino/nav/src/index.js"></script>
69
+ <dotrino-back></dotrino-back>
70
+ ```
71
+
72
+ ```js
73
+ // Vue: importa el paquete una vez y usa el tag en el header.
74
+ import '@dotrino/nav'
75
+ ```
76
+ ```html
77
+ <header class="topbar">
78
+ <dotrino-back lang="es" />
79
+ <div class="brand">…</div>
80
+ </header>
81
+ ```
82
+
83
+ Al hacer click hace lo mismo que el botón físico de volver. Atributos: `lang`
84
+ (`es`|`en`|auto), `label` (override), `floating` (posición fija arriba-izquierda
85
+ para apps sin header donde anclar), `home` (fallback si no hay controlador).
86
+ Emite el evento cancelable `cc-back`. Variables CSS: `--cc-back-size`,
87
+ `--cc-back-color`, `--cc-back-bg`, `--cc-back-radius`, `--cc-back-icon`, …
88
+
89
+ ### Helper Vue (opcional)
90
+
91
+ Sincroniza un `ref` de modal con la pila sin cablear `open`/`close` a mano:
92
+
93
+ ```js
94
+ import { useBackLayer } from '@dotrino/nav/vue'
95
+
96
+ const showNotifs = ref(false)
97
+ useBackLayer(showNotifs) // el volver cierra el modal en vez de salir de la app
98
+
99
+ // Con routing real: la vista pasa a tener URL propia enlazable/indexable.
100
+ const aboutOpen = ref(false)
101
+ useBackLayer(aboutOpen, { url: '/que-es' }) // string o función que lo devuelva
102
+ ```
103
+
104
+ ## Test
105
+
106
+ ```
107
+ npm test # smoke con Playwright: cascada popstate, LIFO, cierre programático, fallback a home
108
+ ```
package/package.json ADDED
@@ -0,0 +1,53 @@
1
+ {
2
+ "name": "@dotrino/nav",
3
+ "version": "0.2.1",
4
+ "description": "Navegación \"volver\" unificada del ecosistema Dotrino: controlador de pila (modal → pestaña → página anterior → dotrino.com) que intercepta el botón físico de Android / gesto de iOS / atrás del navegador, más el Web Component <dotrino-back> (chevron de header). Sin JS de terceros ni cookies.",
5
+ "type": "module",
6
+ "main": "src/index.js",
7
+ "module": "src/index.js",
8
+ "types": "src/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./src/index.d.ts",
12
+ "import": "./src/index.js"
13
+ },
14
+ "./vue": {
15
+ "types": "./src/vue.d.ts",
16
+ "import": "./src/vue.js"
17
+ }
18
+ },
19
+ "files": [
20
+ "src",
21
+ "README.md",
22
+ "LICENSE"
23
+ ],
24
+ "scripts": {
25
+ "test": "node test/smoke.mjs"
26
+ },
27
+ "peerDependencies": {
28
+ "vue": ">=3.3.0"
29
+ },
30
+ "peerDependenciesMeta": {
31
+ "vue": {
32
+ "optional": true
33
+ }
34
+ },
35
+ "keywords": [
36
+ "dotrino",
37
+ "web-component",
38
+ "custom-element",
39
+ "back",
40
+ "navigation",
41
+ "history",
42
+ "popstate",
43
+ "android-back",
44
+ "pwa",
45
+ "cross-app"
46
+ ],
47
+ "author": "seyacat",
48
+ "license": "MIT",
49
+ "repository": {
50
+ "type": "git",
51
+ "url": "git+https://github.com/imdotrino/dotrino-nav.git"
52
+ }
53
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,53 @@
1
+ export interface BackNavOptions {
2
+ /** A dónde ir cuando no hay capas internas ni página anterior. Default dotrino.com. */
3
+ home?: string
4
+ /** Interceptar el botón físico/gesto/atrás del navegador vía history. Default true. */
5
+ trap?: boolean
6
+ }
7
+
8
+ export interface BackLayerHandle {
9
+ /** Cierra esta capa programáticamente (botón X, backdrop…). */
10
+ close(): void
11
+ /** true mientras la capa siga en la pila. */
12
+ readonly active: boolean
13
+ }
14
+
15
+ export interface BackLayerOptions {
16
+ /**
17
+ * Routing real (opcional): URL/path a reflejar mientras la capa esté abierta
18
+ * (p. ej. '/que-es' para una vista/pestaña enlazable e indexable). Al cerrar
19
+ * la capa el navegador restaura la URL anterior. Sin `url` = modal clásico
20
+ * (no cambia la barra de direcciones).
21
+ */
22
+ url?: string
23
+ }
24
+
25
+ export interface BackNavController {
26
+ /** Empuja una capa (modal o vista/pestaña); onClose define cómo cerrarla. */
27
+ open(onClose: () => void, opts?: BackLayerOptions): BackLayerHandle
28
+ /** Volver programático (idéntico al botón físico de volver). */
29
+ back(): void
30
+ /** Número de capas actualmente en la pila. */
31
+ size(): number
32
+ /** Destino de fallback (dotrino.com por defecto). */
33
+ readonly home: string
34
+ /** Quita el listener de history y libera el singleton. */
35
+ destroy(): void
36
+ }
37
+
38
+ /** Crea (e instala como singleton) el controlador de navegación "volver". */
39
+ export function createBackNav(opts?: BackNavOptions): BackNavController
40
+
41
+ /** Devuelve el controlador activo, o null si no se creó ninguno. */
42
+ export function getBackNav(): BackNavController | null
43
+
44
+ /** Custom element del chevron de volver (`<dotrino-back>`). */
45
+ export class DotrinoBack extends HTMLElement {
46
+ back(): void
47
+ }
48
+
49
+ declare global {
50
+ interface HTMLElementTagNameMap {
51
+ 'dotrino-back': DotrinoBack
52
+ }
53
+ }
package/src/index.js ADDED
@@ -0,0 +1,309 @@
1
+ /**
2
+ * @dotrino/nav
3
+ *
4
+ * Navegación "volver" unificada y reutilizable por CUALQUIER app del ecosistema
5
+ * Dotrino (Vue o vanilla). Resuelve el problema de que en iOS/PWA no hay
6
+ * forma de volver a dotrino.com, y unifica el botón físico de Android / el
7
+ * gesto de volver de iOS / el botón atrás del navegador con un chevron de UI.
8
+ *
9
+ * Dos piezas:
10
+ *
11
+ * 1. createBackNav() — un controlador JS con una PILA de "capas" (modales,
12
+ * vistas/pestañas) que intercepta `popstate` (que es lo que dispara el
13
+ * botón físico de Android, el gesto de volver de iOS y el botón atrás del
14
+ * navegador) mediante el truco del centinela de history. La cascada al
15
+ * volver es SIEMPRE la misma en todas las apps:
16
+ *
17
+ * modal abierto → ciérralo
18
+ * historial de pestañas/vistas → vuelve a la anterior
19
+ * sin historial interno → página anterior del navegador
20
+ * sin página anterior → dotrino.com
21
+ *
22
+ * 2. <dotrino-back> — un Web Component (custom element, Shadow DOM, sin
23
+ * JS de terceros) con el chevron de volver para poner arriba a la izquierda
24
+ * del header de cualquier app. Al hacer click hace lo mismo que el botón
25
+ * físico de volver (history.back()), así que comparte el código del punto 1.
26
+ *
27
+ * Filosofía Dotrino: sin JS de terceros, sin cookies, autohosteado.
28
+ *
29
+ * Uso del controlador (vanilla o Vue):
30
+ * import { createBackNav } from '@dotrino/nav'
31
+ * const nav = createBackNav({ home: 'https://dotrino.com' })
32
+ * // al abrir un modal:
33
+ * const layer = nav.open(() => { cerrarModalEnElDOM() })
34
+ * // al cerrarlo desde su propio botón X / backdrop:
35
+ * layer.close()
36
+ * // navegación entre pestañas (deja "miga" para volver a la anterior):
37
+ * nav.open(() => { setTab(tabAnterior) })
38
+ *
39
+ * Uso del chevron (vanilla):
40
+ * import '@dotrino/nav' // registra el custom element
41
+ * <dotrino-back></dotrino-back>
42
+ *
43
+ * Uso del chevron (Vue 3): el tag funciona tal cual tras importar el paquete.
44
+ * import '@dotrino/nav'
45
+ * <dotrino-back lang="es" />
46
+ *
47
+ * Helper Vue para sincronizar un ref de modal con la pila (sin cablear a mano):
48
+ * import { useBackLayer } from '@dotrino/nav/vue'
49
+ * useBackLayer(showModal) // showModal es un ref(false)
50
+ */
51
+
52
+ const HOME_DEFAULT = 'https://dotrino.com'
53
+
54
+ // Singleton: el Web Component <dotrino-back> y cualquier código que quiera
55
+ // "volver" programáticamente encuentran el controlador activo por aquí.
56
+ let _active = null
57
+
58
+ /** Devuelve el controlador de back activo (o null si no se creó ninguno). */
59
+ export function getBackNav () {
60
+ return _active
61
+ }
62
+
63
+ /**
64
+ * Crea (e instala) el controlador de navegación "volver".
65
+ *
66
+ * @param {object} [opts]
67
+ * @param {string} [opts.home='https://dotrino.com'] A dónde ir cuando no hay
68
+ * ni capas internas ni página anterior del navegador.
69
+ * @param {boolean} [opts.trap=true] Si intercepta el botón físico/gesto/atrás
70
+ * del navegador vía history. Ponlo en false solo para tests.
71
+ * @returns {{ open:Function, back:Function, size:Function, destroy:Function, home:string }}
72
+ */
73
+ export function createBackNav (opts = {}) {
74
+ const home = opts.home || HOME_DEFAULT
75
+ const trap = opts.trap !== false
76
+
77
+ /** @type {{ onClose: Function, _gone: boolean }[]} pila LIFO de capas. */
78
+ const layers = []
79
+ // Número de popstate que debemos IGNORAR (los que disparamos nosotros al
80
+ // cerrar una capa programáticamente con history.back()).
81
+ let suppress = 0
82
+
83
+ // ¿Hay una página real anterior a la que volver (req. 3) o vamos directo a
84
+ // dotrino.com (req. 4)? En una PWA lanzada standalone normalmente no hay
85
+ // referrer → vamos a dotrino.com, que es justo lo que falta hoy en iOS.
86
+ const hadPrev = (() => {
87
+ try {
88
+ const r = document.referrer
89
+ return !!r && r !== location.href
90
+ } catch (_) {
91
+ return false
92
+ }
93
+ })()
94
+
95
+ function runClose (layer) {
96
+ try {
97
+ if (typeof layer.onClose === 'function') layer.onClose()
98
+ } catch (e) {
99
+ // Nunca dejes que el handler de una app rompa la navegación.
100
+ try { console.error('[dotrino-nav] onClose error:', e) } catch (_) {}
101
+ }
102
+ }
103
+
104
+ function onPop () {
105
+ if (suppress > 0) {
106
+ suppress--
107
+ return
108
+ }
109
+ if (layers.length) {
110
+ // El botón de volver consumió la entrada de history de la capa de arriba:
111
+ // ciérrala. La marcamos _gone para que el cierre que dispara la app (p.ej.
112
+ // un watcher de Vue que pone el ref en false) NO intente sacar otra
113
+ // entrada de history.
114
+ const layer = layers.pop()
115
+ layer._gone = true
116
+ runClose(layer)
117
+ return
118
+ }
119
+ // Sin capas internas: estamos en el centinela base. Decidimos req. 3 / 4.
120
+ if (hadPrev) {
121
+ // Hay página anterior real del navegador: sal hacia ella.
122
+ try { history.back() } catch (_) { location.href = home }
123
+ } else {
124
+ // Standalone / sin referrer: a dotrino.com.
125
+ location.href = home
126
+ }
127
+ }
128
+
129
+ if (trap) {
130
+ // Centinela base: una entrada extra para atrapar el PRIMER "volver" cuando
131
+ // no hay capas, y así poder enrutar a dotrino.com en vez de quedar atrapado
132
+ // (el bug de iOS). Misma URL → es una entrada same-document, no recarga.
133
+ try { history.pushState({ ccNav: 'base' }, '') } catch (_) {}
134
+ window.addEventListener('popstate', onPop)
135
+ }
136
+
137
+ /**
138
+ * Empuja una capa (modal o vista/pestaña). Devuelve un handle con close().
139
+ * @param {Function} onClose Cómo cerrar esta capa (cerrar modal, volver a la
140
+ * pestaña anterior, etc.). Se llama tanto si el
141
+ * usuario pulsa volver como si llamas handle.close().
142
+ * @param {object} [opts]
143
+ * @param {string} [opts.url] Routing real (opcional): URL/path a reflejar
144
+ * mientras esta capa esté abierta (p. ej. '/que-es' para una
145
+ * vista). Se escribe en la entrada de history de la capa, así
146
+ * la vista es enlazable/indexable y compartible. Al cerrarla
147
+ * (volver físico o handle.close()) el navegador restaura la
148
+ * URL anterior automáticamente. Sin `url` se mantiene la URL
149
+ * actual (comportamiento clásico de modal).
150
+ */
151
+ function open (onClose, opts = {}) {
152
+ const layer = { onClose, _gone: false }
153
+ layers.push(layer)
154
+ if (trap) {
155
+ // url='' (o ausente) = misma URL (entrada same-document para atrapar el
156
+ // volver sin tocar la barra de direcciones). Con url → routing real.
157
+ const url = opts.url == null ? '' : String(opts.url)
158
+ try { history.pushState({ ccNav: layers.length }, '', url) } catch (_) {}
159
+ }
160
+ return {
161
+ close () { dismiss(layer) },
162
+ get active () { return layers.indexOf(layer) !== -1 }
163
+ }
164
+ }
165
+
166
+ // Cierre programático de una capa (botón X del modal, backdrop, etc.).
167
+ function dismiss (layer) {
168
+ const idx = layers.indexOf(layer)
169
+ if (idx === -1) return // ya estaba cerrada (p.ej. por el botón físico)
170
+ layers.splice(idx, 1)
171
+ if (trap && !layer._gone) {
172
+ // Quita la entrada de history que empujamos al abrir, sin re-disparar el
173
+ // cierre (lo ignoramos vía suppress).
174
+ suppress++
175
+ try { history.back() } catch (_) { suppress-- }
176
+ }
177
+ runClose(layer)
178
+ }
179
+
180
+ /** Volver programático (lo usa el chevron): idéntico al botón físico. */
181
+ function back () {
182
+ if (trap) {
183
+ try { history.back() } catch (_) { onPop() }
184
+ } else {
185
+ onPop()
186
+ }
187
+ }
188
+
189
+ function destroy () {
190
+ if (trap) window.removeEventListener('popstate', onPop)
191
+ if (_active === controller) _active = null
192
+ }
193
+
194
+ const controller = {
195
+ open,
196
+ back,
197
+ home,
198
+ size: () => layers.length,
199
+ destroy
200
+ }
201
+ _active = controller
202
+ return controller
203
+ }
204
+
205
+ /* ────────────────────────────────────────────────────────────────────────────
206
+ Web Component: <dotrino-back>
207
+ Chevron de volver para el header. Al hacer click se comporta EXACTAMENTE
208
+ como el botón físico de volver (dispara el controlador / history.back()).
209
+ ──────────────────────────────────────────────────────────────────────────── */
210
+
211
+ const CHEVRON = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="15 18 9 12 15 6"/></svg>'
212
+
213
+ const BACK_I18N = { es: 'Volver', en: 'Back' }
214
+
215
+ const BACK_STYLE = `
216
+ :host {
217
+ all: initial;
218
+ display: inline-flex;
219
+ vertical-align: middle;
220
+ font-family: inherit;
221
+ }
222
+ :host([hidden]) { display: none; }
223
+ /* Modo flotante para apps sin header donde anclar (canvas a pantalla completa). */
224
+ :host([floating]) {
225
+ position: fixed;
226
+ top: max(10px, env(safe-area-inset-top, 0px));
227
+ left: max(10px, env(safe-area-inset-left, 0px));
228
+ z-index: 2147483000;
229
+ }
230
+ button {
231
+ all: unset;
232
+ box-sizing: border-box;
233
+ display: inline-flex;
234
+ align-items: center;
235
+ justify-content: center;
236
+ width: var(--cc-back-size, 38px);
237
+ height: var(--cc-back-size, 38px);
238
+ border-radius: var(--cc-back-radius, 12px);
239
+ color: var(--cc-back-color, currentColor);
240
+ background: var(--cc-back-bg, transparent);
241
+ cursor: pointer;
242
+ transition: background .15s ease, transform .1s ease, opacity .15s ease;
243
+ -webkit-tap-highlight-color: transparent;
244
+ }
245
+ button:hover { background: var(--cc-back-bg-hover, rgba(127,127,127,.16)); }
246
+ button:active { transform: translateX(-1px) scale(.94); }
247
+ button:focus-visible { outline: 2px solid var(--cc-back-focus, currentColor); outline-offset: 2px; }
248
+ svg { width: var(--cc-back-icon, 22px); height: var(--cc-back-icon, 22px); display: block; }
249
+ `
250
+
251
+ class DotrinoBack extends HTMLElement {
252
+ static get observedAttributes () { return ['lang', 'label'] }
253
+
254
+ constructor () {
255
+ super()
256
+ this.attachShadow({ mode: 'open' })
257
+ this._onClick = this._onClick.bind(this)
258
+ }
259
+
260
+ connectedCallback () {
261
+ this._render()
262
+ }
263
+
264
+ attributeChangedCallback () {
265
+ if (this.shadowRoot) this._render()
266
+ }
267
+
268
+ _resolveLang () {
269
+ const a = (this.getAttribute('lang') || '').toLowerCase()
270
+ if (a === 'es' || a === 'en') return a
271
+ let doc = 'es'
272
+ try { doc = (document.documentElement.lang || navigator.language || 'es').slice(0, 2) } catch (_) {}
273
+ return doc === 'en' ? 'en' : 'es'
274
+ }
275
+
276
+ _render () {
277
+ const lang = this._resolveLang()
278
+ const label = this.getAttribute('label') || BACK_I18N[lang]
279
+ this.shadowRoot.innerHTML = `<style>${BACK_STYLE}</style>` +
280
+ `<button type="button" part="button" aria-label="${label}" title="${label}">${CHEVRON}</button>`
281
+ this.shadowRoot.querySelector('button').addEventListener('click', this._onClick)
282
+ }
283
+
284
+ _onClick () {
285
+ // Evento cancelable: una app puede prevenirlo para hacer algo propio.
286
+ const ev = new CustomEvent('cc-back', { bubbles: true, composed: true, cancelable: true })
287
+ const proceed = this.dispatchEvent(ev)
288
+ if (!proceed) return
289
+
290
+ const nav = getBackNav()
291
+ if (nav) { nav.back(); return }
292
+
293
+ // Sin controlador instalado: fallback defensivo razonable.
294
+ const home = this.getAttribute('home') || HOME_DEFAULT
295
+ if (window.history.length > 1) {
296
+ try { window.history.back(); return } catch (_) {}
297
+ }
298
+ window.location.href = home
299
+ }
300
+
301
+ /** Volver programático desde JS de la app. */
302
+ back () { this._onClick() }
303
+ }
304
+
305
+ if (typeof customElements !== 'undefined' && !customElements.get('dotrino-back')) {
306
+ customElements.define('dotrino-back', DotrinoBack)
307
+ }
308
+
309
+ export { DotrinoBack }
package/src/vue.d.ts ADDED
@@ -0,0 +1,25 @@
1
+ import type { Ref } from 'vue'
2
+ import type { BackLayerHandle, BackNavController } from './index'
3
+
4
+ export interface UseBackLayerOptions {
5
+ /** Cómo cerrar la capa (default: `openRef.value = false`). */
6
+ onClose?: () => void
7
+ /** Controlador a usar (default: el activo, `getBackNav()`). */
8
+ nav?: BackNavController | null
9
+ /**
10
+ * Routing real (opcional): URL/path a reflejar mientras la capa esté abierta.
11
+ * String o función que lo devuelva (se evalúa al abrir). Sin `url` = modal
12
+ * clásico (no toca la barra de direcciones).
13
+ */
14
+ url?: string | (() => string)
15
+ }
16
+
17
+ /**
18
+ * Sincroniza un ref booleano (u objeto|null, se observa su veracidad) de "modal
19
+ * abierto" con la pila de back del controlador. Devuelve `{ nav }` (o
20
+ * `{ nav: null }` si no hay controlador instalado: no-op seguro).
21
+ */
22
+ export function useBackLayer (
23
+ openRef: Ref<unknown>,
24
+ opts?: UseBackLayerOptions
25
+ ): { nav: BackNavController | null }
package/src/vue.js ADDED
@@ -0,0 +1,63 @@
1
+ /**
2
+ * @dotrino/nav/vue
3
+ *
4
+ * Helper opcional para apps Vue 3: sincroniza un ref booleano de "modal abierto"
5
+ * con la pila de back del controlador, sin cablear open()/close() a mano.
6
+ *
7
+ * Cuando el ref pasa a true → empuja una capa (history) cuyo cierre pone el ref
8
+ * en false. Cuando el ref vuelve a false por CUALQUIER vía (botón X, backdrop,
9
+ * o el propio volver) → la capa se retira de forma consistente. Así el botón de
10
+ * volver de Android/iOS/navegador cierra el modal en lugar de salir de la app.
11
+ *
12
+ * import { useBackLayer } from '@dotrino/nav/vue'
13
+ * const showNotifs = ref(false)
14
+ * useBackLayer(showNotifs)
15
+ *
16
+ * Para pestañas/vistas (volver a la anterior en vez de cerrar), usa el
17
+ * controlador directamente: nav.open(() => goToPrevTab()).
18
+ */
19
+
20
+ import { watch, onScopeDispose } from 'vue'
21
+ import { getBackNav } from './index.js'
22
+
23
+ /**
24
+ * @param {import('vue').Ref} openRef ref que controla el modal (booleano u
25
+ * objeto|null; se observa su veracidad).
26
+ * @param {object} [opts]
27
+ * @param {Function} [opts.onClose] Cómo cerrar (default: openRef.value = false).
28
+ * @param {object} [opts.nav] Controlador a usar (default: el activo).
29
+ * @param {string|Function} [opts.url] Routing real (opcional): URL/path a
30
+ * reflejar mientras la capa esté abierta (p. ej. '/que-es'
31
+ * para una vista/pestaña enlazable). String o función que lo
32
+ * devuelva (se evalúa al abrir). Al cerrar, el navegador
33
+ * restaura la URL anterior. Sin `url` = modal clásico.
34
+ *
35
+ * No crea un controlador si no hay ninguno instalado (p. ej. en un iframe
36
+ * embebido donde no se llamó createBackNav): en ese caso es un no-op seguro.
37
+ */
38
+ export function useBackLayer (openRef, opts = {}) {
39
+ const nav = opts.nav || getBackNav()
40
+ if (!nav) return { nav: null }
41
+ const onClose = opts.onClose || (() => { openRef.value = false })
42
+ let handle = null
43
+
44
+ const stop = watch(openRef, (open) => {
45
+ if (open && !handle) {
46
+ const url = typeof opts.url === 'function' ? opts.url() : opts.url
47
+ handle = nav.open(onClose, { url })
48
+ } else if (!open && handle) {
49
+ // Cerrado por la app (X / backdrop): retira la capa de history.
50
+ // Si fue el botón físico de volver, la capa ya no está activa y close()
51
+ // es un no-op seguro.
52
+ handle.close()
53
+ handle = null
54
+ }
55
+ }, { flush: 'post' })
56
+
57
+ onScopeDispose(() => {
58
+ stop()
59
+ if (handle) { handle.close(); handle = null }
60
+ })
61
+
62
+ return { nav }
63
+ }