/
react.ts
80 lines (72 loc) · 2.13 KB
/
react.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
import React, { useState, useRef, useEffect } from 'react';
import { manage, run } from '.';
import type { Managed, ManateEvent } from './models';
export class Component<P = {}, S = {}> extends React.Component<P, S> {
public managed?: Managed<P>;
public isTrigger!: (event: ManateEvent) => boolean;
public constructor(props: Readonly<P>) {
super(props);
// rewrite render()
const render = this.render.bind(this);
this.render = () => {
this.dispose();
this.managed = manage(this.props);
const [result, isTrigger] = run(this.managed, render);
this.isTrigger = isTrigger;
this.managed.$e.on(this.listener);
return result;
};
// rewrite componentDidMount()
const componentDidMount = this.componentDidMount ? this.componentDidMount.bind(this) : () => {};
this.componentDidMount = () => {
// strict mode re-mount
if (!this.managed) {
this.managed = manage(this.props);
this.managed.$e.on(this.listener);
}
componentDidMount();
};
// rewrite componentWillUnmount()
const componentWillUnmount = this.componentWillUnmount ? this.componentWillUnmount.bind(this) : () => {};
this.componentWillUnmount = () => {
this.dispose();
componentWillUnmount();
};
}
public listener = (event: ManateEvent) => {
if (this.isTrigger(event)) {
this.forceUpdate();
}
};
public dispose() {
this.managed?.dispose();
this.managed = undefined;
}
}
export const auto = (render: () => JSX.Element, props): JSX.Element => {
const prev = useRef<() => void>();
prev.current?.();
const dispose = () => {
managed?.dispose();
managed = undefined;
};
prev.current = dispose;
useEffect(() => {
if (!managed) {
// strict mode re-mount
managed = manage(props);
managed.$e.on(listener);
}
return dispose;
}, []);
let managed = manage(props);
const [result, isTrigger] = run(managed, render);
const [, refresh] = useState(0);
const listener = (event: ManateEvent) => {
if (isTrigger(event)) {
refresh((i) => i + 1);
}
};
managed.$e.on(listener);
return result;
};