Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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/calm-locations-wait.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'svelte': patch
---

fix: don't let elements without dev locations shift the `__svelte_meta` locations of following elements on the client
Original file line number Diff line number Diff line change
Expand Up @@ -31,27 +31,31 @@ function build_locations(nodes) {
}

/**
* In dev, returns a statement that assigns source locations to the elements of the current template.
* It must run after the template's content has been created, so that during hydration the elements
* belonging to child components (which already have their own locations) can be skipped
* In dev, returns the statements that assign source locations to the elements of the current template:
* - `create` must run right after the template has been created. When rendering on the client, the
* template only contains its own elements at that point, so they can be matched against the locations
* - `hydrate` must run after the template's content has been created. During hydration, the elements
* belonging to child components, snippets and `{@html ...}` tags aren't delimited by hydration
* markers, so we wait until they have their own locations and skip them
* @param {ComponentClientTransformState} state
* @param {Expression} node
* @returns {Statement | undefined}
* @returns {{ create: Statement, hydrate: Statement } | null}
*/
export function build_locations_statement(state, node) {
if (!dev) return;
export function build_locations_statements(state, node) {
if (!dev) return null;

const locations = build_locations(state.template.nodes);
if (locations.elements.length === 0) return;

return b.stmt(
b.call(
'$.add_locations',
node,
b.member(b.id(state.analysis.name), '$.FILENAME', true),
locations
)
);
if (locations.elements.length === 0) return null;

const id = state.scope.root.unique('locations');
state.hoisted.push(b.var(id, locations));

const filename = b.member(b.id(state.analysis.name), '$.FILENAME', true);

return {
create: b.stmt(b.call('$.add_locations', node, filename, id)),
hydrate: b.stmt(b.call('$.add_hydration_locations', node, filename, id))
};
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import * as b from '#compiler/builders';
import { TEMPLATE_FRAGMENT, TEMPLATE_USE_IMPORT_NODE } from '../../../../../constants.js';
import { clean_nodes, infer_namespace } from '../../utils.js';
import { build_locations_statement, transform_template } from '../transform-template/index.js';
import { build_locations_statements, transform_template } from '../transform-template/index.js';
import { Template } from '../transform-template/template.js';
import { process_children } from './shared/fragment.js';
import { build_render_statement, Memoizer } from './shared/utils.js';
Expand Down Expand Up @@ -59,8 +59,8 @@ export function Fragment(node, context) {
/** @type {Statement | undefined} */
let close = undefined;

/** @type {Statement | undefined} */
let locations = undefined;
/** @type {{ create: Statement, hydrate: Statement } | null} */
let locations = null;

/** @type {ComponentClientTransformState} */
const state = {
Expand Down Expand Up @@ -100,8 +100,8 @@ export function Fragment(node, context) {

const template_name = transform_template(state, 'root', flags);

state.init.unshift(b.var(id, b.call(template_name)));
locations = build_locations_statement(state, id);
locations = build_locations_statements(state, id);
state.init.unshift(b.var(id, b.call(template_name)), ...(locations ? [locations.create] : []));
close = b.stmt(b.call('$.append', b.id('$$anchor'), id));
} else if (is_single_child_not_needing_template) {
context.visit(trimmed[0], state);
Expand Down Expand Up @@ -147,9 +147,12 @@ export function Fragment(node, context) {

const template_name = transform_template(state, 'root', flags);

state.init.unshift(b.var(id, b.call(template_name)));
locations = build_locations_statements(state, id);
state.init.unshift(
b.var(id, b.call(template_name)),
...(locations ? [locations.create] : [])
);

locations = build_locations_statement(state, id);
close = b.stmt(b.call('$.append', b.id('$$anchor'), id));
}
}
Expand All @@ -173,8 +176,8 @@ export function Fragment(node, context) {

body.push(...state.after_update);

if (locations !== undefined) {
body.push(locations);
if (locations !== null) {
body.push(locations.hydrate);
}

if (close !== undefined) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ import { process_children, is_static_element } from './shared/fragment.js';
import { build_render_statement, build_template_chunk, Memoizer } from './shared/utils.js';
import { visit_event_attribute } from './shared/events.js';
import { Template } from '../transform-template/template.js';
import { build_locations_statement, transform_template } from '../transform-template/index.js';
import { build_locations_statements, transform_template } from '../transform-template/index.js';
import { TEMPLATE_FRAGMENT } from '../../../../../constants.js';

/**
Expand Down Expand Up @@ -404,17 +404,18 @@ export function RegularElement(node, context) {

// Transform the template to $.from_html(...) and hoist it (deduplicating identical templates)
const template_name = transform_template(select_state, `${name}_content`, TEMPLATE_FRAGMENT);
const locations = build_locations_statement(select_state, fragment_id);
const locations = build_locations_statements(select_state, fragment_id);

// Build the rich content function body
// The anchor is the child of the element (a hydration marker during hydration)
const body = b.block([
b.var(anchor_id, b.call('$.child', element_node)),
b.var(fragment_id, b.call(template_name)),
...(locations ? [locations.create] : []),
...select_state.init,
...(select_state.update.length > 0 ? [build_render_statement(select_state)] : []),
...select_state.after_update,
...(locations ? [locations] : []),
...(locations ? [locations.hydrate] : []),
b.stmt(b.call('$.append', anchor_id, fragment_id))
]);

Expand Down
25 changes: 21 additions & 4 deletions packages/svelte/src/internal/client/dev/elements.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,32 @@ import { hydrating } from '../dom/hydration.js';
import { dev_stack } from '../context.js';

/**
* Called once the template's content has been created. At that point the elements belonging
* to child components, snippets and `{@html ...}` tags (which during hydration aren't
* delimited by hydration markers) already have their own locations, so we skip them
* Called right after a template has been created. When rendering on the client, the template only
* contains its own elements at that point (unlike at the end of the template's body, by which time
* blocks, child components etc may have inserted elements that don't have locations of their own)
* @param {DocumentFragment | Element} dom
* @param {string} filename
* @param {SourceLocation[]} locations
*/
export function add_locations(dom, filename, locations) {
var node = hydrating ? dom : dom.nodeType === DOCUMENT_FRAGMENT_NODE ? dom.firstChild : dom;
if (hydrating) return;
assign_locations(
dom.nodeType === DOCUMENT_FRAGMENT_NODE ? dom.firstChild : dom,
filename,
locations
);
}

/**
* Called once the template's content has been created. During hydration, the elements belonging
* to child components, snippets and `{@html ...}` tags aren't delimited by hydration markers, but
* at this point they already have their own locations, so we skip them
* @param {Node} node
* @param {string} filename
* @param {SourceLocation[]} locations
*/
export function add_hydration_locations(node, filename, locations) {
if (!hydrating) return;
assign_locations(node, filename, locations);
}

Expand Down
2 changes: 1 addition & 1 deletion packages/svelte/src/internal/client/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ export { FILENAME, HMR, NAMESPACE_SVG } from '../../constants.js';
export { push, pop, add_svelte_meta } from './context.js';
export { assign, assign_async } from './dev/assign.js';
export { cleanup_styles } from './dev/css.js';
export { add_locations } from './dev/elements.js';
export { add_locations, add_hydration_locations } from './dev/elements.js';
export { hmr } from './dev/hmr.js';
export { create_ownership_validator } from './dev/ownership.js';
export { check_target, legacy_api } from './dev/legacy.js';
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
// Stands in for a component that wasn't compiled with `dev: true`
// (or isn't a Svelte component at all), so its elements have no `__svelte_meta`
/** @param {Comment} anchor */
export default function Foreign(anchor) {
anchor.before(document.createElement('section'));
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { test } from '../../test';

export default test({
// the stand-in component can't hydrate
mode: ['client'],
compileOptions: {
dev: true
},

test({ target, assert }) {
const [output] = target.querySelectorAll('output');
assert.htmlEqual(output.innerHTML, '<section></section><p>after</p>');

const [section] = output.querySelectorAll('section');
const [p] = output.querySelectorAll('p');

// The foreign component's element must not take the location of the following element
// @ts-expect-error
assert.equal(section.__svelte_meta, null);
// @ts-expect-error
assert.deepEqual(p.__svelte_meta?.loc, { file: 'main.svelte', line: 7, column: 1 });
}
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<script lang="ts">
import Foreign from './Foreign.js';
</script>

<output>
<Foreign />
<p>after</p>
</output>
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { tick } from 'svelte';
import { test } from '../../test';

export default test({
// the promise never resolves, so there is nothing to server-render
mode: ['client'],
skip_no_async: true,
compileOptions: {
dev: true
},

async test({ target, assert }) {
await tick();

const [output] = target.querySelectorAll('output');
assert.htmlEqual(output.innerHTML, '<section>loading</section><p>after</p>');

const [p] = output.querySelectorAll('p');

// The raw `pending` snippet's root has no location of its own,
// so it must not take the location of the following element
// @ts-expect-error
assert.deepEqual(p.__svelte_meta?.loc, { file: 'main.svelte', line: 13, column: 1 });
}
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<script lang="ts">
import { createRawSnippet } from 'svelte';

const pending = createRawSnippet(() => ({
render: () => '<section>loading</section>'
}));
</script>

<output>
<svelte:boundary {pending}>
{await new Promise(() => {})}
</svelte:boundary>
<p>after</p>
</output>
Loading