sigpro 2.1.4 → 2.1.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sigpro",
3
- "version": "2.1.4",
3
+ "version": "2.1.7",
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",
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
@@ -1,5 +1,451 @@
1
- import { effect, effectScope, reportError } from './sigpro.core.js';
2
- export * from './sigpro.core.js';
1
+ /* ALIEN SIGNALS */
2
+ const None = 0, Mutable = 1, Watching = 2, RecursedCheck = 4,
3
+ Recursed = 8, Dirty = 16, Pending = 32, HasChildEffect = 64;
4
+
5
+ let errorHandler;
6
+ export function onError(fn) { errorHandler = fn; }
7
+ export function reportError(err, where) {
8
+ if (errorHandler) {
9
+ try { errorHandler(err, where); } catch { }
10
+ } else {
11
+ console.error('[sigpro] error in', where, err);
12
+ }
13
+ }
14
+
15
+ function createReactiveSystem({ update, notify, unwatched }) {
16
+ return { link, unlink, propagate, checkDirty, shallowPropagate };
17
+
18
+ function link(dep, sub, version) {
19
+ const prevDep = sub.depsTail;
20
+ if (prevDep !== undefined && prevDep.dep === dep) return;
21
+ const nextDep = prevDep !== undefined ? prevDep.nextDep : sub.deps;
22
+ if (nextDep !== undefined && nextDep.dep === dep) {
23
+ nextDep.version = version; sub.depsTail = nextDep; return;
24
+ }
25
+ const prevSub = dep.subsTail;
26
+ if (prevSub !== undefined && prevSub.version === version && prevSub.sub === sub) return;
27
+ const newLink = sub.depsTail = dep.subsTail = {
28
+ version, dep, sub, prevDep, nextDep, prevSub, nextSub: undefined,
29
+ };
30
+ if (nextDep !== undefined) nextDep.prevDep = newLink;
31
+ if (prevDep !== undefined) prevDep.nextDep = newLink; else sub.deps = newLink;
32
+ if (prevSub !== undefined) prevSub.nextSub = newLink; else dep.subs = newLink;
33
+ }
34
+
35
+ function unlink(link, sub = link.sub) {
36
+ const { dep, prevDep, nextDep, nextSub, prevSub } = link;
37
+ if (nextDep !== undefined) nextDep.prevDep = prevDep; else sub.depsTail = prevDep;
38
+ if (prevDep !== undefined) prevDep.nextDep = nextDep; else sub.deps = nextDep;
39
+ if (nextSub !== undefined) nextSub.prevSub = prevSub; else dep.subsTail = prevSub;
40
+ if (prevSub !== undefined) prevSub.nextSub = nextSub;
41
+ else if ((dep.subs = nextSub) === undefined) unwatched(dep);
42
+ return nextDep;
43
+ }
44
+
45
+ function propagate(link, innerWrite) {
46
+ let next = link.nextSub, stack;
47
+ top: do {
48
+ const sub = link.sub;
49
+ let flags = sub.flags;
50
+ if (!(flags & (RecursedCheck | Recursed | Dirty | Pending))) {
51
+ sub.flags = flags | Pending;
52
+ if (innerWrite) sub.flags |= Recursed;
53
+ } else if (!(flags & (RecursedCheck | Recursed))) {
54
+ flags = None;
55
+ } else if (!(flags & RecursedCheck)) {
56
+ sub.flags = (flags & ~Recursed) | Pending;
57
+ } else if (!(flags & (Dirty | Pending)) && isValidLink(link, sub)) {
58
+ sub.flags = flags | Recursed | Pending;
59
+ flags &= Mutable;
60
+ } else flags = None;
61
+ if (flags & Watching) notify(sub);
62
+ if (flags & Mutable) {
63
+ const subSubs = sub.subs;
64
+ if (subSubs !== undefined) {
65
+ const nextSub = (link = subSubs).nextSub;
66
+ if (nextSub !== undefined) { stack = { value: next, prev: stack }; next = nextSub; }
67
+ continue;
68
+ }
69
+ }
70
+ if ((link = next) !== undefined) { next = link.nextSub; continue; }
71
+ while (stack !== undefined) {
72
+ link = stack.value; stack = stack.prev;
73
+ if (link !== undefined) { next = link.nextSub; continue top; }
74
+ }
75
+ break;
76
+ } while (true);
77
+ }
78
+
79
+ function checkDirty(link, sub) {
80
+ let stack, checkDepth = 0, dirty = false;
81
+ top: do {
82
+ const dep = link.dep, flags = dep.flags;
83
+ if (sub.flags & Dirty) dirty = true;
84
+ else if ((flags & (Mutable | Dirty)) === (Mutable | Dirty)) {
85
+ const subs = dep.subs;
86
+ if (update(dep)) {
87
+ if (subs.nextSub !== undefined) shallowPropagate(subs);
88
+ dirty = true;
89
+ }
90
+ } else if ((flags & (Mutable | Pending)) === (Mutable | Pending)) {
91
+ stack = { value: link, prev: stack };
92
+ link = dep.deps; sub = dep; ++checkDepth; continue;
93
+ }
94
+ if (!dirty) {
95
+ const nextDep = link.nextDep;
96
+ if (nextDep !== undefined) { link = nextDep; continue; }
97
+ }
98
+ while (checkDepth--) {
99
+ link = stack.value; stack = stack.prev;
100
+ if (dirty) {
101
+ const subs = sub.subs;
102
+ if (update(sub)) {
103
+ if (subs.nextSub !== undefined) shallowPropagate(subs);
104
+ sub = link.sub; continue;
105
+ }
106
+ dirty = false;
107
+ } else sub.flags &= ~Pending;
108
+ sub = link.sub;
109
+ const nextDep = link.nextDep;
110
+ if (nextDep !== undefined) { link = nextDep; continue top; }
111
+ }
112
+ return dirty && !!sub.flags;
113
+ } while (true);
114
+ }
115
+
116
+ function shallowPropagate(link) {
117
+ do {
118
+ const sub = link.sub, flags = sub.flags;
119
+ if ((flags & (Pending | Dirty)) === Pending) {
120
+ sub.flags = flags | Dirty;
121
+ if ((flags & (Watching | RecursedCheck)) === Watching) notify(sub);
122
+ }
123
+ } while ((link = link.nextSub) !== undefined);
124
+ }
125
+
126
+ function isValidLink(checkLink, sub) {
127
+ let link = sub.depsTail;
128
+ while (link !== undefined) {
129
+ if (link === checkLink) return true;
130
+ link = link.prevDep;
131
+ }
132
+ return false;
133
+ }
134
+ }
135
+
136
+ let cycle = 0, runDepth = 0, batchDepth = 0, notifyIndex = 0, queuedLength = 0;
137
+ let activeSub;
138
+ const queued = [];
139
+
140
+ const { link, unlink, propagate, checkDirty, shallowPropagate } = createReactiveSystem({
141
+ update(node) {
142
+ if ('getter' in node) return updateComputed(node);
143
+ if ('currentValue' in node) return updateSignal(node);
144
+ node.flags = Mutable; return true;
145
+ },
146
+ notify(effect) {
147
+ let insertIndex = queuedLength, firstInsertedIndex = insertIndex;
148
+ do {
149
+ queued[insertIndex++] = effect;
150
+ effect.flags &= ~Watching;
151
+ effect = effect.subs?.sub;
152
+ if (effect === undefined || !(effect.flags & Watching)) break;
153
+ } while (true);
154
+ queuedLength = insertIndex;
155
+ while (firstInsertedIndex < --insertIndex) {
156
+ const left = queued[firstInsertedIndex];
157
+ queued[firstInsertedIndex++] = queued[insertIndex];
158
+ queued[insertIndex] = left;
159
+ }
160
+ },
161
+ unwatched(node) {
162
+ if ('getter' in node) {
163
+ if (node.depsTail !== undefined) {
164
+ node.flags = Mutable | Dirty;
165
+ disposeAllDepsInReverse(node);
166
+ }
167
+ } else if ('currentValue' in node) {
168
+ } else if ('fn' in node) {
169
+ effectOper.call(node);
170
+ } else {
171
+ effectScopeOper.call(node);
172
+ }
173
+ },
174
+ });
175
+
176
+ export function signal(initialValue) {
177
+ return signalOper.bind({
178
+ currentValue: initialValue, pendingValue: initialValue,
179
+ subs: undefined, subsTail: undefined, flags: Mutable,
180
+ });
181
+ }
182
+
183
+ export function computed(getter) {
184
+ return computedOper.bind({
185
+ value: undefined, subs: undefined, subsTail: undefined,
186
+ deps: undefined, depsTail: undefined, flags: None, getter,
187
+ });
188
+ }
189
+
190
+ export function effect(fn) {
191
+ if (typeof fn !== 'function') {
192
+ console.error('[sigpro] effect() expects a function, got', typeof fn);
193
+ return () => { };
194
+ }
195
+ const e = {
196
+ fn, cleanup: undefined,
197
+ subs: undefined, subsTail: undefined,
198
+ deps: undefined, depsTail: undefined,
199
+ flags: Watching | RecursedCheck,
200
+ };
201
+ const prevSub = activeSub;
202
+ activeSub = e;
203
+ if (prevSub !== undefined) { link(e, prevSub, 0); prevSub.flags |= HasChildEffect; }
204
+ try {
205
+ ++runDepth;
206
+ const r = e.fn();
207
+ e.cleanup = typeof r === 'function' ? r : undefined;
208
+ } catch (err) {
209
+ e.flags = None;
210
+ disposeAllDepsInReverse(e);
211
+ reportError(err, e.fn);
212
+ } finally {
213
+ --runDepth; activeSub = prevSub;
214
+ e.flags &= ~RecursedCheck;
215
+ }
216
+ return effectOper.bind(e);
217
+ }
218
+
219
+ export function effectScope(fn) {
220
+ const e = {
221
+ deps: undefined, depsTail: undefined,
222
+ subs: undefined, subsTail: undefined, flags: Mutable,
223
+ };
224
+ const prevSub = activeSub;
225
+ activeSub = e;
226
+ if (prevSub !== undefined) { link(e, prevSub, 0); prevSub.flags |= HasChildEffect; }
227
+ try { fn(); }
228
+ finally { activeSub = prevSub; }
229
+ return effectScopeOper.bind(e);
230
+ }
231
+
232
+ export function batch(fn) {
233
+ ++batchDepth;
234
+ try { return fn(); }
235
+ finally { if (!--batchDepth) flush(); }
236
+ }
237
+
238
+ function updateComputed(c) {
239
+ if (c.flags & HasChildEffect) {
240
+ let link = c.depsTail;
241
+ while (link !== undefined) {
242
+ const prev = link.prevDep, dep = link.dep;
243
+ if (!('getter' in dep) && !('currentValue' in dep)) unlink(link, c);
244
+ link = prev;
245
+ }
246
+ }
247
+ c.depsTail = undefined;
248
+ c.flags = Mutable | RecursedCheck;
249
+ const prevSub = activeSub;
250
+ activeSub = c;
251
+ try {
252
+ ++cycle;
253
+ const oldValue = c.value;
254
+ return !Object.is(oldValue, (c.value = c.getter(oldValue)));
255
+ } finally {
256
+ activeSub = prevSub;
257
+ c.flags &= ~RecursedCheck;
258
+ purgeDeps(c);
259
+ }
260
+ }
261
+
262
+ function updateSignal(s) {
263
+ s.flags = Mutable;
264
+ return !Object.is(s.currentValue, (s.currentValue = s.pendingValue));
265
+ }
266
+
267
+ function run(e) {
268
+ const flags = e.flags;
269
+ if (flags & Dirty || (flags & Pending && checkDirty(e.deps, e))) {
270
+ if (flags & HasChildEffect) {
271
+ let link = e.depsTail;
272
+ while (link !== undefined) {
273
+ const prev = link.prevDep, dep = link.dep;
274
+ if (!('getter' in dep) && !('currentValue' in dep)) unlink(link, e);
275
+ link = prev;
276
+ }
277
+ }
278
+ if (e.cleanup) { runCleanup(e); if (!e.flags) return; }
279
+ e.depsTail = undefined;
280
+ e.flags = Watching | RecursedCheck;
281
+ const prevSub = activeSub;
282
+ activeSub = e;
283
+ try {
284
+ ++cycle; ++runDepth;
285
+ const r = e.fn();
286
+ e.cleanup = typeof r === 'function' ? r : undefined;
287
+ } catch (err) {
288
+ e.flags = None;
289
+ disposeAllDepsInReverse(e);
290
+ reportError(err, e.fn);
291
+ } finally {
292
+ --runDepth; activeSub = prevSub;
293
+ e.flags &= ~RecursedCheck;
294
+ purgeDeps(e);
295
+ }
296
+ } else if (e.deps !== undefined) {
297
+ e.flags = Watching | (flags & HasChildEffect);
298
+ }
299
+ }
300
+
301
+ function flush() {
302
+ try {
303
+ while (notifyIndex < queuedLength) {
304
+ const effect = queued[notifyIndex];
305
+ queued[notifyIndex++] = undefined;
306
+ run(effect);
307
+ }
308
+ } finally {
309
+ while (notifyIndex < queuedLength) {
310
+ const effect = queued[notifyIndex];
311
+ queued[notifyIndex++] = undefined;
312
+ effect.flags |= Watching | Recursed;
313
+ }
314
+ notifyIndex = 0;
315
+ queuedLength = 0;
316
+ if (queued.length > 64) queued.length = 64;
317
+ }
318
+ }
319
+
320
+ function computedOper() {
321
+ const flags = this.flags;
322
+ if (flags & Dirty || (flags & Pending && (checkDirty(this.deps, this) || (this.flags = flags & ~Pending, false)))) {
323
+ if (updateComputed(this)) {
324
+ const subs = this.subs;
325
+ if (subs !== undefined) shallowPropagate(subs);
326
+ }
327
+ } else if (!flags) {
328
+ this.flags = Mutable | RecursedCheck;
329
+ const prevSub = activeSub;
330
+ activeSub = this;
331
+ try { this.value = this.getter(); }
332
+ finally { activeSub = prevSub; this.flags &= ~RecursedCheck; }
333
+ }
334
+ const sub = activeSub;
335
+ if (sub !== undefined) link(this, sub, cycle);
336
+ return this.value;
337
+ }
338
+
339
+ function signalOper(...value) {
340
+ if (value.length) {
341
+ if (!Object.is(this.pendingValue, (this.pendingValue = value[0]))) {
342
+ this.flags = Mutable | Dirty;
343
+ const subs = this.subs;
344
+ if (subs !== undefined) {
345
+ propagate(subs, !!runDepth);
346
+ if (!batchDepth) flush();
347
+ }
348
+ }
349
+ } else {
350
+ if (this.flags & Dirty) {
351
+ if (updateSignal(this)) {
352
+ const subs = this.subs;
353
+ if (subs !== undefined) shallowPropagate(subs);
354
+ }
355
+ }
356
+ const sub = activeSub;
357
+ if (sub !== undefined) link(this, sub, cycle);
358
+ return this.currentValue;
359
+ }
360
+ }
361
+
362
+ function runCleanup(e) {
363
+ const cleanup = e.cleanup;
364
+ e.cleanup = undefined;
365
+ const prevSub = activeSub;
366
+ activeSub = undefined;
367
+ try { cleanup(); }
368
+ finally { activeSub = prevSub; }
369
+ }
370
+
371
+ function effectOper() {
372
+ effectScopeOper.call(this);
373
+ if (this.cleanup) runCleanup(this);
374
+ }
375
+
376
+ function effectScopeOper() {
377
+ this.flags = None;
378
+ disposeAllDepsInReverse(this);
379
+ const sub = this.subs;
380
+ if (sub !== undefined) unlink(sub);
381
+ }
382
+
383
+ function disposeAllDepsInReverse(sub) {
384
+ let link = sub.depsTail;
385
+ while (link !== undefined) {
386
+ const prev = link.prevDep;
387
+ unlink(link, sub);
388
+ link = prev;
389
+ }
390
+ }
391
+
392
+ function purgeDeps(sub) {
393
+ const depsTail = sub.depsTail;
394
+ let dep = depsTail !== undefined ? depsTail.nextDep : sub.deps;
395
+ while (dep !== undefined) dep = unlink(dep, sub);
396
+ }
397
+
398
+ export function untrack(fn) {
399
+ const prev = activeSub;
400
+ activeSub = undefined;
401
+ try { return fn(); }
402
+ finally { activeSub = prev; }
403
+ }
404
+
405
+ export function onMount(fn) {
406
+ return effect(() => {
407
+ const cleanup = untrack(fn);
408
+ return typeof cleanup === 'function' ? cleanup : undefined;
409
+ });
410
+ }
411
+
412
+ export function watch(source, cb, { immediate = false } = {}) {
413
+ let prev, first = true;
414
+ return effect(() => {
415
+ const value = source();
416
+ if (first) {
417
+ first = false;
418
+ prev = value;
419
+ if (immediate) untrack(() => cb(value, undefined));
420
+ return;
421
+ }
422
+ if (Object.is(prev, value)) return;
423
+ const old = prev;
424
+ prev = value;
425
+ untrack(() => cb(value, old));
426
+ });
427
+ }
428
+
429
+ export function local(key, initial) {
430
+ let value = initial;
431
+ let last;
432
+ try {
433
+ const raw = localStorage.getItem(key);
434
+ if (raw !== null) { value = JSON.parse(raw); last = raw; }
435
+ } catch { }
436
+ const s = signal(value);
437
+ effect(() => {
438
+ try {
439
+ const json = JSON.stringify(s());
440
+ if (last !== json) { localStorage.setItem(key, json); last = json; }
441
+ } catch { }
442
+ });
443
+ return s;
444
+ }
445
+
446
+ // ============================================================================
447
+ // DOM Rendering
448
+ // ============================================================================
3
449
 
