Skip to content

Commit

Permalink
feat: migrate <svelte:element this="div"> (#11659)
Browse files Browse the repository at this point in the history
  • Loading branch information
Rich-Harris committed May 16, 2024
1 parent 110a5a8 commit c29b746
Show file tree
Hide file tree
Showing 6 changed files with 45 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/thin-years-rhyme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'svelte': patch
---

feat: migrate `<svelte:element this="div">`
20 changes: 20 additions & 0 deletions packages/svelte/src/compiler/migrate/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -427,6 +427,26 @@ const template = {
next();
},
SvelteElement(node, { state, next }) {
if (node.tag.type === 'Literal') {
let is_static = true;

let a = /** @type {number} */ (node.tag.start);
let b = /** @type {number} */ (node.tag.end);
let quote_mark = state.str.original[a - 1];

while (state.str.original[--a] !== '=') {
if (state.str.original[a] === '{') {
is_static = false;
break;
}
}

if (is_static && state.str.original[b] === quote_mark) {
state.str.prependLeft(a + 1, '{');
state.str.appendRight(/** @type {number} */ (node.tag.end) + 1, '}');
}
}

handle_events(node, state);
next();
},
Expand Down
8 changes: 7 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 @@ -280,7 +280,13 @@ export default function tag(parser) {
// TODO in 6.0, error
element.tag =
chunk.type === 'Text'
? { type: 'Literal', value: chunk.data, raw: `'${chunk.raw}'` }
? {
type: 'Literal',
value: chunk.data,
raw: `'${chunk.raw}'`,
start: chunk.start,
end: chunk.end
}
: chunk.expression;
} else {
element.tag = chunk.expression;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<svelte:element this="div" />
<svelte:element this='div' />
<svelte:element this={"div"} />

<!-- we don't try to fix this bug, we just leave it as-is -->
<svelte:element this="h{n}" />
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<svelte:element this={"div"} />
<svelte:element this={'div'} />
<svelte:element this={"div"} />

<!-- we don't try to fix this bug, we just leave it as-is -->
<svelte:element this="h{n}" />
2 changes: 1 addition & 1 deletion packages/svelte/tests/migrate/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ const { test, run } = suite<ParserTest>(async (config, cwd) => {
fs.writeFileSync(`${cwd}/_actual.svelte`, actual);

const expected = try_read_file(`${cwd}/output.svelte`);
assert.deepEqual(actual, expected);
assert.deepEqual(actual.trim(), expected?.trim());
}
});

Expand Down

0 comments on commit c29b746

Please sign in to comment.