Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement spread binding #6162

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions site/content/docs/02-template-syntax.md
Original file line number Diff line number Diff line change
Expand Up @@ -762,6 +762,68 @@ To get a reference to a DOM node, use `bind:this`.
<canvas bind:this={canvasElement}></canvas>
```

#### [{...bind:*property*}](spread_bind_element_property)

```sv
{...bind:variable}
```

---

This type of binding works the same as simply using the spread syntax, but gives the advantages of two-way binding.

A scenario where one would want this would be for passing binds from a parent to a child component (A → B → C).

```sv
<!-- A.svelte -->
<script>
import B from './B.svelte';

let foo = 1;
let bar = 2;

// ... edit `foo` & `bar` here, and have their changes reflect in `C.svelte`
</script>

<B bind:foo bind:bar />
```

```sv
<!-- B.svelte -->
<script>
import C from './C.svelte';

let baz = 3; // baz was abstracted out from A.svelte

$: restProps = $$restProps;
$: restProps, updateRestProps(restProps);

function updateRestProps(restProps) {
Object.entries(restProps).forEach(([key, value]) => {
$$restProps[key] = value;
})
}
</script>

<C bind:baz {...bind:restProps} />
```

```sv
<!-- C.svelte -->
<script>
import { onMount, onDestroy } from 'svelte';

let interval;

export let foo;
export let bar;
export let baz;

// ... edit `foo` & `bar` here, and have their changes reflect in `A.svelte`
</script>

