-
-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathcustom-element.js
More file actions
277 lines (242 loc) · 9.62 KB
/
Copy pathcustom-element.js
File metadata and controls
277 lines (242 loc) · 9.62 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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
import { createHooks } from "../hooks/create-hooks.js";
import { flat, isHydrate } from "../utils.js";
import { ParseError } from "./errors.js";
import { setPrototype, transformValue } from "./set-prototype.js";
export { Any, createType } from "./set-prototype.js";
let ID = 0;
/**
*
* @param {Element & {dataset?:object}} node
* @returns {string|number}
*/
const getHydrateId = (node) => {
const id = (node?.dataset || {})?.hydrate || "";
if (id) {
return id;
}
return `c${ID++}`;
};
/**
* @type {import("component").C}
*/
export const c = (component, base) => {
/**
* @type {import("./set-prototype").Attrs}
*/
const attrs = {};
/**
* @type {import("./set-prototype").Values}
*/
const values = {};
const { props, styles, name } = component;
const className = (name[0] || "").toUpperCase() + name.slice(1);
/**
* @todo Discover a more aesthetic solution at the type level
* TS tries to set local class rules, these should be ignored
* @type {any}
*/
const ctx = {
[className]: class extends (base || HTMLElement) {
constructor() {
super();
this._setup();
this._render = () => component({ ...this._props });
for (const prop in values) {
if (Object.prototype.hasOwnProperty.call(values, prop)) {
this[prop] = values[prop];
}
}
}
/**
* @returns {import("core").Sheets}
*/
static get styles() {
// @ts-ignore
return [super.styles, styles];
}
async _setup() {
// _setup only continues if _props has not been defined
if (this._props) return;
this._props = {};
/**
* @type {Node}
*/
let lastParentMount;
/**
* @type {Node}
*/
let lastParentUnmount;
this.mounted = new Promise((resolve) => {
this.mount = () => {
resolve();
if (lastParentMount != this.parentNode) {
this.update();
lastParentMount = this.parentNode;
}
};
});
this.unmounted = new Promise((resolve) => {
this.unmount = () => {
resolve();
/**
* to recycle the node, its cycle must be closed and
* the cycle depends on the parent to preserve the
* state in case the nodes move within the same
* parent as a result of the use of keys
*/
lastParentUnmount =
lastParentUnmount || lastParentMount;
if (
lastParentUnmount != lastParentMount ||
!this.isConnected
) {
hooks.cleanEffects(true)()();
lastParentUnmount = lastParentMount;
}
};
});
this.symbolId = this.symbolId || Symbol(className);
const hooks = createHooks(
() => this.update(),
this,
getHydrateId(this),
);
let prevent;
let firstRender = true;
// some DOM emulators don't define dataset
const hydrate = isHydrate(this);
this.update = () => {
if (!prevent) {
prevent = true;
/**
* this.updated is defined at the runtime of the render,
* if it fails it is caught by mistake to unlock prevent
*/
this.updated = (this.updated || this.mounted)
.then(() => {
try {
const result = hooks.load(this._render);
const cleanUseLayoutEffects =
hooks.cleanEffects();
result &&
result.render(
this,
this.symbolId,
hydrate,
);
prevent = false;
if (firstRender && !hooks.isSuspense()) {
firstRender = false;
// @ts-ignore
!hydrate && applyStyles(this);
}
return cleanUseLayoutEffects();
} finally {
// Remove lock in case of synchronous error
prevent = false;
}
})
.then(
/**
* @param {import("internal/hooks").CleanUseEffects} [cleanUseEffect]
*/
(cleanUseEffect) => {
cleanUseEffect && cleanUseEffect();
},
);
}
return this.updated;
};
this.update();
}
connectedCallback() {
this.mount();
// @ts-ignore
super.connectedCallback && super.connectedCallback();
}
async disconnectedCallback() {
// @ts-ignore
super.disconnectedCallback && super.disconnectedCallback();
// The webcomponent will only resolve disconnected if it is
// actually disconnected of the document, otherwise it will keep the record.
await this.mounted;
this.unmount();
}
/**
* @this {import("dom").AtomicoThisInternal}
* @param {string} attr
* @param {(string|null)} oldValue
* @param {(string|null)} value
*/
attributeChangedCallback(attr, oldValue, value) {
if (attrs[attr]) {
// _ignoreAttr exists temporarily
// @ts-ignore
if (attr === this._ignoreAttr || oldValue === value) return;
// Choose the property name to send the update
const { prop, type } = attrs[attr];
// The following error cannot be caught
try {
this[prop] = transformValue(type, value);
} catch (e) {
throw new ParseError(
this,
`The value defined as attr '${attr}' cannot be parsed by type '${type.name}'`,
value,
);
}
} else {
// If the attribute does not exist in the scope attrs, the event is sent to super
// @ts-ignore
super.attributeChangedCallback(attr, oldValue, value);
}
}
static get props() {
// @ts-ignore
return { ...super.props, ...props };
}
static get observedAttributes() {
// See if there is an observedAttributes declaration to match with the current one
// @ts-ignore
const superAttrs = super.observedAttributes || [];
for (const prop in props) {
if (Object.prototype.hasOwnProperty.call(props, prop)) {
setPrototype(
this.prototype,
prop,
props[prop],
attrs,
values,
);
}
}
return Object.keys(attrs).concat(superAttrs);
}
},
};
return ctx[className];
};
/**
* Attach the css to the shadowDom
* @param {import("dom").AtomicoThisInternal} host
*/
function applyStyles(host) {
const { styles } = host.constructor;
const { shadowRoot } = host;
if (shadowRoot && styles.length) {
/**
* @type {CSSStyleSheet[]}
*/
const sheets = [];
flat(styles, (value) => {
if (value) {
if (value instanceof Element) {
shadowRoot.appendChild(value.cloneNode(true));
} else {
sheets.push(value);
}
}
});
if (sheets.length) shadowRoot.adoptedStyleSheets = sheets;
}
}