-
Notifications
You must be signed in to change notification settings - Fork 439
Expand file tree
/
Copy pathrender.ts
More file actions
305 lines (272 loc) · 10.2 KB
/
render.ts
File metadata and controls
305 lines (272 loc) · 10.2 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
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
/*
* Copyright (c) 2025, Salesforce, Inc.
* All rights reserved.
* SPDX-License-Identifier: MIT
* For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT
*/
import {
getOwnPropertyNames,
isNull,
isString,
isUndefined,
DEFAULT_SSR_MODE,
htmlEscape,
type Stylesheet,
} from '@lwc/shared';
import { mutationTracker } from './mutation-tracker';
import { SYMBOL__GENERATE_MARKUP } from './lightning-element';
import type { CompilationMode } from '@lwc/shared';
import type { LightningElement, LightningElementConstructor } from './lightning-element';
import type { Attributes, Properties } from './types';
/** Parameters used by all `generateMarkup` variants that don't get transmogrified. */
type BaseGenerateMarkupParams = readonly [
tagName: string,
props: Properties | null,
attrs: Attributes | null,
// Not always null when invoked internally, but should always be
// null when invoked by ssr-runtime
parent: LightningElement | null,
scopeToken: string | null,
contextfulParent: LightningElement | null,
];
/** Text emitter used by transmogrified formats. */
type Emit = (str: string) => void;
/** Slotted content function used by `asyncYield` mode. */
type SlottedContentGenerator = (
instance: LightningElement
) => AsyncGenerator<string, void, unknown>;
/** Slotted content function used by `sync` and `async` modes. */
type SlottedContentEmitter = ($$emit: Emit, instance: LightningElement) => void;
/** Slotted content map used by `asyncYield` mode. */
type SlottedContentGeneratorMap = Record<number | string, SlottedContentGenerator[]>;
/** Slotted content map used by `sync` and `async` modes. */
type SlottedContentEmitterMap = Record<number | string, SlottedContentEmitter[]>;
/** `generateMarkup` parameters used by `asyncYield` mode. */
type GenerateMarkupGeneratorParams = readonly [
...BaseGenerateMarkupParams,
shadowSlottedContent: SlottedContentGenerator | null,
lightSlottedContent: SlottedContentGeneratorMap | null,
scopedSlottedContent: SlottedContentGeneratorMap | null,
];
/** `generateMarkup` parameters used by `sync` and `async` modes. */
type GenerateMarkupEmitterParams = readonly [
emit: Emit,
...BaseGenerateMarkupParams,
shadowSlottedContent: SlottedContentEmitter | null,
lightSlottedContent: SlottedContentEmitterMap | null,
scopedSlottedContent: SlottedContentEmitterMap | null,
];
/** Signature for `asyncYield` compilation mode. */
export type GenerateMarkupAsyncYield = (
...args: GenerateMarkupGeneratorParams
) => AsyncGenerator<string>;
/** Signature for `async` compilation mode. */
export type GenerateMarkupAsync = (...args: GenerateMarkupEmitterParams) => Promise<void>;
/** Signature for `sync` compilation mode. */
export type GenerateMarkupSync = (...args: GenerateMarkupEmitterParams) => void;
type GenerateMarkupVariants = GenerateMarkupAsyncYield | GenerateMarkupAsync | GenerateMarkupSync;
function renderAttrsPrivate(
instance: LightningElement,
attrs: Attributes,
hostScopeToken: string | undefined,
scopeToken: string | undefined
): string {
// The scopeToken is e.g. `lwc-xyz123` which is the token our parent gives us.
// The hostScopeToken is e.g. `lwc-abc456-host` which is the token for our own component.
// It's possible to have both, one, the other, or neither.
const combinedScopeToken =
scopeToken && hostScopeToken
? `${scopeToken} ${hostScopeToken}`
: scopeToken || hostScopeToken || '';
let result = '';
let hasClassAttribute = false;
for (const attrName of getOwnPropertyNames(attrs)) {
let attrValue = attrs[attrName];
// Backwards compatibility with historical patchStyleAttribute() behavior:
// https://github.com/salesforce/lwc/blob/59e2c6c/packages/%40lwc/engine-core/src/framework/modules/computed-style-attr.ts#L40
if (attrName === 'style' && (!isString(attrValue) || attrValue === '')) {
// If the style attribute is invalid, we don't render it.
continue;
}
if (isNull(attrValue) || isUndefined(attrValue)) {
attrValue = '';
} else if (!isString(attrValue)) {
attrValue = String(attrValue);
}
if (attrName === 'class') {
if (attrValue === '') {
// If the class attribute is empty, we don't render it.
continue;
}
if (combinedScopeToken) {
attrValue += ' ' + combinedScopeToken;
hasClassAttribute = true;
}
}
result +=
attrValue === '' ? ` ${attrName}` : ` ${attrName}="${htmlEscape(attrValue, true)}"`;
}
// If we didn't render any `class` attribute, render one for the scope token(s)
if (!hasClassAttribute && combinedScopeToken) {
result += ` class="${combinedScopeToken}"`;
}
// For the host scope token only, we encode a special attribute for hydration
if (hostScopeToken) {
result += ` data-lwc-host-scope-token="${hostScopeToken}"`;
}
result += mutationTracker.renderMutatedAttrs(instance);
return result;
}
export function* renderAttrs(
instance: LightningElement,
attrs: Attributes,
hostScopeToken: string | undefined,
scopeToken: string | undefined
) {
yield renderAttrsPrivate(instance, attrs, hostScopeToken, scopeToken);
}
export function renderAttrsNoYield(
emit: (segment: string) => void,
instance: LightningElement,
attrs: Attributes,
hostScopeToken: string | undefined,
scopeToken: string | undefined
) {
emit(renderAttrsPrivate(instance, attrs, hostScopeToken, scopeToken));
}
export async function* fallbackTmpl(
shadowSlottedContent: SlottedContentGenerator | null,
_lightSlottedContent: SlottedContentGeneratorMap | null,
_scopedSlottedContent: SlottedContentGeneratorMap | null,
Cmp: LightningElementConstructor,
instance: LightningElement
): AsyncGenerator<string> {
if (Cmp.renderMode !== 'light') {
yield `<template shadowrootmode="open"></template>`;
if (shadowSlottedContent) {
yield* shadowSlottedContent(instance);
}
}
}
export function fallbackTmplNoYield(
emit: Emit,
shadowSlottedContent: SlottedContentEmitter | null,
_lightSlottedContent: SlottedContentEmitterMap | null,
_scopedSlottedContent: SlottedContentEmitterMap | null,
Cmp: LightningElementConstructor,
instance: LightningElement
): void {
if (Cmp.renderMode !== 'light') {
emit(`<template shadowrootmode="open"></template>`);
if (shadowSlottedContent) {
shadowSlottedContent(emit, instance);
}
}
}
interface ComponentWithGenerateMarkup extends LightningElementConstructor {
[SYMBOL__GENERATE_MARKUP]?: GenerateMarkupVariants;
}
export class RenderContext {
styleDedupeIsEnabled: boolean;
styleDedupePrefix: string;
stylesheetToId = new WeakMap<Stylesheet, string>();
nextId = 0;
constructor(styleDedupe: string | boolean) {
if (styleDedupe || styleDedupe === '') {
this.styleDedupePrefix = typeof styleDedupe === 'string' ? styleDedupe : '';
this.styleDedupeIsEnabled = true;
} else {
this.styleDedupePrefix = '';
this.styleDedupeIsEnabled = false;
}
}
}
/**
* Create a string representing an LWC component for server-side rendering.
* @param tagName The HTML tag name of the component
* @param Component The `LightningElement` component constructor
* @param props HTML attributes to provide for the root component
* @param styleDedupe Provide a string key or `true` to enable style deduping via the `<lwc-style>`
* helper. The key is used to avoid collisions of global IDs.
* @param mode SSR render mode. Can be 'sync', 'async' or 'asyncYield'. Must match the render mode
* used to compile your component.
* @returns String representation of the component
*/
export async function serverSideRenderComponent(
tagName: string,
Component: ComponentWithGenerateMarkup,
props: Properties = {},
styleDedupe: string | boolean = false,
mode: CompilationMode = DEFAULT_SSR_MODE
): Promise<string> {
// TODO [#5309]: Remove this warning after a single release
if (process.env.NODE_ENV !== 'production') {
if (arguments.length === 6 || !['sync', 'async', 'asyncYield'].includes(mode)) {
throw new Error(
"The signature for @lwc/ssr-runtime's `renderComponent` has changed. There is now only one parameter for style dedupe."
);
}
}
if (typeof tagName !== 'string') {
throw new Error(`tagName must be a string, found: ${tagName}`);
}
const generateMarkup = Component[SYMBOL__GENERATE_MARKUP];
let markup = '';
const emit = (segment: string) => {
markup += segment;
};
emit.cxt = new RenderContext(styleDedupe);
if (!generateMarkup) {
// If a non-component is accidentally provided, render an empty template
emit(`<${tagName}>`);
// Using a false type assertion for the `instance` param is safe because it's only used
// if there's slotted content, which we are not providing
fallbackTmplNoYield(emit, null, null, null, Component, null as any);
emit(`</${tagName}>`);
return markup;
}
if (mode === 'asyncYield') {
for await (const segment of (generateMarkup as GenerateMarkupAsyncYield)(
tagName,
props,
null,
null,
null,
null,
null,
null,
null
)) {
markup += segment;
}
} else if (mode === 'async') {
await (generateMarkup as GenerateMarkupAsync)(
emit,
tagName,
props,
null,
null,
null,
null,
null,
null,
null
);
} else if (mode === 'sync') {
(generateMarkup as GenerateMarkupSync)(
emit,
tagName,
props,
null,
null,
null,
null,
null,
null,
null
);
} else {
throw new Error(`Invalid mode: ${mode}`);
}
return markup;
}