@deijose/nix-js 1.0.6 → 1.0.7

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.
@@ -1,124 +1,30 @@
1
1
  import type { NixTemplate } from "./template";
2
- /**
3
- * Tipos válidos para pasar como children a un componente.
4
- * Acepta un template, un componente, arrays de ellos, o nada.
5
- */
2
+ /** Valid child content for components. */
6
3
  export type NixChildren = NixTemplate | NixComponent | Array<NixTemplate | NixComponent> | null | undefined;
7
- /**
8
- * Clase base para componentes con lifecycle.
9
- *
10
- * Implementa `render()` y haz override de los hooks que necesites.
11
- *
12
- * @example
13
- * class Timer extends NixComponent {
14
- * ticks = signal(0);
15
- *
16
- * onMount() {
17
- * const id = setInterval(() => this.ticks.update(n => n + 1), 1000);
18
- * return () => clearInterval(id); // cleanup automático al desmontar
19
- * }
20
- *
21
- * render() {
22
- * return html`<span>${() => this.ticks.value}s</span>`;
23
- * }
24
- * }
25
- *
26
- * mount(new Timer(), "#app");
27
- */
4
+ /** Base class for components with lifecycle hooks. */
28
5
  export declare abstract class NixComponent {
29
- /** @internal – marca que identifica instancias NixComponent en el engine. */
6
+ /** @internal */
30
7
  readonly __isNixComponent: true;
31
- /**
32
- * Slot por defecto — contenido hijo que el componente padre inyecta.
33
- *
34
- * Úsalo en `render()` como cualquier valor interpolado:
35
- * ```typescript
36
- * render() {
37
- * return html`<div class="card">${this.children}</div>`;
38
- * }
39
- * ```
40
- * Se puede asignar directamente o con el método fluido `setChildren()`.
41
- */
8
+ /** Default slot — child content injected by the parent. */
42
9
  children?: NixChildren;
43
10
  /** @internal */
44
11
  private _slots;
45
- /**
46
- * Asigna el slot por defecto. Versión fluida de `this.children = content`.
47
- * @returns `this` para encadenar con `setSlot()`.
48
- *
49
- * @example
50
- * html`${new Card().setChildren(html`<p>Body</p>`)}`
51
- */
12
+ /** Sets the default slot content. Returns `this` for chaining. */
52
13
  setChildren(content: NixChildren): this;
53
- /**
54
- * Asigna un slot con nombre. El componente lo lee con `this.slot(name)`.
55
- * @returns `this` para encadenar.
56
- *
57
- * @example
58
- * new Card()
59
- * .setSlot("header", html`<h1>Título</h1>`)
60
- * .setSlot("footer", html`<small>Footer</small>`)
61
- * .setChildren(html`<p>Cuerpo</p>`)
62
- */
14
+ /** Sets a named slot. Returns `this` for chaining. */
63
15
  setSlot(name: string, content: NixChildren): this;
64
- /**
65
- * Obtiene el contenido de un slot con nombre.
66
- * Úsalo dentro de `render()`:
67
- * ```typescript
68
- * render() {
69
- * return html`
70
- * <div>
71
- * <header>${this.slot("header")}</header>
72
- * <main>${this.children}</main>
73
- * <footer>${this.slot("footer")}</footer>
74
- * </div>
75
- * `;
76
- * }
77
- * ```
78
- */
16
+ /** Returns content for a named slot. */
79
17
  slot(name: string): NixChildren;
80
- /**
81
- * Debe implementarse: retorna el template del componente.
82
- * Se llama UNA sola vez al montar — las actualizaciones ocurren por signals.
83
- */
18
+ /** Returns the component template. Called once on mount; updates happen via signals. */
84
19
  abstract render(): NixTemplate;
85
- /**
86
- * Llamado ANTES de `render()` — sin DOM todavía.
87
- * Útil para inicializar estado complejo derivado de props u otras
88
- * operaciones síncronas que render() necesita.
89
- *
90
- * Los errores aquí son capturados por `onError` si está implementado.
91
- *
92
- * @example
93
- * onInit() {
94
- * this.derived = computed(() => this.base.value * 2);
95
- * }
96
- */
20
+ /** Called before `render()` — no DOM yet. Errors are caught by `onError` if present. */
97
21
  onInit?(): void;
98
- /**
99
- * Llamado DESPUÉS de que el componente se inserta en el DOM.
100
- * Si retorna una función, se usa como cleanup automático al desmontar.
101
- *
102
- * @example
103
- * onMount() {
104
- * const id = setInterval(() => this.count.update(n => n + 1), 1000);
105
- * return () => clearInterval(id);
106
- * }
107
- */
22
+ /** Called after DOM insertion. May return a cleanup function. */
108
23
  onMount?(): (() => void) | void;
109
- /**
110
- * Llamado ANTES de remover el componente del DOM.
111
- * Se ejecuta siempre al desmontar, incluso si no se definió onMount.
112
- */
24
+ /** Called before DOM removal. */
113
25
  onUnmount?(): void;
114
- /**
115
- * Captura errores lanzados dentro de `onMount`.
116
- * Si se implementa, el error queda absorbido y el componente permanece montado.
117
- * Si no se implementa, el error se re-lanza.
118
- */
26
+ /** Catches errors thrown in `onInit` and `onMount`. */
119
27
  onError?(err: unknown): void;
120
28
  }