4
450
  const DOC = typeof document !== 'undefined' ? document : null;
5
451
 
@@ -248,6 +694,23 @@ export function unmount(node) {
248
694
  if (node.parentNode) node.parentNode.removeChild(node);
249
695
  }
250
696
 
697
+ export function teleport(target = DOC.body) {
698
+ let scope, node;
699
+ const set = (fn) => {
700
+ scope?.();
701
+ scope = effectScope(() => { node = fn(); });
702
+ const nodes = (Array.isArray(node) ? node : [node])
703
+ .filter(n => n != null && n !== false && n !== true)
704
+ .map(n => (n instanceof Node ? n : DOC.createTextNode(String(n))));
705
+ while (target.firstChild) {
706
+ cleanupNode(target.firstChild);
707
+ target.removeChild(target.firstChild);
708
+ }
709
+ for (const n of nodes) target.appendChild(n);
710
+ };
711
+ return set;
712
+ }
713
+
251
714
  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";
252
715
 
253
716
  export const exposeTags = (target = typeof window !== 'undefined' ? window : null) => {
@@ -276,5 +739,84 @@ export const onDebounce = (ms, fn) => { let t; return e => { clearTimeout(t); t
276
739
  export const onKey = (key, fn) => e => { if (e.key === key) fn(e); };
277
740
  export const onEnter = fn => onKey("Enter", fn);
278
741
  export const onEscape = fn => onKey("Escape", fn);
742
+ export const onContextMenu = fn => e => { e.preventDefault(); fn(e); };
743
+ export const onRightClick = fn => e => { if (e.button === 2) fn(e); };
744
+ export const onSwipe = (dir, { distance = 50, threshold = 0.7 } = {}, fn) => {
745
+ let sx, sy, active;
746
+ const start = e => { const t = e.changedTouches || [e]; sx = t[0].clientX; sy = t[0].clientY; active = true; };
747
+ const end = e => {
748
+ if (!active) return;
749
+ const t = e.changedTouches || [e];
750
+ const dx = t[0].clientX - sx, dy = t[0].clientY - sy;
751
+ if (dir === 'x' && Math.abs(dx) > distance && Math.abs(dx) > Math.abs(dy) * threshold) { active = false; fn(e); }
752
+ if (dir === 'y' && Math.abs(dy) > distance && Math.abs(dy) > Math.abs(dx) * threshold) { active = false; fn(e); }
753
+ };
754
+ return h => {
755
+ h.addEventListener('touchstart', start, { passive: true });
756
+ h.addEventListener('touchend', end, { passive: true });
757
+ h.addEventListener('mousedown', start);
758
+ h.addEventListener('mouseup', end);
759
+ };
760
+ };
761
+ export const onPullRefresh = (threshold = 60, fn) => {
762
+ let startY, pulling;
763
+ const start = e => { const t = e.changedTouches || [e]; startY = t[0].clientY; pulling = true; };
764
+ const move = e => {
765
+ if (!pulling) return;
766
+ const t = e.changedTouches || [e];
767
+ if (t[0].clientY - startY > threshold) { pulling = false; fn(e); }
768
+ };
769
+ return h => {
770
+ h.addEventListener('touchstart', start, { passive: true });
771
+ h.addEventListener('touchmove', move, { passive: true });
772
+ };
773
+ };
279
774
  export const bindvalue = s => ({ value: () => s(), oninput: e => s(e.target.value) });
280
- export const bindcheck = s => ({ checked: () => !!s(), onchange: e => s(e.target.checked) });
775
+ export const bindcheck = s => ({ checked: () => !!s(), onchange: e => s(e.target.checked) });
776
+
777
+ export const resize = (el, opts = {}) => {
778
+ const { axis = 'both', min = 0, max = Infinity, handle, onStart, onResize, onEnd } = opts;
779
+ const w = signal(el.offsetWidth || 0);
780
+ const h = signal(el.offsetHeight || 0);
781
+
782
+ let sx, sy, sw, sh, active;
783
+
784
+ const start = e => {
785
+ if (handle && !handle.contains(e.target) && handle !== e.target) return;
786
+ const t = e.changedTouches || [e];
787
+ sx = t[0].clientX; sy = t[0].clientY;
788
+ sw = el.offsetWidth; sh = el.offsetHeight;
789
+ active = true;
790
+ document.addEventListener('pointermove', move);
791
+ document.addEventListener('pointerup', end);
792
+ document.addEventListener('pointercancel', end);
793
+ if (onStart) onStart();
794
+ };
795
+
796
+ const move = e => {
797
+ if (!active) return;
798
+ const t = e.changedTouches || [e];
799
+ const dx = t[0].clientX - sx, dy = t[0].clientY - sy;
800
+ if (axis === 'x' || axis === 'both') {
801
+ const nw = Math.min(max, Math.max(min, sw + dx));
802
+ if (nw !== w()) w(nw);
803
+ }
804
+ if (axis === 'y' || axis === 'both') {
805
+ const nh = Math.min(max, Math.max(min, sh + dy));
806
+ if (nh !== h()) h(nh);
807
+ }
808
+ if (onResize) onResize({ w: w(), h: h() });
809
+ };
810
+
811
+ const end = () => {
812
+ if (!active) return;
813
+ active = false;
814
+ document.removeEventListener('pointermove', move);
815
+ document.removeEventListener('pointerup', end);
816
+ document.removeEventListener('pointercancel', end);
817
+ if (onEnd) onEnd();
818
+ };
819
+
820
+ el.addEventListener('mousedown', start);
821
+ return { w, h };
822
+ };
@@ -1,444 +0,0 @@
1
- /* ALIEN SIGNALS */
2
- const None = 0, Mutable = 1, Watching = 2, RecursedCheck = 4,
3
- Recursed = 8, Dirty = 16, Pending = 32, HasChildEffect = 64;
4
-
5
- let errorHandler;
6
- export function onError(fn) { errorHandler = fn; }
7
- export function reportError(err, where) {
8
- if (errorHandler) {
9
- try { errorHandler(err, where); } catch { }
10
- } else {
11
- console.error('[sigpro] error in', where, err);
12
- }
13
- }
14
-
15
- function createReactiveSystem({ update, notify, unwatched }) {
16
- return { link, unlink, propagate, checkDirty, shallowPropagate };
17
-
18
- function link(dep, sub, version) {
19
- const prevDep = sub.depsTail;
20
- if (prevDep !== undefined && prevDep.dep === dep) return;
21
- const nextDep = prevDep !== undefined ? prevDep.nextDep : sub.deps;
22
- if (nextDep !== undefined && nextDep.dep === dep) {
23
- nextDep.version = version; sub.depsTail = nextDep; return;
24
- }
25
- const prevSub = dep.subsTail;
26
- if (prevSub !== undefined && prevSub.version === version && prevSub.sub === sub) return;
27
- const newLink = sub.depsTail = dep.subsTail = {
28
- version, dep, sub, prevDep, nextDep, prevSub, nextSub: undefined,
29
- };
30
- if (nextDep !== undefined) nextDep.prevDep = newLink;
31
- if (prevDep !== undefined) prevDep.nextDep = newLink; else sub.deps = newLink;
32
- if (prevSub !== undefined) prevSub.nextSub = newLink; else dep.subs = newLink;
33
- }
34
-
35
- function unlink(link, sub = link.sub) {
36
- const { dep, prevDep, nextDep, nextSub, prevSub } = link;
37
- if (nextDep !== undefined) nextDep.prevDep = prevDep; else sub.depsTail = prevDep;
38
- if (prevDep !== undefined) prevDep.nextDep = nextDep; else sub.deps = nextDep;
39
- if (nextSub !== undefined) nextSub.prevSub = prevSub; else dep.subsTail = prevSub;
40
- if (prevSub !== undefined) prevSub.nextSub = nextSub;
41
- else if ((dep.subs = nextSub) === undefined) unwatched(dep);
42
- return nextDep;
43
- }
44
-
45
- function propagate(link, innerWrite) {
46
- let next = link.nextSub, stack;
47
- top: do {
48
- const sub = link.sub;
49
- let flags = sub.flags;
50
- if (!(flags & (RecursedCheck | Recursed | Dirty | Pending))) {
51
- sub.flags = flags | Pending;
52
- if (innerWrite) sub.flags |= Recursed;
53
- } else if (!(flags & (RecursedCheck | Recursed))) {
54
- flags = None;
55
- } else if (!(flags & RecursedCheck)) {
56
- sub.flags = (flags & ~Recursed) | Pending;
57
- } else if (!(flags & (Dirty | Pending)) && isValidLink(link, sub)) {
58
- sub.flags = flags | Recursed | Pending;
59
- flags &= Mutable;
60
- } else flags = None;
61
- if (flags & Watching) notify(sub);
62
- if (flags & Mutable) {
63
- const subSubs = sub.subs;
64
- if (subSubs !== undefined) {
65
- const nextSub = (link = subSubs).nextSub;
66
- if (nextSub !== undefined) { stack = { value: next, prev: stack }; next = nextSub; }
67
- continue;
68
- }
69
- }
70
- if ((link = next) !== undefined) { next = link.nextSub; continue; }
71
- while (stack !== undefined) {
72
- link = stack.value; stack = stack.prev;
73
- if (link !== undefined) { next = link.nextSub; continue top; }
74
- }
75
- break;
76
- } while (true);
77
- }
78
-
79
- function checkDirty(link, sub) {
80
- let stack, checkDepth = 0, dirty = false;
81
- top: do {
82
- const dep = link.dep, flags = dep.flags;
83
- if (sub.flags & Dirty) dirty = true;
84
- else if ((flags & (Mutable | Dirty)) === (Mutable | Dirty)) {
85
- const subs = dep.subs;
86
- if (update(dep)) {
87
- if (subs.nextSub !== undefined) shallowPropagate(subs);
88
- dirty = true;
89
- }
90
- } else if ((flags & (Mutable | Pending)) === (Mutable | Pending)) {
91
- stack = { value: link, prev: stack };
92
- link = dep.deps; sub = dep; ++checkDepth; continue;
93
- }
94
- if (!dirty) {
95
- const nextDep = link.nextDep;
96
- if (nextDep !== undefined) { link = nextDep; continue; }
97
- }
98
- while (checkDepth--) {
99
- link = stack.value; stack = stack.prev;
100
- if (dirty) {
101
- const subs = sub.subs;
102
- if (update(sub)) {
103
- if (subs.nextSub !== undefined) shallowPropagate(subs);
104
- sub = link.sub; continue;
105
- }
106
- dirty = false;
107
- } else sub.flags &= ~Pending;
108
- sub = link.sub;
109
- const nextDep = link.nextDep;
110
- if (nextDep !== undefined) { link = nextDep; continue top; }
111
- }
112
- return dirty && !!sub.flags;
113
- } while (true);
114
- }
115
-
116
- function shallowPropagate(link) {
117
- do {
118
- const sub = link.sub, flags = sub.flags;
119
- if ((flags & (Pending | Dirty)) === Pending) {
120
- sub.flags = flags | Dirty;
121
- if ((flags & (Watching | RecursedCheck)) === Watching) notify(sub);
122
- }
123
- } while ((link = link.nextSub) !== undefined);
124
- }
125
-
126
- function isValidLink(checkLink, sub) {
127
- let link = sub.depsTail;
128
- while (link !== undefined) {
129
- if (link === checkLink) return true;
130
- link = link.prevDep;
131
- }
132
- return false;
133
- }
134
- }
135
-
136
- let cycle = 0, runDepth = 0, batchDepth = 0, notifyIndex = 0, queuedLength = 0;
137
- let activeSub;
138
- const queued = [];
139
-
140
- const { link, unlink, propagate, checkDirty, shallowPropagate } = createReactiveSystem({
141
- update(node) {
142
- if ('getter' in node) return updateComputed(node);
143
- if ('currentValue' in node) return updateSignal(node);
144
- node.flags = Mutable; return true;
145
- },
146
- notify(effect) {
147
- let insertIndex = queuedLength, firstInsertedIndex = insertIndex;
148
- do {
149
- queued[insertIndex++] = effect;
150
- effect.flags &= ~Watching;
151
- effect = effect.subs?.sub;
152
- if (effect === undefined || !(effect.flags & Watching)) break;
153
- } while (true);
154
- queuedLength = insertIndex;
155
- while (firstInsertedIndex < --insertIndex) {
156
- const left = queued[firstInsertedIndex];
157
- queued[firstInsertedIndex++] = queued[insertIndex];
158
- queued[insertIndex] = left;
159
- }
160
- },
161
- unwatched(node) {
162
- if ('getter' in node) {
163
- if (node.depsTail !== undefined) {
164
- node.flags = Mutable | Dirty;
165
- disposeAllDepsInReverse(node);
166
- }
167
- } else if ('currentValue' in node) {
168
- } else if ('fn' in node) {
169
- effectOper.call(node);
170
- } else {
171
- effectScopeOper.call(node);
172
- }
173
- },
174
- });
175
-
176
- export function signal(initialValue) {
177
- return signalOper.bind({
178
- currentValue: initialValue, pendingValue: initialValue,
179
- subs: undefined, subsTail: undefined, flags: Mutable,
180
- });
181
- }
182
-
183
- export function computed(getter) {
184
- return computedOper.bind({
185
- value: undefined, subs: undefined, subsTail: undefined,
186
- deps: undefined, depsTail: undefined, flags: None, getter,
187
- });
188
- }
189
-
190
- export function effect(fn) {
191
- if (typeof fn !== 'function') {
192
- console.error('[sigpro] effect() expects a function, got', typeof fn);
193
- return () => { };
194
- }
195
- const e = {
196
- fn, cleanup: undefined,
197
- subs: undefined, subsTail: undefined,
198
- deps: undefined, depsTail: undefined,
199
- flags: Watching | RecursedCheck,
200
- };
201
- const prevSub = activeSub;
202
- activeSub = e;
203
- if (prevSub !== undefined) { link(e, prevSub, 0); prevSub.flags |= HasChildEffect; }
204
- try {
205
- ++runDepth;
206
- const r = e.fn();
207
- e.cleanup = typeof r === 'function' ? r : undefined;
208
- } catch (err) {
209
- e.flags = None;
210
- disposeAllDepsInReverse(e);
211
- reportError(err, e.fn);
212
- } finally {
213
- --runDepth; activeSub = prevSub;
214
- e.flags &= ~RecursedCheck;
215
- }
216
- return effectOper.bind(e);
217
- }
218
-
219
- export function effectScope(fn) {
220
- const e = {
221
- deps: undefined, depsTail: undefined,
222
- subs: undefined, subsTail: undefined, flags: Mutable,
223
- };
224
- const prevSub = activeSub;
225
- activeSub = e;
226
- if (prevSub !== undefined) { link(e, prevSub, 0); prevSub.flags |= HasChildEffect; }
227
- try { fn(); }
228
- finally { activeSub = prevSub; }
229
- return effectScopeOper.bind(e);
230
- }
231
-
232
- export function batch(fn) {
233
- ++batchDepth;
234
- try { return fn(); }
235
- finally { if (!--batchDepth) flush(); }
236
- }
237
-
238
- function updateComputed(c) {
239
- if (c.flags & HasChildEffect) {
240
- let link = c.depsTail;
241
- while (link !== undefined) {
242
- const prev = link.prevDep, dep = link.dep;
243
- if (!('getter' in dep) && !('currentValue' in dep)) unlink(link, c);
244
- link = prev;
245
- }
246
- }
247
- c.depsTail = undefined;
248
- c.flags = Mutable | RecursedCheck;
249
- const prevSub = activeSub;
250
- activeSub = c;
251
- try {
252
- ++cycle;
253
- const oldValue = c.value;
254
- return !Object.is(oldValue, (c.value = c.getter(oldValue)));
255
- } finally {
256
- activeSub = prevSub;
257
- c.flags &= ~RecursedCheck;
258
- purgeDeps(c);
259
- }
260
- }
261
-
262
- function updateSignal(s) {
263
- s.flags = Mutable;
264
- return !Object.is(s.currentValue, (s.currentValue = s.pendingValue));
265
- }
266
-
267
- function run(e) {
268
- const flags = e.flags;
269
- if (flags & Dirty || (flags & Pending && checkDirty(e.deps, e))) {
270
- if (flags & HasChildEffect) {
271
- let link = e.depsTail;
272
- while (link !== undefined) {
273
- const prev = link.prevDep, dep = link.dep;
274
- if (!('getter' in dep) && !('currentValue' in dep)) unlink(link, e);
275
- link = prev;
276
- }
277
- }
278
- if (e.cleanup) { runCleanup(e); if (!e.flags) return; }
279
- e.depsTail = undefined;
280
- e.flags = Watching | RecursedCheck;
281
- const prevSub = activeSub;
282
- activeSub = e;
283
- try {
284
- ++cycle; ++runDepth;
285
- const r = e.fn();
286
- e.cleanup = typeof r === 'function' ? r : undefined;
287
- } catch (err) {
288
- e.flags = None;
289
- disposeAllDepsInReverse(e);
290
- reportError(err, e.fn);
291
- } finally {
292
- --runDepth; activeSub = prevSub;
293
- e.flags &= ~RecursedCheck;
294
- purgeDeps(e);
295
- }
296
- } else if (e.deps !== undefined) {
297
- e.flags = Watching | (flags & HasChildEffect);
298
- }
299
- }
300
-
301
- function flush() {
302
- try {
303
- while (notifyIndex < queuedLength) {
304
- const effect = queued[notifyIndex];
305
- queued[notifyIndex++] = undefined;
306
- run(effect);
307
- }
308
- } finally {
309
- while (notifyIndex < queuedLength) {
310
- const effect = queued[notifyIndex];
311
- queued[notifyIndex++] = undefined;
312
- effect.flags |= Watching | Recursed;
313
- }
314
- notifyIndex = 0;
315
- queuedLength = 0;
316
- if (queued.length > 64) queued.length = 64;
317
- }
318
- }
319
-
320
- function computedOper() {
321
- const flags = this.flags;
322
- if (flags & Dirty || (flags & Pending && (checkDirty(this.deps, this) || (this.flags = flags & ~Pending, false)))) {
323
- if (updateComputed(this)) {
324
- const subs = this.subs;
325
- if (subs !== undefined) shallowPropagate(subs);
326
- }
327
- } else if (!flags) {
328
- this.flags = Mutable | RecursedCheck;
329
- const prevSub = activeSub;
330
- activeSub = this;
331
- try { this.value = this.getter(); }
332
- finally { activeSub = prevSub; this.flags &= ~RecursedCheck; }
333
- }
334
- const sub = activeSub;
335
- if (sub !== undefined) link(this, sub, cycle);
336
- return this.value;
337
- }
338
-
339
- function signalOper(...value) {
340
- if (value.length) {
341
- if (!Object.is(this.pendingValue, (this.pendingValue = value[0]))) {
342
- this.flags = Mutable | Dirty;
343
- const subs = this.subs;
344
- if (subs !== undefined) {
345
- propagate(subs, !!runDepth);
346
- if (!batchDepth) flush();
347
- }
348
- }
349
- } else {
350
- if (this.flags & Dirty) {
351
- if (updateSignal(this)) {
352
- const subs = this.subs;
353
- if (subs !== undefined) shallowPropagate(subs);
354
- }
355
- }
356
- const sub = activeSub;
357
- if (sub !== undefined) link(this, sub, cycle);
358
- return this.currentValue;
359
- }
360
- }
361
-
362
- function runCleanup(e) {
363
- const cleanup = e.cleanup;
364
- e.cleanup = undefined;
365
- const prevSub = activeSub;
366
- activeSub = undefined;
367
- try { cleanup(); }
368
- finally { activeSub = prevSub; }
369
- }
370
-
371
- function effectOper() {
372
- effectScopeOper.call(this);
373
- if (this.cleanup) runCleanup(this);
374
- }
375
-
376
- function effectScopeOper() {
377
- this.flags = None;
378
- disposeAllDepsInReverse(this);
379
- const sub = this.subs;
380
- if (sub !== undefined) unlink(sub);
381
- }
382
-
383
- function disposeAllDepsInReverse(sub) {
384
- let link = sub.depsTail;
385
- while (link !== undefined) {
386
- const prev = link.prevDep;
387
- unlink(link, sub);
388
- link = prev;
389
- }
390
- }
391
-
392
- function purgeDeps(sub) {
393
- const depsTail = sub.depsTail;
394
- let dep = depsTail !== undefined ? depsTail.nextDep : sub.deps;
395
- while (dep !== undefined) dep = unlink(dep, sub);
396
- }
397
-
398
- export function untrack(fn) {
399
- const prev = activeSub;
400
- activeSub = undefined;
401
- try { return fn(); }
402
- finally { activeSub = prev; }
403
- }
404
-
405
- export function onMount(fn) {
406
- return effect(() => {
407
- const cleanup = untrack(fn);
408
- return typeof cleanup === 'function' ? cleanup : undefined;
409
- });
410
- }
411
-
412
- export function watch(source, cb, { immediate = false } = {}) {
413
- let prev, first = true;
414
- return effect(() => {
415
- const value = source();
416
- if (first) {
417
- first = false;
418
- prev = value;
419
- if (immediate) untrack(() => cb(value, undefined));
420
- return;
421
- }
422
- if (Object.is(prev, value)) return;
423
- const old = prev;
424
- prev = value;
425
- untrack(() => cb(value, old));
426
- });
427
- }
428
-
429
- export function local(key, initial) {
430
- let value = initial;
431
- let last;
432
- try {
433
- const raw = localStorage.getItem(key);
434
- if (raw !== null) { value = JSON.parse(raw); last = raw; }
435
- } catch { }
436
- const s = signal(value);
437
- effect(() => {
438
- try {
439
- const json = JSON.stringify(s());
440
- if (last !== json) { localStorage.setItem(key, json); last = json; }
441
- } catch { }
442
- });
443
- return s;
444
- }