forked from glimmerjs/glimmer-vm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcomponent.ts
945 lines (759 loc) · 27.7 KB
/
component.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
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
import type {
Bounds,
CapabilityMask,
CapturedArguments,
CompilableProgram,
ComponentDefinition,
ComponentDefinitionState,
ComponentInstance,
ComponentInstanceState,
ComponentInstanceWithCreate,
Dict,
DynamicScope,
ElementOperations,
InternalComponentManager,
ModifierInstance,
Nullable,
Owner,
ProgramSymbolTable,
Recast,
ScopeSlot,
UpdatingOpcode,
VMArguments,
WithDynamicTagName,
WithElementHook,
WithUpdateHook,
} from '@glimmer/interfaces';
import type { Reference } from '@glimmer/reference';
import {
check,
CheckFunction,
CheckHandle,
CheckInstanceof,
CheckInterface,
CheckOr,
CheckProgramSymbolTable,
CheckString,
} from '@glimmer/debug';
import { registerDestructor } from '@glimmer/destroyable';
import { managerHasCapability } from '@glimmer/manager';
import { isConstRef, valueForRef } from '@glimmer/reference';
import {
assert,
assign,
debugToString,
dict,
EMPTY_STRING_ARRAY,
enumerate,
expect,
unwrap,
unwrapTemplate,
} from '@glimmer/util';
import { $t0, $t1, CurriedTypes, InternalComponentCapabilities, Op } from '@glimmer/vm';
import type { CurriedValue } from '../../curried-value';
import type { UpdatingVM } from '../../vm';
import type { InternalVM } from '../../vm/append';
import type { BlockArgumentsImpl } from '../../vm/arguments';
import { ConcreteBounds } from '../../bounds';
import { hasCustomDebugRenderTreeLifecycle } from '../../component/interfaces';
import { resolveComponent } from '../../component/resolve';
import { isCurriedType, isCurriedValue, resolveCurriedValue } from '../../curried-value';
import { APPEND_OPCODES } from '../../opcodes';
import createClassListRef from '../../references/class-list';
import { ARGS, CONSTANTS } from '../../symbols';
import { EMPTY_ARGS, VMArgumentsImpl } from '../../vm/arguments';
import {
CheckArguments,
CheckComponentDefinition,
CheckComponentInstance,
CheckCurriedComponentDefinition,
CheckFinishedComponentInstance,
CheckInvocation,
CheckReference,
} from './-debug-strip';
import { UpdateDynamicAttributeOpcode } from './dom';
/**
* The VM creates a new ComponentInstance data structure for every component
* invocation it encounters.
*
* Similar to how a ComponentDefinition contains state about all components of a
* particular type, a ComponentInstance contains state specific to a particular
* instance of a component type. It also contains a pointer back to its
* component type's ComponentDefinition.
*/
export interface InitialComponentInstance {
definition: ComponentDefinition;
manager: Nullable<InternalComponentManager>;
capabilities: Nullable<CapabilityMask>;
state: null;
handle: Nullable<number>;
table: Nullable<ProgramSymbolTable>;
lookup: Nullable<Dict<ScopeSlot>>;
}
export interface PopulatedComponentInstance {
definition: ComponentDefinition;
manager: InternalComponentManager;
capabilities: CapabilityMask;
state: null;
handle: number;
table: Nullable<ProgramSymbolTable>;
lookup: Nullable<Dict<ScopeSlot>>;
}
export interface PartialComponentDefinition {
state: Nullable<ComponentDefinitionState>;
manager: InternalComponentManager;
}
APPEND_OPCODES.add(Op.PushComponentDefinition, (vm, { op1: handle }) => {
let definition = vm[CONSTANTS].getValue<ComponentDefinition>(handle);
assert(!!definition, `Missing component for ${handle}`);
let { manager, capabilities } = definition;
let instance: InitialComponentInstance = {
definition,
manager,
capabilities,
state: null,
handle: null,
table: null,
lookup: null,
};
vm.stack.push(instance);
});
APPEND_OPCODES.add(Op.ResolveDynamicComponent, (vm, { op1: _isStrict }) => {
let stack = vm.stack;
let component = check(
valueForRef(check(stack.pop(), CheckReference)),
CheckOr(CheckString, CheckCurriedComponentDefinition)
);
let constants = vm[CONSTANTS];
let owner = vm.getOwner();
let isStrict = constants.getValue<boolean>(_isStrict);
vm.loadValue($t1, null); // Clear the temp register
let definition: ComponentDefinition | CurriedValue;
if (typeof component === 'string') {
if (import.meta.env.DEV && isStrict) {
throw new Error(
`Attempted to resolve a dynamic component with a string definition, \`${component}\` in a strict mode template. In strict mode, using strings to resolve component definitions is prohibited. You can instead import the component definition and use it directly.`
);
}
let resolvedDefinition = resolveComponent(vm.runtime.resolver, constants, component, owner);
definition = expect(resolvedDefinition, `Could not find a component named "${component}"`);
} else if (isCurriedValue(component)) {
definition = component;
} else {
definition = constants.component(component, owner);
}
stack.push(definition);
});
APPEND_OPCODES.add(Op.ResolveCurriedComponent, (vm) => {
let stack = vm.stack;
let ref = check(stack.pop(), CheckReference);
let value = valueForRef(ref);
let constants = vm[CONSTANTS];
let definition: CurriedValue | ComponentDefinition | null;
if (
import.meta.env.DEV &&
!(typeof value === 'function' || (typeof value === 'object' && value !== null))
) {
throw new Error(
`Expected a component definition, but received ${value}. You may have accidentally done <${ref.debugLabel}>, where "${ref.debugLabel}" was a string instead of a curried component definition. You must either use the component definition directly, or use the {{component}} helper to create a curried component definition when invoking dynamically.`
);
}
if (isCurriedValue(value)) {
definition = value;
} else {
definition = constants.component(value as object, vm.getOwner(), true);
if (import.meta.env.DEV && definition === null) {
throw new Error(
`Expected a dynamic component definition, but received an object or function that did not have a component manager associated with it. The dynamic invocation was \`<${
ref.debugLabel
}>\` or \`{{${
ref.debugLabel
}}}\`, and the incorrect definition is the value at the path \`${
ref.debugLabel
}\`, which was: ${debugToString!(value)}`
);
}
}
stack.push(definition);
});
APPEND_OPCODES.add(Op.PushDynamicComponentInstance, (vm) => {
let { stack } = vm;
let definition = stack.pop<ComponentDefinition>();
let capabilities, manager;
if (isCurriedValue(definition)) {
manager = capabilities = null;
} else {
manager = definition.manager;
capabilities = definition.capabilities;
}
stack.push({ definition, capabilities, manager, state: null, handle: null, table: null });
});
APPEND_OPCODES.add(Op.PushArgs, (vm, { op1: _names, op2: _blockNames, op3: flags }) => {
let stack = vm.stack;
let names = vm[CONSTANTS].getArray<string>(_names);
let positionalCount = flags >> 4;
let atNames = flags & 0b1000;
let blockNames =
flags & 0b0111 ? vm[CONSTANTS].getArray<string>(_blockNames) : EMPTY_STRING_ARRAY;
vm[ARGS].setup(stack, names, blockNames, positionalCount, !!atNames);
stack.push(vm[ARGS]);
});
APPEND_OPCODES.add(Op.PushEmptyArgs, (vm) => {
let { stack } = vm;
stack.push(vm[ARGS].empty(stack));
});
APPEND_OPCODES.add(Op.CaptureArgs, (vm) => {
let stack = vm.stack;
let args = check(stack.pop(), CheckInstanceof(VMArgumentsImpl));
let capturedArgs = args.capture();
stack.push(capturedArgs);
});
APPEND_OPCODES.add(Op.PrepareArgs, (vm, { op1: _state }) => {
let stack = vm.stack;
let instance = vm.fetchValue<ComponentInstance>(_state);
let args = check(stack.pop(), CheckInstanceof(VMArgumentsImpl));
let { definition } = instance;
if (isCurriedType(definition, CurriedTypes.Component)) {
assert(
!definition.manager,
"If the component definition was curried, we don't yet have a manager"
);
let constants = vm[CONSTANTS];
let {
definition: resolvedDefinition,
owner,
resolved,
positional,
named,
} = resolveCurriedValue(definition);
if (resolved === true) {
definition = resolvedDefinition as ComponentDefinition;
} else if (typeof resolvedDefinition === 'string') {
let resolvedValue = vm.runtime.resolver.lookupComponent(resolvedDefinition, owner);
definition = constants.resolvedComponent(
expect(resolvedValue, 'BUG: expected resolved component'),
resolvedDefinition
);
} else {
definition = constants.component(resolvedDefinition, owner);
}
if (named !== undefined) {
args.named.merge(assign({}, ...named));
}
if (positional !== undefined) {
args.realloc(positional.length);
args.positional.prepend(positional);
}
let { manager } = definition;
assert(instance.manager === null, 'component instance manager should not be populated yet');
assert(
instance.capabilities === null,
'component instance manager should not be populated yet'
);
instance.definition = definition;
instance.manager = manager;
instance.capabilities = definition.capabilities;
// Save off the owner that this component was curried with. Later on,
// we'll fetch the value of this register and set it as the owner on the
// new root scope.
vm.loadValue($t1, owner);
}
let { manager, state } = definition;
let capabilities = instance.capabilities;
if (!managerHasCapability(manager, capabilities, InternalComponentCapabilities.prepareArgs)) {
stack.push(args);
return;
}
let blocks = args.blocks.values;
let blockNames = args.blocks.names;
let preparedArgs = manager.prepareArgs(state, args);
if (preparedArgs) {
args.clear();
for (let i = 0; i < blocks.length; i++) {
stack.push(blocks[i]);
}
let { positional, named } = preparedArgs;
let positionalCount = positional.length;
for (let i = 0; i < positionalCount; i++) {
stack.push(positional[i]);
}
let names = Object.keys(named);
for (let i = 0; i < names.length; i++) {
stack.push(named[unwrap(names[i])]);
}
args.setup(stack, names, blockNames, positionalCount, false);
}
stack.push(args);
});
APPEND_OPCODES.add(Op.CreateComponent, (vm, { op1: flags, op2: _state }) => {
let instance = check(vm.fetchValue(_state), CheckComponentInstance);
let { definition, manager, capabilities } = instance;
if (!managerHasCapability(manager, capabilities, InternalComponentCapabilities.createInstance)) {
// TODO: Closure and Main components are always invoked dynamically, so this
// opcode may run even if this capability is not enabled. In the future we
// should handle this in a better way.
return;
}
let dynamicScope: Nullable<DynamicScope> = null;
if (managerHasCapability(manager, capabilities, InternalComponentCapabilities.dynamicScope)) {
dynamicScope = vm.dynamicScope();
}
let hasDefaultBlock = flags & 1;
let args: Nullable<VMArguments> = null;
if (managerHasCapability(manager, capabilities, InternalComponentCapabilities.createArgs)) {
args = check(vm.stack.peek(), CheckArguments);
}
let self: Nullable<Reference> = null;
if (managerHasCapability(manager, capabilities, InternalComponentCapabilities.createCaller)) {
self = vm.getSelf();
}
let state = manager.create(
vm.getOwner(),
definition.state,
args,
vm.env,
dynamicScope,
self,
!!hasDefaultBlock
);
// We want to reuse the `state` POJO here, because we know that the opcodes
// only transition at exactly one place.
instance.state = state;
if (managerHasCapability(manager, capabilities, InternalComponentCapabilities.updateHook)) {
vm.updateWith(new UpdateComponentOpcode(state, manager, dynamicScope));
}
});
APPEND_OPCODES.add(Op.RegisterComponentDestructor, (vm, { op1: _state }) => {
let { manager, state, capabilities } = check(vm.fetchValue(_state), CheckComponentInstance);
let d = manager.getDestroyable(state);
if (
import.meta.env.DEV &&
!managerHasCapability(manager, capabilities, InternalComponentCapabilities.willDestroy) &&
d !== null &&
(typeof 'willDestroy') in d
) {
throw new Error(
'BUG: Destructor has willDestroy, but the willDestroy capability was not enabled for this component. Pre-destruction hooks must be explicitly opted into'
);
}
if (d) vm.associateDestroyable(d);
});
APPEND_OPCODES.add(Op.BeginComponentTransaction, (vm, { op1: _state }) => {
let name;
if (import.meta.env.DEV) {
let { definition, manager } = check(vm.fetchValue(_state), CheckComponentInstance);
name = definition.resolvedName ?? manager.getDebugName(definition.state);
}
vm.beginCacheGroup(name);
vm.elements().pushSimpleBlock();
});
APPEND_OPCODES.add(Op.PutComponentOperations, (vm) => {
vm.loadValue($t0, new ComponentElementOperations());
});
APPEND_OPCODES.add(Op.ComponentAttr, (vm, { op1: _name, op2: _trusting, op3: _namespace }) => {
let name = vm[CONSTANTS].getValue<string>(_name);
let trusting = vm[CONSTANTS].getValue<boolean>(_trusting);
let reference = check(vm.stack.pop(), CheckReference);
let namespace = _namespace ? vm[CONSTANTS].getValue<string>(_namespace) : null;
check(vm.fetchValue($t0), CheckInstanceof(ComponentElementOperations)).setAttribute(
name,
reference,
trusting,
namespace
);
});
APPEND_OPCODES.add(Op.StaticComponentAttr, (vm, { op1: _name, op2: _value, op3: _namespace }) => {
let name = vm[CONSTANTS].getValue<string>(_name);
let value = vm[CONSTANTS].getValue<string>(_value);
let namespace = _namespace ? vm[CONSTANTS].getValue<string>(_namespace) : null;
check(vm.fetchValue($t0), CheckInstanceof(ComponentElementOperations)).setStaticAttribute(
name,
value,
namespace
);
});
type DeferredAttribute = {
value: string | Reference<unknown>;
namespace: Nullable<string>;
trusting?: boolean;
};
export class ComponentElementOperations implements ElementOperations {
private attributes = dict<DeferredAttribute>();
private classes: (string | Reference<unknown>)[] = [];
private modifiers: ModifierInstance[] = [];
setAttribute(
name: string,
value: Reference<unknown>,
trusting: boolean,
namespace: Nullable<string>
) {
let deferred = { value, namespace, trusting };
if (name === 'class') {
this.classes.push(value);
}
this.attributes[name] = deferred;
}
setStaticAttribute(name: string, value: string, namespace: Nullable<string>): void {
let deferred = { value, namespace };
if (name === 'class') {
this.classes.push(value);
}
this.attributes[name] = deferred;
}
addModifier(vm: InternalVM, modifier: ModifierInstance, capturedArgs: CapturedArguments): void {
this.modifiers.push(modifier);
if (vm.env.debugRenderTree !== undefined) {
const { manager, definition, state } = modifier;
// TODO: we need a stable object for the debugRenderTree as the key, add support for
// the case where the state is a primitive, or if in practice we always have/require
// an object, then change the internal types to reflect that
if (state === null || (typeof state !== 'object' && typeof state !== 'function')) {
return;
}
let { element, constructing } = vm.elements();
let name = manager.getDebugName(definition.state);
let instance = manager.getDebugInstance(state);
assert(constructing, `Expected a constructing element in addModifier`);
let bounds = new ConcreteBounds(element, constructing, constructing);
vm.env.debugRenderTree.create(state, {
type: 'modifier',
name,
args: capturedArgs,
instance,
});
vm.env.debugRenderTree.didRender(state, bounds);
// For tearing down the debugRenderTree
vm.associateDestroyable(state);
vm.updateWith(new DebugRenderTreeUpdateOpcode(state));
vm.updateWith(new DebugRenderTreeDidRenderOpcode(state, bounds));
registerDestructor(state, () => {
vm.env.debugRenderTree?.willDestroy(state);
});
}
}
flush(vm: InternalVM): ModifierInstance[] {
let type: DeferredAttribute | undefined;
let attributes = this.attributes;
for (let name in this.attributes) {
if (name === 'type') {
type = attributes[name];
continue;
}
let attr = unwrap(this.attributes[name]);
if (name === 'class') {
setDeferredAttr(vm, 'class', mergeClasses(this.classes), attr.namespace, attr.trusting);
} else {
setDeferredAttr(vm, name, attr.value, attr.namespace, attr.trusting);
}
}
if (type !== undefined) {
setDeferredAttr(vm, 'type', type.value, type.namespace, type.trusting);
}
return this.modifiers;
}
}
function mergeClasses(classes: (string | Reference)[]): string | Reference<unknown> {
if (classes.length === 0) {
return '';
}
if (classes.length === 1) {
return unwrap(classes[0]);
}
if (allStringClasses(classes)) {
return classes.join(' ');
}
return createClassListRef(classes as Reference[]);
}
function allStringClasses(classes: (string | Reference<unknown>)[]): classes is string[] {
return classes.every((c) => typeof c === 'string');
}
function setDeferredAttr(
vm: InternalVM,
name: string,
value: string | Reference<unknown>,
namespace: Nullable<string>,
trusting = false
) {
if (typeof value === 'string') {
vm.elements().setStaticAttribute(name, value, namespace);
} else {
let attribute = vm
.elements()
.setDynamicAttribute(name, valueForRef(value), trusting, namespace);
if (!isConstRef(value)) {
vm.updateWith(new UpdateDynamicAttributeOpcode(value, attribute, vm.env));
}
}
}
APPEND_OPCODES.add(Op.DidCreateElement, (vm, { op1: _state }) => {
let { definition, state } = check(vm.fetchValue(_state), CheckComponentInstance);
let { manager } = definition;
let operations = check(vm.fetchValue($t0), CheckInstanceof(ComponentElementOperations));
(manager as WithElementHook<unknown>).didCreateElement(
state,
expect(vm.elements().constructing, `Expected a constructing element in DidCreateOpcode`),
operations
);
});
APPEND_OPCODES.add(Op.GetComponentSelf, (vm, { op1: _state, op2: _names }) => {
let instance = check(vm.fetchValue(_state), CheckComponentInstance);
let { definition, state } = instance;
let { manager } = definition;
let selfRef = manager.getSelf(state);
if (vm.env.debugRenderTree !== undefined) {
let instance = check(vm.fetchValue(_state), CheckComponentInstance);
let { definition, manager } = instance;
let args: CapturedArguments;
if (vm.stack.peek() === vm[ARGS]) {
args = vm[ARGS].capture();
} else {
let names = vm[CONSTANTS].getArray<string>(_names);
vm[ARGS].setup(vm.stack, names, [], 0, true);
args = vm[ARGS].capture();
}
let moduleName: string;
let compilable: CompilableProgram | null = definition.compilable;
if (compilable === null) {
assert(
managerHasCapability(
manager,
instance.capabilities,
InternalComponentCapabilities.dynamicLayout
),
'BUG: No template was found for this component, and the component did not have the dynamic layout capability'
);
compilable = manager.getDynamicLayout(state, vm.runtime.resolver);
if (compilable !== null) {
moduleName = compilable.moduleName;
} else {
moduleName = '__default__.hbs';
}
} else {
moduleName = compilable.moduleName;
}
// For tearing down the debugRenderTree
vm.associateDestroyable(instance);
if (hasCustomDebugRenderTreeLifecycle(manager)) {
let nodes = manager.getDebugCustomRenderTree(
instance.definition.state,
instance.state,
args,
moduleName
);
nodes.forEach((node) => {
let { bucket } = node;
vm.env.debugRenderTree!.create(bucket, node);
registerDestructor(instance, () => {
vm.env.debugRenderTree?.willDestroy(bucket);
});
vm.updateWith(new DebugRenderTreeUpdateOpcode(bucket));
});
} else {
let name = definition.resolvedName ?? manager.getDebugName(definition.state);
vm.env.debugRenderTree.create(instance, {
type: 'component',
name,
args,
template: moduleName,
instance: valueForRef(selfRef),
});
registerDestructor(instance, () => {
vm.env.debugRenderTree?.willDestroy(instance);
});
vm.updateWith(new DebugRenderTreeUpdateOpcode(instance));
}
}
vm.stack.push(selfRef);
});
APPEND_OPCODES.add(Op.GetComponentTagName, (vm, { op1: _state }) => {
let { definition, state } = check(vm.fetchValue(_state), CheckComponentInstance);
let { manager } = definition;
let tagName = (
manager as Recast<InternalComponentManager, WithDynamicTagName<unknown>>
).getTagName(state);
// User provided value from JS, so we don't bother to encode
vm.stack.push(tagName);
});
// Dynamic Invocation Only
APPEND_OPCODES.add(Op.GetComponentLayout, (vm, { op1: _state }) => {
let instance = check(vm.fetchValue(_state), CheckComponentInstance);
let { manager, definition } = instance;
let { stack } = vm;
let { compilable } = definition;
if (compilable === null) {
let { capabilities } = instance;
assert(
managerHasCapability(manager, capabilities, InternalComponentCapabilities.dynamicLayout),
'BUG: No template was found for this component, and the component did not have the dynamic layout capability'
);
compilable = manager.getDynamicLayout(instance.state, vm.runtime.resolver);
if (compilable === null) {
if (managerHasCapability(manager, capabilities, InternalComponentCapabilities.wrapped)) {
compilable = unwrapTemplate(vm[CONSTANTS].defaultTemplate).asWrappedLayout();
} else {
compilable = unwrapTemplate(vm[CONSTANTS].defaultTemplate).asLayout();
}
}
}
let handle = compilable.compile(vm.context);
stack.push(compilable.symbolTable);
stack.push(handle);
});
APPEND_OPCODES.add(Op.Main, (vm, { op1: register }) => {
let definition = check(vm.stack.pop(), CheckComponentDefinition);
let invocation = check(vm.stack.pop(), CheckInvocation);
let { manager, capabilities } = definition;
let state: PopulatedComponentInstance = {
definition,
manager,
capabilities,
state: null,
handle: invocation.handle,
table: invocation.symbolTable,
lookup: null,
};
vm.loadValue(register, state);
});
APPEND_OPCODES.add(Op.PopulateLayout, (vm, { op1: _state }) => {
let { stack } = vm;
// In import.meta.env.DEV handles could be ErrHandle objects
let handle = check(stack.pop(), CheckHandle);
let table = check(stack.pop(), CheckProgramSymbolTable);
let state = check(vm.fetchValue(_state), CheckComponentInstance);
state.handle = handle;
state.table = table;
});
APPEND_OPCODES.add(Op.VirtualRootScope, (vm, { op1: _state }) => {
let { table, manager, capabilities, state } = check(
vm.fetchValue(_state),
CheckFinishedComponentInstance
);
let owner;
if (managerHasCapability(manager, capabilities, InternalComponentCapabilities.hasSubOwner)) {
owner = manager.getOwner(state);
vm.loadValue($t1, null); // Clear the temp register
} else {
// Check the temp register to see if an owner was resolved from currying
owner = vm.fetchValue<Owner | null>($t1);
if (owner === null) {
// If an owner wasn't found, default to using the current owner. This
// will happen for normal dynamic component invocation,
// e.g. <SomeClassicEmberComponent/>
owner = vm.getOwner();
} else {
// Else the owner was found, so clear the temp register. This will happen
// if we are loading a curried component, e.g. <@someCurriedComponent/>
vm.loadValue($t1, null);
}
}
vm.pushRootScope(table.symbols.length + 1, owner);
});
APPEND_OPCODES.add(Op.SetupForEval, (vm, { op1: _state }) => {
let state = check(vm.fetchValue(_state), CheckFinishedComponentInstance);
if (state.table.hasEval) {
let lookup = (state.lookup = dict<ScopeSlot>());
vm.scope().bindEvalScope(lookup);
}
});
APPEND_OPCODES.add(Op.SetNamedVariables, (vm, { op1: _state }) => {
let state = check(vm.fetchValue(_state), CheckFinishedComponentInstance);
let scope = vm.scope();
let args = check(vm.stack.peek(), CheckArguments);
let callerNames = args.named.atNames;
for (let i = callerNames.length - 1; i >= 0; i--) {
let atName = unwrap(callerNames[i]);
let symbol = state.table.symbols.indexOf(atName);
let value = args.named.get(atName, true);
if (symbol !== -1) scope.bindSymbol(symbol + 1, value);
if (state.lookup) state.lookup[atName] = value;
}
});
function bindBlock(
symbolName: string,
blockName: string,
state: ComponentInstance,
blocks: BlockArgumentsImpl,
vm: InternalVM
) {
let symbol = state.table.symbols.indexOf(symbolName);
let block = blocks.get(blockName);
if (symbol !== -1) vm.scope().bindBlock(symbol + 1, block);
if (state.lookup) state.lookup[symbolName] = block;
}
APPEND_OPCODES.add(Op.SetBlocks, (vm, { op1: _state }) => {
let state = check(vm.fetchValue(_state), CheckFinishedComponentInstance);
let { blocks } = check(vm.stack.peek(), CheckArguments);
for (const [i] of enumerate(blocks.names)) {
bindBlock(unwrap(blocks.symbolNames[i]), unwrap(blocks.names[i]), state, blocks, vm);
}
});
// Dynamic Invocation Only
APPEND_OPCODES.add(Op.InvokeComponentLayout, (vm, { op1: _state }) => {
let state = check(vm.fetchValue(_state), CheckFinishedComponentInstance);
vm.call(state.handle);
});
APPEND_OPCODES.add(Op.DidRenderLayout, (vm, { op1: _state }) => {
let instance = check(vm.fetchValue(_state), CheckComponentInstance);
let { manager, state, capabilities } = instance;
let bounds = vm.elements().popBlock();
if (vm.env.debugRenderTree !== undefined) {
if (hasCustomDebugRenderTreeLifecycle(manager)) {
let nodes = manager.getDebugCustomRenderTree(instance.definition.state, state, EMPTY_ARGS);
nodes.reverse().forEach((node) => {
let { bucket } = node;
vm.env.debugRenderTree!.didRender(bucket, bounds);
vm.updateWith(new DebugRenderTreeDidRenderOpcode(bucket, bounds));
});
} else {
vm.env.debugRenderTree.didRender(instance, bounds);
vm.updateWith(new DebugRenderTreeDidRenderOpcode(instance, bounds));
}
}
if (managerHasCapability(manager, capabilities, InternalComponentCapabilities.createInstance)) {
let mgr = check(manager, CheckInterface({ didRenderLayout: CheckFunction }));
mgr.didRenderLayout(state, bounds);
vm.env.didCreate(instance as ComponentInstanceWithCreate);
vm.updateWith(new DidUpdateLayoutOpcode(instance as ComponentInstanceWithCreate, bounds));
}
});
APPEND_OPCODES.add(Op.CommitComponentTransaction, (vm) => {
vm.commitCacheGroup();
});
export class UpdateComponentOpcode implements UpdatingOpcode {
constructor(
private component: ComponentInstanceState,
private manager: WithUpdateHook,
private dynamicScope: Nullable<DynamicScope>
) {}
evaluate(_vm: UpdatingVM) {
let { component, manager, dynamicScope } = this;
manager.update(component, dynamicScope);
}
}
export class DidUpdateLayoutOpcode implements UpdatingOpcode {
constructor(
private component: ComponentInstanceWithCreate,
private bounds: Bounds
) {}
evaluate(vm: UpdatingVM) {
let { component, bounds } = this;
let { manager, state } = component;
manager.didUpdateLayout(state, bounds);
vm.env.didUpdate(component);
}
}
class DebugRenderTreeUpdateOpcode implements UpdatingOpcode {
constructor(private bucket: object) {}
evaluate(vm: UpdatingVM) {
vm.env.debugRenderTree?.update(this.bucket);
}
}
class DebugRenderTreeDidRenderOpcode implements UpdatingOpcode {
constructor(
private bucket: object,
private bounds: Bounds
) {}
evaluate(vm: UpdatingVM) {
vm.env.debugRenderTree?.didRender(this.bucket, this.bounds);
}
}