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 17 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
3 changes: 3 additions & 0 deletions packages/svelte/elements.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -859,6 +859,9 @@ export interface HTMLAttributes<T extends EventTarget> extends AriaAttributes, D

// allow any data- attribute
[key: `data-${string}`]: any;

// allow any attachment
[key: symbol]: (node: T) => void | (() => void);
}

export type HTMLAttributeAnchorTarget = '_self' | '_blank' | '_parent' | '_top' | (string & {});
Expand Down
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 attachment = {
type: 'AttachTag',
start,
end: parser.index,
expression
};

return attachment;
}

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

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 @@ -74,7 +75,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 All @@ -91,15 +93,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 All @@ -113,6 +110,10 @@ export function visit_component(node, context) {
if (attribute.type === 'BindDirective' && attribute.name !== 'this') {
context.state.analysis.uses_component_bindings = true;
}

if (attribute.type === 'AttachTag') {
disallow_unparenthesized_sequences(attribute.expression, context.state.analysis.source);
}
}

// If the component has a slot attribute — `<Foo slot="whatever" .../>` —
Expand Down Expand Up @@ -158,3 +159,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 @@ -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('Symbol'),
/** @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
11 changes: 11 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,11 @@
import { effect } from '../../reactivity/effects.js';

/**
* @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
});
}
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 @@ -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,10 @@ export function set_attributes(
}
}

for (let symbol of Object.getOwnPropertySymbols(next)) {
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 } from './dom/elements/attachments.js';
export {
remove_input_defaults,
set_attribute,
Expand Down
6 changes: 6 additions & 0 deletions packages/svelte/src/internal/client/reactivity/props.js
Original file line number Diff line number Diff line change
Expand Up @@ -231,9 +231,15 @@ const spread_props_handler = {

for (let p of target.props) {
if (is_function(p)) p = p();
if (!p) continue;

for (const key in p) {
if (!keys.includes(key)) keys.push(key);
}

for (const key of Object.getOwnPropertySymbols(p)) {
if (!keys.includes(key)) keys.push(key);
}
}

return keys;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<div {@attach (node) => {}} {@attach (node) => {}}></div>
Loading
Loading