Skip to content

feat: support using, link top-level using declarations in components to lifecycle #16192

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

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
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/dull-cheetahs-watch.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'svelte': patch
---

fix: support `using` keyword
5 changes: 5 additions & 0 deletions .changeset/nasty-hotels-clap.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'svelte': minor
---

feat: link top-level `using` declarations in components to lifecycle
4 changes: 2 additions & 2 deletions packages/svelte/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -164,9 +164,9 @@
"dependencies": {
"@ampproject/remapping": "^2.3.0",
"@jridgewell/sourcemap-codec": "^1.5.0",
"@types/estree": "^1.0.5",
"acorn": "^8.12.1",
"@sveltejs/acorn-typescript": "^1.0.5",
"@types/estree": "^1.0.5",
"acorn": "^8.15.0",
"aria-query": "^5.3.1",
"axobject-query": "^4.1.0",
"clsx": "^2.1.1",
Expand Down
4 changes: 2 additions & 2 deletions packages/svelte/src/compiler/phases/1-parse/acorn.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export function parse(source, typescript, is_script) {
ast = parser.parse(source, {
onComment,
sourceType: 'module',
ecmaVersion: 16,
ecmaVersion: 'latest',
locations: true
});
} finally {
Expand Down Expand Up @@ -64,7 +64,7 @@ export function parse_expression_at(source, typescript, index) {
const ast = parser.parseExpressionAt(source, index, {
onComment,
sourceType: 'module',
ecmaVersion: 16,
ecmaVersion: 'latest',
locations: true
});

Expand Down
3 changes: 2 additions & 1 deletion packages/svelte/src/compiler/phases/2-analyze/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -472,7 +472,8 @@ export function analyze_component(root, source, options) {
source,
undefined_exports: new Map(),
snippet_renderers: new Map(),
snippets: new Set()
snippets: new Set(),
disposable: []
};

if (!runes) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -350,7 +350,7 @@ export function client_component(analysis, options) {
const push_args = [b.id('$$props'), b.literal(analysis.runes)];
if (dev) push_args.push(b.id(analysis.name));

const component_block = b.block([
let component_block = b.block([
...store_setup,
...legacy_reactive_declarations,
...group_binding_declarations,
Expand Down Expand Up @@ -491,6 +491,16 @@ export function client_component(analysis, options) {

body = [...imports, ...state.module_level_snippets, ...body];

if (analysis.disposable.length > 0) {
component_block = b.block([
b.declaration(
'var',
analysis.disposable.map((id) => b.declarator(id))
),
b.try(component_block.body, null, [b.stmt(b.call('$.dispose', ...analysis.disposable))])
]);
}

const component = b.function_declaration(
b.id(analysis.name),
should_inject_props ? [b.id('$$anchor'), b.id('$$props')] : [b.id('$$anchor')],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import { get_value } from './shared/declarations.js';
*/
export function VariableDeclaration(node, context) {
/** @type {VariableDeclarator[]} */
const declarations = [];
let declarations = [];

if (context.state.analysis.runes) {
for (const declarator of node.declarations) {
Expand Down Expand Up @@ -343,8 +343,27 @@ export function VariableDeclaration(node, context) {
return b.empty;
}

let kind = node.kind;

// @ts-expect-error
if (kind === 'using' && context.state.is_instance && context.path.length === 1) {
context.state.analysis.disposable.push(
...node.declarations.map((declarator) => /** @type {Identifier} */ (declarator.id))
);

const assignments = declarations.map((declarator) => {
let init = /** @type {Expression} */ (declarator.init);
if (dev) init = b.call('$.disposable', init);

return b.assignment('=', declarator.id, init);
});

return assignments.length === 1 ? assignments[0] : b.sequence(assignments);
}

return {
...node,
kind,
declarations
};
}
Expand Down
4 changes: 4 additions & 0 deletions packages/svelte/src/compiler/phases/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,10 @@ export interface ComponentAnalysis extends Analysis {
* Every snippet that is declared locally
*/
snippets: Set<AST.SnippetBlock>;
/**
* An array of any `using` declarations
*/
disposable: Identifier[];
}

declare module 'estree' {
Expand Down
33 changes: 32 additions & 1 deletion packages/svelte/src/compiler/utils/builders.js
Original file line number Diff line number Diff line change
Expand Up @@ -635,6 +635,35 @@ export function throw_error(str) {
};
}

/**
* @param {ESTree.Statement[]} body
* @param {ESTree.CatchClause | null} handler
* @param {ESTree.Statement[] | null} finalizer
* @returns {ESTree.TryStatement}
*/
function try_builder(body, handler, finalizer) {
return {
type: 'TryStatement',
block: block(body),
handler,
finalizer: finalizer && block(finalizer)
};
}

/**
*
* @param {ESTree.Pattern | null} param
* @param {ESTree.Statement[]} body
* @returns {ESTree.CatchClause}
*/
function catch_clause(param, body) {
return {
type: 'CatchClause',
param,
body: block(body)
};
}

export {
await_builder as await,
let_builder as let,
Expand All @@ -648,7 +677,9 @@ export {
if_builder as if,
this_instance as this,
null_instance as null,
debugger_builder as debugger
debugger_builder as debugger,
try_builder as try,
catch_clause as catch
};

/**
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 @@ -118,6 +118,7 @@ export {
update_pre_prop,
update_prop
} from './reactivity/props.js';
export { dispose, disposable } from './resource-management/index.js';
export {
invalidate_store,
store_mutate,
Expand Down
28 changes: 28 additions & 0 deletions packages/svelte/src/internal/client/resource-management/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { teardown } from '../reactivity/effects.js';

/**
* @param {...any} disposables
*/
export function dispose(...disposables) {
teardown(() => {
for (const disposable of disposables) {
// @ts-ignore Symbol.dispose may or may not exist as far as TypeScript is concerned
disposable?.[Symbol.dispose]();
}
});
}

/**
* In dev, check that a value used with `using` is in fact disposable. We need this
* because we're replacing `using foo = ...` with `const foo = ...` if the
* declaration is at the top level of a component
* @param {any} value
*/
export function disposable(value) {
// @ts-ignore Symbol.dispose may or may not exist as far as TypeScript is concerned
if (value != null && !value[Symbol.dispose]) {
throw new TypeError('Symbol(Symbol.dispose) is not a function');
}

return value;
}
Original file line number Diff line number Diff line change
Expand Up @@ -259,7 +259,8 @@
"kind": "let"
},
"specifiers": [],
"source": null
"source": null,
"attributes": []
}
],
"sourceType": "module"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,8 @@
"kind": "const"
},
"specifiers": [],
"source": null
"source": null,
"attributes": []
}
],
"sourceType": "module"
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<script>
let { message } = $props();
using x = {
message,
[Symbol.dispose]() {
console.log(`disposing ${message}`);
}
}
</script>

<p>{x.message}</p>
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { flushSync } from 'svelte';
import { test } from '../../test';

export default test({
// TODO unskip this for applicable node versions, once supported
skip: true,

html: `<button>toggle</button><p>hello</p>`,

test({ assert, target, logs }) {
const [button] = target.querySelectorAll('button');

flushSync(() => button.click());
assert.htmlEqual(target.innerHTML, `<button>toggle</button>`);

assert.deepEqual(logs, ['disposing hello']);
}
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<script>
import Child from './Child.svelte';
let message = $state('hello');
</script>

<button onclick={() => message = message ? null : 'hello'}>
toggle
</button>

{#if message}
<Child {message} />
{/if}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { test } from '../../test';

export default test({
compileOptions: {
dev: true
}
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import 'svelte/internal/disclose-version';

Using_top_level[$.FILENAME] = 'packages/svelte/tests/snapshot/samples/using-top-level/index.svelte';

import * as $ from 'svelte/internal/client';

var root = $.add_locations($.from_html(`<p> </p>`), Using_top_level[$.FILENAME], [[12, 0]]);

export default function Using_top_level($$anchor, $$props) {
$.check_target(new.target);

var x;

try {
$.push($$props, true, Using_top_level);

x = $.disposable({
message: $$props.message,
[Symbol.dispose]() {
console.log(...$.log_if_contains_state('log', `disposing ${$$props.message}`));
}
})

var p = root();
var text = $.child(p, true);

$.reset(p);
$.template_effect(() => $.set_text(text, x.message));
$.append($$anchor, p);
return $.pop({ ...$.legacy_api() });
} finally {
$.dispose(x);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
Using_top_level[$.FILENAME] = 'packages/svelte/tests/snapshot/samples/using-top-level/index.svelte';

import * as $ from 'svelte/internal/server';

function Using_top_level($$payload, $$props) {
$.push(Using_top_level);

let { message } = $$props;

using x = {
message,
[Symbol.dispose]() {
console.log(`disposing ${message}`);
}
};

$$payload.out += `<p>`;
$.push_element($$payload, 'p', 12, 0);
$$payload.out += `${$.escape(x.message)}</p>`;
$.pop_element();
$.pop();
}

Using_top_level.render = function () {
throw new Error('Component.render(...) is no longer valid in Svelte 5. See https://svelte.dev/docs/svelte/v5-migration-guide#Components-are-no-longer-classes for more information');
};

export default Using_top_level;
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<script>
let { message } = $props();
using x = {
message,
[Symbol.dispose]() {
console.log(`disposing ${message}`);
}
}
</script>

<p>{x.message}</p>
Loading