-
Notifications
You must be signed in to change notification settings - Fork 1
/
BaseElement.ts
97 lines (81 loc) · 2.18 KB
/
BaseElement.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
import _ from 'lodash';
import { ParserOptions } from '@babel/parser';
import { BaseNode, Path, Node, Instance, Props } from '../types';
import { flattenPath } from '../util';
export interface IElement {
new (props?: Props, parserOptions?: ParserOptions): BaseElement;
propTypes: object;
defaultProps: Props;
}
export interface Meta {
bodyPath: Path;
parentBodyPath: Path | null;
}
export default class BaseElement implements Instance {
static defaultProps: Props = {};
static propTypes: object = {};
node: Node;
props: Props;
children: BaseElement[] = [];
meta: Meta = {
bodyPath: 'body.body',
parentBodyPath: null
};
getBodyPath(path?: Path | null): string {
return flattenPath(path || this.meta.bodyPath);
}
getBody(
body: BaseNode | BaseNode[],
path?: Path | null
): BaseNode | BaseNode[] {
const bodyPath = this.getBodyPath(path);
if (!bodyPath.length) return body;
return _.get(body, bodyPath);
}
setBody(
body: BaseNode | BaseNode[],
value: BaseNode | BaseNode[],
path?: Path | null
): BaseNode | BaseNode[] {
const bodyPath = this.getBodyPath(path);
if (!bodyPath.length) return body;
return _.set(body, bodyPath, value);
}
constructor(
baseNode: BaseNode | BaseNode[],
props: Props = {},
meta?: Partial<Meta>
) {
if (Array.isArray(baseNode)) throw new Error('cannot be array');
if (meta) {
this.meta = {
...this.meta,
...meta
};
}
this.node = baseNode;
this.props = props;
}
appendChild(child: BaseElement) {
const body = this.getBody(this.node, child.meta.parentBodyPath);
this.children.push(child);
if (Array.isArray(body)) {
body.push(child.node);
} else {
this.setBody(this.node, child.node, child.meta.parentBodyPath);
}
}
removeChild(child: BaseElement) {
const body = this.getBody(this.node, child.meta.parentBodyPath);
if (!body || !Array.isArray(body)) return;
this.children.splice(this.children.indexOf(child), 1);
body.splice(body.indexOf(child.node), 1);
}
commitMount() {}
commitUpdate(newProps: Props) {
this.props = {
...this.props,
...newProps
};
}
}