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

feat: attachments (alternative syntax) #15045

Closed
wants to merge 20 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
5 changes: 5 additions & 0 deletions .changeset/poor-days-pay.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'svelte': minor
---

feat: attachments
2 changes: 2 additions & 0 deletions packages/svelte/elements.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -840,6 +840,8 @@ export interface HTMLAttributes<T extends EventTarget> extends AriaAttributes, D
readonly 'bind:borderBoxSize'?: Array<ResizeObserverSize> | undefined | null;
readonly 'bind:devicePixelContentBoxSize'?: Array<ResizeObserverSize> | undefined | null;

attachments: Array<(node: T) => void | (() => void)>;

// SvelteKit
'data-sveltekit-keepfocus'?: true | '' | 'off' | undefined | null;
'data-sveltekit-noscroll'?: true | '' | 'off' | undefined | null;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/** @import { Expression } from 'estree' */
/** @import { AST } from '#compiler' */
/** @import { AnalysisState, Context } from '../../types' */
import * as e from '../../../../errors.js';
Expand Down Expand Up @@ -91,15 +92,10 @@ export function visit_component(node, context) {
validate_attribute(attribute, node);

if (is_expression_attribute(attribute)) {
const expression = get_attribute_expression(attribute);
if (expression.type === 'SequenceExpression') {
let i = /** @type {number} */ (expression.start);
while (--i > 0) {
const char = context.state.analysis.source[i];
if (char === '(') break; // parenthesized sequence expressions are ok
if (char === '{') e.attribute_invalid_sequence_expression(expression);
}
}
disallow_unparenthesized_sequences(
get_attribute_expression(attribute),
context.state.analysis.source
);
}
}

Expand Down Expand Up @@ -158,3 +154,18 @@ export function visit_component(node, context) {
context.visit({ ...node.fragment, nodes: nodes[slot_name] }, state);
}
}

/**
* @param {Expression} expression
* @param {string} source
*/
function disallow_unparenthesized_sequences(expression, source) {
if (expression.type === 'SequenceExpression') {
let i = /** @type {number} */ (expression.start);
while (--i > 0) {
const char = source[i];
if (char === '(') break; // parenthesized sequence expressions are ok
if (char === '{') e.attribute_invalid_sequence_expression(expression);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,19 @@ export function RegularElement(node, context) {
}
}

if (attribute.name === 'attachments') {
context.state.init.push(
b.stmt(
b.call(
'$.attach',
context.state.node,
b.thunk(/** @type {Expression} */ (context.visit(attribute.value.expression)))
)
)
);
continue;
}

attributes.push(attribute);
lookup.set(attribute.name, attribute);
break;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,6 @@ export function build_element_attributes(node, context) {
// effect on the selected value after the user interacts with the select element (the value _property_ does, but not the attribute)
attributes.push(attribute);
}

// omit event handlers except for special cases
} else if (is_event_attribute(attribute)) {
if (
Expand All @@ -82,6 +81,8 @@ export function build_element_attributes(node, context) {
) {
events_to_capture.add(attribute.name);
}
} else if (attribute.name === 'attachments') {
continue;
// the defaultValue/defaultChecked properties don't exist as attributes
} else if (attribute.name !== 'defaultValue' && attribute.name !== 'defaultChecked') {
if (attribute.name === 'class') {
Expand Down
17 changes: 17 additions & 0 deletions packages/svelte/src/internal/client/dom/elements/attachments.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { effect } from '../../reactivity/effects.js';

/**
* @param {Element} node
* @param {() => Array<(node: Element) => void>} get_fn
*/
export function attach(node, get_fn) {
effect(() => {
const fns = get_fn();

fns.forEach((fn) => {
// we use `&&` rather than `?.` so that things like
// `attachments={[DEV && something_dev_only()]}` work
return fn && fn(node);
});
});
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
set_active_effect,
set_active_reaction
} from '../../runtime.js';
import { attach } from './attachments.js';
import { clsx } from '../../../shared/attributes.js';

/**
Expand Down Expand Up @@ -313,6 +314,11 @@ export function set_attributes(

current[key] = value;

if (key === 'attachments') {
attach(element, () => value);
continue;
}

var prefix = key[0] + key[1]; // this is faster than key.slice(0, 2)
if (prefix === '$$') continue;

Expand Down
1 change: 1 addition & 0 deletions packages/svelte/src/internal/client/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export { element } from './dom/blocks/svelte-element.js';
export { head } from './dom/blocks/svelte-head.js';
export { append_styles } from './dom/css.js';
export { action } from './dom/elements/actions.js';
export { attach } from './dom/elements/attachments.js';
export {
remove_input_defaults,
set_attribute,
Expand Down
1 change: 1 addition & 0 deletions packages/svelte/src/internal/server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,7 @@ export function spread_attributes(attrs, classes, styles, flags = 0) {
if (typeof attrs[name] === 'function') continue;
if (name[0] === '$' && name[1] === '$') continue; // faster than name.startsWith('$$')
if (INVALID_ATTR_NAME_CHAR_REGEX.test(name)) continue;
if (name === 'attachments') continue;

var value = attrs[name];

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { test } from '../../test';

export default test({
ssrHtml: `<div></div>`,
html: `<div>DIV</div>`
});
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<div attachments={[(node) => node.textContent = node.nodeName]}></div>
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<script>
let props = $props();
</script>

<div {...props}></div>
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { test } from '../../test';

export default test({
ssrHtml: `<div></div>`,
html: `<div>set from component</div>`
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<script>
import Child from './Child.svelte';

let stuff = $state({
attachments: [(node) => node.textContent = 'set from component']
});
</script>

<Child {...stuff} />
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<script>
let props = $props();
</script>

<div {...props}></div>
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { test } from '../../test';

export default test({
ssrHtml: `<div></div>`,
html: `<div>set from component</div>`
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<script>
import Child from './Child.svelte';
</script>

<Child attachments={[(node) => node.textContent = 'set from component']} />
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { flushSync } from 'svelte';
import { test } from '../../test';

export default test({
ssrHtml: `<div></div><button>increment</button>`,
html: `<div>1</div><button>increment</button>`,

test: ({ assert, target }) => {
const btn = target.querySelector('button');

flushSync(() => btn?.click());
assert.htmlEqual(target.innerHTML, `<div>2</div><button>increment</button>`);
}
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<script>
let value = $state(1);
</script>

<div attachments={[(node) => node.textContent = value]}></div>
<button onclick={() => value += 1}>increment</button>
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { flushSync } from 'svelte';
import { test } from '../../test';

export default test({
test({ assert, logs, target }) {
assert.deepEqual(logs, ['hello']);
}
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<script>
let stuff = $state({
attachments: [() => console.log('hello')]
});
</script>

<div {...stuff}></div>
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { test } from '../../test';

export default test({
ssrHtml: `<div></div>`,
html: `<div>DIV</div>`
});
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<svelte:element this={'div'} attachments={[(node) => node.textContent = node.nodeName]}></svelte:element>
Loading