sigpro 1.2.40 → 2.0.4

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/sigpro.d.ts CHANGED
@@ -1,7 +1,13 @@
1
1
  /**
2
- * SigPro
3
- * A minimalistic reactive library with fine-grained reactivity,
4
- * direct DOM updates, and built-in component helpers.
2
+ * SigPro — Type Definitions
3
+ *
4
+ * A minimal reactive library built on an alien-signals-class push-pull core
5
+ * with a thin, direct-to-DOM rendering layer.
6
+ *
7
+ * - Explicit API: `signal()`, `computed()`, `effect()`
8
+ * - Lazy computeds with checkDirty verification
9
+ * - Atomic updates: no virtual DOM, no diffing
10
+ * - Built-in: hash router, i18n, localStorage signals, DI, fetch helper
5
11
  */
6
12
 
7
13
  // ============================================================================
@@ -9,176 +15,273 @@
9
15
  // ============================================================================
10
16
 
11
17
  /**
12
- * Creates a reactive signal. When a function is passed, it becomes a computed signal.
13
- * If a `localStorageKey` is provided, the value persists.
18
+ * A reactive signal. Call with no args to read, with a value or an updater
19
+ * function to write.
14
20
  *
15
- * @param value - Initial value or computation function
16
- * @param localStorageKey - Optional key for persistence
17
- * @returns A getter/setter function
21
+ * @example
22
+ * const count = signal(0);
23
+ * count(); // read → 0
24
+ * count(1); // write
25
+ * count(c => c + 1);// updater
18
26
  */
19
- export function $<T>(value: T, localStorageKey?: string): Signal<T>;
20
- export function $<T>(computation: () => T): Signal<T>;
21
-
22
27
  export interface Signal<T> {
23
28
  (): T;
24
29
  (value: T | ((prev: T) => T)): void;
25
30
  }
26
31
 
27
32
  /**
28
- * Creates a deep reactive proxy for objects and arrays.
29
- * Tracks property access and mutations automatically.
30
- *
31
- * @param target - Object or array to make reactive
32
- * @returns A reactive proxy
33
+ * Creates a reactive signal with an initial value.
34
+ */
35
+ export function signal<T>(initialValue: T): Signal<T>;
36
+
37
+ /**
38
+ * A read-only derived value. Call with no args to read.
33
39
  */
34
- export function $$<T extends object>(target: T): DeepReactive<T>;
40
+ export type ReadonlySignal<T> = () => T;
35
41
 
36
- export type DeepReactive<T> = T extends object
37
- ? {
38
- [K in keyof T]: T[K] extends object ? DeepReactive<T[K]> : T[K];
39
- }
40
- : T;
42
+ /**
43
+ * Creates a derived value computed lazily from dependencies.
44
+ * Recomputed on read only when dependencies have actually changed.
45
+ */
46
+ export function computed<T>(getter: (oldValue?: T) => T): ReadonlySignal<T>;
41
47
 
42
48
  /**
43
- * Watches reactive sources and runs a callback.
44
- *
45
- * @example
46
- * // Auto-track mode
47
- * watch(() => {
48
- * console.log(count());
49
- * });
49
+ * Runs `fn` reactively. Re-executes when its tracked dependencies change.
50
+ * `fn` may return a cleanup function, run before the next re-execution and
51
+ * on stop.
50
52
  *
51
- * @example
52
- * // Explicit sources
53
- * watch([count, name], ([c, n]) => {
54
- * console.log(c, n);
55
- * });
53
+ * @returns A function that stops the effect.
54
+ */
55
+ export function effect(fn: () => void | (() => void)): () => void;
56
+
57
+ /**
58
+ * Creates a scope that groups child effects. Does not track dependencies
59
+ * and does not re-execute. Returns a function that disposes all effects
60
+ * created inside.
61
+ */
62
+ export function effectScope(fn: () => void): () => void;
63
+
64
+ /**
65
+ * Runs `fn` without tracking signal reads as dependencies.
66
+ */
67
+ export function untrack<T>(fn: () => T): T;
68
+
69
+ /**
70
+ * Batches multiple signal writes into a single flush.
71
+ */
72
+ export function batch<T>(fn: () => T): T;
73
+
74
+ /**
75
+ * Watches a signal or getter and calls `cb` when the value changes.
76
+ * Skips the initial run by default. Set `immediate` to call once on setup.
56
77
  *
57
- * @returns A function to stop the watcher.
78
+ * @returns A function that stops the watcher.
58
79
  */