<p>foo: {foo}; bar: {bar}; baz: {baz}</p>
```

#### class:*name*

Expand Down
2 changes: 2 additions & 0 deletions src/compiler/compile/nodes/Binding.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ export default class Binding extends Node {
raw_expression: ESTreeNode; // TODO exists only for bind:this — is there a more elegant solution?
is_contextual: boolean;
is_readonly: boolean;
is_spread: boolean;

constructor(component: Component, parent: Element | InlineComponent | Window, scope: TemplateScope, info: TemplateNode) {
super(component, parent, scope, info);
Expand All @@ -42,6 +43,7 @@ export default class Binding extends Node {
}

this.name = info.name;
this.is_spread = info.modifiers.includes('spread');
this.expression = new Expression(component, this, scope, info.expression);
this.raw_expression = clone(info.expression);

Expand Down
97 changes: 71 additions & 26 deletions src/compiler/compile/render_dom/wrappers/InlineComponent/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { extract_names } from 'periscopic';
import mark_each_block_bindings from '../shared/mark_each_block_bindings';
import { string_to_member_expression } from '../../../utils/string_to_member_expression';
import SlotTemplate from '../../../nodes/SlotTemplate';
import Binding from '../../../nodes/Binding';

type SlotDefinition = { block: Block; scope: TemplateScope; get_context?: Node; get_changes?: Node };

Expand Down Expand Up @@ -136,7 +137,9 @@ export default class InlineComponentWrapper extends Wrapper {
let props;
const name_changes = block.get_unique_name(`${name.name}_changes`);

const uses_spread = !!this.node.attributes.find(a => a.is_spread);
const attributes_uses_spread = !!this.node.attributes.find(a => a.is_spread);
const bindings_uses_spread = !!this.node.bindings.find(b => b.is_spread);
const uses_spread = attributes_uses_spread || bindings_uses_spread;

// removing empty slot
for (const slot of this.slots.keys()) {
Expand Down Expand Up @@ -199,7 +202,8 @@ export default class InlineComponentWrapper extends Wrapper {
updates.push(b`const ${name_changes} = {};`);
}

if (this.node.attributes.length) {
if (this.node.attributes.length
|| this.node.bindings.length) {
if (uses_spread) {
const levels = block.get_unique_name(`${this.var.name}_spread_levels`);

Expand All @@ -212,26 +216,39 @@ export default class InlineComponentWrapper extends Wrapper {
add_to_set(all_dependencies, attr.dependencies);
});

this.node.attributes.forEach((attr, i) => {
const { name, dependencies } = attr;
this.node.bindings.forEach(binding => {
add_to_set(all_dependencies, binding.expression.dependencies);
});

[
...this.node.attributes,
...this.node.bindings.filter(binding => binding.is_spread)
].forEach((node: Attribute | Binding, i) => {
const { name } = node;
const dependencies = node.type === 'Attribute'
? node.dependencies
: node.expression.dependencies;

const condition = dependencies.size > 0 && (dependencies.size !== all_dependencies.size)
? renderer.dirty(Array.from(dependencies))
: null;
const unchanged = dependencies.size === 0;

let change_object;
if (attr.is_spread) {
const value = attr.expression.manipulate(block);
if (node.is_spread) {
const value = node.expression.manipulate(block);
initial_props.push(value);

let value_object = value;
if (attr.expression.node.type !== 'ObjectExpression') {
if (node.expression.node.type !== 'ObjectExpression') {
value_object = x`@get_spread_object(${value})`;
}
change_object = value_object;
} else {
const obj = x`{ ${name}: ${attr.get_value(block)} }`;
}

if (!node.is_spread
&& node.type === 'Attribute') {
const obj = x`{ ${name}: ${node.get_value(block)} }`;
initial_props.push(obj);
change_object = obj;
}
Expand Down Expand Up @@ -307,19 +324,28 @@ export default class InlineComponentWrapper extends Wrapper {

const snippet = binding.expression.manipulate(block);

statements.push(b`
if (${snippet} !== void 0) {
${props}.${binding.name} = ${snippet};
}`
);
if (binding.is_spread) {
updates.push(b`
if (!${updating} && ${renderer.dirty(Array.from(binding.expression.dependencies))}) {
${updating} = true;
@add_flush_callback(() => ${updating} = false);
}
`);
} else {
statements.push(b`
if (${snippet} !== void 0) {
${props}.${binding.name} = ${snippet};
}`
);

updates.push(b`
if (!${updating} && ${renderer.dirty(Array.from(binding.expression.dependencies))}) {
${updating} = true;
${name_changes}.${binding.name} = ${snippet};
@add_flush_callback(() => ${updating} = false);
}
`);
updates.push(b`
if (!${updating} && ${renderer.dirty(Array.from(binding.expression.dependencies))}) {
${updating} = true;
${name_changes}.${binding.name} = ${snippet};
@add_flush_callback(() => ${updating} = false);
}
`);
}

const contextual_dependencies = Array.from(binding.expression.contextual_dependencies);
const dependencies = Array.from(binding.expression.dependencies);
Expand All @@ -335,10 +361,17 @@ export default class InlineComponentWrapper extends Wrapper {
contextual_dependencies.push(object.name, property.name);
}

const params = [x`#value`];
const args = [x`#value`];
if (contextual_dependencies.length > 0) {
if (binding.is_spread) {
lhs = x`${lhs}[#key]`;
}

const params = binding.is_spread
? [x`#key`, x`#value`]
: [x`#value`];
const args = binding.is_spread
? [x`#key`, x`#value`]
: [x`#value`];
if (contextual_dependencies.length > 0) {
contextual_dependencies.forEach(name => {
params.push({
type: 'Identifier',
Expand All @@ -349,12 +382,11 @@ export default class InlineComponentWrapper extends Wrapper {
args.push(renderer.reference(name));
});


block.maintain_context = true; // TODO put this somewhere more logical
}

block.chunks.init.push(b`
function ${id}(#value) {
function ${id}(${params}) {
${callee}(${args});
}
`);
Expand All @@ -379,6 +411,19 @@ export default class InlineComponentWrapper extends Wrapper {

component.partly_hoisted.push(body);

if (binding.is_spread) {
return b`
@binding_callbacks.push(
() => Object
.keys(
#ctx[${renderer.context_lookup.get(dependencies[0]).index.value}]
)
.forEach(
#key => @bind(${this.var}, #key, ${id}.bind(undefined, #key))
)
);`;
}

return b`@binding_callbacks.push(() => @bind(${this.var}, '${binding.name}', ${id}));`;
});

Expand Down
25 changes: 25 additions & 0 deletions src/compiler/parse/state/tag.ts
Original file line number Diff line number Diff line change
Expand Up @@ -314,6 +314,31 @@ function read_attribute(parser: Parser, unique_names: Set<string>) {
if (parser.eat('...')) {
const expression = read_expression(parser);

if (parser.eat(':')
&& expression.type === 'Identifier'
&& expression.name === 'bind') {
const bind_expression = read_expression(parser);

if (bind_expression.type === 'Identifier') {
parser.allow_whitespace();
parser.eat('}', true);

return {
start,
end: parser.index,
type: 'Binding',
name: bind_expression.name,
modifiers: ['spread'],
expression: bind_expression
};
} else {
parser.error({
code: 'unexpected-token',
message: 'Expected identifier'
}, parser.index);
}
}

parser.allow_whitespace();
parser.eat('}', true);

Expand Down
8 changes: 8 additions & 0 deletions test/parser/samples/binding-spread/input.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<script>
let item = {
prop1: 'foo',
prop2: 'bar'
};
</script>

<Widget {...bind:item} />
Loading