@dotrino/nav 0.3.0 → 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 CHANGED
File without changes
package/README.md CHANGED
File without changes
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dotrino/nav",
3
- "version": "0.3.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",
@@ -52,7 +52,9 @@
52
52
  "url": "git+https://github.com/imdotrino/dotrino-nav.git"
53
53
  },
54
54
  "devDependencies": {
55
+ "@types/node": "22.20.1",
56
+ "playwright": "1.60.0",
55
57
  "typescript": "5.9.3",
56
- "@types/node": "^22.0.0"
58
+ "vue": "3.5.25"
57
59
  }
58
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
- /** Devuelve el controlador de back activo (o null si no se creó ninguno). */
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,24 +73,25 @@ export function getBackNav () {
65
73
  /**
66
74
  * Crea (e instala) el controlador de navegación "volver".
67
75
  *
68
- * @param {object} [opts]
69
- * @param {string} [opts.home='https://dotrino.com'] A dónde ir cuando no hay
70
- * ni capas internas ni página anterior del navegador.
71
- * @param {boolean} [opts.trap=true] Si intercepta el botón físico/gesto/atrás
72
- * del navegador vía history. Ponlo en false solo para tests.
73
- * @returns {{ open:Function, back:Function, size:Function, destroy:Function, home:string }}
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 {{ onClose: Function, depth: number }[]} pila LIFO de capas. */
87
+ /** @type {Layer[]} pila LIFO de capas. */
80
88
  const layers = []
81
89
  // Traversals que disparamos nosotros (history.back() al cerrar una capa) y cuyo
82
90
  // popstate aún no llegó. Mientras haya uno en vuelo, abrir/cerrar se ENCOLA:
83
91
  // history.back() es asíncrono y un pushState en medio corrompe la pila (la capa
84
92
  // nueva queda "adelante" y el siguiente back sale de la app).
85
93
  let inflight = 0
94
+ /** @type {(() => void)[]} */
86
95
  const queued = []
87
96
 
88
97
  // ¿Hay una página real anterior EN ESTA PESTAÑA a la que volver (req. 3), o hay
@@ -110,6 +119,7 @@ export function createBackNav (opts = {}) {
110
119
  setTimeout(() => { try { location.href = home } catch (_) {} }, 150)
111
120
  }
112
121
 
122
+ /** @param {Layer} layer */
113
123
  function runClose (layer) {
114
124
  try {
115
125
  if (typeof layer.onClose === 'function') layer.onClose()
@@ -120,7 +130,11 @@ export function createBackNav (opts = {}) {
120
130
  }
121
131
 
122
132
  /** Profundidad que dice la entrada de history en la que estamos: 0 = centinela
123
- * base, n = capa n, -1 = por debajo del centinela (fuera de lo nuestro). */
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
+ */
124
138
  function depthOf (state) {
125
139
  const v = state && state.ccNav
126
140
  if (v === 'base') return 0
@@ -128,18 +142,23 @@ export function createBackNav (opts = {}) {
128
142
  return -1
129
143
  }
130
144
 
131
- /** Cierra (sin tocar history) todas las capas por encima de `depth`. */
145
+ /**
146
+ * Cierra (sin tocar history) todas las capas por encima de `depth`.
147
+ *
148
+ * @param {number} depth
149
+ */
132
150
  function closeAbove (depth) {
133
- while (layers.length > Math.max(0, depth)) runClose(layers.pop())
151
+ while (layers.length > Math.max(0, depth)) runClose(/** @type {Layer} */ (layers.pop()))
134
152
  }
135
153
 
154
+ /** @param {{ state: { ccNav?: unknown } | null } | null | undefined} ev */
136
155
  function onPop (ev) {
137
156
  const depth = depthOf(ev && ev.state)
138
157
  if (inflight > 0) {
139
158
  // Llegó el popstate de un back() nuestro. La pila ya se ajustó al cerrar; solo
140
159
  // se vacía la cola de lo que quedó esperando a que el historial se asentara.
141
160
  inflight--
142
- if (inflight === 0) { while (queued.length) queued.shift()() }
161
+ if (inflight === 0) { while (queued.length) /** @type {() => void} */ (queued.shift())() }
143
162
  return
144
163
  }
145
164
  if (depth >= 0) {
@@ -154,6 +173,7 @@ export function createBackNav (opts = {}) {
154
173
  // la app, por ejemplo). Se adopta como una capa más, transparente, para que el
155
174
  // historial siga casando con la pila y el siguiente volver no salga de la app.
156
175
  if (trap && baseHref && location.href !== baseHref) {
176
+ /** @type {Layer} */
157
177
  const layer = { onClose: null, depth: layers.length + 1 }
158
178
  layers.push(layer)
159
179
  try { history.replaceState({ ccNav: layer.depth }, '') } catch (_) {}
@@ -182,7 +202,11 @@ export function createBackNav (opts = {}) {
182
202
  window.addEventListener('popstate', onPop)
183
203
  }
184
204
 
185
- /** Ejecuta ya, o cuando se asiente el back() que está en vuelo. */
205
+ /**
206
+ * Ejecuta ya, o cuando se asiente el back() que está en vuelo.
207
+ *
208
+ * @param {() => void} fn
209
+ */
186
210
  function settled (fn) {
187
211
  if (trap && inflight > 0) queued.push(fn)
188
212
  else fn()
@@ -190,19 +214,20 @@ export function createBackNav (opts = {}) {
190
214
 
191
215
  /**
192
216
  * Empuja una capa (modal o vista/pestaña). Devuelve un handle con close().
193
- * @param {Function} onClose Cómo cerrar esta capa (cerrar modal, volver a la
217
+ * @param {() => void} onClose Cómo cerrar esta capa (cerrar modal, volver a la
194
218
  * pestaña anterior, etc.). Se llama tanto si el
195
219
  * usuario pulsa volver como si llamas handle.close().
196
- * @param {object} [opts]
197
- * @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
198
221
  * mientras esta capa esté abierta (p. ej. '/que-es' para una
199
222
  * vista). Se escribe en la entrada de history de la capa, así
200
223
  * la vista es enlazable/indexable y compartible. Al cerrarla
201
224
  * (volver físico o handle.close()) el navegador restaura la
202
225
  * URL anterior automáticamente. Sin `url` se mantiene la URL
203
226
  * actual (comportamiento clásico de modal).
227
+ * @returns {import('./index.js').BackLayerHandle}
204
228
  */
205
229
  function open (onClose, opts = {}) {
230
+ /** @type {Layer} */
206
231
  const layer = { onClose, depth: 0 }
207
232
  settled(() => {
208
233
  layer.depth = layers.length + 1
@@ -221,13 +246,14 @@ export function createBackNav (opts = {}) {
221
246
  }
222
247
 
223
248
  // Cierre programático de una capa (botón X del modal, backdrop, etc.).
249
+ /** @param {Layer} layer */
224
250
  function dismiss (layer) {
225
251
  const idx = layers.indexOf(layer)
226
252
  if (idx === -1) return // ya estaba cerrada (p.ej. por el botón físico)
227
253
  // Se cierra esta y todo lo que tuviera encima (cerrar por debajo deja capas
228
254
  // huérfanas cuyas entradas de history ya no casan con nada).
229
255
  const above = layers.length - idx
230
- while (layers.length > idx) runClose(layers.pop())
256
+ while (layers.length > idx) runClose(/** @type {Layer} */ (layers.pop()))
231
257
  if (!trap) return
232
258
  // Solo se retiran entradas de history si de verdad ESTAMOS sobre la de la capa
233
259
  // de arriba. Si el historial está en otra parte (un back() ajeno, un hash que
@@ -245,7 +271,7 @@ export function createBackNav (opts = {}) {
245
271
  try { history.back() } catch (_) { onPop({ state: null }) }
246
272
  } else {
247
273
  // Sin trampa (tests): simula el gesto sobre la pila, sin history.
248
- if (layers.length) runClose(layers.pop())
274
+ if (layers.length) runClose(/** @type {Layer} */ (layers.pop()))
249
275
  else if (hadPrev) { try { history.back() } catch (_) { goHomeOrClose() } } else goHomeOrClose()
250
276
  }
251
277
  }
@@ -255,6 +281,7 @@ export function createBackNav (opts = {}) {
255
281
  if (_active === controller) _active = null
256
282
  }
257
283
 
284
+ /** @type {BackNavController} */
258
285
  const controller = {
259
286
  open,
260
287
  back,
@@ -312,6 +339,10 @@ const BACK_STYLE = `
312
339
  svg { width: var(--cc-back-icon, 22px); height: var(--cc-back-icon, 22px); display: block; }
313
340
  `
314
341
 
342
+ /**
343
+ * Chevron de volver (`<dotrino-back>`). Atributos: `lang`, `label`, `home`, `floating`.
344
+ * Emite `cc-back` (cancelable) antes de volver.
345
+ */
315
346
  class DotrinoBack extends HTMLElement {
316
347
  static get observedAttributes () { return ['lang', 'label'] }
317
348
 
@@ -329,6 +360,7 @@ class DotrinoBack extends HTMLElement {
329
360
  if (this.shadowRoot) this._render()
330
361
  }
331
362
 
363
+ /** @returns {'es'|'en'} */
332
364
  _resolveLang () {
333
365
  const a = (this.getAttribute('lang') || '').toLowerCase()
334
366
  if (a === 'es' || a === 'en') return a
@@ -340,9 +372,11 @@ class DotrinoBack extends HTMLElement {
340
372
  _render () {
341
373
  const lang = this._resolveLang()
342
374
  const label = this.getAttribute('label') || BACK_I18N[lang]
343
- this.shadowRoot.innerHTML = `<style>${BACK_STYLE}</style>` +
375
+ const root = /** @type {ShadowRoot} */ (this.shadowRoot) // attached in the constructor
376
+ root.innerHTML = `<style>${BACK_STYLE}</style>` +
344
377
  `<button type="button" part="button" aria-label="${label}" title="${label}">${CHEVRON}</button>`
345
- this.shadowRoot.querySelector('button').addEventListener('click', this._onClick)
378
+ const button = /** @type {HTMLButtonElement} */ (root.querySelector('button'))
379
+ button.addEventListener('click', this._onClick)
346
380
  }
347
381
 
348
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 {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
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) => {