59
- export function watch(fn: () => void): () => void;
60
80
  export function watch<T>(
61
- sources: Array<Signal<any>> | (() => T),
62
- callback: (values: T | any[]) => void
81
+ source: Signal<T> | ReadonlySignal<T>,
82
+ cb: (value: T, oldValue: T | undefined) => void,
83
+ options?: { immediate?: boolean }
63
84
  ): () => void;
64
85
 
65
86
  /**
66
- * Batches multiple reactive updates into a single flush.
87
+ * Creates a signal persisted to `localStorage` under `key`.
88
+ * The value is JSON-serialized. Falls back to `initial` if unavailable
89
+ * or if the stored value cannot be parsed.
67
90
  */
68
- export function batch<T>(fn: () => T): T;
91
+ export function local<T>(key: string, initial: T): Signal<T>;
92
+
93
+ // ============================================================================
94
+ // Dependency Injection
95
+ // ============================================================================
96
+
97
+ /**
98
+ * Provides a value in the current effect/scope context.
99
+ * Only visible to descendants.
100
+ */
101
+ export function provide<T = any>(key: string | symbol, value: T): void;
102
+
103
+ /**
104
+ * Injects the nearest value for `key` from an ancestor context.
105
+ * Returns `fallback` if not found.
106
+ */
107
+ export function inject<T = any>(key: string | symbol, fallback?: T): T | undefined;
69
108
 
70
109
  // ============================================================================
71
110
  // DOM Creation
72
111
  // ============================================================================
73
112
 
74
113
  /**
75
- * Hyperscript function to create DOM elements or components.
76
- *
77
- * @param tag - HTML/SVG tag name or component function
78
- * @param props - Optional properties/attributes
79
- * @param children - Child nodes or reactive functions
80
- * @returns DOM node or array of nodes
114
+ * A prop value may be static or a reactive getter.
81
115
  */
82
- export function h(
83
- tag: string | ((props: any, ctx: ComponentContext) => any),
84
- props?: any,
85
- children?: any
86
- ): Node;
87
-
88
- export interface ComponentContext {
89
- children: any;
90
- emit: (event: string, ...args: any[]) => void;
91
- }
116
+ export type PropValue<T = any> = T | (() => T);
92
117
 
93
118
  /**
94
- * Conditionally renders content.
119
+ * Props accepted by `h` and all tag helpers.
95
120
  *
96
- * @param condition - Boolean, signal, or function returning boolean
97
- * @param thenBranch - Content when truthy (Node or function)
98
- * @param elseBranch - Optional content when falsy
99
- * @returns A placeholder element that updates reactively
121
+ * Special props:
122
+ * - `ref`: function `(el) => void` or object with `.current`
123
+ * - `html`: sets `innerHTML` reactively (skips `children` if present)
124
+ * - `on*`: DOM event listeners (case-insensitive: `onclick`, `onInput`)
125
+ * - any other: assigned to the element (property if it exists, otherwise attribute)
100
126
  */
101
- export function when(
102
- condition: boolean | (() => boolean) | Signal<boolean>,
103
- thenBranch: any | (() => any),
104
- elseBranch?: any | (() => any)
105
- ): HTMLElement;
127
+ export type Props = {
128
+ ref?: ((el: Element) => void) | { current: Element | null };
129
+ html?: PropValue<string | null | undefined>;
130
+ class?: PropValue<string | null | undefined>;
131
+ className?: PropValue<string | null | undefined>;
132
+ style?: PropValue<string | null | undefined>;
133
+ [key: string]: PropValue<any>;
134
+ };
106
135
 