121
- /**
122
- * @internal – Verifica si un valor es una instancia de NixComponent.
123
- */
29
+ /** @internal */
124
30
  export declare function isNixComponent(v: unknown): v is NixComponent;
@@ -10,26 +10,13 @@ export declare class Signal<T> {
10
10
  private _value;
11
11
  private _subs;
12
12
  constructor(initialValue: T);
13
- /**
14
- * Leer el valor.
15
- * Si hay un effect activo, se suscribe automáticamente.
16
- */
13
+ /** Read the current value. Subscribes the active effect if one exists. */
17
14
  get value(): T;
18
- /**
19
- * Escribir un nuevo valor.
20
- * Si es diferente al actual, notifica a todos los effects suscritos.
21
- */
15
+ /** Write a new value. Notifies subscribers when the value changes. */
22
16
  set value(newValue: T);
23
- /**
24
- * Modificar el valor con una función.
25
- * count.update(n => n + 1)
26
- */
17
+ /** Mutate the value via a updater function. */
27
18
  update(fn: (current: T) => T): void;
28
- /**
29
- * Leer SIN suscribirse.
30
- * Útil cuando necesitas el valor pero no quieres
31
- * que el effect se re-ejecute si cambia.
32
- */
19
+ /** Read without subscribing the active effect. */
33
20
  peek(): T;
34
21
  /** @internal */
35
22
  _removeSub(sub: () => void): void;
@@ -38,87 +25,28 @@ export declare class Signal<T> {
38
25
  }
39
26
  export declare function signal<T>(initialValue: T): Signal<T>;
40
27
  /**
41
- * Ejecuta una función y la RE-EJECUTA cada vez que
42
- * algún signal leído dentro de ella cambie.
43
- *
44
- * Retorna una función dispose() para destruir el effect.
45
- *
46
- * const dispose = effect(() => {
47
- * console.log(count.value);
48
- * return () => console.log("cleanup");
49
- * });
50
- *
51
- * dispose();
28
+ * Runs `fn` and re-runs it whenever any signal read inside changes.
29
+ * Returns a dispose function to tear down the effect.
30
+ * If `fn` returns a function, it is called as cleanup before each re-run
31
+ * and on disposal.
52
32
  */
53
33
  export declare function effect(fn: () => void | (() => void)): () => void;
54
- /**
55
- * Valor derivado que se recalcula automáticamente.
56
- *
57
- * const doubled = computed(() => count.value * 2);
58
- */
34
+ /** Derived signal that recalculates when its dependencies change. */
59
35
  export declare function computed<T>(fn: () => T): Signal<T>;
60
- /**
61
- * Agrupa múltiples cambios para que los effects
62
- * se ejecuten UNA sola vez al final.
63
- *
64
- * batch(() => {
65
- * x.value = 1;
66
- * y.value = 2;
67
- * });
68
- */
36
+ /** Groups multiple signal writes so effects flush once at the end. */
69
37
  export declare function batch(fn: () => void): void;
70
- /**
71
- * Ejecuta `fn` sin suscribirse a ninguna signal que lea dentro de ella.
72
- * Útil para leer valores reactivos sin que esas lecturas re-disparen el
73
- * efecto actual (p.ej. en callbacks de `watch`).
74
- *
75
- * const total = untrack(() => price.value * qty.value); // no se suscribe
76
- */
38
+ /** Executes `fn` without subscribing to any signals read inside it. */
77
39
  export declare function untrack<T>(fn: () => T): T;
78
40
  export interface WatchOptions {
79
- /**
80
- * Si es `true`, el callback se ejecuta inmediatamente con el valor
81
- * actual antes de que haya ningún cambio. Por defecto: `false`.
82
- */
41
+ /** Fire the callback immediately with the current value. Default: `false`. */
83
42
  immediate?: boolean;
84
- /**
85
- * Si es `true`, el watcher se elimina automáticamente después de la
86
- * primera vez que el callback se dispara. Por defecto: `false`.
87
- */
43
+ /** Automatically dispose after the first callback invocation. Default: `false`. */
88
44
  once?: boolean;
89
45
  }
90
46
  /**
91
- * Observa una fuente reactiva y ejecuta `callback(newValue, oldValue)` cada
92
- * vez que cambia.
93
- *
94
- * La fuente puede ser:
95
- * - Un getter: `() => count.value + other.value`
96
- * - Una Signal directamente: `count`
97
- *
98
- * Retorna una función `dispose()` para detener la observación.
99
- *
100
- * @example
101
- * const stop = watch(
102
- * () => user.value.name,
103
- * (newName, oldName) => console.log(newName, oldName),
104
- * { immediate: true }
105
- * );
106
- * stop(); // deja de observar
47
+ * Watches a reactive source and calls `callback(newValue, oldValue)` on each change.
48
+ * Accepts a Signal or a getter function. Returns a dispose function.
107
49
  */
108
50
  export declare function watch<T>(source: Signal<T> | (() => T), callback: (newValue: T, oldValue: T | undefined) => void, options?: WatchOptions): () => void;
109
- /**
110
- * Espera a que todos los efectos síncronos pendientes hayan corrido y el
111
- * DOM esté actualizado, devolviendo una promesa que resuelve en el próximo
112
- * microtask.
113
- *
114
- * Úsala cuando necesitas leer el DOM *después* de un cambio reactivo:
115
- *
116
- * count.value++;
117
- * await nextTick();
118
- * console.log(el.textContent); // ya refleja el nuevo valor
119
- *
120
- * También acepta un callback opcional:
121
- *
122
- * nextTick(() => el.focus());
123
- */
51
+ /** Returns a promise that resolves on the next microtask. Accepts an optional callback. */
124
52
  export declare function nextTick(fn?: () => void): Promise<void>;
@@ -8,57 +8,16 @@ import type { NixTemplate } from "./template";
8
8
  * - `void` / `undefined` — allow the navigation.
9
9
  */
10
10
  export type NavigationGuardResult = void | undefined | false | string;
11
- /**
12
- * A navigation guard function.
13
- *
14
- * @param to Destination pathname (e.g. `"/admin"`).
15
- * @param from Current pathname before the navigation.
16
- * @returns `false` to cancel, a path string to redirect, or nothing to allow.
17
- * May return a Promise for async guard logic.
18
- *
19
- * @example
20
- * router.beforeEach((to, from) => {
21
- * if (!auth.isLoggedIn && to !== "/login") return "/login";
22
- * });
23
- */
11
+ /** Guard function invoked before navigation commits. */
24
12
  export type NavigationGuard = (to: string, from: string) => NavigationGuardResult | Promise<NavigationGuardResult>;
25
13
  export interface RouteRecord {
26
- /**
27
- * Segmento de ruta. Soporta:
28
- * - Literal: "/about", "/users"
29
- * - Parámetro: "/users/:id", "/posts/:slug/comments/:cid"
30
- * - Wildcard: "*" (fallback global o de prefijo con children)
31
- *
32
- * Los paths de children se concatenan con el del padre.
33
- *
34
- * @example
35
- * { path: "/users/:id", component: UserDetail }
36
- * // Navegar a "/users/42" → params.value = { id: "42" }
37
- *
38
- * @example
39
- * { path: "/dash", component: DashLayout, children: [
40
- * { path: "/users", component: UsersPage },
41
- * ]}
42
- * // Genera las rutas planas: /dash, /dash/users
43
- */
14
+ /** Route path segment. Supports literals, params (`:id`), and wildcards (`*`). */
44
15
  path: string;
45
- /** Factory que devuelve la vista a renderizar en este nivel */
16
+ /** Factory returning the view for this route level. */
46
17
  component: () => NixTemplate | NixComponent;
47
- /**
48
- * Rutas hijas. Sus paths se unen con el del padre.
49
- * El componente padre debe incluir `new RouterView(1)` para renderizarlas.
50
- */
18
+ /** Child routes. Paths are joined with the parent. */
51
19
  children?: RouteRecord[];
52
- /**
53
- * Guard de nivel de ruta. Se ejecuta solo al entrar en esta ruta concreta.
54
- * Misma semántica de retorno que `beforeEach`.
55
- *
56
- * @example
57
- * { path: "/admin", component: () => new AdminPage(),
58
- * beforeEnter: (to, from) => {
59
- * if (!isAdmin) return "/";
60
- * }}
61
- */
20
+ /** Route-level guard. Runs only when entering this specific route. */
62
21
  beforeEnter?: NavigationGuard;
63
22
  }
64
23
  /**
@@ -77,174 +36,52 @@ export interface ResolvedRoute {
77
36
  route: RouteRecord | undefined;
78
37
  }
79
38
  export interface Router {
80
- /** Señal con la ruta activa actual (pathname, p.ej. "/users/42") */
39
+ /** Signal with the current active pathname. */
81
40
  readonly current: Signal<string>;
82
- /**
83
- * Señal con los parámetros dinámicos de la ruta activa (:id, :slug…).
84
- * Se actualiza síncronamente con cada `navigate()`.
85
- *
86
- * @example
87
- * // Ruta: "/users/:id" → navigate("/users/42")
88
- * router.params.value // { id: "42" }
89
- */
41
+ /** Signal with the extracted dynamic route params. */
90
42
  readonly params: Signal<Record<string, string>>;
91
- /**
92
- * Señal con los query params de la URL (?clave=valor…).
93
- * Se actualiza síncronamente con cada `navigate()`.
94
- *
95
- * @example
96
- * router.navigate("/users?page=2&sort=name")
97
- * router.query.value // { page: "2", sort: "name" }
98
- *
99
- * @example
100
- * router.navigate("/users", { page: 2, sort: "name" })
101
- * router.query.value // { page: "2", sort: "name" }
102
- */
43
+ /** Signal with the URL query params. */
103
44
  readonly query: Signal<Record<string, string>>;
104
- /**
105
- * Navegar a una ruta nueva (pushState + actualiza señales).
106
- * Si hay guards registrados, la navegación espera a que todos pasen.
107
- *
108
- * @param path Ruta destino. Puede incluir query string: "/users?page=2"
109
- * @param query Query params como objeto. Se mezclan con los del path.
110
- * Un valor `null`/`undefined` elimina el parámetro.
111
- */
45
+ /** Navigate to a new path via `pushState`. Guards run before committing. */
112
46
  navigate(path: string, query?: Record<string, string | number | boolean | null | undefined>): void;
113
- /**
114
- * Navigate without adding an entry to the browser history.
115
- * Uses `history.replaceState` instead of `pushState`.
116
- * Guards still run normally.
117
- *
118
- * @param path Destination path. May include query string.
119
- * @param query Query params as an object.
120
- *
121
- * @example
122
- * // After login — pressing "back" won't return to /login
123
- * router.replace("/home");
124
- */
47
+ /** Navigate via `replaceState` (no new history entry). Guards still run. */
125
48
  replace(path: string, query?: Record<string, string | number | boolean | null | undefined>): void;
126
- /**
127
- * Go back one entry in the browser history.
128
- * Equivalent to `history.back()`.
129
- *
130
- * @example
131
- * router.back();
132
- */
49
+ /** Go back one entry in the browser history. */
133
50
  back(): void;
134
- /**
135
- * Go forward one entry in the browser history.
136
- * Equivalent to `history.forward()`.
137
- *
138
- * @example
139
- * router.forward();
140
- */
51
+ /** Go forward one entry in the browser history. */
141
52
  forward(): void;
142
- /**
143
- * Move `delta` entries in the browser history.
144
- * Negative values go back, positive go forward.
145
- *
146
- * @example
147
- * router.go(-2); // two pages back
148
- * router.go(1); // same as forward()
149
- */
53
+ /** Move `delta` entries in the browser history. */
150
54
  go(delta: number): void;
151
- /**
152
- * Check if a path is currently active.
153
- * By default performs an exact match.
154
- *
155
- * @param path The path to test.
156
- * @param exact If `false`, matches when `current` starts with `path`.
157
- * Default: `true`.
158
- *
159
- * @example
160
- * router.isActive("/admin"); // exact match
161
- * router.isActive("/admin", false); // prefix: /admin/users → true
162
- */
55
+ /** Check if `path` is currently active. `exact=false` enables prefix matching. */
163
56
  isActive(path: string, exact?: boolean): boolean;
164
- /**
165
- * Inspect what route would match a given path without actually navigating.
166
- *
167
- * @example
168
- * const info = router.resolve("/user/42");
169
- * // { matched: true, params: { id: "42" }, route: { path: "/user/:id", ... } }
170
- */
57
+ /** Inspect what route would match `path` without navigating. */
171
58
  resolve(path: string): ResolvedRoute;
172
- /** Árbol de rutas original (tal como se pasó a createRouter) */
59
+ /** Original route tree passed to `createRouter`. */
173
60
  readonly routes: RouteRecord[];
174
- /**
175
- * Registra un guard de navegación global.
176
- * Se ejecuta (en orden de registro) antes de cada navegación.
177
- *
178
- * Retorna una función para eliminar el guard.
179
- *
180
- * @example
181
- * const stop = router.beforeEach((to, from) => {
182
- * if (!auth && to !== "/login") return "/login";
183
- * });
184
- * stop(); // elimina el guard
185
- */
61
+ /** Register a global navigation guard. Returns a removal function. */
186
62
  beforeEach(guard: NavigationGuard): () => void;
187
- /**
188
- * Register a hook that runs after every successful navigation.
189
- * Useful for analytics, scroll reset, etc.
190
- *
191
- * Returns a function to remove the hook.
192
- *
193
- * @example
194
- * const stop = router.afterEach((to, from) => {
195
- * window.scrollTo(0, 0);
196
- * });
197
- * stop();
198
- */
63
+ /** Register a hook that runs after every successful navigation. Returns a removal function. */
199
64
  afterEach(hook: AfterEachHook): () => void;
200
65
  }
