sigpro 2.1.3 → 2.1.6

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sigpro",
3
- "version": "2.1.3",
3
+ "version": "2.1.6",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "author": {
@@ -22,6 +22,11 @@
22
22
  "import": "./src/sigpro.router.js",
23
23
  "default": "./src/sigpro.router.js"
24
24
  },
25
+ "./drag": {
26
+ "types": "./sigpro.d.ts",
27
+ "import": "./src/sigpro.drag.js",
28
+ "default": "./src/sigpro.drag.js"
29
+ },
25
30
  "./lang": {
26
31
  "types": "./sigpro.d.ts",
27
32
  "import": "./src/sigpro.lang.js",
@@ -36,11 +41,6 @@
36
41
  "types": "./sigpro.d.ts",
37
42
  "import": "./src/sigpro.vite.js",
38
43
  "default": "./src/sigpro.vite.js"
39
- },
40
- "./hmr": {
41
- "types": "./sigpro.d.ts",
42
- "import": "./src/sigpro.hmr.js",
43
- "default": "./src/sigpro.hmr.js"
44
44
  }
45
45
  },
46
46
  "files": [
package/sigpro.d.ts CHANGED
@@ -195,6 +195,16 @@ export function mount(
195
195
  */
196
196
  export function unmount(node: Node): void;
197
197
 
198
+ /**
199
+ * Renders a component into a different target (default `document.body`) and
200
+ * swaps the content reactively. Returns a setter function: call it with a new
201
+ * component function to replace the previous content, or `null` to clear it.
202
+ *
203
+ * Useful for modals, winboxes, and any node that must float over the entire
204
+ * tree rather than being clipped by a parent's `overflow`, `transform`, or `z-index`.
205
+ */
206
+ export function teleport(target?: HTMLElement | string): (fn: () => Node | Node[] | null) => void;
207
+
198
208
 
199
209
  // ============================================================================
200
210
  // Event helpers
@@ -226,6 +236,12 @@ export function onEnter<T extends Event = Event>(fn: EventListener<T>): EventLis
226
236
  /** Invokes `fn` when the pressed key is `Escape`. */
227
237
  export function onEscape<T extends Event = Event>(fn: EventListener<T>): EventListener<T>;
228
238
 
239
+ /** Wraps a handler to `preventDefault()` on right-click (context menu). */
240
+ export function onContextMenu<T extends Event = Event>(fn: EventListener<T>): EventListener<T>;
241
+
242
+ /** Invokes `fn` only when the right mouse button (button 2) is pressed. */
243
+ export function onRightClick<T extends Event = Event>(fn: EventListener<T>): EventListener<T>;
244
+
229
245
  /** Binds an input's value to a signal: `{ value, oninput }` props for `h`. */
230
246
  export function bindvalue<T>(s: () => T): { value: () => T; oninput: (e: Event) => void };
231
247
 
@@ -334,9 +350,10 @@ declare const SigPro: {
334
350
  local: typeof local;
335
351
  h: typeof h;
336
352
  slots: typeof slots;
337
- mount: typeof mount;
338
- unmount: typeof unmount;
339
- onMount: typeof onMount;
353
+ mount: typeof mount;
354
+ unmount: typeof unmount;
355
+ teleport: typeof teleport;
356
+ onMount: typeof onMount;
340
357
  onError: typeof onError;
341
358
  exposeTags: typeof exposeTags;
342
359
  currentLocale: typeof currentLocale;
@@ -367,6 +384,7 @@ declare global {
367
384
  slots: typeof slots;
368
385
  mount: typeof mount;
369
386
  unmount: typeof unmount;
387
+ teleport: typeof teleport;
370
388
  onMount: typeof onMount;
371
389
  onError: typeof onError;
372
390
  exposeTags: typeof exposeTags;
@@ -0,0 +1,302 @@
1
+ // sigpro.drag.js — core interaction logic (no rendering)
2
+ import { signal, effect } from 'sigpro';
3
+
4
+ const clamp = (v, a, b) => (v < a ? a : v > b ? b : v);
5
+ const isEl = v => typeof Element !== 'undefined' && v instanceof Element;
6
+
7
+ function matchHandle(root, handle, target) {
8
+ if (!handle) return true;
9
+ if (typeof handle === 'function') return !!handle(target, root);
10
+ if (isEl(handle)) return handle === target || handle.contains(target);
11
+ if (typeof handle === 'string') {
12
+ const hit = target.closest?.(handle);
13
+ return !!hit && root.contains(hit);
14
+ }
15
+ return true;
16
+ }
17
+
18
+ export function drag(el, opts = {}) {
19
+ if (!el || typeof el.addEventListener !== 'function') return null;
20
+ return opts.items ? sortable(el, opts) : moveDrag(el, opts);
21
+ }
22
+
23
+ export const vDrag = (opts = {}) => (el) => {
24
+ const d = drag(el, opts);
25
+ if (d) (el._cln || (el._cln = [])).push(d.destroy);
26
+ return d;
27
+ };
28
+
29
+ /* FREE MOVE — position an element reactively */
30
+ function moveDrag(el, opts) {
31
+ const {
32
+ handle, disabled = false, threshold = 4, bounds = null,
33
+ axis = 'both', grid = null, useTransform = true,
34
+ cursor = 'grab', activeCursor = 'grabbing', dragClass = 'dragging',
35
+ initial = { x: 0, y: 0 }, stopPropagation = true,
36
+ onStart, onMove, onEnd,
37
+ } = opts;
38
+
39
+ const x = signal(initial.x ?? 0);
40
+ const y = signal(initial.y ?? 0);
41
+ const dragging = signal(false);
42
+
43
+ let session = null, minDx, maxDx, minDy, maxDy;
44
+
45
+ effect(() => {
46
+ if (useTransform) el.style.translate = `${x()}px ${y()}px`;
47
+ else { el.style.left = x() + 'px'; el.style.top = y() + 'px'; }
48
+ });
49
+ if (!useTransform && getComputedStyle(el).position === 'static') el.style.position = 'relative';
50
+
51
+ const isDisabled = typeof disabled === 'function' ? disabled : () => disabled === true;
52
+
53
+ function measure() {
54
+ minDx = minDy = -Infinity; maxDx = maxDy = Infinity;
55
+ const c = bounds === 'window' ? window
56
+ : bounds === 'parent' ? el.parentElement
57
+ : typeof bounds === 'string' ? document.querySelector(bounds)
58
+ : isEl(bounds) ? bounds : null;
59
+ if (!c) return;
60
+ const cr = c === window
61
+ ? { left: 0, top: 0, right: innerWidth, bottom: innerHeight }
62
+ : c.getBoundingClientRect();
63
+ const er = el.getBoundingClientRect();
64
+ const bx = er.left - x(), by = er.top - y();
65
+ minDx = cr.left - bx; maxDx = cr.right - bx - er.width;
66
+ minDy = cr.top - by; maxDy = cr.bottom - by - er.height;
67
+ if (minDx > maxDx) minDx = maxDx;
68
+ if (minDy > maxDy) minDy = maxDy;
69
+ }
70
+
71
+ function onDown(e) {
72
+ if (e.button !== 0 && e.pointerType === 'mouse') return;
73
+ if (isDisabled()) return;
74
+ if (!matchHandle(el, handle, e.target)) return;
75
+ if (session) return;
76
+
77
+ session = {
78
+ pointerId: e.pointerId, startX: e.clientX, startY: e.clientY,
79
+ ox: x(), oy: y(), started: false, el,
80
+ };
81
+ document.addEventListener('pointermove', onPointerMove);
82
+ document.addEventListener('pointerup', onPointerUp);
83
+ document.addEventListener('pointercancel', onPointerUp);
84
+ if (stopPropagation) e.stopPropagation();
85
+ }
86
+
87
+ function onPointerMove(e) {
88
+ if (!session || e.pointerId !== session.pointerId) return;
89
+ const dx = e.clientX - session.startX, dy = e.clientY - session.startY;
90
+
91
+ if (!session.started) {
92
+ if (Math.hypot(dx, dy) < threshold) return;
93
+ session.started = true;
94
+ measure();
95
+ try { el.setPointerCapture(e.pointerId); } catch {}
96
+ if (dragClass) el.classList.add(dragClass);
97
+ el.style.cursor = activeCursor;
98
+ dragging(true);
99
+ if (onStart?.({ x: x(), y: y() }, el) === false) return end(e);
100
+ }
101
+ e.preventDefault();
102
+
103
+ let nx = axis === 'y' ? session.ox : session.ox + dx;
104
+ let ny = axis === 'x' ? session.oy : session.oy + dy;
105
+ if (grid) {
106
+ const [gx = 0, gy = gx] = Array.isArray(grid) ? grid : [grid, grid];
107
+ if (gx) nx = Math.round(nx / gx) * gx;
108
+ if (gy) ny = Math.round(ny / gy) * gy;
109
+ }
110
+ nx = clamp(nx, minDx, maxDx);
111
+ ny = clamp(ny, minDy, maxDy);
112
+ x(nx); y(ny);
113
+ onMove?.({ x: nx, y: ny }, el);
114
+ }
115
+
116
+ function onPointerUp(e) { if (session && e.pointerId === session.pointerId) end(e); }
117
+
118
+ function end(e) {
119
+ if (!session) return;
120
+ if (session.started) {
121
+ try { el.releasePointerCapture?.(session.pointerId); } catch {}
122
+ if (dragClass) el.classList.remove(dragClass);
123
+ el.style.cursor = cursor;
124
+ dragging(false);
125
+ onEnd?.({ x: x(), y: y() }, el);
126
+ }
127
+ document.removeEventListener('pointermove', onPointerMove);
128
+ document.removeEventListener('pointerup', onPointerUp);
129
+ document.removeEventListener('pointercancel', onPointerUp);
130
+ session = null;
131
+ }
132
+
133
+ el.addEventListener('pointerdown', onDown);
134
+ el.style.cursor = cursor;
135
+ el.style.userSelect = 'none';
136
+ el.style.touchAction = 'none';
137
+
138
+ return {
139
+ x, y, dragging,
140
+ setPosition(nx, ny) { measure(); x(clamp(nx, minDx, maxDx)); y(clamp(ny, minDy, maxDy)); },
141
+ destroy() { el.removeEventListener('pointerdown', onDown); },
142
+ };
143
+ }
144
+
145
+ /* SORTABLE — reorder items (logic only; ghost/placeholder rendering delegated) */
146
+ const ITEM_ATTR = 'data-drag-item';
147
+ const KEY_ATTR = 'data-drag-key';
148
+ const KEY_OF = 'data-drag-key-of';
149
+
150
+ const registry = new WeakMap();
151
+
152
+ function findContainerAt(x, y) {
153
+ for (const el of document.elementsFromPoint(x, y)) {
154
+ if (registry.has(el)) return el;
155
+ const p = el.parentElement;
156
+ if (p && registry.has(p)) return p;
157
+ }
158
+ return null;
159
+ }
160
+
161
+ function itemsOf(container) {
162
+ return [...container.children].filter(c => c.hasAttribute?.(ITEM_ATTR));
163
+ }
164
+
165
+ function indexAt(els, y, draggedKey) {
166
+ const list = els.filter(c => c.getAttribute(KEY_ATTR) !== String(draggedKey));
167
+ for (let i = 0; i < list.length; i++) {
168
+ const r = list[i].getBoundingClientRect();
169
+ if (y < r.top + r.height / 2) return i;
170
+ }
171
+ return list.length;
172
+ }
173
+
174
+ export function sortable(container, opts = {}) {
175
+ const {
176
+ handle, disabled = false, threshold = 4, stopPropagation = true,
177
+ items, key = 'id', group = 'default',
178
+ onStart, onMove, onEnd, onChange,
179
+ } = opts;
180
+
181
+ const cfg = { items, key, group, onChange };
182
+ registry.set(container, cfg);
183
+
184
+ let session = null;
185
+
186
+ function onDown(e) {
187
+ if (e.button !== 0 && e.pointerType === 'mouse') return;
188
+ if (disabled === true || (typeof disabled === 'function' && disabled())) return;
189
+ if (session) return;
190
+
191
+ const itemEl = e.target.closest?.(`[${ITEM_ATTR}]`);
192
+ if (!itemEl || !container.contains(itemEl)) return;
193
+ if (!matchHandle(container, handle, e.target)) return;
194
+
195
+ const arr = items();
196
+ const els = itemsOf(container);
197
+ const idx = els.indexOf(itemEl);
198
+ if (idx < 0) return;
199
+ const item = arr[idx];
200
+ if (item === undefined) return;
201
+
202
+ const rect = itemEl.getBoundingClientRect();
203
+ const keyVal = typeof key === 'function' ? key(item, idx) : item?.[key];
204
+
205
+ session = {
206
+ pointerId: e.pointerId, startX: e.clientX, startY: e.clientY,
207
+ offsetX: e.clientX - rect.left, offsetY: e.clientY - rect.top,
208
+ item, itemEl, fromList: container, fromIdx: idx,
209
+ targetList: container, targetIdx: idx,
210
+ keyVal, started: false, rect,
211
+ };
212
+ document.addEventListener('pointermove', onPointerMove);
213
+ document.addEventListener('pointerup', onPointerUp);
214
+ document.addEventListener('pointercancel', onPointerUp);
215
+ if (stopPropagation) e.stopPropagation();
216
+ }
217
+
218
+ function onPointerMove(e) {
219
+ if (!session || e.pointerId !== session.pointerId) return;
220
+ const s = session;
221
+ const dx = e.clientX - s.startX, dy = e.clientY - s.startY;
222
+
223
+ if (!s.started) {
224
+ if (Math.hypot(dx, dy) < threshold) return;
225
+ s.started = true;
226
+ try { s.itemEl.setPointerCapture(e.pointerId); } catch {}
227
+ onStart?.(s);
228
+ }
229
+
230
+ e.preventDefault();
231
+
232
+ const hoverContainer = findContainerAt(e.clientX, e.clientY);
233
+ if (!hoverContainer) return;
234
+ const hoverCfg = registry.get(hoverContainer);
235
+ const srcCfg = registry.get(s.fromList);
236
+ if (!hoverCfg || !srcCfg || hoverCfg.group !== srcCfg.group) return;
237
+
238
+ const sameList = hoverContainer === s.fromList;
239
+ const idx = indexAt(itemsOf(hoverContainer), e.clientY, s.keyVal);
240
+ const effectiveIdx = sameList ? idx : (() => {
241
+ const list = itemsOf(hoverContainer);
242
+ for (let i = 0; i < list.length; i++) {
243
+ const r = list[i].getBoundingClientRect();
244
+ if (e.clientY < r.top + r.height / 2) return i;
245
+ }
246
+ return list.length;
247
+ })();
248
+
249
+ s.targetList = hoverContainer;
250
+ s.targetIdx = effectiveIdx;
251
+
252
+ onMove?.(s, e);
253
+ }
254
+
255
+ function onPointerUp(e) { if (session && e.pointerId === session.pointerId) end(); }
256
+
257
+ function end() {
258
+ const s = session;
259
+ if (!s) return;
260
+ document.removeEventListener('pointermove', onPointerMove);
261
+ document.removeEventListener('pointerup', onPointerUp);
262
+ document.removeEventListener('pointercancel', onPointerUp);
263
+ session = null;
264
+
265
+ if (s.started) commit(s);
266
+ if (s.started) onEnd?.(s);
267
+ }
268
+
269
+ function commit(s) {
270
+ const srcCfg = registry.get(s.fromList);
271
+ const dstCfg = registry.get(s.targetList);
272
+ if (!srcCfg || !dstCfg) return;
273
+
274
+ if (s.fromList === s.targetList) {
275
+ if (s.fromIdx === s.targetIdx) return;
276
+ const arr = [...srcCfg.items()];
277
+ const [moved] = arr.splice(s.fromIdx, 1);
278
+ arr.splice(s.targetIdx, 0, moved);
279
+ srcCfg.items(arr);
280
+ srcCfg.onChange?.({ item: moved, from: s.fromIdx, to: s.targetIdx, list: s.fromList });
281
+ } else {
282
+ const srcArr = [...srcCfg.items()];
283
+ const [moved] = srcArr.splice(s.fromIdx, 1);
284
+ srcCfg.items(srcArr);
285
+
286
+ const dstArr = [...dstCfg.items()];
287
+ dstArr.splice(s.targetIdx, 0, moved);
288
+ dstCfg.items(dstArr);
289
+
290
+ srcCfg.onChange?.({ item: moved, from: s.fromIdx, to: -1, list: s.fromList, otherList: s.targetList });
291
+ dstCfg.onChange?.({ item: moved, from: -1, to: s.targetIdx, list: s.targetList, otherList: s.fromList });
292
+ }
293
+ }
294
+
295
+ container.addEventListener('pointerdown', onDown);
296
+ return {
297
+ destroy() {
298
+ container.removeEventListener('pointerdown', onDown);
299
+ registry.delete(container);
300
+ },
301
+ };
302
+ }
package/src/sigpro.js CHANGED
@@ -91,7 +91,16 @@ function setAttr(el, key, res, isSVG) {
91
91
  else el.setAttribute(key, res === true ? '' : res);
92
92
  }
93
93
 
94
-
94
+ function cleanupNode(n) {
95
+ const stack = [n];
96
+ while (stack.length) {
97
+ const node = stack.pop();
98
+ if (node._stopScope) { node._stopScope(); node._stopScope = null; }
99
+ if (node._cln) { for (const f of node._cln) f(); node._cln = null; }
100
+ const children = node.childNodes;
101
+ for (let i = 0, len = children.length; i < len; i++) stack.push(children[i]);
102
+ }
103
+ }
95
104
 
96
105
  export function h(tag, props = {}, ...children) {
97
106
  if (tag == null) {
@@ -239,6 +248,23 @@ export function unmount(node) {
239
248
  if (node.parentNode) node.parentNode.removeChild(node);
240
249
  }
241
250
 
251
+ export function teleport(target = DOC.body) {
252
+ let scope, node;
253
+ const set = (fn) => {
254
+ scope?.();
255
+ scope = effectScope(() => { node = fn(); });
256
+ const nodes = (Array.isArray(node) ? node : [node])
257
+ .filter(n => n != null && n !== false && n !== true)
258
+ .map(n => (n instanceof Node ? n : DOC.createTextNode(String(n))));
259
+ while (target.firstChild) {
260
+ cleanupNode(target.firstChild);
261
+ target.removeChild(target.firstChild);
262
+ }
263
+ for (const n of nodes) target.appendChild(n);
264
+ };
265
+ return set;
266
+ }
267
+
242
268
  const htmlTags = "a abbr article aside audio b blockquote br button canvas caption cite code col colgroup datalist dd del details dfn dialog div dl dt em embed fieldset figcaption figure footer form h1 h2 h3 h4 h5 h6 header hr i iframe img input ins kbd label legend li main mark meter nav object ol optgroup option output p picture pre progress section select slot small source span strong sub summary sup table tbody td template textarea tfoot th thead time tr u ul video";
243
269
 
244
270
  export const exposeTags = (target = typeof window !== 'undefined' ? window : null) => {
@@ -267,5 +293,84 @@ export const onDebounce = (ms, fn) => { let t; return e => { clearTimeout(t); t
267
293
  export const onKey = (key, fn) => e => { if (e.key === key) fn(e); };
268
294
  export const onEnter = fn => onKey("Enter", fn);
269
295
  export const onEscape = fn => onKey("Escape", fn);
296
+ export const onContextMenu = fn => e => { e.preventDefault(); fn(e); };
297
+ export const onRightClick = fn => e => { if (e.button === 2) fn(e); };
298
+ export const onSwipe = (dir, { distance = 50, threshold = 0.7 } = {}, fn) => {
299
+ let sx, sy, active;
300
+ const start = e => { const t = e.changedTouches || [e]; sx = t[0].clientX; sy = t[0].clientY; active = true; };
301
+ const end = e => {
302
+ if (!active) return;
303
+ const t = e.changedTouches || [e];
304
+ const dx = t[0].clientX - sx, dy = t[0].clientY - sy;
305
+ if (dir === 'x' && Math.abs(dx) > distance && Math.abs(dx) > Math.abs(dy) * threshold) { active = false; fn(e); }
306
+ if (dir === 'y' && Math.abs(dy) > distance && Math.abs(dy) > Math.abs(dx) * threshold) { active = false; fn(e); }
307
+ };
308
+ return h => {
309
+ h.addEventListener('touchstart', start, { passive: true });
310
+ h.addEventListener('touchend', end, { passive: true });
311
+ h.addEventListener('mousedown', start);
312
+ h.addEventListener('mouseup', end);
313
+ };
314
+ };
315
+ export const onPullRefresh = (threshold = 60, fn) => {
316
+ let startY, pulling;
317
+ const start = e => { const t = e.changedTouches || [e]; startY = t[0].clientY; pulling = true; };
318
+ const move = e => {
319
+ if (!pulling) return;
320
+ const t = e.changedTouches || [e];
321
+ if (t[0].clientY - startY > threshold) { pulling = false; fn(e); }
322
+ };
323
+ return h => {
324
+ h.addEventListener('touchstart', start, { passive: true });
325
+ h.addEventListener('touchmove', move, { passive: true });
326
+ };
327
+ };
270
328
  export const bindvalue = s => ({ value: () => s(), oninput: e => s(e.target.value) });
271
- export const bindcheck = s => ({ checked: () => !!s(), onchange: e => s(e.target.checked) });
329
+ export const bindcheck = s => ({ checked: () => !!s(), onchange: e => s(e.target.checked) });
330
+
331
+ export const resize = (el, opts = {}) => {
332
+ const { axis = 'both', min = 0, max = Infinity, handle, onStart, onResize, onEnd } = opts;
333
+ const w = signal(el.offsetWidth || 0);
334
+ const h = signal(el.offsetHeight || 0);
335
+
336
+ let sx, sy, sw, sh, active;
337
+
338
+ const start = e => {
339
+ if (handle && !handle.contains(e.target) && handle !== e.target) return;
340
+ const t = e.changedTouches || [e];
341
+ sx = t[0].clientX; sy = t[0].clientY;
342
+ sw = el.offsetWidth; sh = el.offsetHeight;
343
+ active = true;
344
+ document.addEventListener('pointermove', move);
345
+ document.addEventListener('pointerup', end);
346
+ document.addEventListener('pointercancel', end);
347
+ if (onStart) onStart();
348
+ };
349
+
350
+ const move = e => {
351
+ if (!active) return;
352
+ const t = e.changedTouches || [e];
353
+ const dx = t[0].clientX - sx, dy = t[0].clientY - sy;
354
+ if (axis === 'x' || axis === 'both') {
355
+ const nw = Math.min(max, Math.max(min, sw + dx));
356
+ if (nw !== w()) w(nw);
357
+ }
358
+ if (axis === 'y' || axis === 'both') {
359
+ const nh = Math.min(max, Math.max(min, sh + dy));
360
+ if (nh !== h()) h(nh);
361
+ }
362
+ if (onResize) onResize({ w: w(), h: h() });
363
+ };
364
+
365
+ const end = () => {
366
+ if (!active) return;
367
+ active = false;
368
+ document.removeEventListener('pointermove', move);
369
+ document.removeEventListener('pointerup', end);
370
+ document.removeEventListener('pointercancel', end);
371
+ if (onEnd) onEnd();
372
+ };
373
+
374
+ el.addEventListener('mousedown', start);
375
+ return { w, h };
376
+ };
@@ -1,20 +1,33 @@
1
1
  // sigpro.router.js
2
2
  import { signal, effect } from 'sigpro';
3
3
 
4
- export const currentPath = signal(typeof window !== 'undefined' ? location.hash.slice(1) || '/' : '/');
4
+ export const currentPath = signal(
5
+ typeof window !== 'undefined' ? location.hash.slice(1) || '/' : '/'
6
+ );
5
7
  export const routerParams = signal({});
6
8
 
7
9
  if (typeof window !== 'undefined') {
8
10
  addEventListener('hashchange', () => currentPath(location.hash.slice(1) || '/'));
9
11
  }
10
12
 
11
- const hmrTick = signal(0);
12
- const hmrRegistry = new Map();
13
- window.__sigpro_hmr_page__ = (url, component) => { hmrRegistry.set(url, component); hmrTick(hmrTick() + 1); };
13
+ let hmrTick, hmrRegistry;
14
14
 
15
- export const router = routes => {
16
- const sorted = [...routes].sort((a, b) => a.path.split('/').filter(p => p[0] === ':').length -
17
- b.path.split('/').filter(p => p[0] === ':').length || (b.path === '*') - (a.path === '*'));
15
+ if (import.meta.hot) {
16
+ hmrTick = signal(0);
17
+ hmrRegistry = new Map();
18
+
19
+ window.__sigpro_hmr_page__ = (url, component) => {
20
+ hmrRegistry.set(url, component);
21
+ hmrTick(hmrTick() + 1);
22
+ };
23
+ }
24
+
25
+ export const router = (routes) => {
26
+ const sorted = [...routes].sort((a, b) =>
27
+ a.path.split('/').filter(p => p[0] === ':').length -
28
+ b.path.split('/').filter(p => p[0] === ':').length ||
29
+ (b.path === '*') - (a.path === '*')
30
+ );
18
31
 
19
32
  const hook = document.createElement('div');
20
33
  hook.classList.add('router-hook');
@@ -32,37 +45,48 @@ export const router = routes => {
32
45
  };
33
46
 
34
47
  const effectStop = effect(() => {
35
- hmrTick();
48
+ if (import.meta.hot) hmrTick();
49
+
36
50
  const hash = currentPath().split(/[?#]/)[0];
37
51
  const p2 = hash.split('/').filter(Boolean);
38
52
 
39
- let route = sorted.find(r => r.path.split('/').filter(Boolean).length === p2.length &&
40
- r.path.split('/').every((p, i) => p[0] === ':' || p === p2[i]));
53
+ let route = sorted.find(r =>
54
+ r.path.split('/').filter(Boolean).length === p2.length &&
55
+ r.path.split('/').every((p, i) => p[0] === ':' || p === p2[i])
56
+ );
41
57
  if (!route) route = sorted[sorted.length - 1];
42
58
 
43
59
  const params = {};
44
60
  route.path.split('/').filter(Boolean).reduce((acc, p, i) => {
45
- if (p[0] === ':') try { params[p.slice(1)] = decodeURIComponent(p2[i]); } catch { params[p.slice(1)] = p2[i]; }
61
+ if (p[0] === ':') {
62
+ try { params[p.slice(1)] = decodeURIComponent(p2[i]); }
63
+ catch { params[p.slice(1)] = p2[i]; }
64
+ }
46
65
  return acc;
47
66
  }, null);
48
67
 
49
- const component = hmrRegistry.get(route.path) ?? route.component;
68
+ const component = (import.meta.hot && hmrRegistry.get(route.path)) || route.component;
69
+
50
70
  if (hash === lastPath && component === lastComponent) return;
51
71
  lastPath = hash; lastComponent = component;
52
72
 
53
73
  if (scopeStop) { scopeStop(); scopeStop = undefined; }
54
74
  clearHook();
55
75
  routerParams(params);
76
+
56
77
  scopeStop = effect(() => {
57
78
  const node = typeof component === 'function' ? component(params) : component;
58
79
  hook.replaceChildren(...(node == null ? [] : Array.isArray(node) ? node : [node]));
59
80
  });
60
81
  });
61
82
 
62
- hook._stopScope = () => { if (scopeStop) { scopeStop(); scopeStop = undefined; } effectStop(); };
83
+ hook._stopScope = () => {
84
+ if (scopeStop) { scopeStop(); scopeStop = undefined; }
85
+ effectStop();
86
+ };
63
87
  return hook;
64
88
  };
65
89
 
66
90
  router.to = path => location.hash = '#/' + path.replace(/^\//, '');
67
91
  router.back = () => history.back();
68
- router.path = () => currentPath();
92
+ router.path = () => currentPath();
@@ -12,7 +12,9 @@ export function sigproRouter({ pagesDir = "src/pages" } = {}) {
12
12
  const pagesRootPosix = pagesRoot.split(path.sep).join("/");
13
13
 
14
14
  const isPage = (f) =>
15
- /\.(js|jsx)$/.test(f) && !path.basename(f).startsWith("_");
15
+ /\.(js|jsx|ts|tsx)$/.test(f) &&
16
+ !path.basename(f).startsWith("_") &&
17
+ !f.includes(".store.");
16
18
 
17
19
  const getFiles = (dir) => {
18
20
  if (!fs.existsSync(dir)) return [];
@@ -26,7 +28,7 @@ export function sigproRouter({ pagesDir = "src/pages" } = {}) {
26
28
  const relative = path
27
29
  .relative(dir, filePath)
28
30
  .replace(/\\/g, "/")
29
- .replace(/\.(js|jsx)$/, "")
31
+ .replace(/\.(js|jsx|ts|tsx)$/, "")
30
32
  .replace(/\/index$/, "")
31
33
  .replace(/^index$/, "");
32
34
  return (
@@ -40,8 +42,7 @@ export function sigproRouter({ pagesDir = "src/pages" } = {}) {
40
42
 
41
43
  const sortRoutes = (dir, files) =>
42
44
  files.slice().sort((a, b) => {
43
- const ua = pathToUrl(dir, a),
44
- ub = pathToUrl(dir, b);
45
+ const ua = pathToUrl(dir, a), ub = pathToUrl(dir, b);
45
46
  const wa = ua.includes(":") || ua.includes("*");
46
47
  const wb = ub.includes(":") || ub.includes("*");
47
48
  if (wa !== wb) return wa ? 1 : -1;
@@ -57,8 +58,7 @@ export function sigproRouter({ pagesDir = "src/pages" } = {}) {
57
58
 
58
59
  files.forEach((fullPath, i) => {
59
60
  const url = pathToUrl(dir, fullPath);
60
- const importPath =
61
- "/" + path.relative(root, fullPath).replace(/\\/g, "/");
61
+ const importPath = "/" + path.relative(root, fullPath).replace(/\\/g, "/");
62
62
  const name = `Page${i}`;
63
63
  imports += `import ${name} from '${importPath}';\n`;
64
64
  routes += ` { path: '${url}', component: ${name} },\n`;
@@ -71,23 +71,19 @@ export function sigproRouter({ pagesDir = "src/pages" } = {}) {
71
71
 
72
72
  return {
73
73
  name: "sigpro-router",
74
-
75
74
  resolveId(id) {
76
75
  if (id === virtualModuleId) return resolvedVirtualModuleId;
77
76
  },
78
-
79
77
  load(id) {
80
78
  if (id !== resolvedVirtualModuleId) return;
81
79
  return generateModule();
82
80
  },
83
-
84
81
  transform(code, id) {
85
82
  const clean = id.split("?")[0];
86
83
  const cleanPosix = clean.split(path.sep).join("/");
87
84
 
88
85
  if (!cleanPosix.startsWith(pagesRootPosix + "/")) return;
89
- if (!/\.(js|jsx)$/.test(cleanPosix)) return;
90
- if (path.basename(cleanPosix).startsWith("_")) return;
86
+ if (!isPage(cleanPosix)) return;
91
87
 
92
88
  const url = pathToUrl(pagesRoot, clean);
93
89
 
@@ -96,22 +92,25 @@ export function sigproRouter({ pagesDir = "src/pages" } = {}) {
96
92
  if (import.meta.hot) {
97
93
  import.meta.hot.accept((newMod) => {
98
94
  if (newMod && typeof window !== 'undefined' && window.__sigpro_hmr_page__) {
99
- window.__sigpro_hmr_page__(${JSON.stringify(url)}, newMod.default ?? newMod);
95
+ Promise.resolve().then(() => {
96
+ window.__sigpro_hmr_page__(${JSON.stringify(url)}, newMod.default ?? newMod);
97
+ });
100
98
  }
101
99
  });
102
100
  }
103
101
  `;
104
102
  return { code: code + hmr, map: null };
105
103
  },
106
-
107
104
  configureServer(server) {
108
105
  const onChange = (file) => {
109
106
  const posix = file.split(path.sep).join("/");
110
107
  if (!posix.startsWith(pagesRootPosix + "/")) return;
111
108
  if (!isPage(posix)) return;
112
109
  const vm = server.moduleGraph.getModuleById(resolvedVirtualModuleId);
113
- if (vm) server.moduleGraph.invalidateModule(vm);
114
- server.ws.send({ type: "full-reload" });
110
+ if (vm) {
111
+ server.moduleGraph.invalidateModule(vm);
112
+ server.ws.send({ type: "full-reload" });
113
+ }
115
114
  };
116
115
  server.watcher.on("add", onChange);
117
116
  server.watcher.on("unlink", onChange);
@@ -119,28 +118,31 @@ if (import.meta.hot) {
119
118
  };
120
119
  }
121
120
 
121
+
122
122
  /* Vite Config
123
123
 
124
124
  import { defineConfig } from "vite";
125
- import tailwindcss from "@tailwindcss/vite";
126
- import { sigproRouter } from "./sigpro.vite.js";
125
+ import { sigproRouter } from "sigpro/vite";
127
126
 
128
127
  const dev = process.env.NODE_ENV === "development";
129
128
 
130
129
  export default defineConfig({
131
130
  plugins: [sigproRouter({ pagesDir: "src/pages" }), tailwindcss()],
132
- base: dev ? "/absproxy/5173/" : "/",
133
- server: { host: "0.0.0.0", allowedHosts: true, port: 5173 },
134
- build: { chunkSizeWarningLimit: 1500 },
135
131
  });
136
132
 
137
133
  */
138
134
 
139
135
  /* main.js
136
+
137
+ import { mount } from 'sigpro'
138
+ import App from './pages/App.js'
139
+
140
+ let dispose = mount(App, '#root')
141
+
140
142
  if (import.meta.hot) {
141
- import.meta.hot.accept(["./App.js"], ([newApp]) => {
143
+ import.meta.hot.accept('./pages/App.js', (newModule) => {
142
144
  dispose?.();
143
- dispose = mount(newApp.App, "#app");
145
+ dispose = mount(newModule.default, '#root');
144
146
  });
145
147
  }
146
- */
148
+ */
package/src/sigpro.hmr.js DELETED
@@ -1,47 +0,0 @@
1
- // sigpro.hmr.js
2
-
3
- import path from "path";
4
-
5
- const PAGES = path.resolve(import.meta.dir, "src/pages") + path.sep;
6
- const isDev = process.env.NODE_ENV === "development";
7
-
8
- export const hmr = {
9
- name: "sigpro-hmr",
10
- setup(build) {
11
- build.onLoad({ filter: /\.js$/ }, async (args) => {
12
- if (!args.path.startsWith(PAGES)) return;
13
-
14
- let source;
15
- try {
16
- source = await Bun.file(args.path).text();
17
- } catch {
18
- return;
19
- }
20
-
21
- if (isDev) {
22
- const rel = path
23
- .relative(PAGES, args.path)
24
- .replace(/\\/g, "/")
25
- .replace(/\.js$/, "");
26
-
27
- const routePath =
28
- rel === "index"
29
- ? "/"
30
- : "/" +
31
- rel.replace(/\/index$/, "").replace(/\[([^\]]+)\]/g, ":$1");
32
-
33
- source += `
34
- if (import.meta.hot) {
35
- import.meta.hot.accept((newMod) => {
36
- const component = newMod && newMod.default;
37
- if (typeof component === 'function' && typeof window !== 'undefined' && window.__sigpro_hmr_page__) {
38
- window.__sigpro_hmr_page__(${JSON.stringify(routePath)}, component);
39
- }
40
- });
41
- }`;
42
- }
43
-
44
- return { contents: source, loader: "js" };
45
- });
46
- },
47
- };