-
-
Notifications
You must be signed in to change notification settings - Fork 99
/
Copy pathindex.ts
422 lines (378 loc) · 11.3 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
import { options, Component } from "preact";
import { useRef, useMemo, useEffect } from "preact/hooks";
import {
signal,
computed,
batch,
effect,
Signal,
type ReadonlySignal,
} from "@preact/signals-core";
import {
VNode,
OptionsTypes,
HookFn,
Effect,
PropertyUpdater,
AugmentedComponent,
AugmentedElement as Element,
} from "./internal";
export { signal, computed, batch, effect, Signal, type ReadonlySignal };
const HAS_PENDING_UPDATE = 1 << 0;
const HAS_HOOK_STATE = 1 << 1;
const HAS_COMPUTEDS = 1 << 2;
// Install a Preact options hook
function hook<T extends OptionsTypes>(hookName: T, hookFn: HookFn<T>) {
// @ts-ignore-next-line private options hooks usage
options[hookName] = hookFn.bind(null, options[hookName] || (() => {}));
}
let currentComponent: AugmentedComponent | undefined;
let finishUpdate: (() => void) | undefined;
function setCurrentUpdater(updater?: Effect) {
// end tracking for the current update:
if (finishUpdate) finishUpdate();
// start tracking the new update:
finishUpdate = updater && updater._start();
}
function createUpdater(update: () => void) {
let updater!: Effect;
effect(function (this: Effect) {
updater = this;
});
updater._callback = update;
return updater;
}
/** @todo This may be needed for complex prop value detection. */
// function isSignalValue(value: any): value is Signal {
// if (typeof value !== "object" || value == null) return false;
// if (value instanceof Signal) return true;
// // @TODO: uncomment this when we land Reactive (ideally behind a brand check)
// // for (let i in value) if (value[i] instanceof Signal) return true;
// return false;
// }
/**
* A wrapper component that renders a Signal directly as a Text node.
* @todo: in Preact 11, just decorate Signal with `type:null`
*/
function Text(this: AugmentedComponent, { data }: { data: Signal }) {
// hasComputeds.add(this);
// Store the props.data signal in another signal so that
// passing a new signal reference re-runs the text computed:
const currentSignal = useSignal(data);
currentSignal.value = data;
const s = useMemo(() => {
// mark the parent component as having computeds so it gets optimized
let v = this.__v;
while ((v = v.__!)) {
if (v.__c) {
v.__c._updateFlags |= HAS_COMPUTEDS;
break;
}
}
// Replace this component's vdom updater with a direct text one:
this._updater!._callback = () => {
(this.base as Text).data = s.peek();
};
return computed(() => {
let data = currentSignal.value;
let s = data.value;
return s === 0 ? 0 : s === true ? "" : s || "";
});
}, []);
return s.value;
}
Text.displayName = "_st";
Object.defineProperties(Signal.prototype, {
constructor: { configurable: true },
type: { configurable: true, value: Text },
props: {
configurable: true,
get() {
return { data: this };
},
},
// Setting a VNode's _depth to 1 forces Preact to clone it before modifying:
// https://github.com/preactjs/preact/blob/d7a433ee8463a7dc23a05111bb47de9ec729ad4d/src/diff/children.js#L77
// @todo remove this for Preact 11
__b: { configurable: true, value: 1 },
});
/** Inject low-level property/attribute bindings for Signals into Preact's diff */
hook(OptionsTypes.DIFF, (old, vnode) => {
if (typeof vnode.type === "string") {
let signalProps: Record<string, any> | undefined;
let props = vnode.props;
for (let i in props) {
if (i === "children") continue;
let value = props[i];
if (value instanceof Signal) {
if (!signalProps) vnode.__np = signalProps = {};
signalProps[i] = value;
props[i] = value.peek();
}
}
}
old(vnode);
});
/** Set up Updater before rendering a component */
hook(OptionsTypes.RENDER, (old, vnode) => {
setCurrentUpdater();
let updater;
let component = vnode.__c;
if (component) {
component._updateFlags &= ~HAS_PENDING_UPDATE;
updater = component._updater;
if (updater === undefined) {
component._updater = updater = createUpdater(() => {
component._updateFlags |= HAS_PENDING_UPDATE;
component.setState({});
});
}
}
currentComponent = component;
setCurrentUpdater(updater);
old(vnode);
});
/** Finish current updater if a component errors */
hook(OptionsTypes.CATCH_ERROR, (old, error, vnode, oldVNode) => {
setCurrentUpdater();
currentComponent = undefined;
old(error, vnode, oldVNode);
});
/** Finish current updater after rendering any VNode */
hook(OptionsTypes.DIFFED, (old, vnode) => {
setCurrentUpdater();
currentComponent = undefined;
let dom: Element;
// vnode._dom is undefined during string rendering,
// so we use this to skip prop subscriptions during SSR.
if (typeof vnode.type === "string" && (dom = vnode.__e as Element)) {
let props = vnode.__np;
let renderedProps = vnode.props;
if (props) {
let updaters = dom._updaters;
if (updaters) {
for (let prop in updaters) {
let updater = updaters[prop];
if (updater !== undefined && !(prop in props)) {
updater._dispose();
// @todo we could just always invoke _dispose() here
updaters[prop] = undefined;
}
}
} else {
updaters = {};
dom._updaters = updaters;
}
for (let prop in props) {
let updater = updaters[prop];
let signal = props[prop];
if (updater === undefined) {
updater = createPropUpdater(dom, prop, signal, renderedProps);
updaters[prop] = updater;
} else {
updater._update(signal, renderedProps);
}
}
}
}
old(vnode);
});
function createPropUpdater(
dom: Element,
prop: string,
propSignal: Signal,
props: Record<string, any>
): PropertyUpdater {
const setAsProperty =
prop in dom &&
// SVG elements need to go through `setAttribute` because they
// expect things like SVGAnimatedTransformList instead of strings.
// @ts-ignore
dom.ownerSVGElement === undefined;
const changeSignal = signal(propSignal);
return {
_update: (newSignal: Signal, newProps: typeof props) => {
changeSignal.value = newSignal;
props = newProps;
},
_dispose: effect(() => {
const value = changeSignal.value.value;
// If Preact just rendered this value, don't render it again:
if (props[prop] === value) return;
props[prop] = value;
if (setAsProperty) {
// @ts-ignore-next-line silly
dom[prop] = value;
} else if (value) {
dom.setAttribute(prop, value);
} else {
dom.removeAttribute(prop);
}
}),
};
}
/** Unsubscribe from Signals when unmounting components/vnodes */
hook(OptionsTypes.UNMOUNT, (old, vnode: VNode) => {
if (typeof vnode.type === "string") {
let dom = vnode.__e as Element | undefined;
// vnode._dom is undefined during string rendering
if (dom) {
const updaters = dom._updaters;
if (updaters) {
dom._updaters = undefined;
for (let prop in updaters) {
let updater = updaters[prop];
if (updater) updater._dispose();
}
}
}
} else {
let component = vnode.__c;
if (component) {
const updater = component._updater;
if (updater) {
component._updater = undefined;
updater._dispose();
}
}
}
old(vnode);
});
/** Mark components that use hook state so we can skip sCU optimization. */
hook(OptionsTypes.HOOK, (old, component, index, type) => {
if (type < 3)
(component as AugmentedComponent)._updateFlags |= HAS_HOOK_STATE;
old(component, index, type);
});
/**
* Auto-memoize components that use Signals/Computeds.
* Note: Does _not_ optimize components that use hook/class state.
*/
Component.prototype.shouldComponentUpdate = function (
this: AugmentedComponent,
props,
state
) {
// @todo: Once preactjs/preact#3671 lands, this could just use `currentUpdater`:
const updater = this._updater;
const hasSignals = updater && updater._sources !== undefined;
// let reason;
// if (!hasSignals && !hasComputeds.has(this)) {
// reason = "no signals or computeds";
// } else if (hasPendingUpdate.has(this)) {
// reason = "has pending update";
// } else if (hasHookState.has(this)) {
// reason = "has hook state";
// }
// if (reason) {
// if (!this) reason += " (`this` bug)";
// console.log("not optimizing", this?.constructor?.name, ": ", reason, {
// details: {
// hasSignals,
// hasComputeds: hasComputeds.has(this),
// hasPendingUpdate: hasPendingUpdate.has(this),
// hasHookState: hasHookState.has(this),
// deps: Array.from(updater._deps),
// updater,
// },
// });
// }
// if this component used no signals or computeds, update:
if (!hasSignals && !(this._updateFlags & HAS_COMPUTEDS)) return true;
// if there is a pending re-render triggered from Signals,
// or if there is hook or class state, update:
if (this._updateFlags & (HAS_PENDING_UPDATE | HAS_HOOK_STATE)) return true;
// @ts-ignore
for (let i in state) return true;
// if any non-Signal props changed, update:
for (let i in props) {
if (i !== "__source" && props[i] !== this.props[i]) return true;
}
for (let i in this.props) if (!(i in props)) return true;
// this is a purely Signal-driven component, don't update:
return false;
};
export function useSignal<T>(value: T) {
return useMemo(() => signal<T>(value), []);
}
export function useComputed<T>(compute: () => T) {
const $compute = useRef(compute);
$compute.current = compute;
(currentComponent as AugmentedComponent)._updateFlags |= HAS_COMPUTEDS;
return useMemo(() => computed<T>(() => $compute.current()), []);
}
export function useSignalEffect(cb: () => void | (() => void)) {
const callback = useRef(cb);
callback.current = cb;
useEffect(() => {
return effect(() => {
callback.current();
});
}, []);
}
/**
* @todo Determine which Reactive implementation we'll be using.
* @internal
*/
// export function useReactive<T extends object>(value: T): Reactive<T> {
// return useMemo(() => reactive<T>(value), []);
// }
/**
* @internal
* Update a Reactive's using the properties of an object or other Reactive.
* Also works for Signals.
* @example
* // Update a Reactive with Object.assign()-like syntax:
* const r = reactive({ name: "Alice" });
* update(r, { name: "Bob" });
* update(r, { age: 42 }); // property 'age' does not exist in type '{ name?: string }'
* update(r, 2); // '2' has no properties in common with '{ name?: string }'
* console.log(r.name.value); // "Bob"
*
* @example
* // Update a Reactive with the properties of another Reactive:
* const A = reactive({ name: "Alice" });
* const B = reactive({ name: "Bob", age: 42 });
* update(A, B);
* console.log(`${A.name} is ${A.age}`); // "Bob is 42"
*
* @example
* // Update a signal with assign()-like syntax:
* const s = signal(42);
* update(s, "hi"); // Argument type 'string' not assignable to type 'number'
* update(s, {}); // Argument type '{}' not assignable to type 'number'
* update(s, 43);
* console.log(s.value); // 43
*
* @param obj The Reactive or Signal to be updated
* @param update The value, Signal, object or Reactive to update `obj` to match
* @param overwrite If `true`, any properties `obj` missing from `update` are set to `undefined`
*/
/*
export function update<T extends SignalOrReactive>(
obj: T,
update: Partial<Unwrap<T>>,
overwrite = false
) {
if (obj instanceof Signal) {
obj.value = peekValue(update);
} else {
for (let i in update) {
if (i in obj) {
obj[i].value = peekValue(update[i]);
} else {
let sig = signal(peekValue(update[i]));
sig[KEY] = i;
obj[i] = sig;
}
}
if (overwrite) {
for (let i in obj) {
if (!(i in update)) {
obj[i].value = undefined;
}
}
}
}
}
*/