201
66
  /**
202
- * Crea el router History API y lo establece como singleton activo del módulo.
203
- * Usa `history.pushState` URLs limpias sin `#`.
204
- * `RouterView` y `Link` lo consumen automáticamente — no necesitan que se los pases.
205
- *
206
- * @note En producción el servidor debe responder con `index.html` para cualquier
207
- * ruta no-archivo. Vite dev y `vite preview` lo hacen automáticamente.
67
+ * Creates the History API router and sets it as the active singleton.
68
+ * In production the server must serve `index.html` for all non-file routes.
208
69
  */
209
70
  export declare function createRouter(routes: RouteRecord[]): Router;
210
- /**
211
- * Devuelve el router activo (singleton).
212
- * Útil dentro de componentes para acceder a `params` y `current` sin prop-drilling.
213
- *
214
- * @example
215
- * class UserDetail extends NixComponent {
216
- * render() {
217
- * return html`<div>User: ${() => useRouter().params.value.id}</div>`;
218
- * }
219
- * }
220
- */
71
+ /** Returns the active router singleton. */
221
72
  export declare function useRouter(): Router;
222
73
  /**
223
74
  * @internal — Resets the router singleton. Used by tests to avoid
224
75
  * "A router already exists" warnings between test cases.
225
76
  */
