-
Notifications
You must be signed in to change notification settings - Fork 597
/
Copy pathcontroller.ts
438 lines (361 loc) · 13.6 KB
/
controller.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
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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
import { FASTElementDefinition } from "./fast-definitions";
import { ElementView } from "./view";
import { PropertyChangeNotifier } from "./observation/notifier";
import {
defaultExecutionContext,
Observable,
observable,
} from "./observation/observable";
import { Behavior } from "./directives/behavior";
import { ElementStyles, StyleTarget } from "./styles";
import { Mutable } from "./interfaces";
import { ElementViewTemplate } from "./template";
import { DOM } from "./dom";
const shadowRoots = new WeakMap<HTMLElement, ShadowRoot>();
const defaultEventOptions: CustomEventInit = {
bubbles: true,
composed: true,
};
function getShadowRoot(element: HTMLElement): ShadowRoot | null {
return element.shadowRoot || shadowRoots.get(element) || null;
}
/**
* Controls the lifecycle and rendering of a `FASTElement`.
* @public
*/
export class Controller extends PropertyChangeNotifier {
private boundObservables: Record<string, any> | null = null;
private behaviors: Behavior[] | null = null;
private needsInitialization = true;
private _template: ElementViewTemplate | null = null;
private _styles: ElementStyles | null = null;
/**
* The element being controlled by this controller.
*/
public readonly element: HTMLElement;
/**
* The element definition that instructs this controller
* in how to handle rendering and other platform integrations.
*/
public readonly definition: FASTElementDefinition;
/**
* The view associated with the custom element.
* @remarks
* If `null` then the element is managing its own rendering.
*/
public readonly view: ElementView | null = null;
/**
* Indicates whether or not the custom element has been
* connected to the document.
*/
@observable
public readonly isConnected: boolean = false;
/**
* Gets/sets the template used to render the component.
* @remarks
* This value can only be accurately read after connect but can be set at any time.
*/
get template() {
return this._template;
}
set template(value: ElementViewTemplate | null) {
if (this._template === value) {
return;
}
this._template = value;
if (!this.needsInitialization) {
this.renderTemplate(value);
}
}
/**
* Gets/sets the primary styles used for the component.
* @remarks
* This value can only be accurately read after connect but can be set at any time.
*/
get styles() {
return this._styles;
}
set styles(value: ElementStyles | null) {
if (this._styles === value) {
return;
}
if (this._styles !== null) {
this.removeStyles(this._styles);
}
this._styles = value;
if (!this.needsInitialization && value !== null) {
this.addStyles(value);
}
}
/**
* Creates a Controller to control the specified element.
* @param element - The element to be controlled by this controller.
* @param definition - The element definition metadata that instructs this
* controller in how to handle rendering and other platform integrations.
* @internal
*/
public constructor(element: HTMLElement, definition: FASTElementDefinition) {
super(element);
this.element = element;
this.definition = definition;
const shadowOptions = definition.shadowOptions;
if (shadowOptions !== void 0) {
const shadowRoot = element.attachShadow(shadowOptions);
if (shadowOptions.mode === "closed") {
shadowRoots.set(element, shadowRoot);
}
}
// Capture any observable values that were set by the binding engine before
// the browser upgraded the element. Then delete the property since it will
// shadow the getter/setter that is required to make the observable operate.
// Later, in the connect callback, we'll re-apply the values.
const accessors = Observable.getAccessors(element);
if (accessors.length > 0) {
const boundObservables = (this.boundObservables = Object.create(null));
for (let i = 0, ii = accessors.length; i < ii; ++i) {
const propertyName = accessors[i].name;
const value = (element as any)[propertyName];
if (value !== void 0) {
delete (element as any)[propertyName];
boundObservables[propertyName] = value;
}
}
}
}
/**
* Adds styles to this element. Providing an HTMLStyleElement will attach the element instance to the shadowRoot.
* @param styles - The styles to add.
*/
public addStyles(styles: ElementStyles | HTMLStyleElement): void {
const target =
getShadowRoot(this.element) ||
((this.element.getRootNode() as any) as StyleTarget);
if (styles instanceof HTMLStyleElement) {
target.prepend(styles);
} else {
const sourceBehaviors = styles.behaviors;
styles.addStylesTo(target);
if (sourceBehaviors !== null) {
this.addBehaviors(sourceBehaviors);
}
}
}
/**
* Removes styles from this element. Providing an HTMLStyleElement will detach the element instance from the shadowRoot.
* @param styles - the styles to remove.
*/
public removeStyles(styles: ElementStyles | HTMLStyleElement): void {
const target =
getShadowRoot(this.element) ||
((this.element.getRootNode() as any) as StyleTarget);
if (styles instanceof HTMLStyleElement) {
target.removeChild(styles);
} else {
const sourceBehaviors = styles.behaviors;
styles.removeStylesFrom(target);
if (sourceBehaviors !== null) {
this.removeBehaviors(sourceBehaviors);
}
}
}
/**
* Adds behaviors to this element.
* @param behaviors - The behaviors to add.
*/
public addBehaviors(behaviors: ReadonlyArray<Behavior>): void {
const targetBehaviors = this.behaviors || (this.behaviors = []);
const length = behaviors.length;
for (let i = 0; i < length; ++i) {
targetBehaviors.push(behaviors[i]);
}
if (this.isConnected) {
const element = this.element;
for (let i = 0; i < length; ++i) {
behaviors[i].bind(element, defaultExecutionContext);
}
}
}
/**
* Removes behaviors from this element.
* @param behaviors - The behaviors to remove.
*/
public removeBehaviors(behaviors: ReadonlyArray<Behavior>): void {
const targetBehaviors = this.behaviors;
if (targetBehaviors === null) {
return;
}
const length = behaviors.length;
for (let i = 0; i < length; ++i) {
const index = targetBehaviors.indexOf(behaviors[i]);
if (index !== -1) {
targetBehaviors.splice(index, 1);
}
}
if (this.isConnected) {
const element = this.element;
for (let i = 0; i < length; ++i) {
behaviors[i].unbind(element);
}
}
}
/**
* Runs connected lifecycle behavior on the associated element.
*/
public onConnectedCallback(): void {
if (this.isConnected) {
return;
}
const element = this.element;
if (this.needsInitialization) {
this.finishInitialization();
} else if (this.view !== null) {
this.view.bind(element, defaultExecutionContext);
}
const behaviors = this.behaviors;
if (behaviors !== null) {
for (let i = 0, ii = behaviors.length; i < ii; ++i) {
behaviors[i].bind(element, defaultExecutionContext);
}
}
(this as Mutable<Controller>).isConnected = true;
}
/**
* Runs disconnected lifecycle behavior on the associated element.
*/
public onDisconnectedCallback(): void {
if (this.isConnected === false) {
return;
}
(this as Mutable<Controller>).isConnected = false;
const view = this.view;
if (view !== null) {
view.unbind();
}
const behaviors = this.behaviors;
if (behaviors !== null) {
const element = this.element;
for (let i = 0, ii = behaviors.length; i < ii; ++i) {
behaviors[i].unbind(element);
}
}
}
/**
* Runs the attribute changed callback for the associated element.
* @param name - The name of the attribute that changed.
* @param oldValue - The previous value of the attribute.
* @param newValue - The new value of the attribute.
*/
public onAttributeChangedCallback(
name: string,
oldValue: string,
newValue: string
): void {
const attrDef = this.definition.attributeLookup[name];
if (attrDef !== void 0) {
attrDef.onAttributeChangedCallback(this.element, newValue);
}
}
/**
* Emits a custom HTML event.
* @param type - The type name of the event.
* @param detail - The event detail object to send with the event.
* @param options - The event options. By default bubbles and composed.
* @remarks
* Only emits events if connected.
*/
public emit(
type: string,
detail?: any,
options?: Omit<CustomEventInit, "detail">
): void | boolean {
if (this.isConnected) {
return this.element.dispatchEvent(
new CustomEvent(type, { detail, ...defaultEventOptions, ...options })
);
}
return false;
}
private finishInitialization() {
const element = this.element;
const boundObservables = this.boundObservables;
// If we have any observables that were bound, re-apply their values.
if (boundObservables !== null) {
const propertyNames = Object.keys(boundObservables);
for (let i = 0, ii = propertyNames.length; i < ii; ++i) {
const propertyName = propertyNames[i];
(element as any)[propertyName] = boundObservables[propertyName];
}
this.boundObservables = null;
}
const definition = this.definition;
// 1. Template overrides take top precedence.
if (this._template === null) {
if ((this.element as any).resolveTemplate) {
// 2. Allow for element instance overrides next.
this._template = (this.element as any).resolveTemplate();
} else if (definition.template) {
// 3. Default to the static definition.
this._template = definition.template || null;
}
}
// If we have a template after the above process, render it.
// If there's no template, then the element author has opted into
// custom rendering and they will managed the shadow root's content themselves.
if (this._template !== null) {
this.renderTemplate(this._template);
}
// 1. Styles overrides take top precedence.
if (this._styles === null) {
if ((this.element as any).resolveStyles) {
// 2. Allow for element instance overrides next.
this._styles = (this.element as any).resolveStyles();
} else if (definition.styles) {
// 3. Default to the static definition.
this._styles = definition.styles || null;
}
}
// If we have styles after the above process, add them.
if (this._styles !== null) {
this.addStyles(this._styles);
}
this.needsInitialization = false;
}
private renderTemplate(template: ElementViewTemplate | null | undefined) {
const element = this.element;
// When getting the host to render to, we start by looking
// up the shadow root. If there isn't one, then that means
// we're doing a Light DOM render to the element's direct children.
const host = getShadowRoot(element) || element;
if (this.view !== null) {
// If there's already a view, we need to unbind and remove through dispose.
this.view.dispose();
(this as Mutable<this>).view = null;
} else if (!this.needsInitialization) {
// If there was previous custom rendering, we need to clear out the host.
DOM.removeChildNodes(host);
}
if (template) {
// If a new template was provided, render it.
(this as Mutable<this>).view = template.render(element, host, element);
}
}
/**
* Locates or creates a controller for the specified element.
* @param element - The element to return the controller for.
* @remarks
* The specified element must have a {@link FASTElementDefinition}
* registered either through the use of the {@link customElement}
* decorator or a call to `FASTElement.define`.
*/
public static forCustomElement(element: HTMLElement): Controller {
const controller: Controller = (element as any).$fastController;
if (controller !== void 0) {
return controller;
}
const definition = FASTElementDefinition.forType(element.constructor);
if (definition === void 0) {
throw new Error("Missing FASTElement definition.");
}
return ((element as any).$fastController = new Controller(element, definition));
}
}