107
136
  /**
108
- * Keyed list renderer. Uses `item?.id` by default or a custom key field.
137
+ * Any value accepted as a child: nodes, strings, numbers, arrays, or
138
+ * reactive getter functions returning any of these.
139
+ */
140
+ export type Child =
141
+ | Node
142
+ | string
143
+ | number
144
+ | boolean
145
+ | null
146
+ | undefined
147
+ | (() => Child | Child[])
148
+ | Child[];
149
+
150
+ /**
151
+ * Creates a DOM element from a tag name, or renders a component.
109
152
  *
110
- * @param src - Array, signal, or function returning array
111
- * @param itemFn - Render function (item, index) => Node
112
- * @param keyField - Optional property name for unique key (e.g., "id")
113
- * @returns A container element with reactive list
153
+ * - `tag` as string → creates HTML or SVG element (auto-detected).
154
+ * - `tag` as function → treated as a component: `(props, children[]) => Node | Node[]`.
155
+ * - First argument may be children if it is not a plain object.
156
+ * - Multiple children may be passed variadically.
114
157
  */
115
- export function each<T>(
116
- src: T[] | (() => T[]) | Signal<T[]>,
117
- itemFn: (item: T, index: number) => any,
118
- keyField?: keyof T
119
- ): HTMLElement;
158
+ export function h(
159
+ tag: string,
160
+ props?: Props | Child | null,
161
+ ...children: Child[]
162
+ ): Element | SVGElement;
163
+
164
+ export function h<P extends object>(
165
+ tag: (props: P, children: Child[]) => Node | Node[] | null,
166
+ props?: P | null,
167
+ ...children: Child[]
168
+ ): Node | Node[] | null;
120
169
 
170
+ /**
171
+ * Registers all standard HTML tag names as globals (`div`, `span`, `button`,
172
+ * `input`, `textarea`, `svg`, etc.).
173
+ *
174
+ * Must be called once at startup. Defaults to `window`.
175
+ */
176
+ export function exposeTags(target?: any): void;
121
177
 
122
178
  // ============================================================================
123
- // Router
179
+ // Mount / Unmount
124
180
  // ============================================================================
125
181
 
126
182
  /**
127
- * Hash-based router.
183
+ * Mounts a component into a DOM target.
184
+ *
185
+ * @param component - Component function or node.
186
+ * @param target - CSS selector or DOM element.
187
+ * @returns A function that stops the app scope and clears the target.
188
+ */
189
+ export function mount(
190
+ component: (props?: any) => Node | Node[] | null,
191
+ target: string | Element
192
+ ): () => void;
193
+
194
+ /**
195
+ * Recursively disposes scopes and removes tracked event listeners on a node
196
+ * and its descendants, then detaches it from the DOM.
128
197
  *
129
- * @param routes - Array of route definitions
130
- * @returns A container that renders the current route
198
+ * Only needed when working with nodes created outside `h()`.
131
199
  */
132
- export function router(routes: RouteDefinition[]): HTMLElement;
200
+ export function unmount(node: Node): void;
201
+
202
+ // ============================================================================
203
+ // Router
204
+ // ============================================================================
133
205
 
134
206
  export interface RouteDefinition {
135
- path: string; // e.g., "/", "/user/:id", "*"
136
- component: any | ((params: Record<string, string>) => any);
207
+ /** Path pattern: `/`, `/user/:id`, `/blog/*`, or `*` for fallback. */
208
+ path: string;
209
+ /** Component function receiving route params, or a static node. */
210
+ component: ((params: Record<string, string>) => Node | Node[] | null) | Node;
137
211
  }
138
212
 
