-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreact.svelte.ts
93 lines (86 loc) · 1.88 KB
/
react.svelte.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
import { has } from 'lodash-es';
import { setContext, untrack } from 'svelte';
export interface RefObject<T> {
readonly current: T | null;
}
export type pluginTypes = any;
type Dispatch<A> = (value: A) => void;
type SetStateAction<S> = S | ((prevState: S) => S);
export type HTMLAttributes = any;
type temp<T> = (props?: T) => T;
type setState<T> = T | temp<T>;
export function useState<T>(state: T | temp<T>) {
let value;
if (typeof state == 'function') {
value = state();
} else {
value = state;
}
let s = $state<T>(value);
const getState: () => T = function () {
return s;
};
//@ts-expect-error
getState._custom_source = 'svelte';
return [
getState,
(newValue: setState<T>): T => {
if (typeof newValue === 'function') {
s = newValue(s);
return s;
}
s = newValue;
return s;
}
] as const;
}
function useEffect(func: () => void, dep?: any[]) {
const cleanup = {
fn: () => {
console.log('no cleanup fn');
}
};
if (dep) {
$effect(() => {
for (const d of dep) {
if (has(d, '_custom_source')) {
d();
}
}
untrack(() => {
cleanup.fn = func();
});
return cleanup.fn;
});
} else $effect(func);
}
export { useEffect };
//TODO cant just return an value, wont be reactive
export function useCallback<T>(fn: T, dep?: any) {
const b = $derived(fn);
return b;
}
//TODO , cant just return an value
export function useMemo<T>(fn: () => T, dep?: any) {
const closure = () => {
if (dep) {
dep;
return untrack(fn);
}
return fn();
};
const data = $derived(closure());
return data;
}
//TODO , cant just return an value
export function useMemoed<T>(fn: () => T, dep?: any) {
const data = $derived(fn());
return () => data;
}
export function useRef<T>(param: T | null) {
let state = $state<{ current: T }>({ current: param });
return state;
}
export function createContext<T>(config) {
return setContext<T>('', config);
}