Convert src/compiler/compile/render_dom/Block.ts to JavaScript

pull/8569/head
Simon Holthausen 3 years ago
parent f241b93ef3
commit da35939361

@ -1,96 +1,113 @@
import Renderer, { BindingGroup } from './Renderer';
import Wrapper from './wrappers/shared/Wrapper';
import { b, x } from 'code-red'; import { b, x } from 'code-red';
import { Node, Identifier, ArrayPattern } from 'estree'; import { is_head } from './wrappers/shared/is_head.js';
import { is_head } from './wrappers/shared/is_head'; import { regex_double_quotes } from '../../utils/patterns.js';
import { regex_double_quotes } from '../../utils/patterns'; export default class Block {
export interface Bindings {
object: Identifier;
property: Identifier;
snippet: Node;
store: string;
modifier: (node: Node) => Node;
}
export interface BlockOptions { /** @type {Block} */
parent?: Block; parent;
name: Identifier;
type: string;
renderer?: Renderer;
comment?: string;
key?: Identifier;
bindings?: Map<string, Bindings>;
dependencies?: Set<string>;
}
export default class Block { /** @type {import('./Renderer.js').default} */
parent?: Block; renderer;
renderer: Renderer;
name: Identifier; /** @type {import('estree').Identifier} */
type: string; name;
comment?: string;
/** @type {string} */
wrappers: Wrapper[]; type;
key: Identifier; /** @type {string} */
first: Identifier; comment;
dependencies: Set<string> = new Set(); /** @type {import('./wrappers/shared/Wrapper.js').default[]} */
wrappers;
bindings: Map<string, Bindings>;
binding_group_initialised: Set<string> = new Set(); /** @type {import('estree').Identifier} */
binding_groups: Set<BindingGroup> = new Set(); key;
chunks: { /** @type {import('estree').Identifier} */
declarations: Array<Node | Node[]>; first;
init: Array<Node | Node[]>;
create: Array<Node | Node[]>; /** @type {Set<string>} */
claim: Array<Node | Node[]>; dependencies = new Set();
hydrate: Array<Node | Node[]>;
mount: Array<Node | Node[]>; /** @type {Map<string, Bindings>} */
measure: Array<Node | Node[]>; bindings;
restore_measurements: Array<Node | Node[]>;
fix: Array<Node | Node[]>;
animate: Array<Node | Node[]>;
intro: Array<Node | Node[]>;
update: Array<Node | Node[]>;
outro: Array<Node | Node[]>;
destroy: Array<Node | Node[]>;
};
event_listeners: Node[] = []; /** @type {Set<string>} */
binding_group_initialised = new Set();
maintain_context: boolean; /** @type {Set<import('./Renderer.js').BindingGroup>} */
has_animation: boolean; binding_groups = new Set();
has_intros: boolean; /**
has_outros: boolean; * @type {{
has_intro_method: boolean; // could have the method without the transition, due to siblings * declarations: Array<import('estree').Node | import('estree').Node[]>;
has_outro_method: boolean; * init: Array<import('estree').Node | import('estree').Node[]>;
outros: number; * create: Array<import('estree').Node | import('estree').Node[]>;
* claim: Array<import('estree').Node | import('estree').Node[]>;
* hydrate: Array<import('estree').Node | import('estree').Node[]>;
* mount: Array<import('estree').Node | import('estree').Node[]>;
* measure: Array<import('estree').Node | import('estree').Node[]>;
* restore_measurements: Array<import('estree').Node | import('estree').Node[]>;
* fix: Array<import('estree').Node | import('estree').Node[]>;
* animate: Array<import('estree').Node | import('estree').Node[]>;
* intro: Array<import('estree').Node | import('estree').Node[]>;
* update: Array<import('estree').Node | import('estree').Node[]>;
* outro: Array<import('estree').Node | import('estree').Node[]>;
* destroy: Array<import('estree').Node | import('estree').Node[]>;
* }}
*/
chunks;
aliases: Map<string, Identifier>; /** @type {import('estree').Node[]} */
variables: Map<string, { id: Identifier; init?: Node }> = new Map(); event_listeners = [];
get_unique_name: (name: string) => Identifier;
/** @type {boolean} */
maintain_context;
/** @type {boolean} */
has_animation;
/** @type {boolean} */
has_intros;
/** @type {boolean} */
has_outros;
/** @type {boolean} */
has_intro_method; // could have the method without the transition, due to siblings
/** @type {boolean} */
has_outro_method;
/** @type {number} */
outros;
/** @type {Map<string, import('estree').Identifier>} */
aliases;
/** @type {Map<string, { id: import('estree').Identifier; init?: import('estree').Node }>} */
variables = new Map();
/** @type {(name: string) => import('estree').Identifier} */
get_unique_name;
/** */
has_update_method = false; has_update_method = false;
autofocus?: { element_var: string; condition_expression?: any };
constructor(options: BlockOptions) { /** @type {{ element_var: string; condition_expression?: any }} */
autofocus;
/** @param {BlockOptions} options */
constructor(options) {
this.parent = options.parent; this.parent = options.parent;
this.renderer = options.renderer; this.renderer = options.renderer;
this.name = options.name; this.name = options.name;
this.type = options.type; this.type = options.type;
this.comment = options.comment; this.comment = options.comment;
this.wrappers = []; this.wrappers = [];
// for keyed each blocks // for keyed each blocks
this.key = options.key; this.key = options.key;
this.first = null; this.first = null;
this.bindings = options.bindings; this.bindings = options.bindings;
this.chunks = { this.chunks = {
declarations: [], declarations: [],
init: [], init: [],
@ -107,44 +124,38 @@ export default class Block {
outro: [], outro: [],
destroy: [] destroy: []
}; };
this.has_animation = false; this.has_animation = false;
this.has_intro_method = false; // a block could have an intro method but not intro transitions, e.g. if a sibling block has intros this.has_intro_method = false; // a block could have an intro method but not intro transitions, e.g. if a sibling block has intros
this.has_outro_method = false; this.has_outro_method = false;
this.outros = 0; this.outros = 0;
this.get_unique_name = this.renderer.component.get_unique_name_maker(); this.get_unique_name = this.renderer.component.get_unique_name_maker();
this.aliases = new Map(); this.aliases = new Map();
if (this.key) this.aliases.set('key', this.get_unique_name('key')); if (this.key)
this.aliases.set('key', this.get_unique_name('key'));
} }
assign_variable_names() { assign_variable_names() {
const seen: Set<string> = new Set();
const dupes: Set<string> = new Set();
let i = this.wrappers.length; /** @type {Set<string>} */
const seen = new Set();
/** @type {Set<string>} */
const dupes = new Set();
let i = this.wrappers.length;
while (i--) { while (i--) {
const wrapper = this.wrappers[i]; const wrapper = this.wrappers[i];
if (!wrapper.var)
if (!wrapper.var) continue; continue;
if (seen.has(wrapper.var.name)) { if (seen.has(wrapper.var.name)) {
dupes.add(wrapper.var.name); dupes.add(wrapper.var.name);
} }
seen.add(wrapper.var.name); seen.add(wrapper.var.name);
} }
const counts = new Map(); const counts = new Map();
i = this.wrappers.length; i = this.wrappers.length;
while (i--) { while (i--) {
const wrapper = this.wrappers[i]; const wrapper = this.wrappers[i];
if (!wrapper.var)
if (!wrapper.var) continue; continue;
let suffix = ''; let suffix = '';
if (dupes.has(wrapper.var.name)) { if (dupes.has(wrapper.var.name)) {
const i = counts.get(wrapper.var.name) || 0; const i = counts.get(wrapper.var.name) || 0;
@ -155,231 +166,228 @@ export default class Block {
} }
} }
add_dependencies(dependencies: Set<string>) { /** @param {Set<string>} dependencies */
add_dependencies(dependencies) {
dependencies.forEach((dependency) => { dependencies.forEach((dependency) => {
this.dependencies.add(dependency); this.dependencies.add(dependency);
}); });
this.has_update_method = true; this.has_update_method = true;
if (this.parent) { if (this.parent) {
this.parent.add_dependencies(dependencies); this.parent.add_dependencies(dependencies);
} }
} }
add_element( /**
id: Identifier, * @param {import('estree').Identifier} id
render_statement: Node, * @param {import('estree').Node} render_statement
claim_statement: Node, * @param {import('estree').Node} claim_statement
parent_node: Node, * @param {import('estree').Node} parent_node
no_detach?: boolean * @param {boolean} [no_detach]
) { */
add_element(id, render_statement, claim_statement, parent_node, no_detach) {
this.add_variable(id); this.add_variable(id);
this.chunks.create.push(b`${id} = ${render_statement};`); this.chunks.create.push(b `${id} = ${render_statement};`);
if (this.renderer.options.hydratable) { if (this.renderer.options.hydratable) {
this.chunks.claim.push(b`${id} = ${claim_statement || render_statement};`); this.chunks.claim.push(b `${id} = ${claim_statement || render_statement};`);
} }
if (parent_node) { if (parent_node) {
this.chunks.mount.push(b`@append(${parent_node}, ${id});`); this.chunks.mount.push(b `@append(${parent_node}, ${id});`);
if (is_head(parent_node) && !no_detach) this.chunks.destroy.push(b`@detach(${id});`); if (is_head(parent_node) && !no_detach)
} else { this.chunks.destroy.push(b `@detach(${id});`);
this.chunks.mount.push(b`@insert(#target, ${id}, #anchor);`); }
if (!no_detach) this.chunks.destroy.push(b`if (detaching) @detach(${id});`); else {
this.chunks.mount.push(b `@insert(#target, ${id}, #anchor);`);
if (!no_detach)
this.chunks.destroy.push(b `if (detaching) @detach(${id});`);
} }
} }
add_intro(local?: boolean) { /** @param {boolean} [local] */
add_intro(local) {
this.has_intros = this.has_intro_method = true; this.has_intros = this.has_intro_method = true;
if (!local && this.parent) this.parent.add_intro(); if (!local && this.parent)
this.parent.add_intro();
} }
add_outro(local?: boolean) { /** @param {boolean} [local] */
add_outro(local) {
this.has_outros = this.has_outro_method = true; this.has_outros = this.has_outro_method = true;
this.outros += 1; this.outros += 1;
if (!local && this.parent) this.parent.add_outro(); if (!local && this.parent)
this.parent.add_outro();
} }
add_animation() { add_animation() {
this.has_animation = true; this.has_animation = true;
} }
add_variable(id: Identifier, init?: Node) { /**
* @param {import('estree').Identifier} id
* @param {import('estree').Node} [init]
*/
add_variable(id, init) {
if (this.variables.has(id.name)) { if (this.variables.has(id.name)) {
throw new Error(`Variable '${id.name}' already initialised with a different value`); throw new Error(`Variable '${id.name}' already initialised with a different value`);
} }
this.variables.set(id.name, { id, init }); this.variables.set(id.name, { id, init });
} }
alias(name: string) { /** @param {string} name */
alias(name) {
if (!this.aliases.has(name)) { if (!this.aliases.has(name)) {
this.aliases.set(name, this.get_unique_name(name)); this.aliases.set(name, this.get_unique_name(name));
} }
return this.aliases.get(name); return this.aliases.get(name);
} }
child(options: BlockOptions) { /** @param {BlockOptions} options */
child(options) {
return new Block(Object.assign({}, this, { key: null }, options, { parent: this })); return new Block(Object.assign({}, this, { key: null }, options, { parent: this }));
} }
get_contents(key?: any) { /** @param {any} [key] */
get_contents(key) {
const { dev } = this.renderer.options; const { dev } = this.renderer.options;
if (this.has_outros) { if (this.has_outros) {
this.add_variable({ type: 'Identifier', name: '#current' }); this.add_variable({ type: 'Identifier', name: '#current' });
if (this.chunks.intro.length > 0) { if (this.chunks.intro.length > 0) {
this.chunks.intro.push(b`#current = true;`); this.chunks.intro.push(b `#current = true;`);
this.chunks.mount.push(b`#current = true;`); this.chunks.mount.push(b `#current = true;`);
} }
if (this.chunks.outro.length > 0) { if (this.chunks.outro.length > 0) {
this.chunks.outro.push(b`#current = false;`); this.chunks.outro.push(b `#current = false;`);
} }
} }
if (this.autofocus) { if (this.autofocus) {
if (this.autofocus.condition_expression) { if (this.autofocus.condition_expression) {
this.chunks.mount.push( this.chunks.mount.push(b `if (${this.autofocus.condition_expression}) ${this.autofocus.element_var}.focus();`);
b`if (${this.autofocus.condition_expression}) ${this.autofocus.element_var}.focus();` }
); else {
} else { this.chunks.mount.push(b `${this.autofocus.element_var}.focus();`);
this.chunks.mount.push(b`${this.autofocus.element_var}.focus();`);
} }
} }
this.render_binding_groups(); this.render_binding_groups();
this.render_listeners(); this.render_listeners();
const properties: Record<string, any> = {}; /** @type {Record<string, any>} */
const properties = {};
const noop = x`@noop`; const noop = x `@noop`;
properties.key = key; properties.key = key;
if (this.first) { if (this.first) {
properties.first = x`null`; properties.first = x `null`;
this.chunks.hydrate.push(b`this.first = ${this.first};`); this.chunks.hydrate.push(b `this.first = ${this.first};`);
} }
if (this.chunks.create.length === 0 && this.chunks.hydrate.length === 0) { if (this.chunks.create.length === 0 && this.chunks.hydrate.length === 0) {
properties.create = noop; properties.create = noop;
} else { }
const hydrate = else {
this.chunks.hydrate.length > 0 && const hydrate = this.chunks.hydrate.length > 0 &&
(this.renderer.options.hydratable ? b`this.h();` : this.chunks.hydrate); (this.renderer.options.hydratable ? b `this.h();` : this.chunks.hydrate);
properties.create = x `function #create() {
properties.create = x`function #create() {
${this.chunks.create} ${this.chunks.create}
${hydrate} ${hydrate}
}`; }`;
} }
if (this.renderer.options.hydratable || this.chunks.claim.length > 0) { if (this.renderer.options.hydratable || this.chunks.claim.length > 0) {
if (this.chunks.claim.length === 0 && this.chunks.hydrate.length === 0) { if (this.chunks.claim.length === 0 && this.chunks.hydrate.length === 0) {
properties.claim = noop; properties.claim = noop;
} else { }
properties.claim = x`function #claim(#nodes) { else {
properties.claim = x `function #claim(#nodes) {
${this.chunks.claim} ${this.chunks.claim}
${this.renderer.options.hydratable && this.chunks.hydrate.length > 0 && b`this.h();`} ${this.renderer.options.hydratable && this.chunks.hydrate.length > 0 && b `this.h();`}
}`; }`;
} }
} }
if (this.renderer.options.hydratable && this.chunks.hydrate.length > 0) { if (this.renderer.options.hydratable && this.chunks.hydrate.length > 0) {
properties.hydrate = x`function #hydrate() { properties.hydrate = x `function #hydrate() {
${this.chunks.hydrate} ${this.chunks.hydrate}
}`; }`;
} }
if (this.chunks.mount.length === 0) { if (this.chunks.mount.length === 0) {
properties.mount = noop; properties.mount = noop;
} else if (this.event_listeners.length === 0) { }
properties.mount = x`function #mount(#target, #anchor) { else if (this.event_listeners.length === 0) {
properties.mount = x `function #mount(#target, #anchor) {
${this.chunks.mount} ${this.chunks.mount}
}`; }`;
} else { }
properties.mount = x`function #mount(#target, #anchor) { else {
properties.mount = x `function #mount(#target, #anchor) {
${this.chunks.mount} ${this.chunks.mount}
}`; }`;
} }
if (this.has_update_method || this.maintain_context) { if (this.has_update_method || this.maintain_context) {
if (this.chunks.update.length === 0 && !this.maintain_context) { if (this.chunks.update.length === 0 && !this.maintain_context) {
properties.update = noop; properties.update = noop;
} else { }
const ctx = this.maintain_context ? x`#new_ctx` : x`#ctx`; else {
const ctx = this.maintain_context ? x `#new_ctx` : x `#ctx`;
let dirty: Identifier | ArrayPattern = { type: 'Identifier', name: '#dirty' }; /** @type {import('estree').Identifier | import('estree').ArrayPattern} */
let dirty = { type: 'Identifier', name: '#dirty' };
if (!this.renderer.context_overflow && !this.parent) { if (!this.renderer.context_overflow && !this.parent) {
dirty = { type: 'ArrayPattern', elements: [dirty] }; dirty = { type: 'ArrayPattern', elements: [dirty] };
} }
properties.update = x `function #update(${ctx}, ${dirty}) {
properties.update = x`function #update(${ctx}, ${dirty}) { ${this.maintain_context && b `#ctx = ${ctx};`}
${this.maintain_context && b`#ctx = ${ctx};`}
${this.chunks.update} ${this.chunks.update}
}`; }`;
} }
} }
if (this.has_animation) { if (this.has_animation) {
properties.measure = x`function #measure() { properties.measure = x `function #measure() {
${this.chunks.measure} ${this.chunks.measure}
}`; }`;
if (this.chunks.restore_measurements.length) { if (this.chunks.restore_measurements.length) {
properties.restore_measurements = x`function #restore_measurements(#measurement) { properties.restore_measurements = x `function #restore_measurements(#measurement) {
${this.chunks.restore_measurements} ${this.chunks.restore_measurements}
}`; }`;
} }
properties.fix = x `function #fix() {
properties.fix = x`function #fix() {
${this.chunks.fix} ${this.chunks.fix}
}`; }`;
properties.animate = x `function #animate() {
properties.animate = x`function #animate() {
${this.chunks.animate} ${this.chunks.animate}
}`; }`;
} }
if (this.has_intro_method || this.has_outro_method) { if (this.has_intro_method || this.has_outro_method) {
if (this.chunks.intro.length === 0) { if (this.chunks.intro.length === 0) {
properties.intro = noop; properties.intro = noop;
} else { }
properties.intro = x`function #intro(#local) { else {
${this.has_outros && b`if (#current) return;`} properties.intro = x `function #intro(#local) {
${this.has_outros && b `if (#current) return;`}
${this.chunks.intro} ${this.chunks.intro}
}`; }`;
} }
if (this.chunks.outro.length === 0) { if (this.chunks.outro.length === 0) {
properties.outro = noop; properties.outro = noop;
} else { }
properties.outro = x`function #outro(#local) { else {
properties.outro = x `function #outro(#local) {
${this.chunks.outro} ${this.chunks.outro}
}`; }`;
} }
} }
if (this.chunks.destroy.length === 0) { if (this.chunks.destroy.length === 0) {
properties.destroy = noop; properties.destroy = noop;
} else { }
properties.destroy = x`function #destroy(detaching) { else {
properties.destroy = x `function #destroy(detaching) {
${this.chunks.destroy} ${this.chunks.destroy}
}`; }`;
} }
if (!this.renderer.component.compile_options.dev) { if (!this.renderer.component.compile_options.dev) {
// allow shorthand names // allow shorthand names
for (const name in properties) { for (const name in properties) {
const property = properties[name]; const property = properties[name];
if (property) property.id = null; if (property)
property.id = null;
} }
} }
const return_value: any = x`{ /** @type {any} */
const return_value = x `{
key: ${properties.key}, key: ${properties.key},
first: ${properties.first}, first: ${properties.first},
c: ${properties.create}, c: ${properties.create},
@ -395,21 +403,18 @@ export default class Block {
o: ${properties.outro}, o: ${properties.outro},
d: ${properties.destroy} d: ${properties.destroy}
}`; }`;
const block = dev && this.get_unique_name('block'); const block = dev && this.get_unique_name('block');
const body = b `
const body = b`
${this.chunks.declarations} ${this.chunks.declarations}
${Array.from(this.variables.values()).map(({ id, init }) => { ${Array.from(this.variables.values()).map(({ id, init }) => {
return init ? b`let ${id} = ${init}` : b`let ${id}`; return init ? b `let ${id} = ${init}` : b `let ${id}`;
})} })}
${this.chunks.init} ${this.chunks.init}
${ ${dev
dev ? b `
? b`
const ${block} = ${return_value}; const ${block} = ${return_value};
@dispatch_dev("SvelteRegisterBlock", { @dispatch_dev("SvelteRegisterBlock", {
block: ${block}, block: ${block},
@ -419,17 +424,15 @@ export default class Block {
ctx: #ctx ctx: #ctx
}); });
return ${block};` return ${block};`
: b` : b `
return ${return_value};` return ${return_value};`}
}
`; `;
return body; return body;
} }
has_content(): boolean { /** @returns {boolean} */
return ( has_content() {
!!this.first || return (!!this.first ||
this.event_listeners.length > 0 || this.event_listeners.length > 0 ||
this.chunks.intro.length > 0 || this.chunks.intro.length > 0 ||
this.chunks.outro.length > 0 || this.chunks.outro.length > 0 ||
@ -439,52 +442,48 @@ export default class Block {
this.chunks.mount.length > 0 || this.chunks.mount.length > 0 ||
this.chunks.update.length > 0 || this.chunks.update.length > 0 ||
this.chunks.destroy.length > 0 || this.chunks.destroy.length > 0 ||
this.has_animation this.has_animation);
);
} }
render() { render() {
const key = this.key && this.get_unique_name('key'); const key = this.key && this.get_unique_name('key');
const args: any[] = [x`#ctx`]; /** @type {any[]} */
if (key) args.unshift(key); const args = [x `#ctx`];
if (key)
const fn = b`function ${this.name}(${args}) { args.unshift(key);
const fn = b `function ${this.name}(${args}) {
${this.get_contents(key)} ${this.get_contents(key)}
}`; }`;
return this.comment return this.comment
? b` ? b `
// ${this.comment} // ${this.comment}
${fn}` ${fn}`
: fn; : fn;
} }
render_listeners(chunk: string = '') { /** @param {string} chunk */
render_listeners(chunk = '') {
if (this.event_listeners.length > 0) { if (this.event_listeners.length > 0) {
this.add_variable({ type: 'Identifier', name: '#mounted' }); this.add_variable({ type: 'Identifier', name: '#mounted' });
this.chunks.destroy.push(b`#mounted = false`); this.chunks.destroy.push(b `#mounted = false`);
const dispose: Identifier = { /** @type {import('estree').Identifier} */
const dispose = {
type: 'Identifier', type: 'Identifier',
name: `#dispose${chunk}` name: `#dispose${chunk}`
}; };
this.add_variable(dispose); this.add_variable(dispose);
if (this.event_listeners.length === 1) { if (this.event_listeners.length === 1) {
this.chunks.mount.push( this.chunks.mount.push(b `
b`
if (!#mounted) { if (!#mounted) {
${dispose} = ${this.event_listeners[0]}; ${dispose} = ${this.event_listeners[0]};
#mounted = true; #mounted = true;
} }
` `);
); this.chunks.destroy.push(b `${dispose}();`);
}
this.chunks.destroy.push(b`${dispose}();`); else {
} else { this.chunks.mount.push(b `
this.chunks.mount.push(b`
if (!#mounted) { if (!#mounted) {
${dispose} = [ ${dispose} = [
${this.event_listeners} ${this.event_listeners}
@ -492,15 +491,34 @@ export default class Block {
#mounted = true; #mounted = true;
} }
`); `);
this.chunks.destroy.push(b `@run_all(${dispose});`);
this.chunks.destroy.push(b`@run_all(${dispose});`);
} }
} }
} }
render_binding_groups() { render_binding_groups() {
for (const binding_group of this.binding_groups) { for (const binding_group of this.binding_groups) {
binding_group.render(this); binding_group.render(this);
} }
} }
} }
/** @typedef {Object} Bindings
* @property {Identifier} object
* @property {Identifier} property
* @property {Node} snippet
* @property {string} store
* @property {(node:Node)=>Node} modifier
*/
/** @typedef {Object} BlockOptions
* @property {Block} [parent]
* @property {Identifier} name
* @property {string} type
* @property {Renderer} [renderer]
* @property {string} [comment]
* @property {Identifier} [key]
* @property {Map<string,Bindings>} [bindings]
* @property {Set<string>} [dependencies]
*/

@ -3,6 +3,7 @@ import { b, x } from 'code-red';
import add_event_handlers from './shared/add_event_handlers.js'; import add_event_handlers from './shared/add_event_handlers.js';
import add_actions from './shared/add_actions.js'; import add_actions from './shared/add_actions.js';
import EventHandler from './Element/EventHandler.js'; import EventHandler from './Element/EventHandler.js';
const associated_events = { const associated_events = {
innerWidth: 'resize', innerWidth: 'resize',
innerHeight: 'resize', innerHeight: 'resize',

Loading…
Cancel
Save