-
-
Notifications
You must be signed in to change notification settings - Fork 260
/
Copy pathsetup-rendering-context.ts
319 lines (273 loc) · 11 KB
/
setup-rendering-context.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
import { run } from '@ember/runloop';
import Ember from 'ember';
import global from './global.ts';
import {
type BaseContext,
type TestContext,
isTestContext,
getContext,
} from './setup-context.ts';
import settled from './settled.ts';
import getRootElement from './dom/get-root-element.ts';
import type { Owner } from './build-owner.ts';
import getTestMetadata from './test-metadata.ts';
import { runHooks } from './helper-hooks.ts';
import hasEmberVersion from './has-ember-version.ts';
import isComponent from './-internal/is-component.ts';
// the built in types do not provide types for @ember/template-compilation
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
import { precompileTemplate } from '@ember/template-compilation';
const OUTLET_TEMPLATE = precompileTemplate(`{{outlet}}`, { strictMode: false });
const EMPTY_TEMPLATE = precompileTemplate(``, { strictMode: false });
const INVOKE_PROVIDED_COMPONENT = precompileTemplate(
`<this.ProvidedComponent />`,
{ strictMode: false },
);
const hasCalledSetupRenderingContext = Symbol();
export interface RenderingTestContext extends TestContext {
element: Element | Document;
[hasCalledSetupRenderingContext]?: true;
}
// Isolates the notion of transforming a TextContext into a RenderingTestContext.
// eslint-disable-next-line require-jsdoc
function prepare(context: TestContext): RenderingTestContext {
(context as RenderingTestContext)[hasCalledSetupRenderingContext] = true;
return context as RenderingTestContext;
}
// eslint-disable-next-line require-jsdoc
export function isRenderingTestContext(
context: BaseContext,
): context is RenderingTestContext {
return isTestContext(context) && hasCalledSetupRenderingContext in context;
}
/**
@private
@param {Ember.ApplicationInstance} owner the current owner instance
@param {string} templateFullName the fill template name
@returns {Template} the template representing `templateFullName`
*/
function lookupTemplate(owner: Owner, templateFullName: `${string}:${string}`) {
const template = owner.lookup(templateFullName);
if (typeof template === 'function') return template(owner);
return template;
}
/**
@private
@param {Ember.ApplicationInstance} owner the current owner instance
@returns {Template} a template representing {{outlet}}
*/
function lookupOutletTemplate(owner: Owner): any {
let OutletTemplate = lookupTemplate(owner, 'template:-outlet');
if (!OutletTemplate) {
owner.register('template:-outlet', OUTLET_TEMPLATE);
OutletTemplate = lookupTemplate(owner, 'template:-outlet');
}
return OutletTemplate;
}
let templateId = 0;
export interface RenderOptions {
/**
The owner object to use as the basis for the template. In most cases you
will not need to specify this, however if you are using ember-engines
it is possible to specify the _engine's_ owner instead of the host
applications.
*/
owner?: Owner;
}
/**
Renders the provided template and appends it to the DOM.
@public
@param {Template|Component} templateFactoryOrComponent the component (or template) to render
@param {RenderOptions} options options hash containing engine owner ({ owner: engineOwner })
@returns {Promise<void>} resolves when settled
@example
<caption>
Render a div element with the class 'container'.
</caption>
await render(hbs`<div class="container"></div>`);
*/
export function render(
templateFactoryOrComponent: object,
options?: RenderOptions,
): Promise<void> {
let context = getContext();
if (!templateFactoryOrComponent) {
throw new Error('you must pass a template to `render()`');
}
return Promise.resolve()
.then(() => runHooks('render', 'start'))
.then(() => {
if (!context || !isRenderingTestContext(context)) {
throw new Error(
'Cannot call `render` without having first called `setupRenderingContext`.',
);
}
const { owner } = context;
const testMetadata = getTestMetadata(context);
testMetadata.usedHelpers.push('render');
// SAFETY: this is all wildly unsafe, because it is all using private API.
// At some point we should define a path forward for this kind of internal
// API. For now, just flagging it as *NOT* being safe!
const toplevelView = owner.lookup('-top-level-view:main') as any;
const OutletTemplate = lookupOutletTemplate(owner);
const ownerToRenderFrom = options?.owner || owner;
if (isComponent(templateFactoryOrComponent)) {
context = {
ProvidedComponent: templateFactoryOrComponent,
};
templateFactoryOrComponent = INVOKE_PROVIDED_COMPONENT;
}
templateId += 1;
const templateFullName = `template:-undertest-${templateId}` as const;
ownerToRenderFrom.register(templateFullName, templateFactoryOrComponent);
const template = lookupTemplate(ownerToRenderFrom, templateFullName);
const outletState = {
render: {
owner, // always use the host app owner for application outlet
into: undefined,
outlet: 'main',
name: 'application',
controller: undefined,
ViewClass: undefined,
template: OutletTemplate,
},
outlets: {
main: {
render: {
owner: ownerToRenderFrom, // the actual owner to be used for any lookups
into: undefined,
outlet: 'main',
name: 'index',
controller: context,
ViewClass: undefined,
template,
outlets: {},
},
outlets: {},
},
},
};
toplevelView.setOutletState(outletState);
// Ember's rendering engine is integration with the run loop so that when a run
// loop starts, the rendering is scheduled to be done.
//
// Ember should be ensuring an instance on its own here (the act of
// setting outletState should ensureInstance, since we know we need to
// render), but on Ember < 3.23 that is not guaranteed.
if (!hasEmberVersion(3, 23)) {
// SAFETY: this was correct and type checked on the Ember v3 types, but
// since the `run` namespace does not exist in Ember v4, this no longer
// can be type checked. When (eventually) dropping support for Ember v3,
// and therefore for versions before 3.23, this can be removed entirely.
(run as any).backburner.ensureInstance();
}
// returning settled here because the actual rendering does not happen until
// the renderer detects it is dirty (which happens on backburner's end
// hook), see the following implementation details:
//
// * [view:outlet](https://github.com/emberjs/ember.js/blob/f94a4b6aef5b41b96ef2e481f35e07608df01440/packages/ember-glimmer/lib/views/outlet.js#L129-L145) manually dirties its own tag upon `setOutletState`
// * [backburner's custom end hook](https://github.com/emberjs/ember.js/blob/f94a4b6aef5b41b96ef2e481f35e07608df01440/packages/ember-glimmer/lib/renderer.js#L145-L159) detects that the current revision of the root is no longer the latest, and triggers a new rendering transaction
return settled();
})
.then(() => runHooks('render', 'end'));
}
/**
Clears any templates previously rendered. This is commonly used for
confirming behavior that is triggered by teardown (e.g.
`willDestroyElement`).
@public
@returns {Promise<void>} resolves when settled
*/
export function clearRender(): Promise<void> {
const context = getContext();
if (!context || !isRenderingTestContext(context)) {
throw new Error(
'Cannot call `clearRender` without having first called `setupRenderingContext`.',
);
}
return render(EMPTY_TEMPLATE);
}
/**
Used by test framework addons to setup the provided context for rendering.
`setupContext` must have been ran on the provided context
prior to calling `setupRenderingContext`.
Responsible for:
- Setup the basic framework used for rendering by the
`render` helper.
- Ensuring the event dispatcher is properly setup.
- Setting `this.element` to the root element of the testing
container (things rendered via `render` will go _into_ this
element).
@public
@param {TestContext} context the context to setup for rendering
@returns {Promise<RenderingTestContext>} resolves with the context that was setup
@example
<caption>
Rendering out a paragraph element containing the content 'hello', and then clearing that content via clearRender.
</caption>
await render(hbs`<p>Hello!</p>`);
assert.equal(this.element.textContent, 'Hello!', 'has rendered content');
await clearRender();
assert.equal(this.element.textContent, '', 'has rendered content');
*/
export default function setupRenderingContext(
context: TestContext,
): Promise<RenderingTestContext> {
const testMetadata = getTestMetadata(context);
testMetadata.setupTypes.push('setupRenderingContext');
const renderingContext = prepare(context);
return Promise.resolve()
.then(() => {
const { owner } = renderingContext;
// When the host app uses `setApplication` (instead of `setResolver`) the event dispatcher has
// already been setup via `applicationInstance.boot()` in `./build-owner`. If using
// `setResolver` (instead of `setApplication`) a "mock owner" is created by extending
// `Ember._ContainerProxyMixin` and `Ember._RegistryProxyMixin` in this scenario we need to
// manually start the event dispatcher.
if (owner._emberTestHelpersMockOwner) {
const dispatcher =
owner.lookup('event_dispatcher:main') ||
(Ember.EventDispatcher as any).create();
dispatcher.setup({}, '#ember-testing');
}
const OutletView = owner.factoryFor
? owner.factoryFor('view:-outlet')
: owner._lookupFactory!('view:-outlet');
const environment = owner.lookup('-environment:main');
const template = owner.lookup('template:-outlet');
const toplevelView = OutletView.create({
template,
environment,
});
owner.register('-top-level-view:main', {
create() {
return toplevelView;
},
});
// initially render a simple empty template
return render(EMPTY_TEMPLATE).then(() => {
run(toplevelView, 'appendTo', getRootElement());
return settled();
});
})
.then(() => {
Object.defineProperty(renderingContext, 'element', {
configurable: true,
enumerable: true,
// ensure the element is based on the wrapping toplevel view
// Ember still wraps the main application template with a
// normal tagged view
//
// In older Ember versions (2.4) the element itself is not stable,
// and therefore we cannot update the `this.element` until after the
// rendering is completed
value:
global.EmberENV._APPLICATION_TEMPLATE_WRAPPER !== false
? getRootElement().querySelector('.ember-view')
: getRootElement(),
writable: false,
});
return renderingContext;
});
}