remove prettier

pull/4742/head
pushkine 5 years ago
parent 4f9566892f
commit 0f96eeaf42

@ -122,7 +122,9 @@ export default class Component {
this.file = this.file =
compile_options.filename && compile_options.filename &&
(typeof process !== 'undefined' (typeof process !== 'undefined'
? compile_options.filename.replace(process.cwd(), '').replace(/^[/\\]/, '') ? compile_options.filename
.replace(process.cwd(), '')
.replace(/^[/\\]/, '')
: compile_options.filename); : compile_options.filename);
this.locate = getLocator(this.source, { offsetLine: 1 }); this.locate = getLocator(this.source, { offsetLine: 1 });
@ -316,9 +318,7 @@ export default class Component {
}); });
js.map.sources = [ js.map.sources = [
compile_options.filename compile_options.filename ? get_relative_path(compile_options.outputFilename || '', compile_options.filename) : null
? get_relative_path(compile_options.outputFilename || '', compile_options.filename)
: null,
]; ];
js.map.sourcesContent = [ js.map.sourcesContent = [
@ -1162,7 +1162,7 @@ export default class Component {
const unsorted_reactive_declarations = []; const unsorted_reactive_declarations = [];
this.ast.instance.content.body.forEach((node) => { this.ast.instance.content.body.forEach(node => {
if (node.type === 'LabeledStatement' && node.label.name === '$') { if (node.type === 'LabeledStatement' && node.label.name === '$') {
this.reactive_declaration_nodes.add(node); this.reactive_declaration_nodes.add(node);

@ -99,7 +99,7 @@ function esm(
type: 'Specifier', type: 'Specifier',
local: { type: 'Identifier', name: x.name }, local: { type: 'Identifier', name: x.name },
exported: { type: 'Identifier', name: x.as } exported: { type: 'Identifier', name: x.as }
})), }))
}; };
program.body = b` program.body = b`

@ -260,7 +260,7 @@ export default class Element extends Node {
} }
if (this.name === 'figure') { if (this.name === 'figure') {
const children = this.children.filter((node) => { const children = this.children.filter(node => {
if (node.type === 'Comment') return false; if (node.type === 'Comment') return false;
if (node.type === 'Text') return /\S/.test(node.data); if (node.type === 'Text') return /\S/.test(node.data);
return true; return true;
@ -384,10 +384,11 @@ export default class Element extends Node {
} }
} }
if (/(^[0-9-.])|[\^$@%&#?!|()[\]{}^*+~;]/.test(name)) { if (/(^[0-9-.])|[\^$@%&#?!|()[\]{}^*+~;]/.test(name)) {
component.error(attribute, { component.error(attribute, {
code: `illegal-attribute`, code: `illegal-attribute`,
message: `'${name}' is not a valid attribute name` message: `'${name}' is not a valid attribute name`,
}); });
} }
@ -395,7 +396,7 @@ export default class Element extends Node {
if (!attribute.is_static) { if (!attribute.is_static) {
component.error(attribute, { component.error(attribute, {
code: `invalid-slot-attribute`, code: `invalid-slot-attribute`,
message: `slot attribute cannot have a dynamic value`, message: `slot attribute cannot have a dynamic value`
}); });
} }
@ -621,6 +622,7 @@ export default class Element extends Node {
message: `'files' binding can only be used with <input type="file">` message: `'files' binding can only be used with <input type="file">`
}); });
} }
} else if (name === 'open') { } else if (name === 'open') {
if (this.name !== 'details') { if (this.name !== 'details') {
component.error(binding, { component.error(binding, {
@ -661,7 +663,7 @@ export default class Element extends Node {
if (this.name === 'svg' && (name === 'offsetWidth' || name === 'offsetHeight')) { if (this.name === 'svg' && (name === 'offsetWidth' || name === 'offsetHeight')) {
component.error(binding, { component.error(binding, {
code: 'invalid-binding', code: 'invalid-binding',
message: `'${binding.name}' is not a valid binding on <svg>. Use '${name.replace('offset', 'client')}' instead`, message: `'${binding.name}' is not a valid binding on <svg>. Use '${name.replace('offset', 'client')}' instead`
}); });
} else if (svg.test(this.name)) { } else if (svg.test(this.name)) {
component.error(binding, { component.error(binding, {
@ -778,7 +780,7 @@ export default class Element extends Node {
new Text(this.component, this, this.scope, { new Text(this.component, this, this.scope, {
type: 'Text', type: 'Text',
data: ` ${id}`, data: ` ${id}`,
synthetic: true, synthetic: true
}) })
); );
} }

@ -275,7 +275,7 @@ export default class Expression {
...(node as FunctionExpression).params ...(node as FunctionExpression).params
]; ];
const context_args = deps.map((name) => block.renderer.reference(name)); const context_args = deps.map(name => block.renderer.reference(name));
component.partly_hoisted.push(declaration); component.partly_hoisted.push(declaration);

@ -1,19 +1,12 @@
import { b, x, p } from "code-red"; import { b, x, p } from 'code-red';
import Component from "../Component"; import Component from '../Component';
import Renderer from "./Renderer"; import Renderer from './Renderer';
import { CompileOptions, CssResult } from "../../interfaces"; import { CompileOptions, CssResult } from '../../interfaces';
import { walk } from "estree-walker"; import { walk } from 'estree-walker';
import { extract_names, Scope } from "../utils/scope"; import { extract_names, Scope } from '../utils/scope';
import { invalidate } from "./invalidate"; import { invalidate } from './invalidate';
import Block from "./Block"; import Block from './Block';
import { import { ClassDeclaration, FunctionExpression, Node, Statement, ObjectExpression, Expression } from 'estree';
ClassDeclaration,
FunctionExpression,
Node,
Statement,
ObjectExpression,
Expression,
} from "estree";
export default function dom( export default function dom(
component: Component, component: Component,
@ -36,19 +29,18 @@ export default function dom(
body.push(b`const ${renderer.file_var} = ${file};`); body.push(b`const ${renderer.file_var} = ${file};`);
} }
const css = component.stylesheet.render( const css = component.stylesheet.render(options.filename, !options.customElement);
options.filename, const styles = component.stylesheet.has_styles && options.dev
!options.customElement
);
const styles =
component.stylesheet.has_styles && options.dev
? `${css.code}\n/*# sourceMappingURL=${css.map.toUrl()} */` ? `${css.code}\n/*# sourceMappingURL=${css.map.toUrl()} */`
: css.code; : css.code;
const add_css = component.get_unique_name("add_css"); const add_css = component.get_unique_name('add_css');
const should_add_css = const should_add_css = (
!options.customElement && !!styles && options.css !== false; !options.customElement &&
!!styles &&
options.css !== false
);
if (should_add_css) { if (should_add_css) {
body.push(b` body.push(b`
@ -65,14 +57,12 @@ export default function dom(
// TODO the deconflicted names of blocks are reversed... should set them here // TODO the deconflicted names of blocks are reversed... should set them here
const blocks = renderer.blocks.slice().reverse(); const blocks = renderer.blocks.slice().reverse();
body.push( body.push(...blocks.map(block => {
...blocks.map((block) => {
// TODO this is a horrible mess — renderer.blocks // TODO this is a horrible mess — renderer.blocks
// contains a mixture of Blocks and Nodes // contains a mixture of Blocks and Nodes
if ((block as Block).render) return (block as Block).render(); if ((block as Block).render) return (block as Block).render();
return block; return block;
}) }));
);
if (options.dev && !options.hydratable) { if (options.dev && !options.hydratable) {
block.chunks.claim.push( block.chunks.claim.push(
@ -155,119 +145,91 @@ export default function dom(
let capture_state: Expression; let capture_state: Expression;
let props_inject: Node[] | Node; let props_inject: Node[] | Node;
props.forEach((prop) => { props.forEach(prop => {
const variable = component.var_lookup.get(prop.name); const variable = component.var_lookup.get(prop.name);
if (!variable.writable || component.component_options.accessors) { if (!variable.writable || component.component_options.accessors) {
accessors.push({ accessors.push({
type: "MethodDefinition", type: 'MethodDefinition',
kind: "get", kind: 'get',
key: { type: "Identifier", name: prop.export_name }, key: { type: 'Identifier', name: prop.export_name },
value: x`function() { value: x`function() {
return ${ return ${prop.hoistable ? prop.name : x`this.$$.ctx[${renderer.context_lookup.get(prop.name).index}]`}
prop.hoistable
? prop.name
: x`this.$$.ctx[${renderer.context_lookup.get(prop.name).index}]`
}
}`, }`,
}); });
} else if (component.compile_options.dev) { } else if (component.compile_options.dev) {
accessors.push({ accessors.push({
type: "MethodDefinition", type: 'MethodDefinition',
kind: "get", kind: 'get',
key: { type: "Identifier", name: prop.export_name }, key: { type: 'Identifier', name: prop.export_name },
value: x`function() { value: x`function() {
throw new @_Error("<${component.tag}>: Props cannot be read directly from the component instance unless compiling with 'accessors: true' or '<svelte:options accessors/>'"); throw new @_Error("<${component.tag}>: Props cannot be read directly from the component instance unless compiling with 'accessors: true' or '<svelte:options accessors/>'");
}`, }`
}); });
} }
if (component.component_options.accessors) { if (component.component_options.accessors) {
if (variable.writable && !renderer.readonly.has(prop.name)) { if (variable.writable && !renderer.readonly.has(prop.name)) {
accessors.push({ accessors.push({
type: "MethodDefinition", type: 'MethodDefinition',
kind: "set", kind: 'set',
key: { type: "Identifier", name: prop.export_name }, key: { type: 'Identifier', name: prop.export_name },
value: x`function(${prop.name}) { value: x`function(${prop.name}) {
this.$set({ ${prop.export_name}: ${prop.name} }); this.$set({ ${prop.export_name}: ${prop.name} });
@flush(); @flush();
}`, }`
}); });
} else if (component.compile_options.dev) { } else if (component.compile_options.dev) {
accessors.push({ accessors.push({
type: "MethodDefinition", type: 'MethodDefinition',
kind: "set", kind: 'set',
key: { type: "Identifier", name: prop.export_name }, key: { type: 'Identifier', name: prop.export_name },
value: x`function(value) { value: x`function(value) {
throw new @_Error("<${component.tag}>: Cannot set read-only property '${prop.export_name}'"); throw new @_Error("<${component.tag}>: Cannot set read-only property '${prop.export_name}'");
}`, }`
}); });
} }
} else if (component.compile_options.dev) { } else if (component.compile_options.dev) {
accessors.push({ accessors.push({
type: "MethodDefinition", type: 'MethodDefinition',
kind: "set", kind: 'set',
key: { type: "Identifier", name: prop.export_name }, key: { type: 'Identifier', name: prop.export_name },
value: x`function(value) { value: x`function(value) {
throw new @_Error("<${component.tag}>: Props cannot be set directly on the component instance unless compiling with 'accessors: true' or '<svelte:options accessors/>'"); throw new @_Error("<${component.tag}>: Props cannot be set directly on the component instance unless compiling with 'accessors: true' or '<svelte:options accessors/>'");
}`, }`
}); });
} }
}); });
if (component.compile_options.dev) { if (component.compile_options.dev) {
// checking that expected ones were passed // checking that expected ones were passed
const expected = props.filter((prop) => prop.writable && !prop.initialised); const expected = props.filter(prop => prop.writable && !prop.initialised);
if (expected.length) { if (expected.length) {
dev_props_check = b` dev_props_check = b`
const { ctx: #ctx } = this.$$; const { ctx: #ctx } = this.$$;
const props = ${ const props = ${options.customElement ? x`this.attributes` : x`options.props || {}`};
options.customElement ? x`this.attributes` : x`options.props || {}` ${expected.map(prop => b`
}; if (${renderer.reference(prop.name)} === undefined && !('${prop.export_name}' in props)) {
${expected.map( @_console.warn("<${component.tag}> was created without expected prop '${prop.export_name}'");
(prop) => b` }`)}
if (${renderer.reference(prop.name)} === undefined && !('${
prop.export_name
}' in props)) {
@_console.warn("<${component.tag}> was created without expected prop '${
prop.export_name
}'");
}`
)}
`; `;
} }
const capturable_vars = component.vars.filter( const capturable_vars = component.vars.filter(v => !v.internal && !v.global && !v.name.startsWith('$$'));
(v) => !v.internal && !v.global && !v.name.startsWith("$$")
);
if (capturable_vars.length > 0) { if (capturable_vars.length > 0) {
capture_state = x`() => ({ ${capturable_vars.map( capture_state = x`() => ({ ${capturable_vars.map(prop => p`${prop.name}`)} })`;
(prop) => p`${prop.name}`
)} })`;
} }
const injectable_vars = capturable_vars.filter( const injectable_vars = capturable_vars.filter(v => !v.module && v.writable && v.name[0] !== '$');
(v) => !v.module && v.writable && v.name[0] !== "$"
);
if (uses_props || injectable_vars.length > 0) { if (uses_props || injectable_vars.length > 0) {
inject_state = x` inject_state = x`
${$$props} => { ${$$props} => {
${ ${uses_props && renderer.invalidate('$$props', x`$$props = { ...$$props, ...$$new_props }`)}
uses_props &&
renderer.invalidate(
"$$props",
x`$$props = { ...$$props, ...$$new_props }`
)
}
${injectable_vars.map( ${injectable_vars.map(
(v) => v => b`if ('${v.name}' in $$props) ${renderer.invalidate(v.name, x`${v.name} = ${$$props}.${v.name}`)};`
b`if ('${v.name}' in $$props) ${renderer.invalidate(
v.name,
x`${v.name} = ${$$props}.${v.name}`
)};`
)} )}
} }
`; `;
@ -294,11 +256,7 @@ export default function dom(
if (!execution_context && !scope.block) { if (!execution_context && !scope.block) {
execution_context = node; execution_context = node;
} }
} else if ( } else if (!execution_context && node.type === 'LabeledStatement' && node.label.name === '$') {
!execution_context &&
node.type === "LabeledStatement" &&
node.label.name === "$"
) {
execution_context = node; execution_context = node;
} }
}, },
@ -312,12 +270,8 @@ export default function dom(
execution_context = null; execution_context = null;
} }
if ( if (node.type === 'AssignmentExpression' || node.type === 'UpdateExpression') {
node.type === "AssignmentExpression" || const assignee = node.type === 'AssignmentExpression' ? node.left : node.argument;
node.type === "UpdateExpression"
) {
const assignee =
node.type === "AssignmentExpression" ? node.left : node.argument;
// normally (`a = 1`, `b.c = 2`), there'll be a single name // normally (`a = 1`, `b.c = 2`), there'll be a single name
// (a or b). In destructuring cases (`[d, e] = [e, d]`) there // (a or b). In destructuring cases (`[d, e] = [e, d]`) there
@ -325,21 +279,18 @@ export default function dom(
// onto the initial function call // onto the initial function call
const names = new Set(extract_names(assignee)); const names = new Set(extract_names(assignee));
this.replace( this.replace(invalidate(renderer, scope, node, names, execution_context === null));
invalidate(renderer, scope, node, names, execution_context === null) }
);
} }
},
}); });
component.rewrite_props(({ name, reassigned, export_name }) => { component.rewrite_props(({ name, reassigned, export_name }) => {
const value = `$${name}`; const value = `$${name}`;
const i = renderer.context_lookup.get(`$${name}`).index; const i = renderer.context_lookup.get(`$${name}`).index;
const insert = const insert = (reassigned || export_name)
reassigned || export_name
? b`${`$$subscribe_${name}`}()` ? b`${`$$subscribe_${name}`}()`
: b`@component_subscribe($$self, ${name}, #value => $$invalidate(${i}, ${value} = #value))`; : b`$$self.$$.on_destroy.push(@subscribe(${name}, #value => $$invalidate(${i}, ${value} = #value))`;
if (component.compile_options.dev) { if (component.compile_options.dev) {
return b`@validate_store_dev(${name}, '${name}'); ${insert}`; return b`@validate_store_dev(${name}, '${name}'); ${insert}`;
@ -350,8 +301,7 @@ export default function dom(
} }
const args = [x`$$self`]; const args = [x`$$self`];
const has_invalidate = const has_invalidate = props.length > 0 ||
props.length > 0 ||
component.has_reactive_assignments || component.has_reactive_assignments ||
component.slots.size > 0 || component.slots.size > 0 ||
capture_state || capture_state ||
@ -363,8 +313,7 @@ export default function dom(
args.push(x`$$props`); args.push(x`$$props`);
} }
const has_create_fragment = const has_create_fragment = component.compile_options.dev || block.has_content();
component.compile_options.dev || block.has_content();
if (has_create_fragment) { if (has_create_fragment) {
body.push(b` body.push(b`
function create_fragment(#ctx) { function create_fragment(#ctx) {
@ -379,21 +328,17 @@ export default function dom(
${component.fully_hoisted} ${component.fully_hoisted}
`); `);
const filtered_props = props.filter((prop) => { const filtered_props = props.filter(prop => {
const variable = component.var_lookup.get(prop.name); const variable = component.var_lookup.get(prop.name);
if (variable.hoistable) return false; if (variable.hoistable) return false;
if (prop.name[0] === "$") return false; if (prop.name[0] === '$') return false;
return true; return true;
}); });
const reactive_stores = component.vars.filter( const reactive_stores = component.vars.filter((variable) => variable.name[0] === '$' && variable.name[1] !=='$');
(variable) => variable.name[0] === "$" && variable.name[1] !== "$"
);
const instance_javascript = component.extract_javascript( const instance_javascript = component.extract_javascript(component.ast.instance);
component.ast.instance
);
let i = renderer.context.length; let i = renderer.context.length;
while (i--) { while (i--) {
@ -406,7 +351,7 @@ export default function dom(
} }
const initial_context = renderer.context.slice(0, i + 1); const initial_context = renderer.context.slice(0, i + 1);
const has_definition = const has_definition = (
component.compile_options.dev || component.compile_options.dev ||
(instance_javascript && instance_javascript.length > 0) || (instance_javascript && instance_javascript.length > 0) ||
filtered_props.length > 0 || filtered_props.length > 0 ||
@ -415,23 +360,21 @@ export default function dom(
initial_context.length > 0 || initial_context.length > 0 ||
component.reactive_declarations.length > 0 || component.reactive_declarations.length > 0 ||
capture_state || capture_state ||
inject_state; inject_state
);
const definition = has_definition const definition = has_definition
? component.alias("instance") ? component.alias('instance')
: { type: "Literal", value: null }; : { type: 'Literal', value: null };
const reactive_store_subscriptions = reactive_stores const reactive_store_subscriptions = reactive_stores
.filter((store) => { .filter(store => {
const variable = component.var_lookup.get(store.name.slice(1)); const variable = component.var_lookup.get(store.name.slice(1));
return !variable || variable.hoistable; return !variable || variable.hoistable;
}) })
.map( .map(
({ name }) => b` ({ name }) => b`
${ ${component.compile_options.dev && b`@validate_store_dev(${name.slice(1)}, '${name.slice(1)}');`}
component.compile_options.dev &&
b`@validate_store_dev(${name.slice(1)}, '${name.slice(1)}');`
}
$$self.$$.on_destroy.push(@subscribe(${name.slice(1)}, #value => { $$self.$$.on_destroy.push(@subscribe(${name.slice(1)}, #value => {
$$invalidate(${renderer.context_lookup.get(name).index}, ${name} = #value); $$invalidate(${renderer.context_lookup.get(name).index}, ${name} = #value);
})); }));
@ -439,44 +382,30 @@ export default function dom(
); );
const resubscribable_reactive_store_unsubscribers = reactive_stores const resubscribable_reactive_store_unsubscribers = reactive_stores
.filter((store) => { .filter(store => {
const variable = component.var_lookup.get(store.name.slice(1)); const variable = component.var_lookup.get(store.name.slice(1));
return variable && (variable.reassigned || variable.export_name); return variable && (variable.reassigned || variable.export_name);
}) })
.map( .map(({ name }) => b`$$self.$$.on_destroy.push(() => ${`$$unsubscribe_${name.slice(1)}`}());`);
({ name }) =>
b`$$self.$$.on_destroy.push(() => ${`$$unsubscribe_${name.slice(
1
)}`}());`
);
if (has_definition) { if (has_definition) {
const reactive_declarations: Node | Node[] = []; const reactive_declarations: (Node | Node[]) = [];
const fixed_reactive_declarations = []; // not really 'reactive' but whatever const fixed_reactive_declarations = []; // not really 'reactive' but whatever
component.reactive_declarations.forEach((d) => { component.reactive_declarations.forEach(d => {
const dependencies = Array.from(d.dependencies); const dependencies = Array.from(d.dependencies);
const uses_rest_or_props = !!dependencies.find( const uses_rest_or_props = !!dependencies.find(n => n === '$$props' || n === '$$restProps');
(n) => n === "$$props" || n === "$$restProps"
);
const writable = dependencies.filter((n) => { const writable = dependencies.filter(n => {
const variable = component.var_lookup.get(n); const variable = component.var_lookup.get(n);
return ( return variable && (variable.export_name || variable.mutated || variable.reassigned);
variable &&
(variable.export_name || variable.mutated || variable.reassigned)
);
}); });
const condition = const condition = !uses_rest_or_props && writable.length > 0 && renderer.dirty(writable, true);
!uses_rest_or_props &&
writable.length > 0 &&
renderer.dirty(writable, true);
let statement = d.node; // TODO remove label (use d.node.body) if it's not referenced let statement = d.node; // TODO remove label (use d.node.body) if it's not referenced
if (condition) if (condition) statement = b`if (${condition}) { ${statement} }`[0] as Statement;
statement = b`if (${condition}) { ${statement} }`[0] as Statement;
if (condition || uses_rest_or_props) { if (condition || uses_rest_or_props) {
reactive_declarations.push(statement); reactive_declarations.push(statement);
@ -485,14 +414,12 @@ export default function dom(
} }
}); });
const injected = Array.from( const injected = Array.from(component.injected_reactive_declaration_vars).filter(name => {
component.injected_reactive_declaration_vars
).filter((name) => {
const variable = component.var_lookup.get(name); const variable = component.var_lookup.get(name);
return variable.injected && variable.name[0] !== "$"; return variable.injected && variable.name[0] !== '$';
}); });
const reactive_store_declarations = reactive_stores.map((variable) => { const reactive_store_declarations = reactive_stores.map(variable => {
const $name = variable.name; const $name = variable.name;
const name = $name.slice(1); const name = $name.slice(1);
@ -517,26 +444,19 @@ export default function dom(
let unknown_props_check; let unknown_props_check;
if (component.compile_options.dev && !(uses_props || uses_rest)) { if (component.compile_options.dev && !(uses_props || uses_rest)) {
unknown_props_check = b` unknown_props_check = b`
const writable_props = [${writable_props.map( const writable_props = [${writable_props.map(prop => x`'${prop.export_name}'`)}];
(prop) => x`'${prop.export_name}'`
)}];
@_Object.keys($$props).forEach(key => { @_Object.keys($$props).forEach(key => {
if (!~writable_props.indexOf(key) && key.slice(0, 2) !== '$$') @_console.warn(\`<${ if (!~writable_props.indexOf(key) && key.slice(0, 2) !== '$$') @_console.warn(\`<${component.tag}> was created with unknown prop '\${key}'\`);
component.tag
}> was created with unknown prop '\${key}'\`);
}); });
`; `;
} }
const return_value = { const return_value = {
type: "ArrayExpression", type: 'ArrayExpression',
elements: initial_context.map( elements: initial_context.map(member => ({
(member) => type: 'Identifier',
({ name: member.name
type: "Identifier", }) as Expression)
name: member.name,
} as Expression)
),
}; };
body.push(b` body.push(b`
@ -553,19 +473,8 @@ export default function dom(
${unknown_props_check} ${unknown_props_check}
${ ${component.slots.size || component.compile_options.dev ? b`let { $$slots = {}, $$scope } = $$props;` : null}
component.slots.size || component.compile_options.dev ${component.compile_options.dev && b`@validate_slots_dev('${component.tag}', $$slots, [${[...component.slots.keys()].map(key => `'${key}'`).join(',')}]);`}
? b`let { $$slots = {}, $$scope } = $$props;`
: null
}
${
component.compile_options.dev &&
b`@validate_slots_dev('${component.tag}', $$slots, [${[
...component.slots.keys(),
]
.map((key) => `'${key}'`)
.join(",")}]);`
}
${ ${
renderer.binding_groups.length renderer.binding_groups.length
@ -583,18 +492,15 @@ export default function dom(
${inject_state && b`$$self.$inject_state = ${inject_state};`} ${inject_state && b`$$self.$inject_state = ${inject_state};`}
${injected.map((name) => b`let ${name};`)} ${injected.map(name => b`let ${name};`)}
${/* before reactive declarations */ props_inject} ${/* before reactive declarations */ props_inject}
${ ${reactive_declarations.length > 0 && b`
reactive_declarations.length > 0 &&
b`
$$self.$$.update = () => { $$self.$$.update = () => {
${reactive_declarations} ${reactive_declarations}
}; };
` `}
}
${fixed_reactive_declarations} ${fixed_reactive_declarations}
@ -611,11 +517,7 @@ export default function dom(
} }
const prop_indexes = x`{ const prop_indexes = x`{
${props ${props.filter(v => v.export_name && !v.module).map(v => p`${v.export_name}: ${renderer.context_lookup.get(v.name).index}`)}
.filter((v) => v.export_name && !v.module)
.map(
(v) => p`${v.export_name}: ${renderer.context_lookup.get(v.name).index}`
)}
}` as ObjectExpression; }` as ObjectExpression;
let dirty; let dirty;
@ -632,19 +534,9 @@ export default function dom(
constructor(options) { constructor(options) {
super(); super();
${ ${css.code && b`this.shadowRoot.innerHTML = \`<style>${css.code.replace(/\\/g, '\\\\')}${options.dev ? `\n/*# sourceMappingURL=${css.map.toUrl()} */` : ''}</style>\`;`}
css.code &&
b`this.shadowRoot.innerHTML = \`<style>${css.code.replace(
/\\/g,
"\\\\"
)}${
options.dev ? `\n/*# sourceMappingURL=${css.map.toUrl()} */` : ""
}</style>\`;`
}
@init(this, { target: this.shadowRoot }, ${definition}, ${ @init(this, { target: this.shadowRoot }, ${definition}, ${has_create_fragment ? 'create_fragment': 'null'}, ${not_equal}, ${prop_indexes}, ${dirty});
has_create_fragment ? "create_fragment" : "null"
}, ${not_equal}, ${prop_indexes}, ${dirty});
${dev_props_check} ${dev_props_check}
@ -665,11 +557,11 @@ export default function dom(
if (props.length > 0) { if (props.length > 0) {
declaration.body.body.push({ declaration.body.body.push({
type: "MethodDefinition", type: 'MethodDefinition',
kind: "get", kind: 'get',
static: true, static: true,
computed: false, computed: false,
key: { type: "Identifier", name: "observedAttributes" }, key: { type: 'Identifier', name: 'observedAttributes' },
value: x`function() { value: x`function() {
return [${props.map(prop => x`"${prop.export_name}"`)}]; return [${props.map(prop => x`"${prop.export_name}"`)}];
}` as FunctionExpression }` as FunctionExpression
@ -687,8 +579,8 @@ export default function dom(
} }
} else { } else {
const superclass = { const superclass = {
type: "Identifier", type: 'Identifier',
name: options.dev ? "@SvelteComponentDev" : "@SvelteComponent" name: options.dev ? '@SvelteComponentDev' : '@SvelteComponent'
}; };
const declaration = b` const declaration = b`

@ -19,7 +19,8 @@ export function invalidate(renderer: Renderer, scope: Scope, node: Node, names:
!variable.hoistable && !variable.hoistable &&
!variable.global && !variable.global &&
!variable.module && !variable.module &&
(variable.referenced || (
variable.referenced ||
variable.subscribable || variable.subscribable ||
variable.is_reactive_dependency || variable.is_reactive_dependency ||
variable.export_name || variable.export_name ||

@ -237,7 +237,9 @@ export default class AwaitBlockWrapper extends Wrapper {
${promise} !== (${promise} = ${snippet}) && ${promise} !== (${promise} = ${snippet}) &&
@handle_promise(${promise}, ${info})`; @handle_promise(${promise}, ${info})`;
block.chunks.update.push(b`${info}.ctx = #ctx;`); block.chunks.update.push(
b`${info}.ctx = #ctx;`
);
if (this.pending.block.has_update_method) { if (this.pending.block.has_update_method) {
block.chunks.update.push(b` block.chunks.update.push(b`

@ -90,7 +90,7 @@ export default class EachBlockWrapper extends Wrapper {
// @ts-ignore todo: probably error // @ts-ignore todo: probably error
key: node.key as string, key: node.key as string,
bindings: new Map(block.bindings), bindings: new Map(block.bindings)
}); });
// TODO this seems messy // TODO this seems messy

@ -508,7 +508,6 @@ export default class ElementWrapper extends Wrapper {
const lock = bindingGroup.bindings.some(binding => binding.needs_lock) ? const lock = bindingGroup.bindings.some(binding => binding.needs_lock) ?
block.get_unique_name(`${this.var.name}_updating`) : block.get_unique_name(`${this.var.name}_updating`) :
null; null;
if (lock) block.add_variable(lock, x`false`); if (lock) block.add_variable(lock, x`false`);
[bindingGroup].forEach(group => { [bindingGroup].forEach(group => {
@ -571,7 +570,7 @@ export default class ElementWrapper extends Wrapper {
callee = handler; callee = handler;
} }
const params = Array.from(contextual_dependencies).map((name) => ({ const params = Array.from(contextual_dependencies).map(name => ({
type: 'Identifier', type: 'Identifier',
name name
})); }));
@ -610,7 +609,7 @@ export default class ElementWrapper extends Wrapper {
.map(binding => x`${binding.snippet} === void 0`) .map(binding => x`${binding.snippet} === void 0`)
.reduce((lhs, rhs) => x`${lhs} || ${rhs}`); .reduce((lhs, rhs) => x`${lhs} || ${rhs}`);
const should_initialise = const should_initialise = (
this.node.name === 'select' || this.node.name === 'select' ||
group.bindings.find(binding => { group.bindings.find(binding => {
return ( return (
@ -619,7 +618,8 @@ export default class ElementWrapper extends Wrapper {
binding.node.name === 'innerHTML' || binding.node.name === 'innerHTML' ||
binding.is_readonly_media_attribute() binding.is_readonly_media_attribute()
); );
}); })
);
if (should_initialise) { if (should_initialise) {
const callback = has_local_function ? handler : x`() => ${callee}.call(${this.var})`; const callback = has_local_function ? handler : x`() => ${callee}.call(${this.var})`;
@ -651,7 +651,7 @@ export default class ElementWrapper extends Wrapper {
add_attributes(block: Block) { add_attributes(block: Block) {
// Get all the class dependencies first // Get all the class dependencies first
this.attributes.forEach(attribute => { this.attributes.forEach((attribute) => {
if (attribute.node.name === 'class') { if (attribute.node.name === 'class') {
const dependencies = attribute.node.get_dependencies(); const dependencies = attribute.node.get_dependencies();
this.class_dependencies.push(...dependencies); this.class_dependencies.push(...dependencies);
@ -663,7 +663,7 @@ export default class ElementWrapper extends Wrapper {
return; return;
} }
this.attributes.forEach(attribute => { this.attributes.forEach((attribute) => {
attribute.render(block); attribute.render(block);
}); });
} }

@ -245,7 +245,7 @@ export default class IfBlockWrapper extends Wrapper {
} }
this.branches.forEach(branch => { this.branches.forEach(branch => {
branch.fragment.render(branch.block, null, (x`#nodes` as unknown) as Identifier); branch.fragment.render(branch.block, null, x`#nodes` as unknown as Identifier);
}); });
} }

@ -94,7 +94,7 @@ export default class InlineComponentWrapper extends Wrapper {
const dependencies: Set<string> = new Set(); const dependencies: Set<string> = new Set();
// TODO is this filtering necessary? (I *think* so) // TODO is this filtering necessary? (I *think* so)
default_slot.dependencies.forEach((name) => { default_slot.dependencies.forEach(name => {
if (!this.node.scope.is_let(name)) { if (!this.node.scope.is_let(name)) {
dependencies.add(name); dependencies.add(name);
} }
@ -169,7 +169,7 @@ export default class InlineComponentWrapper extends Wrapper {
}`, }`,
p`$$scope: { p`$$scope: {
ctx: #ctx ctx: #ctx
}`, }`
] ]
: []; : [];

@ -181,10 +181,7 @@ export default class SlotWrapper extends Wrapper {
if (#changes) ${slot}.p(${context}, #changes); if (#changes) ${slot}.p(${context}, #changes);
} }
`; `;
const fallback_update = const fallback_update = has_fallback && fallback_dynamic_dependencies.length > 0 && b`
has_fallback &&
fallback_dynamic_dependencies.length > 0 &&
b`
if (${slot_or_fallback} && ${slot_or_fallback}.p && ${renderer.dirty(fallback_dynamic_dependencies)}) { if (${slot_or_fallback} && ${slot_or_fallback}.p && ${renderer.dirty(fallback_dynamic_dependencies)}) {
${slot_or_fallback}.p(#ctx, #dirty); ${slot_or_fallback}.p(#ctx, #dirty);
} }

@ -20,7 +20,7 @@ export default function(node: Element, renderer: Renderer, options: RenderOption
const contenteditable = ( const contenteditable = (
node.name !== 'textarea' && node.name !== 'textarea' &&
node.name !== 'input' && node.name !== 'input' &&
node.attributes.some((attribute) => attribute.name === 'contenteditable') node.attributes.some(attribute => attribute.name === 'contenteditable')
); );
const slot = node.get_static_attribute_value('slot'); const slot = node.get_static_attribute_value('slot');

@ -11,7 +11,7 @@ export default function get_slot_data(values: Map<string, Attribute>, block: Blo
.map(attribute => { .map(attribute => {
const value = get_value(block, attribute); const value = get_value(block, attribute);
return p`${attribute.name}: ${value}`; return p`${attribute.name}: ${value}`;
}), })
}; };
} }
@ -20,7 +20,7 @@ function get_value(block: Block, attribute: Attribute) {
if (attribute.chunks.length === 0) return x`""`; if (attribute.chunks.length === 0) return x`""`;
let value = attribute.chunks let value = attribute.chunks
.map((chunk) => (chunk.type === 'Text' ? string_literal(chunk.data) : block ? chunk.manipulate(block) : chunk.node)) .map(chunk => (chunk.type === 'Text' ? string_literal(chunk.data) : block ? chunk.manipulate(block) : chunk.node))
.reduce((lhs, rhs) => x`${lhs} + ${rhs}`); .reduce((lhs, rhs) => x`${lhs} + ${rhs}`);
if (attribute.chunks.length > 1 && attribute.chunks[0].type !== 'Text') { if (attribute.chunks.length > 1 && attribute.chunks[0].type !== 'Text') {

@ -24,6 +24,6 @@ export function flip(
delay, delay,
duration: run_duration(duration, Math.sqrt(dx * dx + dy * dy)), duration: run_duration(duration, Math.sqrt(dx * dx + dy * dy)),
easing, easing,
css: (_t, u) => `transform: ${transform} translate(${u * dx}px, ${u * dy}px);`, css: (_t, u) => `transform: ${transform} translate(${u * dx}px, ${u * dy}px);`
}; };
} }

@ -10,5 +10,5 @@ export {
getContext, getContext,
tick, tick,
createEventDispatcher, createEventDispatcher,
SvelteComponentDev as SvelteComponent, SvelteComponentDev as SvelteComponent
} from 'svelte/internal'; } from 'svelte/internal';

@ -3,21 +3,20 @@ import { current_component, set_current_component } from './lifecycle';
import { children, detach } from './dom'; import { children, detach } from './dom';
import { transition_in } from './transitions'; import { transition_in } from './transitions';
import { noop } from './environment'; import { noop } from './environment';
type binary = 0 | 1;
export interface Fragment { export interface Fragment {
key: string | null; key: string | null;
first: null; first: null;
/* create */ c: () => void; /* create */ c: () => void;
/* claim */ l: (nodes: any) => void; /* claim */ l: (nodes: any) => void;
/* hydrate */ h: () => void; /* hydrate */ h: () => void;
/* mount */ m: (target: HTMLElement, anchor: any, is_remount: binary) => void; /* mount */ m: (target: HTMLElement, anchor: any) => void;
/* update */ p: (ctx: any, dirty: any) => void; /* update */ p: (ctx: any, dirty: any) => void;
/* measure */ r: () => void; /* measure */ r: () => void;
/* fix */ f: () => void; /* fix */ f: () => void;
/* animate */ a: () => void; /* animate */ a: () => void;
/* intro */ i: (local: binary) => void; /* intro */ i: (local: any) => void;
/* outro */ o: (local: binary) => void; /* outro */ o: (local: any) => void;
/* destroy */ d: (detaching: binary) => void; /* destroy */ d: (detaching: 0|1) => void;
} }
// eslint-disable-next-line @typescript-eslint/class-name-casing // eslint-disable-next-line @typescript-eslint/class-name-casing
export interface T$$ { export interface T$$ {
@ -106,7 +105,7 @@ export function init(
if ($$.ctx && not_equal($$.ctx[i], ($$.ctx[i] = 0 in rest ? rest[0] : res))) { if ($$.ctx && not_equal($$.ctx[i], ($$.ctx[i] = 0 in rest ? rest[0] : res))) {
if (i in $$.bound) $$.bound[i]($$.ctx[i]); if (i in $$.bound) $$.bound[i]($$.ctx[i]);
if (ready) { if (ready) {
if (!~$$.dirty[0]) { if (-1 === $$.dirty[0]) {
schedule_update(component); schedule_update(component);
$$.dirty.fill(0); $$.dirty.fill(0);
} }
@ -181,12 +180,13 @@ export const SvelteElement =
callbacks.push(callback); callbacks.push(callback);
return () => { return () => {
const index = callbacks.indexOf(callback); const index = callbacks.indexOf(callback);
if (~index) callbacks.splice(index, 1); if (index !== -1) callbacks.splice(index, 1);
}; };
} }
$set() {
// overridden by instance, if it has props // overridden by instance, if it has props
$set() {} }
}; };
export class SvelteComponent { export class SvelteComponent {
@ -200,9 +200,10 @@ export class SvelteComponent {
callbacks.push(callback); callbacks.push(callback);
return () => { return () => {
const index = callbacks.indexOf(callback); const index = callbacks.indexOf(callback);
if (~index) callbacks.splice(index, 1); if (index !== -1) callbacks.splice(index, 1);
}; };
} }
$set() {
// overridden by instance, if it has props // overridden by instance, if it has props
$set() {} }
} }

@ -53,18 +53,15 @@ export function handle_promise(promise, info) {
if (promise && typeof promise === 'object' && typeof promise.then === 'function') { if (promise && typeof promise === 'object' && typeof promise.then === 'function') {
const current_component = get_current_component(); const current_component = get_current_component();
promise.then( promise.then(value => {
(value) => {
set_current_component(current_component); set_current_component(current_component);
update(info.then, 1, info.value, value); update(info.then, 1, info.value, value);
set_current_component(null); set_current_component(null);
}, }, error => {
(error) => {
set_current_component(current_component); set_current_component(current_component);
update(info.catch, 2, info.error, error); update(info.catch, 2, info.error, error);
set_current_component(null); set_current_component(null);
} });
);
// if we previously had a then/catch block, destroy it // if we previously had a then/catch block, destroy it
if (info.current !== info.pending) { if (info.current !== info.pending) {

@ -2,14 +2,14 @@ import { custom_event, append, insert, detach, listen, attr } from './dom';
import { has_Symbol } from './environment'; import { has_Symbol } from './environment';
import { SvelteComponent } from './Component'; import { SvelteComponent } from './Component';
export function dispatch_dev<T = any>(type: string, detail?: T) {
document.dispatchEvent(custom_event(type, { version: __VERSION__, ...detail }));
}
export function add_location_dev(element, file, line, column, char) { export function add_location_dev(element, file, line, column, char) {
element.__svelte_meta = { element.__svelte_meta = {
loc: { file, line, column, char }, loc: { file, line, column, char },
}; };
} }
export function dispatch_dev<T = any>(type: string, detail?: T) {
document.dispatchEvent(custom_event(type, { version: __VERSION__, ...detail }));
}
export function append_dev(target: Node, node: Node) { export function append_dev(target: Node, node: Node) {
dispatch_dev('SvelteDOMInsert', { target, node }); dispatch_dev('SvelteDOMInsert', { target, node });

@ -12,29 +12,29 @@ const on_init_only = (name: string) => {
}; };
export function get_current_component() { export function get_current_component() {
return current_component; current_component;
} }
export function beforeUpdate(fn) { export function beforeUpdate(fn) {
on_init_only(`beforeUpdate`); on_init_only(`beforeUpdate`);
return current_component.$$.before_update.push(fn); current_component.$$.before_update.push(fn);
} }
export function onMount(fn) { export function onMount(fn) {
on_init_only(`onMount`); on_init_only(`onMount`);
return current_component.$$.on_mount.push(fn); current_component.$$.on_mount.push(fn);
} }
export function afterUpdate(fn) { export function afterUpdate(fn) {
on_init_only(`afterUpdate`); on_init_only(`afterUpdate`);
return current_component.$$.after_update.push(fn); current_component.$$.after_update.push(fn);
} }
export function onDestroy(fn) { export function onDestroy(fn) {
on_init_only(`onDestroy`); on_init_only(`onDestroy`);
return current_component.$$.on_destroy.push(fn); current_component.$$.on_destroy.push(fn);
} }
// todo : deprecate
export function createEventDispatcher() { export function createEventDispatcher() {
on_init_only(`createEventDispatcher`); on_init_only(`createEventDispatcher`);
const component = current_component; const component = current_component;

@ -16,13 +16,13 @@ export function spread(args, classes_to_add) {
} }
let str = ''; let str = '';
Object.keys(attributes).forEach((name) => { Object.keys(attributes).forEach(name => {
if (invalid_attribute_name_character.test(name)) return; if (invalid_attribute_name_character.test(name)) return;
const value = attributes[name]; const value = attributes[name];
if (value === true) str += ' ' + name; if (value === true) str += " " + name;
else if (boolean_attributes.has(name.toLowerCase())) { else if (boolean_attributes.has(name.toLowerCase())) {
if (value) str += ' ' + name; if (value) str += " " + name;
} else if (value != null) { } else if (value != null) {
str += ` ${name}="${String(value).replace(/"/g, '&#34;').replace(/'/g, '&#39;')}"`; str += ` ${name}="${String(value).replace(/"/g, '&#34;').replace(/'/g, '&#39;')}"`;
} }
@ -36,11 +36,11 @@ export const escaped = {
"'": '&#39;', "'": '&#39;',
'&': '&amp;', '&': '&amp;',
'<': '&lt;', '<': '&lt;',
'>': '&gt;', '>': '&gt;'
}; };
export function escape(html) { export function escape(html) {
return String(html).replace(/["'&<>]/g, (match) => escaped[match]); return String(html).replace(/["'&<>]/g, match => escaped[match]);
} }
export function each(items, fn) { export function each(items, fn) {
@ -52,15 +52,13 @@ export function each(items, fn) {
} }
export const missing_component = { export const missing_component = {
$$render: () => '', $$render: () => ''
}; };
export function validate_component(component, name) { export function validate_component(component, name) {
if (!component || !component.$$render) { if (!component || !component.$$render) {
if (name === 'svelte:component') name += ' this={...}'; if (name === 'svelte:component') name += ' this={...}';
throw new Error( throw new Error(`<${name}> is not a valid SSR component. You may need to review your build config to ensure that dependencies are compiled, rather than imported as pre-compiled modules`);
`<${name}> is not a valid SSR component. You may need to review your build config to ensure that dependencies are compiled, rather than imported as pre-compiled modules`
);
} }
return component; return component;
@ -117,24 +115,20 @@ export function create_ssr_component(fn) {
return { return {
html, html,
css: { css: {
code: Array.from(result.css) code: Array.from(result.css).map(css => css.code).join('\n'),
.map((css) => css.code) map: null // TODO
.join('\n'),
map: null, // TODO
}, },
head: result.title + result.head, head: result.title + result.head
}; };
}, },
$$render, $$render
}; };
} }
export function add_attribute(name, value, boolean) { export function add_attribute(name, value, boolean) {
if (value == null || (boolean && !value)) return ''; if (value == null || (boolean && !value)) return '';
return ` ${name}${ return ` ${name}${value === true ? '' : `=${typeof value === 'string' ? JSON.stringify(escape(value)) : `"${value}"`}`}`;
value === true ? '' : `=${typeof value === 'string' ? JSON.stringify(escape(value)) : `"${value}"`}`
}`;
} }
export function add_classes(classes) { export function add_classes(classes) {

Loading…
Cancel
Save