226
77
  export declare function _resetRouter(): void;
227
- /**
228
- * Renderiza el componente de la ruta activa en el nivel `depth`.
229
- *
230
- * - `new RouterView()` → nivel raíz (depth 0).
231
- * - `new RouterView(1)` → primer nivel de rutas anidadas. Úsalo dentro del
232
- * componente padre para que renderice el hijo correspondiente.
233
- *
234
- * Consume el router singleton — no requiere que se le pase el router.
235
- */
78
+ /** Renders the matched route component at the given nesting `depth`. */
236
79
  export declare class RouterView extends NixComponent {
237
80
  private _depth;
238
81
  constructor(depth?: number);
239
82
  render(): NixTemplate;
240
83
  }
241
- /**
242
- * Enlace de navegación reactivo que se estiliza como activo/inactivo según la
243
- * ruta actual. Consume el router singleton — no requiere que se le pase.
244
- *
245
- * @example
246
- * new Link("/about", "About")
247
- */
84
+ /** Reactive navigation link styled as active/inactive based on the current route. */
248
85
  export declare class Link extends NixComponent {
249
86
  private _to;
250
87
  private _label;
@@ -1,40 +1,15 @@
1
1
  import { Signal } from "./reactivity";
2
- /** Transforma cada propiedad del estado inicial en su Signal correspondiente. */
2
+ /** Maps each state property to its corresponding Signal. */
3
3
  export type StoreSignals<T extends Record<string, unknown>> = {
4
4
  readonly [K in keyof T]: Signal<T[K]>;
5
5
  };
6
- /** Tipo del store tal como lo ve el usuario. */
6
+ /** The store as seen by the consumer: signals + actions + `$reset`. */
7
7
  export type Store<T extends Record<string, unknown>, A extends Record<string, unknown> = Record<never, never>> = StoreSignals<T> & A & {
8
- /**
9
- * Restaura todos los signals a sus valores iniciales.
10
- * Equivalente a hacer `signal.value = initialValue` en cada propiedad.
11
- */
8
+ /** Resets all signals to their initial values. */
12
9
  $reset(): void;
13
10
  };
14
11
  /**
15
- * Crea un store reactivo global.
16
- *
17
- * @param initialState Objeto plano con los valores iniciales.
18
- * @param actionsFactory Función que recibe los signals y retorna acciones.
19
- *
20
- * @example
21
- * // Sin acciones
22
- * const theme = createStore({ dark: false, fontSize: 16 });
23
- * theme.dark.value = true;
24
- *
25
- * @example
26
- * // Con acciones
27
- * const cart = createStore(
28
- * { items: [] as string[], total: 0 },
29
- * (s) => ({
30
- * add: (item: string) => s.items.update(arr => [...arr, item]),
31
- * clear: () => cart.$reset(),
32
- * })
33
- * );
34
- *
35
- * cart.add("Manzana");
36
- * cart.items.value; // ["Manzana"]
37
- * cart.clear();
38
- * cart.items.value; // []
12
+ * Creates a reactive global store. Each property becomes a Signal.
13
+ * Optional `actionsFactory` receives the signals and returns action methods.
39
14
  */
40
15
  export declare function createStore<T extends Record<string, unknown>, A extends Record<string, unknown> = Record<never, never>>(initialState: T, actionsFactory?: (signals: StoreSignals<T>) => A): Store<T, A>;