-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathabode.ts
More file actions
256 lines (216 loc) · 6.63 KB
/
abode.ts
File metadata and controls
256 lines (216 loc) · 6.63 KB
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
import { getCurrentScript } from 'tiny-current-script';
import { createElement, FC } from 'react';
import { createRoot, Root } from 'react-dom/client';
interface RegisteredComponents {
[key: string]: {
module: Promise<any>;
options?: { propParsers?: PropParsers };
};
}
interface Props {
[key: string]: string;
}
interface Options {
propParsers?: PropParsers;
}
interface PropParsers {
[key: string]: ParseFN;
}
interface HTMLElementAttributes {
[key: string]: string;
}
interface PopulateOptions {
attributes?: HTMLElementAttributes;
callback?: () => void;
}
export type RegisterPromise = () => Promise<any>;
export type RegisterComponent = () => FC<any>;
export type RegisterFN = RegisterPromise | RegisterComponent;
export type ParseFN = (rawProp: string) => any;
export let componentSelector = 'data-component';
export let components: RegisteredComponents = {};
export let unPopulatedElements: Element[] = [];
export const register = (name: string, fn: RegisterFN, options?: Options) => {
components[name] = { module: retry(fn, 10, 20), options };
};
export const unRegisterAllComponents = () => {
components = {};
};
export const delay = (ms: number) => new Promise(res => setTimeout(res, ms));
const retry = async (
fn: () => any,
times: number,
delayTime: number
): Promise<any> => {
try {
return await fn();
} catch (err) {
if (times > 1) {
await delay(delayTime);
return retry(fn, times - 1, delayTime * 2);
} else {
throw new Error(err as string);
}
}
};
export const setComponentSelector = (selector: string) => {
componentSelector = selector;
};
export const getRegisteredComponents = () => {
return components;
};
export const getActiveComponents = () => {
return Array.from(
new Set(getAbodeElements().map(el => el.getAttribute(componentSelector)))
);
};
// start prop logic
export const getCleanPropName = (raw: string): string => {
return raw.replace('data-prop-', '').replace(/-./g, x => x.toUpperCase()[1]);
};
export const getElementProps = (
el: Element | HTMLScriptElement,
options?: Options
): Props => {
const props: { [key: string]: string } = {};
if (el?.attributes) {
const rawProps = Array.from(el.attributes).filter(attribute =>
attribute.name.startsWith('data-prop-')
);
rawProps.forEach(prop => {
const componentName = getComponentName(el) ?? '';
const propName = getCleanPropName(prop.name);
const propParser =
options?.propParsers?.[propName] ??
components[componentName]?.options?.propParsers?.[propName];
if (propParser) {
// custom parse function for prop
props[propName] = propParser(prop.value);
} else {
// default json parsing
if (/^0+\d+$/.test(prop.value)) {
/*
ie11 bug fix;
in ie11 JSON.parse will parse a string with leading zeros followed
by digits, e.g. '00012' will become 12, whereas in other browsers
an exception will be thrown by JSON.parse
*/
props[propName] = prop.value;
} else {
try {
props[propName] = JSON.parse(prop.value);
} catch (e) {
props[propName] = prop.value;
}
}
}
});
}
return props;
};
export const getScriptProps = (options?: Options) => {
const element = getCurrentScript();
if (element === null) {
throw new Error('Failed to get current script');
}
return getElementProps(element, options);
};
// end prop logic
// start element logic
export const getAbodeElements = (): Element[] => {
return Array.from(document.querySelectorAll(`[${componentSelector}]`)).filter(
el => {
const component = el.getAttribute(componentSelector);
// It should exist in registered components
return component && components[component];
}
);
};
export const setUnpopulatedElements = () => {
unPopulatedElements = getAbodeElements().filter(
el => !el.getAttribute('react-abode-populated')
);
};
export const setAttributes = (
el: Element,
attributes: HTMLElementAttributes
) => {
Object.entries(attributes).forEach(([k, v]) => el.setAttribute(k, v));
};
// end element logic
function getComponentName(el: Element) {
return Array.from(el.attributes).find(at => at.name === componentSelector)
?.value;
}
export const renderAbode = async (el: Element, root: Root) => {
const props = getElementProps(el);
const componentName = getComponentName(el);
if (!componentName || componentName === '') {
throw new Error(
`not all react-abode elements have a value for ${componentSelector}`
);
}
const module = await components[componentName]?.module;
if (!module) {
throw new Error(`no component registered for ${componentName}`);
}
const element = module.default || module;
root.render(createElement(element, props));
};
export const trackPropChanges = (el: Element, root: Root) => {
if (MutationObserver) {
const observer = new MutationObserver(() => {
renderAbode(el, root);
});
observer.observe(el, { attributes: true });
}
};
function unmountOnNodeRemoval(element: any, root: Root) {
const observer = new MutationObserver(function() {
function isDetached(el: any): any {
if (el.parentNode === document) {
return false;
} else if (el.parentNode === null) {
return true;
} else {
return isDetached(el.parentNode);
}
}
if (isDetached(element)) {
observer.disconnect();
root.unmount();
}
});
observer.observe(document, {
childList: true,
subtree: true,
});
}
export const update = async (
elements: Element[],
options?: PopulateOptions
) => {
// tag first, since adding components is a slow process and will cause components to get iterated multiple times
elements.forEach(el => el.setAttribute('react-abode-populated', 'true'));
elements.forEach(el => {
const root = createRoot(el);
if (options?.attributes) setAttributes(el, options.attributes);
renderAbode(el, root);
trackPropChanges(el, root);
unmountOnNodeRemoval(el, root);
});
};
const checkForAndHandleNewComponents = async (options?: PopulateOptions) => {
setUnpopulatedElements();
if (unPopulatedElements.length) {
await update(unPopulatedElements, options);
unPopulatedElements = [];
if (options?.callback) options.callback();
}
};
export const populate = async (options?: PopulateOptions) => {
await checkForAndHandleNewComponents(options);
const callback = await checkForAndHandleNewComponents(options);
const observer = new MutationObserver(async() => callback);
observer.observe(document.body, {childList: true, subtree: true});
};