Merge pull request #971 from sveltejs/gh-640

Implement dynamic components
pull/1004/head
Rich Harris 7 years ago committed by GitHub
commit 1767455c33
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -763,6 +763,10 @@ export default class Generator {
node.metadata = contextualise(node.expression, contextDependencies, indexes); node.metadata = contextualise(node.expression, contextDependencies, indexes);
this.skip(); this.skip();
} }
if (node.type === 'Element' && node.name === ':Component') {
node.metadata = contextualise(node.expression, contextDependencies, indexes);
}
}, },
leave(node: Node, parent: Node) { leave(node: Node, parent: Node) {

@ -256,6 +256,7 @@ const preprocessors = {
) => { ) => {
cannotUseInnerHTML(node); cannotUseInnerHTML(node);
node.var = block.getUniqueName(`each`); node.var = block.getUniqueName(`each`);
node.iterations = block.getUniqueName(`${node.var}_blocks`);
const { dependencies } = node.metadata; const { dependencies } = node.metadata;
block.addDependencies(dependencies); block.addDependencies(dependencies);
@ -436,13 +437,17 @@ const preprocessors = {
} }
const isComponent = const isComponent =
generator.components.has(node.name) || node.name === ':Self'; generator.components.has(node.name) || node.name === ':Self' || node.name === ':Component';
if (isComponent) { if (isComponent) {
cannotUseInnerHTML(node); cannotUseInnerHTML(node);
node.var = block.getUniqueName( node.var = block.getUniqueName(
(node.name === ':Self' ? generator.name : node.name).toLowerCase() (
node.name === ':Self' ? generator.name :
node.name === ':Component' ? 'switch_instance' :
node.name
).toLowerCase()
); );
node._state = getChildState(state, { node._state = getChildState(state, {

@ -3,9 +3,11 @@ import CodeBuilder from '../../../utils/CodeBuilder';
import visit from '../visit'; import visit from '../visit';
import { DomGenerator } from '../index'; import { DomGenerator } from '../index';
import Block from '../Block'; import Block from '../Block';
import isDomNode from './shared/isDomNode';
import getTailSnippet from '../../../utils/getTailSnippet'; import getTailSnippet from '../../../utils/getTailSnippet';
import getObject from '../../../utils/getObject'; import getObject from '../../../utils/getObject';
import getExpressionPrecedence from '../../../utils/getExpressionPrecedence'; import getExpressionPrecedence from '../../../utils/getExpressionPrecedence';
import getStaticAttributeValue from '../../../utils/getStaticAttributeValue';
import { stringify } from '../../../utils/stringify'; import { stringify } from '../../../utils/stringify';
import stringifyProps from '../../../utils/stringifyProps'; import stringifyProps from '../../../utils/stringifyProps';
import { Node } from '../../../interfaces'; import { Node } from '../../../interfaces';
@ -60,12 +62,21 @@ export default function visitComponent(
let beforecreate: string = null; let beforecreate: string = null;
const attributes = node.attributes const attributes = node.attributes
.filter((a: Node) => a.type === 'Attribute') .filter(a => a.type === 'Attribute')
.map((a: Node) => mungeAttribute(a, block)); .map(a => mungeAttribute(a, block));
const bindings = node.attributes const bindings = node.attributes
.filter((a: Node) => a.type === 'Binding') .filter(a => a.type === 'Binding')
.map((a: Node) => mungeBinding(a, block)); .map(a => mungeBinding(a, block));
const eventHandlers = node.attributes
.filter((a: Node) => a.type === 'EventHandler')
.map(a => mungeEventHandler(generator, node, a, block, name_context, allContexts));
const ref = node.attributes.find((a: Node) => a.type === 'Ref');
if (ref) generator.usesRefs = true;
const updates: string[] = [];
if (attributes.length || bindings.length) { if (attributes.length || bindings.length) {
const initialProps = attributes const initialProps = attributes
@ -73,8 +84,6 @@ export default function visitComponent(
const initialPropString = stringifyProps(initialProps); const initialPropString = stringifyProps(initialProps);
const updates: string[] = [];
attributes attributes
.filter((attribute: Attribute) => attribute.dynamic) .filter((attribute: Attribute) => attribute.dynamic)
.forEach((attribute: Attribute) => { .forEach((attribute: Attribute) => {
@ -194,96 +203,161 @@ export default function visitComponent(
} else if (initialProps.length) { } else if (initialProps.length) {
componentInitProperties.push(`data: ${initialPropString}`); componentInitProperties.push(`data: ${initialPropString}`);
} }
}
if (updates.length) { const isDynamicComponent = node.name === ':Component';
block.builders.update.addBlock(deindent`
var ${name}_changes = {}; const switch_vars = isDynamicComponent && {
${updates.join('\n')} value: block.getUniqueName('switch_value'),
${name}._set(${name}_changes); props: block.getUniqueName('switch_props')
${bindings.length && `${name_updating} = {};`} };
`);
const expression = (
node.name === ':Self' ? generator.name :
isDynamicComponent ? switch_vars.value :
`%components-${node.name}`
);
if (isDynamicComponent) {
block.contextualise(node.expression);
const { dependencies, snippet } = node.metadata;
const needsAnchor = node.next ? !isDomNode(node.next, generator) : !state.parentNode || !isDomNode(node.parent, generator);
const anchor = needsAnchor
? block.getUniqueName(`${name}_anchor`)
: (node.next && node.next.var) || 'null';
if (needsAnchor) {
block.addElement(
anchor,
`@createComment()`,
`@createComment()`,
state.parentNode
);
} }
}
const expression = node.name === ':Self' ? generator.name : `%components-${node.name}`; const params = block.params.join(', ');
block.builders.init.addBlock(deindent` block.builders.init.addBlock(deindent`
${statements.join('\n')} var ${switch_vars.value} = ${snippet};
var ${name} = new ${expression}({
${componentInitProperties.join(',\n')}
});
${beforecreate} function ${switch_vars.props}(${params}) {
`); return {
${componentInitProperties.join(',\n')}
};
}
block.builders.create.addLine(`${name}._fragment.c();`); if (${switch_vars.value}) {
${statements.length > 0 && statements.join('\n')}
var ${name} = new ${expression}(${switch_vars.props}(${params}));
block.builders.claim.addLine( ${beforecreate}
`${name}._fragment.l(${state.parentNodes});` }
);
block.builders.mount.addLine( ${eventHandlers.map(handler => deindent`
`${name}._mount(${state.parentNode || '#target'}, ${state.parentNode ? 'null' : 'anchor'});` function ${handler.var}(event) {
); ${handler.body}
}
if (!state.parentNode) block.builders.unmount.addLine(`${name}._unmount();`); if (${name}) ${name}.on("${handler.name}", ${handler.var});
`)}
`);
block.builders.destroy.addLine(`${name}.destroy(false);`); block.builders.create.addLine(
`if (${name}) ${name}._fragment.c();`
);
// event handlers block.builders.claim.addLine(
node.attributes.filter((a: Node) => a.type === 'EventHandler').forEach((handler: Node) => { `if (${name}) ${name}._fragment.l(${state.parentNodes});`
const usedContexts: string[] = []; );
if (handler.expression) { block.builders.mount.addLine(
generator.addSourcemapLocations(handler.expression); `if (${name}) ${name}._mount(${state.parentNode || '#target'}, ${state.parentNode ? 'null' : 'anchor'});`
generator.code.prependRight( );
handler.expression.start,
`${block.alias('component')}.`
);
handler.expression.arguments.forEach((arg: Node) => { block.builders.update.addBlock(deindent`
const { contexts } = block.contextualise(arg, null, true); if (${switch_vars.value} !== (${switch_vars.value} = ${snippet})) {
if (${name}) ${name}.destroy();
contexts.forEach(context => { if (${switch_vars.value}) {
if (!~usedContexts.indexOf(context)) usedContexts.push(context); ${name} = new ${switch_vars.value}(${switch_vars.props}(${params}));
allContexts.add(context); ${name}._fragment.c();
});
});
}
// TODO hoist event handlers? can do `this.__component.method(...)` ${node.children.map(child => remount(generator, child, name))}
const declarations = usedContexts.map(name => { ${name}._mount(${anchor}.parentNode, ${anchor});
if (name === 'state') return `var state = ${name_context}.state;`;
const listName = block.listNames.get(name); ${eventHandlers.map(handler => deindent`
const indexName = block.indexNames.get(name); ${name}.on("${handler.name}", ${handler.var});
`)}
return `var ${listName} = ${name_context}.${listName}, ${indexName} = ${name_context}.${indexName}, ${name} = ${listName}[${indexName}]`; ${ref && `#component.refs.${ref.name} = ${name};`}
}); }
const handlerBody = ${ref && deindent`
(declarations.length ? declarations.join('\n') + '\n\n' : '') + else if (#component.refs.${ref.name} === ${name}) {
(handler.expression ? #component.refs.${ref.name} = null;
`[✂${handler.expression.start}-${handler.expression.end}✂];` : }`}
`${block.alias('component')}.fire('${handler.name}', event);`); }
`);
if (updates.length) {
block.builders.update.addBlock(deindent`
else {
var ${name}_changes = {};
${updates.join('\n')}
${name}._set(${name}_changes);
${bindings.length && `${name_updating} = {};`}
}
`);
}
if (!state.parentNode) block.builders.unmount.addLine(`if (${name}) ${name}._unmount();`);
block.builders.destroy.addLine(`if (${name}) ${name}.destroy(false);`);
} else {
block.builders.init.addBlock(deindent` block.builders.init.addBlock(deindent`
${name}.on("${handler.name}", function(event) { ${statements.join('\n')}
${handlerBody} var ${name} = new ${expression}({
${componentInitProperties.join(',\n')}
}); });
${beforecreate}
${eventHandlers.map(handler => deindent`
${name}.on("${handler.name}", function(event) {
${handler.body}
});
`)}
${ref && `#component.refs.${ref.name} = ${name};`}
`); `);
});
// refs block.builders.create.addLine(`${name}._fragment.c();`);
node.attributes.filter((a: Node) => a.type === 'Ref').forEach((ref: Node) => {
generator.usesRefs = true; block.builders.claim.addLine(
`${name}._fragment.l(${state.parentNodes});`
);
block.builders.init.addLine(`#component.refs.${ref.name} = ${name};`); block.builders.mount.addLine(
`${name}._mount(${state.parentNode || '#target'}, ${state.parentNode ? 'null' : 'anchor'});`
);
if (updates.length) {
block.builders.update.addBlock(deindent`
var ${name}_changes = {};
${updates.join('\n')}
${name}._set(${name}_changes);
${bindings.length && `${name_updating} = {};`}
`);
}
if (!state.parentNode) block.builders.unmount.addLine(`${name}._unmount();`);
block.builders.destroy.addLine(deindent` block.builders.destroy.addLine(deindent`
if (#component.refs.${ref.name} === ${name}) #component.refs.${ref.name} = null; ${name}.destroy(false);
${ref && `if (#component.refs.${ref.name} === ${name}) #component.refs.${ref.name} = null;`}
`); `);
}); }
// maintain component context // maintain component context
if (allContexts.size) { if (allContexts.size) {
@ -427,6 +501,55 @@ function mungeBinding(binding: Node, block: Block): Binding {
}; };
} }
function mungeEventHandler(generator: DomGenerator, node: Node, handler: Node, block: Block, name_context: string, allContexts: Set<string>) {
let body;
if (handler.expression) {
generator.addSourcemapLocations(handler.expression);
generator.code.prependRight(
handler.expression.start,
`${block.alias('component')}.`
);
const usedContexts: string[] = [];
handler.expression.arguments.forEach((arg: Node) => {
const { contexts } = block.contextualise(arg, null, true);
contexts.forEach(context => {
if (!~usedContexts.indexOf(context)) usedContexts.push(context);
allContexts.add(context);
});
});
// TODO hoist event handlers? can do `this.__component.method(...)`
const declarations = usedContexts.map(name => {
if (name === 'state') return `var state = ${name_context}.state;`;
const listName = block.listNames.get(name);
const indexName = block.indexNames.get(name);
return `var ${listName} = ${name_context}.${listName}, ${indexName} = ${name_context}.${indexName}, ${name} = ${listName}[${indexName}]`;
});
body = deindent`
${declarations}
[${handler.expression.start}-${handler.expression.end}];
`;
} else {
body = deindent`
${block.alias('component')}.fire('${handler.name}', event);
`;
}
return {
name: handler.name,
var: block.getUniqueName(`${node.var}_${handler.name}`),
body
};
}
function isComputed(node: Node) { function isComputed(node: Node) {
while (node.type === 'MemberExpression') { while (node.type === 'MemberExpression') {
if (node.computed) return true; if (node.computed) return true;
@ -435,3 +558,31 @@ function isComputed(node: Node) {
return false; return false;
} }
function remount(generator: DomGenerator, node: Node, name: string) {
// TODO make this a method of the nodes
if (node.type === 'Element') {
if (node.name === ':Self' || node.name === ':Component' || generator.components.has(node.name)) {
return `${node.var}._mount(${name}._slotted.default, null);`;
}
const slot = node.attributes.find(attribute => attribute.name === 'slot');
if (slot) {
return `@appendNode(${node.var}, ${name}._slotted.${getStaticAttributeValue(node, 'slot')});`;
}
return `@appendNode(${node.var}, ${name}._slotted.default);`;
}
if (node.type === 'Text' || node.type === 'MustacheTag' || node.type === 'RawMustacheTag') {
return `@appendNode(${node.var}, ${name}._slotted.default);`;
}
if (node.type === 'EachBlock') {
// TODO consider keyed blocks
return `for (var #i = 0; #i < ${node.iterations}.length; #i += 1) ${node.iterations}[#i].m(${name}._slotted.default, null);`;
}
return `${node.var}.m(${name}._slotted.default, null);`;
}

@ -18,7 +18,7 @@ export default function visitEachBlock(
const create_each_block = node._block.name; const create_each_block = node._block.name;
const each_block_value = node._block.listName; const each_block_value = node._block.listName;
const iterations = block.getUniqueName(`${each}_blocks`); const iterations = node.iterations;
const params = block.params.join(', '); const params = block.params.join(', ');
const needsAnchor = node.next ? !isDomNode(node.next, generator) : !state.parentNode || !isDomNode(node.parent, generator); const needsAnchor = node.next ? !isDomNode(node.next, generator) : !state.parentNode || !isDomNode(node.parent, generator);

@ -43,7 +43,7 @@ export default function visitElement(
} }
} }
if (generator.components.has(node.name) || node.name === ':Self') { if (generator.components.has(node.name) || node.name === ':Self' || node.name === ':Component') {
return visitComponent(generator, block, state, node, elementStack, componentStack); return visitComponent(generator, block, state, node, elementStack, componentStack);
} }

@ -189,6 +189,14 @@ export default function ssr(
} }
` `
} }
${
/__missingComponent/.test(generator.renderCode) && deindent`
var __missingComponent = {
render: () => ''
};
`
}
`.replace(/(@+|#+|%+)(\w*(?:-\w*)?)/g, (match: string, sigil: string, name: string) => { `.replace(/(@+|#+|%+)(\w*(?:-\w*)?)/g, (match: string, sigil: string, name: string) => {
if (sigil === '@') return generator.alias(name); if (sigil === '@') return generator.alias(name);
if (sigil === '%') return generator.templateVars.get(name); if (sigil === '%') return generator.templateVars.get(name);

@ -71,7 +71,14 @@ export default function visitComponent(
) )
.join(', '); .join(', ');
const expression = node.name === ':Self' ? generator.name : `%components-${node.name}`; const isDynamicComponent = node.name === ':Component';
if (isDynamicComponent) block.contextualise(node.expression);
const expression = (
node.name === ':Self' ? generator.name :
isDynamicComponent ? `((${node.metadata.snippet}) || __missingComponent)` :
`%components-${node.name}`
);
bindings.forEach(binding => { bindings.forEach(binding => {
block.addBinding(binding, expression); block.addBinding(binding, expression);

@ -40,7 +40,7 @@ export default function visitElement(
return; return;
} }
if (generator.components.has(node.name) || node.name === ':Self') { if (generator.components.has(node.name) || node.name === ':Self' || node.name === ':Component') {
visitComponent(generator, block, node); visitComponent(generator, block, node);
return; return;
} }

@ -4,7 +4,7 @@ import Generator from '../../Generator';
export default function isChildOfComponent(node: Node, generator: Generator) { export default function isChildOfComponent(node: Node, generator: Generator) {
while (node = node.parent) { while (node = node.parent) {
if (node.type !== 'Element') continue; if (node.type !== 'Element') continue;
if (generator.components.has(node.name)) return true; if (node.name === ':Self' || node.name === ':Component' || generator.components.has(node.name)) return true; // TODO extract this out into a helper
if (/-/.test(node.name)) return false; if (/-/.test(node.name)) return false;
} }
} }

@ -15,9 +15,10 @@ import { Node } from '../../interfaces';
const validTagName = /^\!?[a-zA-Z]{1,}:?[a-zA-Z0-9\-]*/; const validTagName = /^\!?[a-zA-Z]{1,}:?[a-zA-Z0-9\-]*/;
const SELF = ':Self'; const SELF = ':Self';
const COMPONENT = ':Component';
const metaTags = { const metaTags = {
':Window': true, ':Window': true
}; };
const specials = new Map([ const specials = new Map([
@ -104,6 +105,15 @@ export default function tag(parser: Parser) {
} }
} }
const element: Node = {
start,
end: null, // filled in later
type: 'Element',
name,
attributes: [],
children: [],
};
parser.allowWhitespace(); parser.allowWhitespace();
if (isClosingTag) { if (isClosingTag) {
@ -156,17 +166,22 @@ export default function tag(parser: Parser) {
} }
} }
const attributes = []; if (name === COMPONENT) {
parser.eat('{', true);
element.expression = readExpression(parser);
parser.allowWhitespace();
parser.eat('}', true);
parser.allowWhitespace();
}
const uniqueNames = new Set(); const uniqueNames = new Set();
let attribute; let attribute;
while ((attribute = readAttribute(parser, uniqueNames))) { while ((attribute = readAttribute(parser, uniqueNames))) {
attributes.push(attribute); element.attributes.push(attribute);
parser.allowWhitespace(); parser.allowWhitespace();
} }
parser.allowWhitespace();
// special cases top-level <script> and <style> // special cases top-level <script> and <style>
if (specials.has(name) && parser.stack.length === 1) { if (specials.has(name) && parser.stack.length === 1) {
const special = specials.get(name); const special = specials.get(name);
@ -179,19 +194,10 @@ export default function tag(parser: Parser) {
} }
parser.eat('>', true); parser.eat('>', true);
parser[special.property] = special.read(parser, start, attributes); parser[special.property] = special.read(parser, start, element.attributes);
return; return;
} }
const element: Node = {
start,
end: null, // filled in later
type: 'Element',
name,
attributes,
children: [],
};
parser.current().children.push(element); parser.current().children.push(element);
const selfClosing = parser.eat('/') || isVoidElementName(name); const selfClosing = parser.eat('/') || isVoidElementName(name);
@ -242,6 +248,8 @@ function readTagName(parser: Parser) {
return SELF; return SELF;
} }
if (parser.eat(COMPONENT)) return COMPONENT;
const name = parser.readUntil(/(\s|\/|>)/); const name = parser.readUntil(/(\s|\/|>)/);
if (name in metaTags) return name; if (name in metaTags) return name;

@ -14,7 +14,7 @@ export default function validateElement(
elementStack: Node[] elementStack: Node[]
) { ) {
const isComponent = const isComponent =
node.name === ':Self' || validator.components.has(node.name); node.name === ':Self' || node.name === ':Component' || validator.components.has(node.name);
if (!isComponent && /^[A-Z]/.test(node.name[0])) { if (!isComponent && /^[A-Z]/.test(node.name[0])) {
// TODO upgrade to validator.error in v2 // TODO upgrade to validator.error in v2
@ -230,7 +230,7 @@ function checkSlotAttribute(validator: Validator, node: Node, attribute: Node, s
const parent = stack[i]; const parent = stack[i];
if (parent.type === 'Element') { if (parent.type === 'Element') {
// if we're inside a component or a custom element, gravy // if we're inside a component or a custom element, gravy
if (validator.components.has(parent.name)) return; if (parent.name === ':Self' || parent.name === ':Component' || validator.components.has(parent.name)) return;
if (/-/.test(parent.name)) return; if (/-/.test(parent.name)) return;
} }

@ -0,0 +1 @@
<:Component {foo ? Foo : Bar}></:Component>

@ -0,0 +1,43 @@
{
"hash": 410218696,
"html": {
"start": 0,
"end": 43,
"type": "Fragment",
"children": [
{
"start": 0,
"end": 43,
"type": "Element",
"name": ":Component",
"attributes": [],
"children": [],
"expression": {
"type": "ConditionalExpression",
"start": 13,
"end": 28,
"test": {
"type": "Identifier",
"start": 13,
"end": 16,
"name": "foo"
},
"consequent": {
"type": "Identifier",
"start": 19,
"end": 22,
"name": "Foo"
},
"alternate": {
"type": "Identifier",
"start": 25,
"end": 28,
"name": "Bar"
}
}
}
]
},
"css": null,
"js": null
}

@ -1,4 +1,5 @@
import assert from "assert"; import assert from "assert";
import chalk from 'chalk';
import * as path from "path"; import * as path from "path";
import * as fs from "fs"; import * as fs from "fs";
import * as acorn from "acorn"; import * as acorn from "acorn";
@ -89,6 +90,9 @@ describe("runtime", () => {
} }
} catch (err) { } catch (err) {
failed.add(dir); failed.add(dir);
if (err.frame) {
console.error(chalk.red(err.frame)); // eslint-disable-line no-console
}
showOutput(cwd, { shared, format: 'cjs', store: !!compileOptions.store }, svelte); // eslint-disable-line no-console showOutput(cwd, { shared, format: 'cjs', store: !!compileOptions.store }, svelte); // eslint-disable-line no-console
throw err; throw err;
} }

@ -0,0 +1,2 @@
<p>bar</p>
<input type='checkbox' bind:checked='z'>

@ -0,0 +1,2 @@
<p>foo</p>
<input bind:value='y'>

@ -0,0 +1,33 @@
export default {
data: {
x: true
},
html: `
<p>foo</p>
<input>
`,
test(assert, component, target, window) {
let input = target.querySelector('input');
input.value = 'abc';
input.dispatchEvent(new window.Event('input'));
assert.equal(component.get('y'), 'abc');
component.set({
x: false
});
assert.htmlEqual(target.innerHTML, `
<p>bar</p>
<input type='checkbox'>
`);
input = target.querySelector('input');
input.checked = true;
input.dispatchEvent(new window.Event('change'));
assert.equal(component.get('z'), true);
}
};

@ -0,0 +1,12 @@
<:Component { x ? Foo : Bar } bind:y bind:z/>
<script>
import Foo from './Foo.html';
import Bar from './Bar.html';
export default {
data() {
return { Foo, Bar };
}
};
</script>

@ -0,0 +1 @@
<button on:click='fire("select", { id: "bar" })'>select bar</button>

@ -0,0 +1 @@
<button on:click='fire("select", { id: "foo" })'>select foo</button>

@ -0,0 +1,27 @@
export default {
data: {
x: true
},
html: `
<button>select foo</button>
`,
test(assert, component, target, window) {
const click = new window.MouseEvent('click');
target.querySelector('button').dispatchEvent(click);
assert.equal(component.get('selected'), 'foo');
component.set({
x: false
});
assert.htmlEqual(target.innerHTML, `
<button>select bar</button>
`);
target.querySelector('button').dispatchEvent(click);
assert.equal(component.get('selected'), 'bar');
}
};

@ -0,0 +1,12 @@
<:Component { x ? Foo : Bar } on:select='set({ selected: event.id })'/>
<script>
import Foo from './Foo.html';
import Bar from './Bar.html';
export default {
data() {
return { Foo, Bar };
}
};
</script>

@ -0,0 +1,3 @@
<h1>Bar</h1>
<slot></slot>
<slot name='other'></slot>

@ -0,0 +1,3 @@
<h1>Foo</h1>
<slot name='other'></slot>
<slot></slot>

@ -0,0 +1,37 @@
export default {
data: {
x: true
},
html: `
<h1>Foo</h1>
<div slot='other'>what goes up must come down</div>
<p>element</p>
you're it
<p>neither foo nor bar</p>
text
<span>a</span>
<span>b</span>
<span>c</span>
<div>baz</div>
`,
test(assert, component, target) {
component.set({
x: false
});
assert.htmlEqual(target.innerHTML, `
<h1>Bar</h1>
<p>element</p>
you're it
<p>neither foo nor bar</p>
text
<span>a</span>
<span>b</span>
<span>c</span>
<div>baz</div>
<div slot='other'>what goes up must come down</div>
`);
}
};

@ -0,0 +1,45 @@
<:Component { x ? Foo : Bar } x='{{x}}'>
<p>element</p>
{{tag}}
{{#if foo}}
<p>foo</p>
{{elseif bar}}
<p>bar</p>
{{else}}
<p>neither foo nor bar</p>
{{/if}}
text
{{#each things as thing}}
<span>{{thing}}</span>
{{/each}}
<Baz/>
<div slot='other'>what goes up must come down</div>
</:Component>
<script>
import Foo from './Foo.html';
import Bar from './Bar.html';
import Baz from './Baz.html';
export default {
data() {
return {
Foo,
Bar,
tag: 'you\'re it',
things: ['a', 'b', 'c']
};
},
components: {
Baz
}
};
</script>

@ -0,0 +1,19 @@
export default {
data: {
x: 1
},
html: `
<p>Foo 1</p>
`,
test(assert, component, target) {
component.set({
x: 2
});
assert.htmlEqual(target.innerHTML, `
<p>Foo 2</p>
`);
}
};

@ -0,0 +1,12 @@
<:Component { x ? Foo : Bar } x='{{x}}'/>
<script>
import Foo from './Foo.html';
import Bar from './Bar.html';
export default {
data() {
return { Foo, Bar };
}
};
</script>

@ -0,0 +1,19 @@
export default {
data: {
x: true
},
html: `
<p>true, therefore Foo</p>
`,
test(assert, component, target) {
component.set({
x: false
});
assert.htmlEqual(target.innerHTML, `
<p>false, therefore Bar</p>
`);
}
};

@ -0,0 +1,12 @@
<:Component { x ? Foo : Bar } x='{{x}}'/>
<script>
import Foo from './Foo.html';
import Bar from './Bar.html';
export default {
data() {
return { Foo, Bar };
}
};
</script>
Loading…
Cancel
Save