139
- export namespace router {
140
- /** Reactive params signal */
141
- export const params: Signal<Record<string, string>>;
213
+ export interface RouterFn {
214
+ (): HTMLElement;
215
+ /** Navigate to a path (updates `window.location.hash`). */
216
+ to(path: string): void;
217
+ /** Go back in browser history. */
218
+ back(): void;
219
+ /** Returns the current path (without leading `#`). */
220
+ path(): string;
221
+ }
142
222
 
143
- /** Navigate to path */
144
- export function to(path: string): void;
223
+ /**
224
+ * Creates a hash-based router. Returns a component that renders the
225
+ * matched route and re-renders on navigation.
226
+ */
227
+ export function router(routes: RouteDefinition[]): RouterFn;
145
228
 
146
- /** Go back in history */
147
- export function back(): void;
229
+ /** Current path as a reactive signal (without leading `#`). */
230
+ export const currentPath: Signal<string>;
148
231
 
149
- /** Current path without hash */
150
- export function path(): string;
151
- }
232
+ /** Current route params as a reactive signal. */
233
+ export const routerParams: Signal<Record<string, string>>;
152
234
 
153
235
  // ============================================================================
154
- // Mount API
236
+ // i18n
155
237
  // ============================================================================
156
238
 
157
- export interface RuntimeInstance {
158
- _isRuntime: true;
159
- container: HTMLElement;
160
- destroy: () => void;
161
- }
239
+ /** Active locale. Reactive. */
240
+ export const currentLocale: Signal<string>;
162
241
 
163
242
  /**
164
- * Mounts a component to a DOM target.
243
+ * Registers translations for one or more locales.
165
244
  *
166
- * @param component - Component function or node
167
- * @param target - CSS selector or DOM element
168
- * @returns Runtime instance
245
+ * @example
246
+ * addLang({ en: { hello: "Hello" }, es: { hello: "Hola" } });
169
247
  */
170
- export function mount(
171
- component: (() => any) | Node,
172
- target: string | HTMLElement
173
- ): RuntimeInstance | undefined;
248
+ export function addLang(translations: Record<string, Record<string, string>>): void;
249
+
250
+ /** Sets the active locale if it has been registered. */
251
+ export function setLocale(locale: string): void;
252
+
253
+ /** Reactive translation getter for a key. */
254
+ export function t(key: string): () => string;
255
+
256
+ /** Imperative translation read for a key. */
257
+ export function tt(key: string): string;
174
258
 
175
259
  // ============================================================================
176
- // Tag Helpers (globally available, lowercase)
260
+ // HTTP Helper
177
261
  // ============================================================================
178
262
 
179
- // All standard HTML tags are available as global functions.
180
- // They follow the same signature as `h` but with predefined tag names.
181
- // Examples:
263
+ /**
264
+ * JSON fetch helper. POSTs when `data` is provided, GETs otherwise.
265
+ * Calls `loading(true/false)` around the request if provided.
266
+ * Pass an `AbortSignal` to cancel.
267
+ */
268
+ export function db<T = any>(
269
+ url: string,
270
+ data?: any | null,
271
+ loading?: ((loading: boolean) => void) | null,
272
+ signal?: AbortSignal | null
273
+ ): Promise<T>;
274
+
275
+ // ============================================================================
276
+ // Tag Helpers (registered by `exposeTags`)
277
+ // ============================================================================
278
+
279
+ /**
280
+ * A tag helper: `div(props?, ...children)`.
281
+ * Available on `window` after calling `exposeTags()`.
282
+ */
283
+ export type TagHelper = (props?: Props | Child | null, ...children: Child[]) => Element;
284
+
182
285
  export const a: TagHelper;
183
286
  export const abbr: TagHelper;
184
287
  export const article: TagHelper;
@@ -265,25 +368,34 @@ export const u: TagHelper;
265
368
  export const ul: TagHelper;
266
369
  export const video: TagHelper;
267
370
 
268
- export type TagHelper = (
269
- props?: any,
270
- children?: any
271
- ) => HTMLElement | SVGElement | Text;
272
-
273
371
  // ============================================================================
274
- // Default Export
372
+ // Aggregate Export
275
373
  // ============================================================================
276
374
 
