Convert src/compiler/compile/render_ssr/index.ts to JavaScript

pull/8569/head
Simon Holthausen 3 years ago
parent 6d5d01efe3
commit 74469618bd

@ -15,9 +15,10 @@ import Text from './handlers/Text.js';
import Title from './handlers/Title.js';
import { collapse_template_literal } from '../utils/collapse_template_literal.js';
import { escape_template } from '../utils/stringify.js';
function noop() {}
/** @type {Record<string, Handler>} */
/** @type {Record<string, {(node: any, renderer: Renderer, options: import('../../interfaces.js').CompileOptions): void}>} */
const handlers = {
AwaitBlock,
Body: noop,
@ -39,18 +40,14 @@ const handlers = {
Title,
Window: noop
};
/** */
export default class Renderer {
/** @default false */
has_bindings = false;
/** @type {import('estree').Identifier} */
name = undefined;
/**
* @default []
* @type {Array<{ current: { value: string }; literal: TemplateLiteral }>}
*/
/** @type {Array<{ current: { value: string }; literal: import('estree').TemplateLiteral }>} */
stack = [];
/** @type {{ value: string }} */
@ -59,10 +56,7 @@ export default class Renderer {
/** @type {import('estree').TemplateLiteral} */
literal = undefined;
/**
* @default []
* @type {AppendTarget[]}
*/
/** @type {import('../../interfaces.js').AppendTarget[]} */
targets = [];
constructor({ name }) {
this.name = name;
@ -111,8 +105,8 @@ export default class Renderer {
}
/**
* @param {INode[]} nodes
* @param {RenderOptions} options
* @param {import('../nodes/interfaces.js').INode[]} nodes
* @param {import('./private.js').RenderOptions} options
*/
render(nodes, options) {
nodes.forEach((node) => {
@ -124,11 +118,3 @@ export default class Renderer {
});
}
}
/** @typedef {(node: any, renderer: Renderer, options: CompileOptions) => void} Handler */
/** @typedef {Object} RenderOptions
* @property {(c:number)=>{line:number;column:number}} locate
* @property {string} [head_id]
* @property {boolean} [has_added_svelte_hash]
*/

@ -4,7 +4,7 @@ import { get_const_tags } from './shared/get_const_tags.js';
/**
* @param {import('../../nodes/AwaitBlock.js').default} node
* @param {import('../Renderer.js').default} renderer
* @param {import('../Renderer.js').RenderOptions} options
* @param {import('../private.js').RenderOptions} options
*/
export default function (node, renderer, options) {
renderer.push();

@ -1,7 +1,7 @@
/**
* @param {import('../../nodes/Comment.js').default} node
* @param {import('../Renderer.js').default} renderer
* @param {import('../Renderer.js').RenderOptions} options
* @param {import('../private.js').RenderOptions} options
*/
export default function (node, renderer, options) {
if (options.preserveComments) {

@ -3,7 +3,7 @@ import { x, p } from 'code-red';
/**
* @param {import('../../nodes/DebugTag.js').default} node
* @param {import('../Renderer.js').default} renderer
* @param {import('../Renderer.js').RenderOptions} options
* @param {import('../private.js').RenderOptions} options
*/
export default function (node, renderer, options) {
if (!options.dev) return;

@ -4,7 +4,7 @@ import { get_const_tags } from './shared/get_const_tags.js';
/**
* @param {import('../../nodes/EachBlock.js').default} node
* @param {import('../Renderer.js').default} renderer
* @param {import('../Renderer.js').RenderOptions} options
* @param {import('../private.js').RenderOptions} options
*/
export default function (node, renderer, options) {
const args = [node.context_node];

@ -15,7 +15,7 @@ import { regex_starts_with_newline } from '../../../utils/patterns.js';
/**
* @param {import('../../nodes/Element.js').default} node
* @param {import('../Renderer.js').default} renderer
* @param {import('../Renderer.js').RenderOptions} options
* @param {import('../private.js').RenderOptions} options
*/
export default function (node, renderer, options) {
const children = remove_whitespace_children(node.children, node.next);

@ -3,7 +3,7 @@ import { x } from 'code-red';
/**
* @param {import('../../nodes/Head.js').default} node
* @param {import('../Renderer.js').default} renderer
* @param {import('../Renderer.js').RenderOptions} options
* @param {import('../private.js').RenderOptions} options
*/
export default function (node, renderer, options) {
const head_options = {

@ -1,7 +1,7 @@
/**
* @param {import('../../nodes/RawMustacheTag.js').default} node
* @param {import('../Renderer.js').default} renderer
* @param {import('../Renderer.js').RenderOptions} options
* @param {import('../private.js').RenderOptions} options
*/
export default function (node, renderer, options) {
if (options.hydratable) renderer.add_string('<!-- HTML_TAG_START -->');

@ -4,7 +4,7 @@ import { get_const_tags } from './shared/get_const_tags.js';
/**
* @param {import('../../nodes/IfBlock.js').default} node
* @param {import('../Renderer.js').default} renderer
* @param {import('../Renderer.js').RenderOptions} options
* @param {import('../private.js').RenderOptions} options
*/
export default function (node, renderer, options) {
const condition = node.expression.node;

@ -18,7 +18,7 @@ function get_prop_value(attribute) {
/**
* @param {import('../../nodes/InlineComponent.js').default} node
* @param {import('../Renderer.js').default} renderer
* @param {import('../Renderer.js').RenderOptions} options
* @param {import('../private.js').RenderOptions} options
*/
export default function (node, renderer, options) {
const binding_props = [];

@ -1,7 +1,7 @@
/**
* @param {import('../../nodes/KeyBlock.js').default} node
* @param {import('../Renderer.js').default} renderer
* @param {import('../Renderer.js').RenderOptions} options
* @param {import('../private.js').RenderOptions} options
*/
export default function (node, renderer, options) {
renderer.render(node.children, options);

@ -5,7 +5,7 @@ import { get_slot_scope } from './shared/get_slot_scope.js';
/**
* @param {import('../../nodes/Slot.js').default} node
* @param {import('../Renderer.js').default} renderer
* @param {import('../Renderer.js').RenderOptions & {
* @param {import('../private.js').RenderOptions & {
* slot_scopes: Map<any, any>;
* }} options
*/

@ -6,7 +6,7 @@ import { get_const_tags } from './shared/get_const_tags.js';
/**
* @param {import('../../nodes/SlotTemplate.js').default} node
* @param {import('../Renderer.js').default} renderer
* @param {import('../Renderer.js').RenderOptions & {
* @param {import('../private.js').RenderOptions & {
* slot_scopes: Map<any, any>;
* }} options
*/

@ -3,7 +3,7 @@ import { x } from 'code-red';
/**
* @param {any} node
* @param {import('../Renderer.js').default} renderer
* @param {import('../Renderer.js').RenderOptions} _options
* @param {import('../private.js').RenderOptions} _options
*/
export default function (node, renderer, _options) {
const snippet = node.expression.node;

@ -3,7 +3,7 @@ import { escape_html } from '../../utils/stringify.js';
/**
* @param {import('../../nodes/Text.js').default} node
* @param {import('../Renderer.js').default} renderer
* @param {import('../Renderer.js').RenderOptions} _options
* @param {import('../private.js').RenderOptions} _options
*/
export default function (node, renderer, _options) {
let text = node.data;
@ -12,7 +12,7 @@ export default function (node, renderer, _options) {
} else if (
!node.parent ||
node.parent.type !== 'Element' ||
(/** @type {import('../../nodes/Element.js').default} */ (node.parent).name !== 'script' &&
/** @type {import('../../nodes/Element.js').default} */ ((node.parent).name !== 'script' &&
/** @type {import('../../nodes/Element.js').default} */ (node.parent).name !== 'style')
) {
// unless this Text node is inside a <script> or <style> element, escape &,<,>

@ -3,7 +3,7 @@ import { x } from 'code-red';
/**
* @param {import('../../nodes/Title.js').default} node
* @param {import('../Renderer.js').default} renderer
* @param {import('../Renderer.js').RenderOptions} options
* @param {import('../private.js').RenderOptions} options
*/
export default function (node, renderer, options) {
renderer.push();

@ -1,176 +1,133 @@
import { b } from 'code-red';
import Component from '../Component';
import { CompileOptions, CssResult } from '../../interfaces';
import { string_literal } from '../utils/stringify';
import Renderer from './Renderer';
import { INode as TemplateNode } from '../nodes/interfaces'; // TODO
import Text from '../nodes/Text';
import { LabeledStatement, Statement, Node } from 'estree';
import { string_literal } from '../utils/stringify.js';
import Renderer from './Renderer.js';
import { extract_names } from 'periscopic';
import { walk } from 'estree-walker';
import { invalidate } from '../render_dom/invalidate';
import check_enable_sourcemap from '../utils/check_enable_sourcemap';
export default function ssr(
component: Component,
options: CompileOptions
): { js: Node[]; css: CssResult } {
const renderer = new Renderer({
name: component.name
});
const { name } = component;
// create $$render function
renderer.render(
trim(component.fragment.children),
Object.assign(
{
locate: component.locate
},
options
)
);
// TODO put this inside the Renderer class
const literal = renderer.pop();
// TODO concatenate CSS maps
const css = options.customElement
? { code: null, map: null }
: component.stylesheet.render(options.filename);
const uses_rest = component.var_lookup.has('$$restProps');
const props = component.vars.filter((variable) => !variable.module && variable.export_name);
const rest = uses_rest
? b`let $$restProps = @compute_rest_props($$props, [${props
.map((prop) => `"${prop.export_name}"`)
.join(',')}]);`
: null;
const uses_slots = component.var_lookup.has('$$slots');
const slots = uses_slots ? b`let $$slots = @compute_slots(#slots);` : null;
const reactive_stores = component.vars.filter(
(variable) => variable.name[0] === '$' && variable.name[1] !== '$'
);
const reactive_store_subscriptions = reactive_stores
.filter((store) => {
const variable = component.var_lookup.get(store.name.slice(1));
return !variable || variable.hoistable;
})
.map(({ name }) => {
const store_name = name.slice(1);
return b`
${component.compile_options.dev && b`@validate_store(${store_name}, '${store_name}');`}
import { invalidate } from '../render_dom/invalidate.js';
import check_enable_sourcemap from '../utils/check_enable_sourcemap.js';
/**
* @param {import('../Component.js').default} component
* @param {import('../../interfaces.js').CompileOptions} options
* @returns {{ js: import("C:/repos/svelte/svelte/node_modules/.pnpm/@types+estree@1.0.0/node_modules/@types/estree/index").Node[]; css: CssResult; }}
*/
export default function ssr(component, options) {
const renderer = new Renderer({
name: component.name
});
const { name } = component;
// create $$render function
renderer.render(trim(component.fragment.children), Object.assign({
locate: component.locate
}, options));
// TODO put this inside the Renderer class
const literal = renderer.pop();
// TODO concatenate CSS maps
const css = options.customElement
? { code: null, map: null }
: component.stylesheet.render(options.filename);
const uses_rest = component.var_lookup.has('$$restProps');
const props = component.vars.filter((variable) => !variable.module && variable.export_name);
const rest = uses_rest
? b `let $$restProps = @compute_rest_props($$props, [${props
.map((prop) => `"${prop.export_name}"`)
.join(',')}]);`
: null;
const uses_slots = component.var_lookup.has('$$slots');
const slots = uses_slots ? b `let $$slots = @compute_slots(#slots);` : null;
const reactive_stores = component.vars.filter((variable) => variable.name[0] === '$' && variable.name[1] !== '$');
const reactive_store_subscriptions = reactive_stores
.filter((store) => {
const variable = component.var_lookup.get(store.name.slice(1));
return !variable || variable.hoistable;
})
.map(({ name }) => {
const store_name = name.slice(1);
return b `
${component.compile_options.dev && b `@validate_store(${store_name}, '${store_name}');`}
${`$$unsubscribe_${store_name}`} = @subscribe(${store_name}, #value => ${name} = #value)
`;
});
const reactive_store_unsubscriptions = reactive_stores.map(
({ name }) => b`${`$$unsubscribe_${name.slice(1)}`}()`
);
const reactive_store_declarations = reactive_stores.map(({ name }) => {
const store_name = name.slice(1);
const store = component.var_lookup.get(store_name);
if (store && store.reassigned) {
const unsubscribe = `$$unsubscribe_${store_name}`;
const subscribe = `$$subscribe_${store_name}`;
return b`let ${name}, ${unsubscribe} = @noop, ${subscribe} = () => (${unsubscribe}(), ${unsubscribe} = @subscribe(${store_name}, $$value => ${name} = $$value), ${store_name})`;
}
return b`let ${name}, ${`$$unsubscribe_${store_name}`};`;
});
// instrument get/set store value
if (component.ast.instance) {
let scope = component.instance_scope;
const map = component.instance_scope_map;
walk(component.ast.instance.content, {
enter(node: Node) {
if (map.has(node)) {
scope = map.get(node);
}
},
leave(node: Node) {
if (map.has(node)) {
scope = scope.parent;
}
if (node.type === 'AssignmentExpression' || node.type === 'UpdateExpression') {
const assignee = node.type === 'AssignmentExpression' ? node.left : node.argument;
const names = new Set(extract_names(assignee as Node));
const to_invalidate = new Set<string>();
for (const name of names) {
const variable = component.var_lookup.get(name);
if (
variable &&
!variable.hoistable &&
!variable.global &&
!variable.module &&
(variable.subscribable || variable.name[0] === '$')
) {
to_invalidate.add(variable.name);
}
}
if (to_invalidate.size) {
this.replace(invalidate({ component } as any, scope, node, to_invalidate, true));
}
}
}
});
}
component.rewrite_props(({ name, reassigned }) => {
const value = `$${name}`;
let insert = reassigned
? b`${`$$subscribe_${name}`}()`
: b`${`$$unsubscribe_${name}`} = @subscribe(${name}, #value => $${value} = #value)`;
if (component.compile_options.dev) {
insert = b`@validate_store(${name}, '${name}'); ${insert}`;
}
return insert;
});
const instance_javascript = component.extract_javascript(component.ast.instance);
// TODO only do this for props with a default value
const parent_bindings = instance_javascript
? component.vars
.filter((variable) => !variable.module && variable.export_name)
.map((prop) => {
return b`if ($$props.${prop.export_name} === void 0 && $$bindings.${prop.export_name} && ${prop.name} !== void 0) $$bindings.${prop.export_name}(${prop.name});`;
})
: [];
const injected = Array.from(component.injected_reactive_declaration_vars).filter((name) => {
const variable = component.var_lookup.get(name);
return variable.injected;
});
const reactive_declarations = component.reactive_declarations.map((d) => {
const body: Statement = (d.node as LabeledStatement).body;
let statement = b`${body}`;
if (!d.declaration) {
// TODO do not add label if it's not referenced
statement = b`$: { ${statement} }`;
}
return statement;
});
const main = renderer.has_bindings
? b`
});
const reactive_store_unsubscriptions = reactive_stores.map(({ name }) => b `${`$$unsubscribe_${name.slice(1)}`}()`);
const reactive_store_declarations = reactive_stores.map(({ name }) => {
const store_name = name.slice(1);
const store = component.var_lookup.get(store_name);
if (store && store.reassigned) {
const unsubscribe = `$$unsubscribe_${store_name}`;
const subscribe = `$$subscribe_${store_name}`;
return b `let ${name}, ${unsubscribe} = @noop, ${subscribe} = () => (${unsubscribe}(), ${unsubscribe} = @subscribe(${store_name}, $$value => ${name} = $$value), ${store_name})`;
}
return b `let ${name}, ${`$$unsubscribe_${store_name}`};`;
});
// instrument get/set store value
if (component.ast.instance) {
let scope = component.instance_scope;
const map = component.instance_scope_map;
walk(component.ast.instance.content, {
enter(node) {
if (map.has(node)) {
scope = map.get(node);
}
},
leave(node) {
if (map.has(node)) {
scope = scope.parent;
}
if (node.type === 'AssignmentExpression' || node.type === 'UpdateExpression') {
const assignee = node.type === 'AssignmentExpression' ? node.left : node.argument;
const names = new Set(extract_names(/** @type {import('estree').Node} */ (assignee)));
const to_invalidate = new Set();
for (const name of names) {
const variable = component.var_lookup.get(name);
if (variable &&
!variable.hoistable &&
!variable.global &&
!variable.module &&
(variable.subscribable || variable.name[0] === '$')) {
to_invalidate.add(variable.name);
}
}
if (to_invalidate.size) {
this.replace(invalidate(/** @type {any} */ ({ component }), scope, node, to_invalidate, true));
}
}
}
});
}
component.rewrite_props(({ name, reassigned }) => {
const value = `$${name}`;
let insert = reassigned
? b `${`$$subscribe_${name}`}()`
: b `${`$$unsubscribe_${name}`} = @subscribe(${name}, #value => $${value} = #value)`;
if (component.compile_options.dev) {
insert = b `@validate_store(${name}, '${name}'); ${insert}`;
}
return insert;
});
const instance_javascript = component.extract_javascript(component.ast.instance);
// TODO only do this for props with a default value
const parent_bindings = instance_javascript
? component.vars
.filter((variable) => !variable.module && variable.export_name)
.map((prop) => {
return b `if ($$props.${prop.export_name} === void 0 && $$bindings.${prop.export_name} && ${prop.name} !== void 0) $$bindings.${prop.export_name}(${prop.name});`;
})
: [];
const injected = Array.from(component.injected_reactive_declaration_vars).filter((name) => {
const variable = component.var_lookup.get(name);
return variable.injected;
});
const reactive_declarations = component.reactive_declarations.map((d) => {
const body = ( /** @type {import('estree').LabeledStatement} */(d.node)).body;
let statement = b `${body}`;
if (!d.declaration) {
// TODO do not add label if it's not referenced
statement = b `$: { ${statement} }`;
}
return statement;
});
const main = renderer.has_bindings
? b `
let $$settled;
let $$rendered;
@ -186,37 +143,32 @@ export default function ssr(
return $$rendered;
`
: b`
: b `
${reactive_declarations}
${reactive_store_unsubscriptions}
return ${literal};`;
const blocks = [
...injected.map((name) => b`let ${name};`),
rest,
slots,
...reactive_store_declarations,
...reactive_store_subscriptions,
instance_javascript,
...parent_bindings,
css.code && b`$$result.css.add(#css);`,
main
].filter(Boolean);
const css_sourcemap_enabled = check_enable_sourcemap(options.enableSourcemap, 'css');
const js = b`
${
css.code
? b`
const blocks = [
...injected.map((name) => b `let ${name};`),
rest,
slots,
...reactive_store_declarations,
...reactive_store_subscriptions,
instance_javascript,
...parent_bindings,
css.code && b `$$result.css.add(#css);`,
main
].filter(Boolean);
const css_sourcemap_enabled = check_enable_sourcemap(options.enableSourcemap, 'css');
const js = b `
${css.code
? b `
const #css = {
code: "${css.code}",
map: ${css_sourcemap_enabled && css.map ? string_literal(css.map.toString()) : 'null'}
};`
: null
}
: null}
${component.extract_javascript(component.ast.module)}
@ -226,28 +178,32 @@ export default function ssr(
${blocks}
});
`;
return { js, css };
return { js, css };
}
function trim(nodes: TemplateNode[]) {
let start = 0;
for (; start < nodes.length; start += 1) {
const node = nodes[start] as Text;
if (node.type !== 'Text') break;
/** @param {TemplateNode[]} nodes */
function trim(nodes) {
let start = 0;
for (; start < nodes.length; start += 1) {
const node = /** @type {import('../nodes/Text.js').default} */ (nodes[start]);
if (node.type !== 'Text')
break;
node.data = node.data.replace(/^\s+/, '');
if (node.data)
break;
}
let end = nodes.length;
for (; end > start; end -= 1) {
const node = /** @type {import('../nodes/Text.js').default} */ (nodes[end - 1]);
if (node.type !== 'Text')
break;
node.data = node.data.trimRight();
if (node.data)
break;
}
return nodes.slice(start, end);
}
node.data = node.data.replace(/^\s+/, '');
if (node.data) break;
}
let end = nodes.length;
for (; end > start; end -= 1) {
const node = nodes[end - 1] as Text;
if (node.type !== 'Text') break;
node.data = node.data.trimRight();
if (node.data) break;
}
return nodes.slice(start, end);
}

@ -0,0 +1,7 @@
import { CompileOptions } from '../../interfaces.js';
export interface RenderOptions extends CompileOptions {
locate: (c: number) => { line: number; column: number };
head_id?: string;
has_added_svelte_hash?: boolean;
}
Loading…
Cancel
Save