/
curly.ts
575 lines (486 loc) · 17.4 KB
/
curly.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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
import { privatize as P } from '@ember/-internals/container';
import { get } from '@ember/-internals/metal';
import { getOwner } from '@ember/-internals/owner';
import { guidFor } from '@ember/-internals/utils';
import { addChildView, OwnedTemplateMeta, setViewElement } from '@ember/-internals/views';
import { assert } from '@ember/debug';
import { _instrumentStart } from '@ember/instrumentation';
import { assign } from '@ember/polyfills';
import { DEBUG } from '@glimmer/env';
import {
ComponentCapabilities,
Option,
ProgramSymbolTable,
Simple,
VMHandle,
} from '@glimmer/interfaces';
import { combine, Tag, VersionedPathReference } from '@glimmer/reference';
import {
Arguments,
Bounds,
ComponentDefinition,
ElementOperations,
Invocation,
PreparedArguments,
PrimitiveReference,
WithDynamicLayout,
WithDynamicTagName,
WithStaticLayout,
} from '@glimmer/runtime';
import { Destroyable, EMPTY_ARRAY } from '@glimmer/util';
import { BOUNDS, DIRTY_TAG, HAS_BLOCK, IS_DISPATCHING_ATTRS, ROOT_REF } from '../component';
import Environment from '../environment';
import { DynamicScope } from '../renderer';
import RuntimeResolver from '../resolver';
import { Factory as TemplateFactory, OwnedTemplate } from '../template';
import {
AttributeBinding,
ClassNameBinding,
IsVisibleBinding,
referenceForKey,
SimpleClassNameBindingReference,
} from '../utils/bindings';
import ComponentStateBucket, { Component } from '../utils/curly-component-state-bucket';
import { processComponentArgs } from '../utils/process-args';
import AbstractManager from './abstract';
import DefinitionState from './definition-state';
function aliasIdToElementId(args: Arguments, props: any) {
if (args.named.has('id')) {
// tslint:disable-next-line:max-line-length
assert(
`You cannot invoke a component with both 'id' and 'elementId' at the same time.`,
!args.named.has('elementId')
);
props.elementId = props.id;
}
}
function isTemplateFactory(template: OwnedTemplate | TemplateFactory): template is TemplateFactory {
return typeof (template as TemplateFactory).create === 'function';
}
// We must traverse the attributeBindings in reverse keeping track of
// what has already been applied. This is essentially refining the concatenated
// properties applying right to left.
function applyAttributeBindings(
element: Simple.Element,
attributeBindings: Array<string>,
component: Component,
operations: ElementOperations
) {
let seen: string[] = [];
let i = attributeBindings.length - 1;
while (i !== -1) {
let binding = attributeBindings[i];
let parsed: [string, string, boolean] = AttributeBinding.parse(binding);
let attribute = parsed[1];
if (seen.indexOf(attribute) === -1) {
seen.push(attribute);
AttributeBinding.install(element, component, parsed, operations);
}
i--;
}
if (seen.indexOf('id') === -1) {
let id = component.elementId ? component.elementId : guidFor(component);
operations.setAttribute('id', PrimitiveReference.create(id), false, null);
}
if (seen.indexOf('style') === -1) {
IsVisibleBinding.install(element, component, operations);
}
}
const DEFAULT_LAYOUT = P`template:components/-default`;
export default class CurlyComponentManager
extends AbstractManager<ComponentStateBucket, DefinitionState>
implements
WithStaticLayout<ComponentStateBucket, DefinitionState, OwnedTemplateMeta, RuntimeResolver>,
WithDynamicTagName<ComponentStateBucket>,
WithDynamicLayout<ComponentStateBucket, OwnedTemplateMeta, RuntimeResolver> {
getLayout(state: DefinitionState, _resolver: RuntimeResolver): Invocation {
return {
// TODO fix
handle: (state.handle as any) as number,
symbolTable: state.symbolTable!,
};
}
templateFor(component: Component, resolver: RuntimeResolver): OwnedTemplate {
let layout = get(component, 'layout') as TemplateFactory | OwnedTemplate | undefined;
if (layout !== undefined) {
// This needs to be cached by template.id
if (isTemplateFactory(layout)) {
return resolver.createTemplate(layout, getOwner(component));
} else {
// we were provided an instance already
return layout;
}
}
let owner = getOwner(component);
let layoutName = get(component, 'layoutName');
if (layoutName) {
let template = owner.lookup<OwnedTemplate>('template:' + layoutName);
if (template) {
return template;
}
}
return owner.lookup<OwnedTemplate>(DEFAULT_LAYOUT);
}
getDynamicLayout({ component }: ComponentStateBucket, resolver: RuntimeResolver): Invocation {
const template = this.templateFor(component, resolver);
const layout = template.asWrappedLayout();
return {
handle: layout.compile(),
symbolTable: layout.symbolTable,
};
}
getTagName(state: ComponentStateBucket): Option<string> {
const { component, hasWrappedElement } = state;
if (!hasWrappedElement) {
return null;
}
return (component && component.tagName) || 'div';
}
getCapabilities(state: DefinitionState) {
return state.capabilities;
}
prepareArgs(state: DefinitionState, args: Arguments): Option<PreparedArguments> {
const { positionalParams } = state.ComponentClass.class!;
// early exits
if (
positionalParams === undefined ||
positionalParams === null ||
args.positional.length === 0
) {
return null;
}
let named: PreparedArguments['named'];
if (typeof positionalParams === 'string') {
assert(
`You cannot specify positional parameters and the hash argument \`${positionalParams}\`.`,
!args.named.has(positionalParams)
);
named = { [positionalParams]: args.positional.capture() };
assign(named, args.named.capture().map);
} else if (Array.isArray(positionalParams) && positionalParams.length > 0) {
const count = Math.min(positionalParams.length, args.positional.length);
named = {};
assign(named, args.named.capture().map);
for (let i = 0; i < count; i++) {
const name = positionalParams[i];
assert(
`You cannot specify both a positional param (at position ${i}) and the hash argument \`${name}\`.`,
!args.named.has(name)
);
named[name] = args.positional.at(i);
}
} else {
return null;
}
return { positional: EMPTY_ARRAY, named };
}
/*
* This hook is responsible for actually instantiating the component instance.
* It also is where we perform additional bookkeeping to support legacy
* features like exposed by view mixins like ChildViewSupport, ActionSupport,
* etc.
*/
create(
environment: Environment,
state: DefinitionState,
args: Arguments,
dynamicScope: DynamicScope,
callerSelfRef: VersionedPathReference,
hasBlock: boolean
): ComponentStateBucket {
if (DEBUG) {
this._pushToDebugStack(`component:${state.name}`, environment);
}
// Get the nearest concrete component instance from the scope. "Virtual"
// components will be skipped.
let parentView = dynamicScope.view;
// Get the Ember.Component subclass to instantiate for this component.
let factory = state.ComponentClass;
// Capture the arguments, which tells Glimmer to give us our own, stable
// copy of the Arguments object that is safe to hold on to between renders.
let capturedArgs = args.named.capture();
let props = processComponentArgs(capturedArgs);
// Alias `id` argument to `elementId` property on the component instance.
aliasIdToElementId(args, props);
// Set component instance's parentView property to point to nearest concrete
// component.
props.parentView = parentView;
// Set whether this component was invoked with a block
// (`{{#my-component}}{{/my-component}}`) or without one
// (`{{my-component}}`).
props[HAS_BLOCK] = hasBlock;
// Save the current `this` context of the template as the component's
// `_target`, so bubbled actions are routed to the right place.
props._target = callerSelfRef.value();
// static layout asserts CurriedDefinition
if (state.template) {
props.layout = state.template;
}
// Now that we've built up all of the properties to set on the component instance,
// actually create it.
let component = factory.create(props);
let finalizer = _instrumentStart('render.component', initialRenderInstrumentDetails, component);
// We become the new parentView for downstream components, so save our
// component off on the dynamic scope.
dynamicScope.view = component;
// Unless we're the root component, we need to add ourselves to our parent
// component's childViews array.
if (parentView !== null && parentView !== undefined) {
addChildView(parentView, component);
}
component.trigger('didReceiveAttrs');
let hasWrappedElement = component.tagName !== '';
// We usually do this in the `didCreateElement`, but that hook doesn't fire for tagless components
if (!hasWrappedElement) {
if (environment.isInteractive) {
component.trigger('willRender');
}
component._transitionTo('hasElement');
if (environment.isInteractive) {
component.trigger('willInsertElement');
}
}
// Track additional lifecycle metadata about this component in a state bucket.
// Essentially we're saving off all the state we'll need in the future.
let bucket = new ComponentStateBucket(
environment,
component,
capturedArgs,
finalizer,
hasWrappedElement
);
if (args.named.has('class')) {
bucket.classRef = args.named.get('class');
}
if (DEBUG) {
processComponentInitializationAssertions(component, props);
}
if (environment.isInteractive && hasWrappedElement) {
component.trigger('willRender');
}
return bucket;
}
getSelf({ component }: ComponentStateBucket): VersionedPathReference {
return component[ROOT_REF];
}
didCreateElement(
{ component, classRef, environment }: ComponentStateBucket,
element: HTMLElement,
operations: ElementOperations
): void {
setViewElement(component, element);
let { attributeBindings, classNames, classNameBindings } = component;
if (attributeBindings && attributeBindings.length) {
applyAttributeBindings(element, attributeBindings, component, operations);
} else {
let id = component.elementId ? component.elementId : guidFor(component);
operations.setAttribute('id', PrimitiveReference.create(id), false, null);
IsVisibleBinding.install(element, component, operations);
}
if (classRef) {
const ref = new SimpleClassNameBindingReference(classRef, classRef['_propertyKey']);
operations.setAttribute('class', ref, false, null);
}
if (classNames && classNames.length) {
classNames.forEach((name: string) => {
operations.setAttribute('class', PrimitiveReference.create(name), false, null);
});
}
if (classNameBindings && classNameBindings.length) {
classNameBindings.forEach((binding: string) => {
ClassNameBinding.install(element, component, binding, operations);
});
}
operations.setAttribute('class', PrimitiveReference.create('ember-view'), false, null);
if ('ariaRole' in component) {
operations.setAttribute('role', referenceForKey(component, 'ariaRole'), false, null);
}
component._transitionTo('hasElement');
if (environment.isInteractive) {
component.trigger('willInsertElement');
}
}
didRenderLayout(bucket: ComponentStateBucket, bounds: Bounds): void {
bucket.component[BOUNDS] = bounds;
bucket.finalize();
if (DEBUG) {
this.debugStack.pop();
}
}
getTag({ args, component }: ComponentStateBucket): Tag {
return args ? combine([args.tag, component[DIRTY_TAG]]) : component[DIRTY_TAG];
}
didCreate({ component, environment }: ComponentStateBucket): void {
if (environment.isInteractive) {
component._transitionTo('inDOM');
component.trigger('didInsertElement');
component.trigger('didRender');
}
}
update(bucket: ComponentStateBucket): void {
let { component, args, argsRevision, environment } = bucket;
if (DEBUG) {
this._pushToDebugStack(component._debugContainerKey, environment);
}
bucket.finalizer = _instrumentStart('render.component', rerenderInstrumentDetails, component);
if (args && !args.tag.validate(argsRevision)) {
let props = processComponentArgs(args!);
bucket.argsRevision = args!.tag.value();
component[IS_DISPATCHING_ATTRS] = true;
component.setProperties(props);
component[IS_DISPATCHING_ATTRS] = false;
component.trigger('didUpdateAttrs');
component.trigger('didReceiveAttrs');
}
if (environment.isInteractive) {
component.trigger('willUpdate');
component.trigger('willRender');
}
}
didUpdateLayout(bucket: ComponentStateBucket): void {
bucket.finalize();
if (DEBUG) {
this.debugStack.pop();
}
}
didUpdate({ component, environment }: ComponentStateBucket): void {
if (environment.isInteractive) {
component.trigger('didUpdate');
component.trigger('didRender');
}
}
getDestructor(stateBucket: ComponentStateBucket): Option<Destroyable> {
return stateBucket;
}
}
export function validatePositionalParameters(
named: { has(name: string): boolean },
positional: { length: number },
positionalParamsDefinition: any
) {
if (DEBUG) {
if (!named || !positional || !positional.length) {
return;
}
let paramType = typeof positionalParamsDefinition;
if (paramType === 'string') {
// tslint:disable-next-line:max-line-length
assert(
`You cannot specify positional parameters and the hash argument \`${positionalParamsDefinition}\`.`,
!named.has(positionalParamsDefinition)
);
} else {
if (positional.length < positionalParamsDefinition.length) {
positionalParamsDefinition = positionalParamsDefinition.slice(0, positional.length);
}
for (let i = 0; i < positionalParamsDefinition.length; i++) {
let name = positionalParamsDefinition[i];
assert(
`You cannot specify both a positional param (at position ${i}) and the hash argument \`${name}\`.`,
!named.has(name)
);
}
}
}
}
export function processComponentInitializationAssertions(component: Component, props: any) {
assert(
`classNameBindings must be non-empty strings: ${component}`,
(() => {
let { classNameBindings } = component;
for (let i = 0; i < classNameBindings.length; i++) {
let binding = classNameBindings[i];
if (typeof binding !== 'string' || binding.length === 0) {
return false;
}
}
return true;
})()
);
assert(
`classNameBindings must not have spaces in them: ${component}`,
(() => {
let { classNameBindings } = component;
for (let i = 0; i < classNameBindings.length; i++) {
let binding = classNameBindings[i];
if (binding.split(' ').length > 1) {
return false;
}
}
return true;
})()
);
assert(
`You cannot use \`classNameBindings\` on a tag-less component: ${component}`,
component.tagName !== '' ||
!component.classNameBindings ||
component.classNameBindings.length === 0
);
assert(
`You cannot use \`elementId\` on a tag-less component: ${component}`,
component.tagName !== '' ||
props.id === component.elementId ||
(!component.elementId && component.elementId !== '')
);
assert(
`You cannot use \`attributeBindings\` on a tag-less component: ${component}`,
component.tagName !== '' ||
!component.attributeBindings ||
component.attributeBindings.length === 0
);
}
export function initialRenderInstrumentDetails(component: any): any {
return component.instrumentDetails({ initialRender: true });
}
export function rerenderInstrumentDetails(component: any): any {
return component.instrumentDetails({ initialRender: false });
}
// This is not any of glimmer-vm's proper Argument types because we
// don't have sufficient public constructors to conveniently
// reassemble one after we mangle the various arguments.
interface CurriedArgs {
positional: any[];
named: any;
}
export const CURLY_CAPABILITIES: ComponentCapabilities = {
dynamicLayout: true,
dynamicTag: true,
prepareArgs: true,
createArgs: true,
attributeHook: true,
elementHook: true,
createCaller: true,
dynamicScope: true,
updateHook: true,
createInstance: true,
};
const CURLY_COMPONENT_MANAGER = new CurlyComponentManager();
export class CurlyComponentDefinition implements ComponentDefinition {
public template: OwnedTemplate;
public args: CurriedArgs | undefined;
public state: DefinitionState;
public symbolTable: ProgramSymbolTable | undefined;
public manager: CurlyComponentManager = CURLY_COMPONENT_MANAGER;
// tslint:disable-next-line:no-shadowed-variable
constructor(
public name: string,
public ComponentClass: any,
public handle: Option<VMHandle>,
template: OwnedTemplate,
args?: CurriedArgs
) {
const layout = template && template.asLayout();
const symbolTable = layout ? layout.symbolTable : undefined;
this.symbolTable = symbolTable;
this.template = template;
this.args = args;
this.state = {
name,
ComponentClass,
handle,
template,
capabilities: CURLY_CAPABILITIES,
symbolTable,
};
}
}