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 #15000

Open
wants to merge 19 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 11 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
4 changes: 4 additions & 0 deletions packages/svelte/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,10 @@
"types": "./types/index.d.ts",
"default": "./src/animate/index.js"
},
"./attachments": {
"types": "./types/index.d.ts",
"default": "./src/attachments/index.js"
},
"./compiler": {
"types": "./types/index.d.ts",
"require": "./compiler/index.js",
Expand Down
1 change: 1 addition & 0 deletions packages/svelte/scripts/generate-types.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ await createBundle({
[pkg.name]: `${dir}/src/index.d.ts`,
[`${pkg.name}/action`]: `${dir}/src/action/public.d.ts`,
[`${pkg.name}/animate`]: `${dir}/src/animate/public.d.ts`,
[`${pkg.name}/attachments`]: `${dir}/src/attachments/index.js`,
[`${pkg.name}/compiler`]: `${dir}/src/compiler/public.d.ts`,
[`${pkg.name}/easing`]: `${dir}/src/easing/index.js`,
[`${pkg.name}/legacy`]: `${dir}/src/legacy/legacy-client.js`,
Expand Down
4 changes: 4 additions & 0 deletions packages/svelte/src/attachments/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export {
create_attachment_key as createAttachmentKey,
is_attachment_key as isAttachmentKey
} from '../internal/client/dom/elements/attachments.js';
2 changes: 1 addition & 1 deletion packages/svelte/src/compiler/phases/1-parse/read/script.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ const ALLOWED_ATTRIBUTES = ['context', 'generics', 'lang', 'module'];
/**
* @param {Parser} parser
* @param {number} start
* @param {Array<AST.Attribute | AST.SpreadAttribute | AST.Directive>} attributes
* @param {Array<AST.Attribute | AST.SpreadAttribute | AST.Directive | AST.AttachTag>} attributes
* @returns {AST.Script}
*/
export function read_script(parser, start, attributes) {
Expand Down
2 changes: 1 addition & 1 deletion packages/svelte/src/compiler/phases/1-parse/read/style.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ const REGEX_HTML_COMMENT_CLOSE = /-->/;
/**
* @param {Parser} parser
* @param {number} start
* @param {Array<AST.Attribute | AST.SpreadAttribute | AST.Directive>} attributes
* @param {Array<AST.Attribute | AST.SpreadAttribute | AST.Directive | AST.AttachTag>} attributes
* @returns {AST.CSS.StyleSheet}
*/
export default function read_style(parser, start, attributes) {
Expand Down
20 changes: 19 additions & 1 deletion packages/svelte/src/compiler/phases/1-parse/state/element.js
Original file line number Diff line number Diff line change
Expand Up @@ -480,14 +480,32 @@ function read_static_attribute(parser) {

/**
* @param {Parser} parser
* @returns {AST.Attribute | AST.SpreadAttribute | AST.Directive | null}
* @returns {AST.Attribute | AST.SpreadAttribute | AST.Directive | AST.AttachTag | null}
*/
function read_attribute(parser) {
const start = parser.index;

if (parser.eat('{')) {
parser.allow_whitespace();

if (parser.eat('@attach')) {
parser.require_whitespace();

const expression = read_expression(parser);
parser.allow_whitespace();
parser.eat('}', true);

/** @type {AST.AttachTag} */
const use = {
type: 'AttachTag',
start,
end: parser.index,
expression
};

return use;
}

if (parser.eat('...')) {
const expression = read_expression(parser);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,8 @@ export function visit_component(node, context) {
attribute.type !== 'SpreadAttribute' &&
attribute.type !== 'LetDirective' &&
attribute.type !== 'OnDirective' &&
attribute.type !== 'BindDirective'
attribute.type !== 'BindDirective' &&
attribute.type !== 'AttachTag'
) {
e.component_invalid_directive(attribute);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ import { TitleElement } from './visitors/TitleElement.js';
import { TransitionDirective } from './visitors/TransitionDirective.js';
import { UpdateExpression } from './visitors/UpdateExpression.js';
import { UseDirective } from './visitors/UseDirective.js';
import { AttachTag } from './visitors/AttachTag.js';
import { VariableDeclaration } from './visitors/VariableDeclaration.js';

/** @type {Visitors} */
Expand Down Expand Up @@ -131,6 +132,7 @@ const visitors = {
TransitionDirective,
UpdateExpression,
UseDirective,
AttachTag,
VariableDeclaration
};

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/** @import { Expression } from 'estree' */
/** @import { AST } from '#compiler' */
/** @import { ComponentContext } from '../types' */
import * as b from '../../../../utils/builders.js';

/**
* @param {AST.AttachTag} node
* @param {ComponentContext} context
*/
export function AttachTag(node, context) {
context.state.init.push(
b.stmt(
b.call(
'$.attach',
context.state.node,
b.thunk(/** @type {Expression} */ (context.visit(node.expression)))
)
)
);
context.next();
}
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ export function RegularElement(node, context) {
/** @type {AST.StyleDirective[]} */
const style_directives = [];

/** @type {Array<AST.AnimateDirective | AST.BindDirective | AST.OnDirective | AST.TransitionDirective | AST.UseDirective>} */
/** @type {Array<AST.AnimateDirective | AST.BindDirective | AST.OnDirective | AST.TransitionDirective | AST.UseDirective | AST.AttachTag>} */
const other_directives = [];

/** @type {ExpressionStatement[]} */
Expand Down Expand Up @@ -152,6 +152,10 @@ export function RegularElement(node, context) {
has_use = true;
other_directives.push(attribute);
break;

case 'AttachTag':
other_directives.push(attribute);
break;
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,16 @@ export function build_component(node, component_name, context, anchor = context.
);
}
}
} else if (attribute.type === 'AttachTag') {
// TODO do we need to create a derived here?
push_prop(
b.prop(
'get',
b.call('$.create_attachment_key'),
/** @type {Expression} */ (context.visit(attribute.expression)),
true
)
);
}
}

Expand Down
9 changes: 8 additions & 1 deletion packages/svelte/src/compiler/types/template.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,12 @@ export namespace AST {
};
}

/** A `{@attach foo(...)} tag */
export interface AttachTag extends BaseNode {
type: 'AttachTag';
expression: Expression;
}

/** An `animate:` directive */
export interface AnimateDirective extends BaseNode {
type: 'AnimateDirective';
Expand Down Expand Up @@ -273,7 +279,7 @@ export namespace AST {

interface BaseElement extends BaseNode {
name: string;
attributes: Array<Attribute | SpreadAttribute | Directive>;
attributes: Array<Attribute | SpreadAttribute | Directive | AttachTag>;
fragment: Fragment;
}

Expand Down Expand Up @@ -549,6 +555,7 @@ export namespace AST {
| AST.Attribute
| AST.SpreadAttribute
| Directive
| AST.AttachTag
| AST.Comment
| Block;

Expand Down
30 changes: 30 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,30 @@
import { effect } from '../../reactivity/effects.js';

const key = `@attach-${/*@__PURE__*/ Math.random().toString(36).slice(2)}`;
const name = `Symbol(${key})`;

// TODO this feels a bit belt-and-braces to me, tbh — are we sure we need it?
/**
* Creates a `Symbol` that Svelte recognises as an attachment key
*/
export function create_attachment_key() {
return Symbol(key);
}

/**
* Returns `true` if the symbol was created with `createAttachmentKey`
* @param {string | symbol} key
*/
export function is_attachment_key(key) {
return typeof key === 'symbol' && key.toString() === name;
}

/**
* @param {Element} node
* @param {() => (node: Element) => void} get_fn
*/
export function attach(node, get_fn) {
effect(() => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is an interesting one, as we probably want the users function to be non-tracking like we have with actions. Otherwise any reads inside their attachment function will cause it to re-run over and over.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's the whole point, no? It re-runs when the attachment changes

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There's when the attachment changes and when something inside the attachment changes. I don't think we want the attachment to re-run if something inside the attachment function changes. People should create their own $effect inside the attachment to handle reactivity.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's not obvious to others either it seems: #15000 (comment)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is explicitly one of the flaws of actions that attachments are designed to overcome. If I had to write the tooltip example like this...

-function tooltip(content) {
+function tooltip(get_content) {
  return (node) => {
+   $effect(() => {
-     const tooltip = tippy(node, { content });
+     const tooltip = tippy(node, { content: get_content() });
      return tooltip.destroy;	
+   });
  };
}
-<button {@attach tooltip(content)}>
+<button {@attach tooltip(() => content)}>
  Hover me
</button>

...I would be very unhappy. (And in fact it's not equivalent, because if tooltip itself changed, nothing would happen.) It would cause much more broken code, not less.

I don't think people should be setting state directly inside attachments any more than they should be setting state inside normal effects. But if they really need to for some reason, untrack exists to prevent it from causing an infinite loop.

return get_fn()(node);
Rich-Harris marked this conversation as resolved.
Show resolved Hide resolved
});
}
11 changes: 9 additions & 2 deletions packages/svelte/src/internal/client/dom/elements/attributes.js
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, is_attachment_key } from './attachments.js';
import { clsx } from '../../../shared/attributes.js';

/**
Expand Down Expand Up @@ -245,8 +246,8 @@ export function set_custom_element_data(node, prop, value) {
/**
* Spreads attributes onto a DOM element, taking into account the currently set attributes
* @param {Element & ElementCSSInlineStyle} element
* @param {Record<string, any> | undefined} prev
* @param {Record<string, any>} next New attributes - this function mutates this object
* @param {Record<string | symbol, any> | undefined} prev
* @param {Record<string | symbol, any>} next New attributes - this function mutates this object
* @param {string} [css_hash]
* @param {boolean} [preserve_attribute_case]
* @param {boolean} [is_custom_element]
Expand Down Expand Up @@ -415,6 +416,12 @@ export function set_attributes(
}
}

for (let symbol of Object.getOwnPropertySymbols(next)) {
if (is_attachment_key(symbol)) {
attach(element, () => next[symbol]);
}
}

return current;
}

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, create_attachment_key, is_attachment_key } from './dom/elements/attachments.js';
export {
remove_input_defaults,
set_attribute,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<div {@attach (node) => {}} {@attach (node) => {}}></div>
Loading
Loading