forked from QwikDev/qwik
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathssr-render-jsx.ts
561 lines (533 loc) · 19.3 KB
/
ssr-render-jsx.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
import { isDev } from '@qwik.dev/core/build';
import { isQwikComponent } from '../shared/component.public';
import { isQrl } from '../shared/qrl/qrl-class';
import type { QRL } from '../shared/qrl/qrl.public';
import { Fragment, directGetPropsProxyProp } from '../shared/jsx/jsx-runtime';
import { Slot } from '../shared/jsx/slot.public';
import type { JSXNodeInternal, JSXOutput } from '../shared/jsx/types/jsx-node';
import type { JSXChildren } from '../shared/jsx/types/jsx-qwik-attributes';
import { SSRComment, SSRRaw, SSRStream, type SSRStreamChildren } from '../shared/jsx/utils.public';
import { trackSignalAndAssignHost } from '../use/use-core';
import { isAsyncGenerator } from '../shared/utils/async-generator';
import { EMPTY_ARRAY } from '../shared/utils/flyweight';
import {
ELEMENT_KEY,
FLUSH_COMMENT,
QDefaultSlot,
QScopedStyle,
QSlot,
qwikInspectorAttr,
} from '../shared/utils/markers';
import { isPromise } from '../shared/utils/promises';
import { isFunction, type ValueOrPromise } from '../shared/utils/types';
import {
convertEventNameFromJsxPropToHtmlAttr,
getEventNameFromJsxProp,
isJsxPropertyAnEventName,
isPreventDefault,
} from '../shared/utils/event-names';
import { addComponentStylePrefix, isClassAttr } from '../shared/utils/scoped-styles';
import { qrlToString, type SerializationContext } from '../shared/shared-serialization';
import { DEBUG_TYPE, VirtualType } from '../shared/types';
import { WrappedSignal, EffectProperty, isSignal } from '../signal/signal';
import { applyInlineComponent, applyQwikComponentBody } from './ssr-render-component';
import type { ISsrComponentFrame, ISsrNode, SSRContainer, SsrAttrs } from './ssr-types';
import { qInspector } from '../shared/utils/qdev';
import { serializeAttribute } from '../shared/utils/styles';
import { QError, qError } from '../shared/error/error';
import { getFileLocationFromJsx } from '../shared/utils/jsx-filename';
class ParentComponentData {
constructor(
public $scopedStyle$: string | null,
public $componentFrame$: ISsrComponentFrame | null
) {}
}
type StackFn = () => ValueOrPromise<void>;
type StackValue = ValueOrPromise<
JSXOutput | StackFn | Promise<JSXOutput> | typeof Promise | ParentComponentData | AsyncGenerator
>;
/** @internal */
export function _walkJSX(
ssr: SSRContainer,
value: JSXOutput,
options: {
allowPromises: true;
currentStyleScoped: string | null;
parentComponentFrame: ISsrComponentFrame | null;
}
): ValueOrPromise<void>;
/** @internal */
export function _walkJSX(
ssr: SSRContainer,
value: JSXOutput,
options: {
allowPromises: false;
currentStyleScoped: string | null;
parentComponentFrame: ISsrComponentFrame | null;
}
): false;
/** @internal */
export function _walkJSX(
ssr: SSRContainer,
value: JSXOutput,
options: {
allowPromises: boolean;
currentStyleScoped: string | null;
parentComponentFrame: ISsrComponentFrame | null;
}
): ValueOrPromise<void> | false {
const stack: StackValue[] = [value];
let resolveDrain: () => void;
let rejectDrain: (reason: any) => void;
const drained =
options.allowPromises &&
new Promise<void>((res, rej) => {
resolveDrain = res;
rejectDrain = rej;
});
const enqueue = (value: StackValue) => stack.push(value);
const resolveValue = (value: JSXOutput) => {
stack.push(value);
drain();
};
const drain = (): void => {
while (stack.length) {
const value = stack.pop();
if (value instanceof ParentComponentData) {
options.currentStyleScoped = value.$scopedStyle$;
options.parentComponentFrame = value.$componentFrame$;
continue;
} else if (typeof value === 'function') {
if (value === Promise) {
if (!options.allowPromises) {
throw qError(QError.promisesNotExpected);
}
(stack.pop() as Promise<JSXOutput>).then(resolveValue, rejectDrain);
return;
}
const waitOn = (value as StackFn).apply(ssr);
if (waitOn) {
if (!options.allowPromises) {
throw qError(QError.promisesNotExpected);
}
waitOn.then(drain, rejectDrain);
return;
}
continue;
}
processJSXNode(ssr, enqueue, value as JSXOutput, {
styleScoped: options.currentStyleScoped,
parentComponentFrame: options.parentComponentFrame,
});
}
if (stack.length === 0 && options.allowPromises) {
resolveDrain();
}
};
drain();
return drained;
}
function processJSXNode(
ssr: SSRContainer,
enqueue: (value: StackValue) => void,
value: JSXOutput,
options: {
styleScoped: string | null;
parentComponentFrame: ISsrComponentFrame | null;
}
) {
// console.log('processJSXNode', value);
if (value === null || value === undefined) {
ssr.textNode('');
} else if (typeof value === 'boolean') {
ssr.textNode('');
} else if (typeof value === 'number') {
ssr.textNode(String(value));
} else if (typeof value === 'string') {
ssr.textNode(value);
} else if (typeof value === 'object') {
if (Array.isArray(value)) {
for (let i = value.length - 1; i >= 0; i--) {
enqueue(value[i]);
}
} else if (isSignal(value)) {
ssr.openFragment(isDev ? [DEBUG_TYPE, VirtualType.WrappedSignal] : EMPTY_ARRAY);
const signalNode = ssr.getLastNode();
enqueue(ssr.closeFragment);
enqueue(trackSignalAndAssignHost(value, signalNode, EffectProperty.VNODE, ssr));
} else if (isPromise(value)) {
ssr.openFragment(isDev ? [DEBUG_TYPE, VirtualType.Awaited] : EMPTY_ARRAY);
enqueue(ssr.closeFragment);
enqueue(value);
enqueue(Promise);
enqueue(() => ssr.commentNode(FLUSH_COMMENT));
} else if (isAsyncGenerator(value)) {
enqueue(async () => {
for await (const chunk of value) {
await _walkJSX(ssr, chunk as JSXOutput, {
allowPromises: true,
currentStyleScoped: options.styleScoped,
parentComponentFrame: options.parentComponentFrame,
});
ssr.commentNode(FLUSH_COMMENT);
}
});
} else {
const jsx = value as JSXNodeInternal;
const type = jsx.type;
// Below, JSXChildren allows functions and regexes, but we assume the dev only uses those as appropriate.
if (typeof type === 'string') {
appendClassIfScopedStyleExists(jsx, options.styleScoped);
let qwikInspectorAttrValue: string | null = null;
if (isDev && jsx.dev && jsx.type !== 'head') {
qwikInspectorAttrValue = getFileLocationFromJsx(jsx.dev);
if (qInspector) {
appendQwikInspectorAttribute(jsx, qwikInspectorAttrValue);
}
}
const innerHTML = ssr.openElement(
type,
varPropsToSsrAttrs(
jsx.varProps,
jsx.constProps,
ssr.serializationCtx,
options.styleScoped,
jsx.key
),
constPropsToSsrAttrs(
jsx.constProps,
jsx.varProps,
ssr.serializationCtx,
options.styleScoped
),
qwikInspectorAttrValue
);
if (innerHTML) {
ssr.htmlNode(innerHTML);
}
enqueue(ssr.closeElement);
if (type === 'head') {
enqueue(ssr.additionalHeadNodes);
enqueue(ssr.emitQwikLoaderAtTopIfNeeded);
} else if (type === 'body') {
enqueue(ssr.additionalBodyNodes);
}
const children = jsx.children as JSXOutput;
children != null && enqueue(children);
} else if (isFunction(type)) {
if (type === Fragment) {
let attrs = jsx.key != null ? [ELEMENT_KEY, jsx.key] : EMPTY_ARRAY;
if (isDev) {
attrs = [DEBUG_TYPE, VirtualType.Fragment, ...attrs]; // Add debug info.
}
ssr.openFragment(attrs);
ssr.addCurrentElementFrameAsComponentChild();
enqueue(ssr.closeFragment);
// In theory we could get functions or regexes, but we assume all is well
const children = jsx.children as JSXOutput;
children != null && enqueue(children);
} else if (type === Slot) {
const componentFrame =
options.parentComponentFrame || ssr.unclaimedProjectionComponentFrameQueue.shift();
if (componentFrame) {
const compId = componentFrame.componentNode.id || '';
const projectionAttrs = isDev ? [DEBUG_TYPE, VirtualType.Projection] : [];
projectionAttrs.push(':', compId);
ssr.openProjection(projectionAttrs);
const host = componentFrame.componentNode;
const node = ssr.getLastNode();
const slotName = getSlotName(host, jsx, ssr);
projectionAttrs.push(QSlot, slotName);
enqueue(new ParentComponentData(options.styleScoped, options.parentComponentFrame));
enqueue(ssr.closeProjection);
const slotDefaultChildren: JSXChildren | null = jsx.children || null;
const slotChildren =
componentFrame.consumeChildrenForSlot(node, slotName) || slotDefaultChildren;
if (slotDefaultChildren && slotChildren !== slotDefaultChildren) {
ssr.addUnclaimedProjection(componentFrame, QDefaultSlot, slotDefaultChildren);
}
enqueue(slotChildren as JSXOutput);
enqueue(
new ParentComponentData(
componentFrame.projectionScopedStyle,
componentFrame.projectionComponentFrame
)
);
} else {
// Even thought we are not projecting we still need to leave a marker for the slot.
ssr.openFragment(isDev ? [DEBUG_TYPE, VirtualType.Projection] : EMPTY_ARRAY);
ssr.closeFragment();
}
} else if (type === SSRComment) {
ssr.commentNode(directGetPropsProxyProp(jsx, 'data') || '');
} else if (type === SSRStream) {
ssr.commentNode(FLUSH_COMMENT);
const generator = jsx.children as SSRStreamChildren;
let value: AsyncGenerator | Promise<void>;
if (isFunction(generator)) {
value = generator({
async write(chunk) {
await _walkJSX(ssr, chunk as JSXOutput, {
allowPromises: true,
currentStyleScoped: options.styleScoped,
parentComponentFrame: options.parentComponentFrame,
});
ssr.commentNode(FLUSH_COMMENT);
},
});
} else {
value = generator;
}
enqueue(value as StackValue);
isPromise(value) && enqueue(Promise);
} else if (type === SSRRaw) {
ssr.htmlNode(directGetPropsProxyProp(jsx, 'data'));
} else if (isQwikComponent(type)) {
// prod: use new instance of an array for props, we always modify props for a component
ssr.openComponent(isDev ? [DEBUG_TYPE, VirtualType.Component] : []);
const host = ssr.getLastNode();
const componentFrame = ssr.getParentComponentFrame()!;
componentFrame!.distributeChildrenIntoSlots(
jsx.children,
options.styleScoped,
options.parentComponentFrame
);
const jsxOutput = applyQwikComponentBody(ssr, jsx, type);
const compStyleComponentId = addComponentStylePrefix(host.getProp(QScopedStyle));
enqueue(new ParentComponentData(options.styleScoped, options.parentComponentFrame));
enqueue(ssr.closeComponent);
enqueue(jsxOutput);
isPromise(jsxOutput) && enqueue(Promise);
enqueue(new ParentComponentData(compStyleComponentId, componentFrame));
} else {
const inlineComponentProps = [ELEMENT_KEY, jsx.key];
ssr.openFragment(
isDev
? [DEBUG_TYPE, VirtualType.InlineComponent, ...inlineComponentProps]
: inlineComponentProps
);
enqueue(ssr.closeFragment);
const component = ssr.getComponentFrame(0)!;
const jsxOutput = applyInlineComponent(
ssr,
component && component.componentNode,
type,
jsx
);
enqueue(jsxOutput);
isPromise(jsxOutput) && enqueue(Promise);
}
}
}
}
}
export function varPropsToSsrAttrs(
varProps: Record<string, unknown>,
constProps: Record<string, unknown> | null,
serializationCtx: SerializationContext,
styleScopedId: string | null,
key?: string | null
): SsrAttrs | null {
return toSsrAttrs(varProps, constProps, serializationCtx, true, styleScopedId, key);
}
export function constPropsToSsrAttrs(
constProps: Record<string, unknown> | null,
varProps: Record<string, unknown>,
serializationCtx: SerializationContext,
styleScopedId: string | null
): SsrAttrs | null {
return toSsrAttrs(constProps, varProps, serializationCtx, false, styleScopedId);
}
export function toSsrAttrs(
record: Record<string, unknown>,
anotherRecord: Record<string, unknown>,
serializationCtx: SerializationContext,
pushMergedEventProps: boolean,
styleScopedId: string | null,
key?: string | null
): SsrAttrs;
export function toSsrAttrs(
record: Record<string, unknown> | null | undefined,
anotherRecord: Record<string, unknown> | null | undefined,
serializationCtx: SerializationContext,
pushMergedEventProps: boolean,
styleScopedId: string | null,
key?: string | null
): SsrAttrs | null;
export function toSsrAttrs(
record: Record<string, unknown> | null | undefined,
anotherRecord: Record<string, unknown> | null | undefined,
serializationCtx: SerializationContext,
pushMergedEventProps: boolean,
styleScopedId: string | null,
key?: string | null
): SsrAttrs | null {
if (record == null) {
return null;
}
const ssrAttrs: SsrAttrs = [];
for (const key in record) {
let value = record[key];
if (isJsxPropertyAnEventName(key)) {
if (anotherRecord) {
/**
* If we have two sources of the same event like this:
*
* ```tsx
* const Counter = component$((props: { initial: number }) => {
* const count = useSignal(props.initial);
* useOnWindow(
* 'dblclick',
* $(() => count.value++)
* );
* return <button window:onDblClick$={() => count.value++}>Count: {count.value}!</button>;
* });
* ```
*
* Then we can end with the const and var props with the same (doubled) event. We process
* the const and var props separately, so:
*
* - For the var props we need to merge them into the one value (array)
* - For the const props we need to just skip, because we will handle this in the var props
*/
const anotherValue = getEventProp(anotherRecord, key);
if (anotherValue) {
if (pushMergedEventProps) {
// merge values from the const props with the var props
value = getMergedEventPropValues(value, anotherValue);
} else {
continue;
}
}
}
const eventValue = setEvent(serializationCtx, key, value);
if (eventValue) {
ssrAttrs.push(convertEventNameFromJsxPropToHtmlAttr(key), eventValue);
}
continue;
}
if (isSignal(value)) {
// write signal as is. We will track this signal inside `writeAttrs`
if (isClassAttr(key)) {
// additionally append styleScopedId for class attr
ssrAttrs.push(key, [value, styleScopedId]);
} else {
ssrAttrs.push(key, value);
}
continue;
}
if (isPreventDefault(key)) {
addPreventDefaultEventToSerializationContext(serializationCtx, key);
}
value = serializeAttribute(key, value, styleScopedId);
ssrAttrs.push(key, value as string);
}
if (key != null) {
ssrAttrs.push(ELEMENT_KEY, key);
}
return ssrAttrs;
}
function getMergedEventPropValues(value: unknown, anotherValue: unknown) {
let mergedValue = value;
// merge values from the const props with the var props
if (Array.isArray(value) && Array.isArray(anotherValue)) {
// both values are arrays
mergedValue = value.concat(anotherValue);
} else if (Array.isArray(mergedValue)) {
// only first value is array
mergedValue.push(anotherValue);
} else if (Array.isArray(anotherValue)) {
// only second value is array
mergedValue = anotherValue;
(mergedValue as unknown[]).push(value);
} else {
// none of these values are array
mergedValue = [value, anotherValue];
}
return mergedValue;
}
function getEventProp(record: Record<string, unknown>, propKey: string): unknown | null {
const eventProp = propKey.toLowerCase();
for (const prop in record) {
if (prop.toLowerCase() === eventProp) {
return record[prop];
}
}
return null;
}
function setEvent(
serializationCtx: SerializationContext,
key: string,
rawValue: unknown
): string | null {
let value: string | null = null;
const qrls = rawValue;
const appendToValue = (valueToAppend: string) => {
value = (value == null ? '' : value + '\n') + valueToAppend;
};
if (Array.isArray(qrls)) {
for (let i = 0; i <= qrls.length; i++) {
const qrl: unknown = qrls[i];
if (isQrl(qrl)) {
appendToValue(qrlToString(serializationCtx, qrl));
addQwikEventToSerializationContext(serializationCtx, key, qrl);
} else if (qrl != null) {
// nested arrays etc.
const nestedValue = setEvent(serializationCtx, key, qrl);
if (nestedValue) {
appendToValue(nestedValue);
}
}
}
} else if (isQrl(qrls)) {
value = qrlToString(serializationCtx, qrls);
addQwikEventToSerializationContext(serializationCtx, key, qrls);
}
return value;
}
function addQwikEventToSerializationContext(
serializationCtx: SerializationContext,
key: string,
qrl: QRL
) {
const eventName = getEventNameFromJsxProp(key);
if (eventName) {
serializationCtx.$eventNames$.add(eventName);
serializationCtx.$eventQrls$.add(qrl);
}
}
function addPreventDefaultEventToSerializationContext(
serializationCtx: SerializationContext,
key: string
) {
// skip first 15 chars, this is length of the `preventdefault:`
const eventName = key.substring(15);
if (eventName) {
serializationCtx.$eventNames$.add(eventName);
}
}
function getSlotName(host: ISsrNode, jsx: JSXNodeInternal, ssr: SSRContainer): string {
const constProps = jsx.constProps;
if (constProps && typeof constProps == 'object' && 'name' in constProps) {
const constValue = constProps.name;
if (constValue instanceof WrappedSignal) {
return trackSignalAndAssignHost(constValue, host, EffectProperty.COMPONENT, ssr);
}
}
return directGetPropsProxyProp(jsx, 'name') || QDefaultSlot;
}
function appendQwikInspectorAttribute(jsx: JSXNodeInternal, qwikInspectorAttrValue: string | null) {
if (qwikInspectorAttrValue && (!jsx.constProps || !(qwikInspectorAttr in jsx.constProps))) {
(jsx.constProps ||= {})[qwikInspectorAttr] = qwikInspectorAttrValue;
}
}
// append class attribute if styleScopedId exists and there is no class attribute
function appendClassIfScopedStyleExists(jsx: JSXNodeInternal, styleScoped: string | null) {
const classAttributeExists = directGetPropsProxyProp(jsx, 'class') != null;
if (!classAttributeExists && styleScoped) {
if (!jsx.constProps) {
jsx.constProps = {};
}
jsx.constProps['class'] = '';
}
}