@dotrino/nav 0.2.2 → 0.3.3
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 +0 -0
- package/README.md +17 -1
- package/package.json +9 -2
- package/src/index.d.ts +0 -0
- package/src/index.js +130 -48
- package/src/vue.d.ts +0 -0
- package/src/vue.js +7 -5
package/LICENSE
CHANGED
|
File without changes
|
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @dotrino/nav
|
|
2
2
|
|
|
3
|
-
> **Parte del ecosistema [Dotrino](https://dotrino.com).**
|
|
3
|
+
> **Parte del ecosistema [Dotrino](https://dotrino.com).** Dotrino es un ecosistema de aplicaciones centradas en la privacidad de los datos: tu información es tuya, y las decisiones sobre ella también — qué compartes, con quién, cuándo y por qué. Sin anuncios, sin cookies, sin rastreo de datos, sin vender tu identidad a nadie.
|
|
4
4
|
|
|
5
5
|
Navegación **"volver"** unificada para todo el ecosistema [Dotrino](https://dotrino.com).
|
|
6
6
|
|
|
@@ -103,6 +103,22 @@ const aboutOpen = ref(false)
|
|
|
103
103
|
useBackLayer(aboutOpen, { url: '/que-es' }) // string o función que lo devuelva
|
|
104
104
|
```
|
|
105
105
|
|
|
106
|
+
## Cómo decide (y por qué no cuenta eventos)
|
|
107
|
+
|
|
108
|
+
El controlador **no lleva la cuenta de los `popstate`**: lee `history.state.ccNav` de
|
|
109
|
+
la entrada en la que acaba de caer (`base`, o el número de capa) y ajusta la pila a
|
|
110
|
+
eso. `history.back()` es asíncrono, y contar eventos se desfasaba en cuanto una capa se
|
|
111
|
+
abría mientras el `back()` de otra estaba en vuelo — la capa nueva quedaba «adelante» y
|
|
112
|
+
el siguiente volver salía de la app (visto en eco, 2026-08-22). Tres reglas:
|
|
113
|
+
|
|
114
|
+
- abrir/cerrar mientras un `back()` nuestro está en vuelo **se encola** hasta que llega
|
|
115
|
+
su `popstate`;
|
|
116
|
+
- cerrar una capa solo retira entradas de history si **de verdad estamos sobre la
|
|
117
|
+
suya** (`history.state` lo dice); si no, se cierra en la pila y el historial se deja
|
|
118
|
+
en paz;
|
|
119
|
+
- una entrada sin estado nuestro con **otra URL** (un `location.hash = …` de la app) se
|
|
120
|
+
adopta como capa transparente, en vez de tomarla por «el usuario quiere salir».
|
|
121
|
+
|
|
106
122
|
## Test
|
|
107
123
|
|
|
108
124
|
```
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dotrino/nav",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.3",
|
|
4
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
5
|
"type": "module",
|
|
6
6
|
"main": "src/index.js",
|
|
@@ -22,7 +22,8 @@
|
|
|
22
22
|
"LICENSE"
|
|
23
23
|
],
|
|
24
24
|
"scripts": {
|
|
25
|
-
"test": "node test/smoke.mjs"
|
|
25
|
+
"test": "node test/smoke.mjs",
|
|
26
|
+
"type-check": "tsc --noEmit"
|
|
26
27
|
},
|
|
27
28
|
"peerDependencies": {
|
|
28
29
|
"vue": ">=3.3.0"
|
|
@@ -49,5 +50,11 @@
|
|
|
49
50
|
"repository": {
|
|
50
51
|
"type": "git",
|
|
51
52
|
"url": "git+https://github.com/imdotrino/dotrino-nav.git"
|
|
53
|
+
},
|
|
54
|
+
"devDependencies": {
|
|
55
|
+
"@types/node": "22.20.1",
|
|
56
|
+
"playwright": "1.60.0",
|
|
57
|
+
"typescript": "5.9.3",
|
|
58
|
+
"vue": "3.5.25"
|
|
52
59
|
}
|
|
53
60
|
}
|
package/src/index.d.ts
CHANGED
|
File without changes
|
package/src/index.js
CHANGED
|
@@ -55,9 +55,17 @@ const HOME_DEFAULT = 'https://dotrino.com'
|
|
|
55
55
|
|
|
56
56
|
// Singleton: el Web Component <dotrino-back> y cualquier código que quiera
|
|
57
57
|
// "volver" programáticamente encuentran el controlador activo por aquí.
|
|
58
|
+
/** @typedef {import('./index.js').BackNavController} BackNavController */
|
|
59
|
+
/** @typedef {{ onClose: (() => void) | null, depth: number }} Layer */
|
|
60
|
+
|
|
61
|
+
/** @type {BackNavController | null} */
|
|
58
62
|
let _active = null
|
|
59
63
|
|
|
60
|
-
/**
|
|
64
|
+
/**
|
|
65
|
+
* Devuelve el controlador de back activo (o null si no se creó ninguno).
|
|
66
|
+
*
|
|
67
|
+
* @returns {BackNavController | null}
|
|
68
|
+
*/
|
|
61
69
|
export function getBackNav () {
|
|
62
70
|
return _active
|
|
63
71
|
}
|
|
@@ -65,22 +73,26 @@ export function getBackNav () {
|
|
|
65
73
|
/**
|
|
66
74
|
* Crea (e instala) el controlador de navegación "volver".
|
|
67
75
|
*
|
|
68
|
-
* @param {
|
|
69
|
-
*
|
|
70
|
-
* ni
|
|
71
|
-
*
|
|
72
|
-
*
|
|
73
|
-
* @returns {
|
|
76
|
+
* @param {import('./index.js').BackNavOptions} [opts] `home` (default
|
|
77
|
+
* 'https://dotrino.com'): a dónde ir cuando no hay ni capas internas
|
|
78
|
+
* ni página anterior del navegador. `trap` (default true): si
|
|
79
|
+
* intercepta el botón físico/gesto/atrás del navegador vía history.
|
|
80
|
+
* Ponlo en false solo para tests.
|
|
81
|
+
* @returns {BackNavController}
|
|
74
82
|
*/
|
|
75
83
|
export function createBackNav (opts = {}) {
|
|
76
84
|
const home = opts.home || HOME_DEFAULT
|
|
77
85
|
const trap = opts.trap !== false
|
|
78
86
|
|
|
79
|
-
/** @type {
|
|
87
|
+
/** @type {Layer[]} pila LIFO de capas. */
|
|
80
88
|
const layers = []
|
|
81
|
-
//
|
|
82
|
-
//
|
|
83
|
-
|
|
89
|
+
// Traversals que disparamos nosotros (history.back() al cerrar una capa) y cuyo
|
|
90
|
+
// popstate aún no llegó. Mientras haya uno en vuelo, abrir/cerrar se ENCOLA:
|
|
91
|
+
// history.back() es asíncrono y un pushState en medio corrompe la pila (la capa
|
|
92
|
+
// nueva queda "adelante" y el siguiente back sale de la app).
|
|
93
|
+
let inflight = 0
|
|
94
|
+
/** @type {(() => void)[]} */
|
|
95
|
+
const queued = []
|
|
84
96
|
|
|
85
97
|
// ¿Hay una página real anterior EN ESTA PESTAÑA a la que volver (req. 3), o hay
|
|
86
98
|
// que cerrar la pestaña / ir a dotrino.com (req. 4)? Se mide el largo del
|
|
@@ -107,6 +119,7 @@ export function createBackNav (opts = {}) {
|
|
|
107
119
|
setTimeout(() => { try { location.href = home } catch (_) {} }, 150)
|
|
108
120
|
}
|
|
109
121
|
|
|
122
|
+
/** @param {Layer} layer */
|
|
110
123
|
function runClose (layer) {
|
|
111
124
|
try {
|
|
112
125
|
if (typeof layer.onClose === 'function') layer.onClose()
|
|
@@ -116,22 +129,58 @@ export function createBackNav (opts = {}) {
|
|
|
116
129
|
}
|
|
117
130
|
}
|
|
118
131
|
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
132
|
+
/** Profundidad que dice la entrada de history en la que estamos: 0 = centinela
|
|
133
|
+
* base, n = capa n, -1 = por debajo del centinela (fuera de lo nuestro).
|
|
134
|
+
*
|
|
135
|
+
* @param {{ ccNav?: unknown } | null | undefined} state
|
|
136
|
+
* @returns {number}
|
|
137
|
+
*/
|
|
138
|
+
function depthOf (state) {
|
|
139
|
+
const v = state && state.ccNav
|
|
140
|
+
if (v === 'base') return 0
|
|
141
|
+
if (typeof v === 'number' && v > 0) return v
|
|
142
|
+
return -1
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Cierra (sin tocar history) todas las capas por encima de `depth`.
|
|
147
|
+
*
|
|
148
|
+
* @param {number} depth
|
|
149
|
+
*/
|
|
150
|
+
function closeAbove (depth) {
|
|
151
|
+
while (layers.length > Math.max(0, depth)) runClose(/** @type {Layer} */ (layers.pop()))
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** @param {{ state: { ccNav?: unknown } | null } | null | undefined} ev */
|
|
155
|
+
function onPop (ev) {
|
|
156
|
+
const depth = depthOf(ev && ev.state)
|
|
157
|
+
if (inflight > 0) {
|
|
158
|
+
// Llegó el popstate de un back() nuestro. La pila ya se ajustó al cerrar; solo
|
|
159
|
+
// se vacía la cola de lo que quedó esperando a que el historial se asentara.
|
|
160
|
+
inflight--
|
|
161
|
+
if (inflight === 0) { while (queued.length) /** @type {() => void} */ (queued.shift())() }
|
|
122
162
|
return
|
|
123
163
|
}
|
|
124
|
-
if (
|
|
125
|
-
//
|
|
126
|
-
//
|
|
127
|
-
//
|
|
128
|
-
|
|
129
|
-
const layer = layers.pop()
|
|
130
|
-
layer._gone = true
|
|
131
|
-
runClose(layer)
|
|
164
|
+
if (depth >= 0) {
|
|
165
|
+
// Seguimos dentro de lo nuestro: la entrada dice cuántas capas quedan vivas
|
|
166
|
+
// (un gesto de volver = una capa; una traversal de varias entradas, las que
|
|
167
|
+
// toque). Con estado y no contando eventos no hay manera de desfasarse.
|
|
168
|
+
closeAbove(depth)
|
|
132
169
|
return
|
|
133
170
|
}
|
|
134
|
-
//
|
|
171
|
+
// Entrada sin estado nuestro. Si la URL no es la del centinela, no es la página
|
|
172
|
+
// de abajo: es una entrada que alguien empujó ENCIMA (un `location.hash = …` de
|
|
173
|
+
// la app, por ejemplo). Se adopta como una capa más, transparente, para que el
|
|
174
|
+
// historial siga casando con la pila y el siguiente volver no salga de la app.
|
|
175
|
+
if (trap && baseHref && location.href !== baseHref) {
|
|
176
|
+
/** @type {Layer} */
|
|
177
|
+
const layer = { onClose: null, depth: layers.length + 1 }
|
|
178
|
+
layers.push(layer)
|
|
179
|
+
try { history.replaceState({ ccNav: layer.depth }, '') } catch (_) {}
|
|
180
|
+
return
|
|
181
|
+
}
|
|
182
|
+
// Por debajo del centinela base: el usuario quiere SALIR. Decidimos req. 3 / 4.
|
|
183
|
+
closeAbove(0)
|
|
135
184
|
if (hadPrev) {
|
|
136
185
|
// Hay página anterior real en esta pestaña: sal hacia ella.
|
|
137
186
|
try { history.back() } catch (_) { goHomeOrClose() }
|
|
@@ -142,63 +191,88 @@ export function createBackNav (opts = {}) {
|
|
|
142
191
|
}
|
|
143
192
|
}
|
|
144
193
|
|
|
194
|
+
// URL del centinela: sirve para distinguir "la página de abajo" (misma URL que
|
|
195
|
+
// la nuestra) de una entrada ajena empujada encima (ver onPop).
|
|
196
|
+
let baseHref = ''
|
|
145
197
|
if (trap) {
|
|
146
198
|
// Centinela base: una entrada extra para atrapar el PRIMER "volver" cuando
|
|
147
199
|
// no hay capas, y así poder enrutar a dotrino.com en vez de quedar atrapado
|
|
148
200
|
// (el bug de iOS). Misma URL → es una entrada same-document, no recarga.
|
|
149
|
-
try { history.pushState({ ccNav: 'base' }, '') } catch (_) {}
|
|
201
|
+
try { history.pushState({ ccNav: 'base' }, ''); baseHref = location.href } catch (_) {}
|
|
150
202
|
window.addEventListener('popstate', onPop)
|
|
151
203
|
}
|
|
152
204
|
|
|
205
|
+
/**
|
|
206
|
+
* Ejecuta ya, o cuando se asiente el back() que está en vuelo.
|
|
207
|
+
*
|
|
208
|
+
* @param {() => void} fn
|
|
209
|
+
*/
|
|
210
|
+
function settled (fn) {
|
|
211
|
+
if (trap && inflight > 0) queued.push(fn)
|
|
212
|
+
else fn()
|
|
213
|
+
}
|
|
214
|
+
|
|
153
215
|
/**
|
|
154
216
|
* Empuja una capa (modal o vista/pestaña). Devuelve un handle con close().
|
|
155
|
-
* @param {
|
|
217
|
+
* @param {() => void} onClose Cómo cerrar esta capa (cerrar modal, volver a la
|
|
156
218
|
* pestaña anterior, etc.). Se llama tanto si el
|
|
157
219
|
* usuario pulsa volver como si llamas handle.close().
|
|
158
|
-
* @param {
|
|
159
|
-
* @param {string} [opts.url] Routing real (opcional): URL/path a reflejar
|
|
220
|
+
* @param {import('./index.js').BackLayerOptions} [opts] `url`: routing real (opcional): URL/path a reflejar
|
|
160
221
|
* mientras esta capa esté abierta (p. ej. '/que-es' para una
|
|
161
222
|
* vista). Se escribe en la entrada de history de la capa, así
|
|
162
223
|
* la vista es enlazable/indexable y compartible. Al cerrarla
|
|
163
224
|
* (volver físico o handle.close()) el navegador restaura la
|
|
164
225
|
* URL anterior automáticamente. Sin `url` se mantiene la URL
|
|
165
226
|
* actual (comportamiento clásico de modal).
|
|
227
|
+
* @returns {import('./index.js').BackLayerHandle}
|
|
166
228
|
*/
|
|
167
229
|
function open (onClose, opts = {}) {
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
230
|
+
/** @type {Layer} */
|
|
231
|
+
const layer = { onClose, depth: 0 }
|
|
232
|
+
settled(() => {
|
|
233
|
+
layer.depth = layers.length + 1
|
|
234
|
+
layers.push(layer)
|
|
235
|
+
if (trap) {
|
|
236
|
+
// url='' (o ausente) = misma URL (entrada same-document para atrapar el
|
|
237
|
+
// volver sin tocar la barra de direcciones). Con url → routing real.
|
|
238
|
+
const url = opts.url == null ? '' : String(opts.url)
|
|
239
|
+
try { history.pushState({ ccNav: layer.depth }, '', url) } catch (_) {}
|
|
240
|
+
}
|
|
241
|
+
})
|
|
176
242
|
return {
|
|
177
|
-
close () { dismiss(layer) },
|
|
243
|
+
close () { settled(() => dismiss(layer)) },
|
|
178
244
|
get active () { return layers.indexOf(layer) !== -1 }
|
|
179
245
|
}
|
|
180
246
|
}
|
|
181
247
|
|
|
182
248
|
// Cierre programático de una capa (botón X del modal, backdrop, etc.).
|
|
249
|
+
/** @param {Layer} layer */
|
|
183
250
|
function dismiss (layer) {
|
|
184
251
|
const idx = layers.indexOf(layer)
|
|
185
252
|
if (idx === -1) return // ya estaba cerrada (p.ej. por el botón físico)
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
253
|
+
// Se cierra esta y todo lo que tuviera encima (cerrar por debajo deja capas
|
|
254
|
+
// huérfanas cuyas entradas de history ya no casan con nada).
|
|
255
|
+
const above = layers.length - idx
|
|
256
|
+
while (layers.length > idx) runClose(/** @type {Layer} */ (layers.pop()))
|
|
257
|
+
if (!trap) return
|
|
258
|
+
// Solo se retiran entradas de history si de verdad ESTAMOS sobre la de la capa
|
|
259
|
+
// de arriba. Si el historial está en otra parte (un back() ajeno, un hash que
|
|
260
|
+
// cambió alguien), retirar a ciegas es lo que saca de la app.
|
|
261
|
+
let cur = -1
|
|
262
|
+
try { cur = depthOf(history.state) } catch (_) {}
|
|
263
|
+
if (cur !== idx + above) return
|
|
264
|
+
inflight++
|
|
265
|
+
try { history.go(-above) } catch (_) { inflight-- }
|
|
194
266
|
}
|
|
195
267
|
|
|
196
268
|
/** Volver programático (lo usa el chevron): idéntico al botón físico. */
|
|
197
269
|
function back () {
|
|
198
270
|
if (trap) {
|
|
199
|
-
try { history.back() } catch (_) { onPop() }
|
|
271
|
+
try { history.back() } catch (_) { onPop({ state: null }) }
|
|
200
272
|
} else {
|
|
201
|
-
|
|
273
|
+
// Sin trampa (tests): simula el gesto sobre la pila, sin history.
|
|
274
|
+
if (layers.length) runClose(/** @type {Layer} */ (layers.pop()))
|
|
275
|
+
else if (hadPrev) { try { history.back() } catch (_) { goHomeOrClose() } } else goHomeOrClose()
|
|
202
276
|
}
|
|
203
277
|
}
|
|
204
278
|
|
|
@@ -207,6 +281,7 @@ export function createBackNav (opts = {}) {
|
|
|
207
281
|
if (_active === controller) _active = null
|
|
208
282
|
}
|
|
209
283
|
|
|
284
|
+
/** @type {BackNavController} */
|
|
210
285
|
const controller = {
|
|
211
286
|
open,
|
|
212
287
|
back,
|
|
@@ -264,6 +339,10 @@ const BACK_STYLE = `
|
|
|
264
339
|
svg { width: var(--cc-back-icon, 22px); height: var(--cc-back-icon, 22px); display: block; }
|
|
265
340
|
`
|
|
266
341
|
|
|
342
|
+
/**
|
|
343
|
+
* Chevron de volver (`<dotrino-back>`). Atributos: `lang`, `label`, `home`, `floating`.
|
|
344
|
+
* Emite `cc-back` (cancelable) antes de volver.
|
|
345
|
+
*/
|
|
267
346
|
class DotrinoBack extends HTMLElement {
|
|
268
347
|
static get observedAttributes () { return ['lang', 'label'] }
|
|
269
348
|
|
|
@@ -281,6 +360,7 @@ class DotrinoBack extends HTMLElement {
|
|
|
281
360
|
if (this.shadowRoot) this._render()
|
|
282
361
|
}
|
|
283
362
|
|
|
363
|
+
/** @returns {'es'|'en'} */
|
|
284
364
|
_resolveLang () {
|
|
285
365
|
const a = (this.getAttribute('lang') || '').toLowerCase()
|
|
286
366
|
if (a === 'es' || a === 'en') return a
|
|
@@ -292,9 +372,11 @@ class DotrinoBack extends HTMLElement {
|
|
|
292
372
|
_render () {
|
|
293
373
|
const lang = this._resolveLang()
|
|
294
374
|
const label = this.getAttribute('label') || BACK_I18N[lang]
|
|
295
|
-
|
|
375
|
+
const root = /** @type {ShadowRoot} */ (this.shadowRoot) // attached in the constructor
|
|
376
|
+
root.innerHTML = `<style>${BACK_STYLE}</style>` +
|
|
296
377
|
`<button type="button" part="button" aria-label="${label}" title="${label}">${CHEVRON}</button>`
|
|
297
|
-
|
|
378
|
+
const button = /** @type {HTMLButtonElement} */ (root.querySelector('button'))
|
|
379
|
+
button.addEventListener('click', this._onClick)
|
|
298
380
|
}
|
|
299
381
|
|
|
300
382
|
_onClick () {
|
package/src/vue.d.ts
CHANGED
|
File without changes
|
package/src/vue.js
CHANGED
|
@@ -21,12 +21,11 @@ import { watch, onScopeDispose } from 'vue'
|
|
|
21
21
|
import { getBackNav } from './index.js'
|
|
22
22
|
|
|
23
23
|
/**
|
|
24
|
-
* @param {import('vue').Ref} openRef ref que controla el modal (booleano u
|
|
24
|
+
* @param {import('vue').Ref<unknown>} openRef ref que controla el modal (booleano u
|
|
25
25
|
* objeto|null; se observa su veracidad).
|
|
26
|
-
* @param {
|
|
27
|
-
*
|
|
28
|
-
*
|
|
29
|
-
* @param {string|Function} [opts.url] Routing real (opcional): URL/path a
|
|
26
|
+
* @param {import('./vue.js').UseBackLayerOptions} [opts]
|
|
27
|
+
* `onClose`: cómo cerrar (default: openRef.value = false). `nav`: controlador a usar
|
|
28
|
+
* (default: el activo). `url`: routing real (opcional): URL/path a
|
|
30
29
|
* reflejar mientras la capa esté abierta (p. ej. '/que-es'
|
|
31
30
|
* para una vista/pestaña enlazable). String o función que lo
|
|
32
31
|
* devuelva (se evalúa al abrir). Al cerrar, el navegador
|
|
@@ -34,11 +33,14 @@ import { getBackNav } from './index.js'
|
|
|
34
33
|
*
|
|
35
34
|
* No crea un controlador si no hay ninguno instalado (p. ej. en un iframe
|
|
36
35
|
* embebido donde no se llamó createBackNav): en ese caso es un no-op seguro.
|
|
36
|
+
*
|
|
37
|
+
* @returns {{ nav: import('./index.js').BackNavController | null }}
|
|
37
38
|
*/
|
|
38
39
|
export function useBackLayer (openRef, opts = {}) {
|
|
39
40
|
const nav = opts.nav || getBackNav()
|
|
40
41
|
if (!nav) return { nav: null }
|
|
41
42
|
const onClose = opts.onClose || (() => { openRef.value = false })
|
|
43
|
+
/** @type {import('./index.js').BackLayerHandle | null} */
|
|
42
44
|
let handle = null
|
|
43
45
|
|
|
44
46
|
const stop = watch(openRef, (open) => {
|