277
375
  declare const SigPro: {
278
- $: typeof $;
279
- $$: typeof $$;
376
+ signal: typeof signal;
377
+ computed: typeof computed;
378
+ effect: typeof effect;
379
+ effectScope: typeof effectScope;
380
+ untrack: typeof untrack;
381
+ batch: typeof batch;
280
382
  watch: typeof watch;
383
+ local: typeof local;
384
+ provide: typeof provide;
385
+ inject: typeof inject;
281
386
  h: typeof h;
282
- when: typeof when;
283
- each: typeof each;
284
- router: typeof router;
285
387
  mount: typeof mount;
286
- batch: typeof batch;
388
+ unmount: typeof unmount;
389
+ exposeTags: typeof exposeTags;
390
+ router: typeof router;
391
+ currentPath: typeof currentPath;
392
+ routerParams: typeof routerParams;
393
+ currentLocale: typeof currentLocale;
394
+ addLang: typeof addLang;
395
+ setLocale: typeof setLocale;
396
+ t: typeof t;
397
+ tt: typeof tt;
398
+ db: typeof db;
287
399
  };
288
400
 
289
401
  export default SigPro;
@@ -294,16 +406,31 @@ export default SigPro;
294
406
 
295
407
  declare global {
296
408
  interface Window {
297
- $: typeof $;
298
- $$: typeof $$;
409
+ SigPro: typeof SigPro;
410
+
411
+ signal: typeof signal;
412
+ computed: typeof computed;
413
+ effect: typeof effect;
414
+ effectScope: typeof effectScope;
415
+ untrack: typeof untrack;
416
+ batch: typeof batch;
299
417
  watch: typeof watch;
418
+ local: typeof local;
419
+ provide: typeof provide;
420
+ inject: typeof inject;
300
421
  h: typeof h;
301
- when: typeof when;
302
- each: typeof each;
303
- router: typeof router;
304
422
  mount: typeof mount;
305
- batch: typeof batch;
306
- SigPro: typeof SigPro;
423
+ unmount: typeof unmount;
424
+ exposeTags: typeof exposeTags;
425
+ router: typeof router;
426
+ currentPath: typeof currentPath;
427
+ routerParams: typeof routerParams;
428
+ currentLocale: typeof currentLocale;
429
+ addLang: typeof addLang;
430
+ setLocale: typeof setLocale;
431
+ t: typeof t;
432
+ tt: typeof tt;
433
+ db: typeof db;
307
434
 
308
435
  // Tag helpers (lowercase)
309
436
  a: TagHelper;
package/dist/sigpro.db.js DELETED
@@ -1 +0,0 @@
1
- var o=async(e,n={},t=null)=>{if(t)t(!0);try{let r=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),credentials:"include"});if(!r.ok){let s=await r.text();throw Error(`Error ${r.status}: ${s}`)}return await r.json()}finally{if(t)t(!1)}};export{o as db};
@@ -1 +0,0 @@
1
- var{$:c}=window.SigPro,s=c("en"),n={},e=(t)=>{for(let o of Object.keys(t)){if(!n[o])n[o]={};Object.assign(n[o],t[o])}},r=(t)=>{if(t&&n[t])s(t)},a=(t)=>{return()=>n[s()]?.[t]??t};export{a as t,r as setLocale,e as addLang};
@@ -1 +0,0 @@
1
- var{$:p,h:u,watch:m,render:g,isF:y}=window.SigPro,d=()=>window.location.hash.slice(1)||"/",s=p(d());window.addEventListener("hashchange",()=>s(d()));var w=p({}),c=(n)=>{let i=u("div",{class:"router-hook"}),r=null;return m([s],()=>{let l=s(),t=n.find((o)=>{let e=o.path.split("/").filter(Boolean),a=l.split("/").filter(Boolean);return e.length===a.length&&e.every((h,f)=>h[0]===":"||h===a[f])})||n.find((o)=>o.path==="*");if(t){r?.destroy();let o={};t.path.split("/").filter(Boolean).forEach((e,a)=>{if(e[0]===":")o[e.slice(1)]=l.split("/").filter(Boolean)[a]}),w(o),r=g(()=>y(t.component)?t.component(o):t.component),i.replaceChildren(r.container)}}),i.destroy=()=>{r?.destroy()},i};c.params=w;c.to=(n)=>window.location.hash=n.replace(/^#?\/?/,"#/");c.back=()=>window.history.back();c.path=()=>s();export{w as routerParams,c as router};