Skip to content
Closed
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/small-chefs-sing.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'svelte': patch
---

fix: remove event listeners on hydration error
10 changes: 9 additions & 1 deletion packages/svelte/src/internal/client/dom/elements/events.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
import { teardown } from '../../reactivity/effects.js';
import { all_registered_events, root_event_handles } from '../../render.js';
import { push_init_error_handler } from '../../render.js';
import { define_property, is_array } from '../../utils.js';
import { hydrating } from '../hydration.js';
import { queue_micro_task } from '../task.js';

/** @type {Set<string>} */
export const all_registered_events = new Set();

/** @type {Set<(events: Array<string>) => void>} */
export const root_event_handles = new Set();

/**
* SSR adds onload and onerror attributes to catch those events before the hydration.
* This function detects those cases, removes the attributes and replays the events.
Expand Down Expand Up @@ -125,6 +131,8 @@ export function event(event_name, dom, handler, capture, passive) {
teardown(() => {
dom.removeEventListener(event_name, target_handler, options);
});

push_init_error_handler(() => dom.removeEventListener(event_name, target_handler, options));
}
}

Expand Down
74 changes: 54 additions & 20 deletions packages/svelte/src/internal/client/render.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,18 +16,17 @@ import {
set_hydrating
} from './dom/hydration.js';
import { array_from } from './utils.js';
import { handle_event_propagation } from './dom/elements/events.js';
import {
all_registered_events,
handle_event_propagation,
root_event_handles
} from './dom/elements/events.js';
import { reset_head_anchor } from './dom/blocks/svelte-head.js';
import * as w from './warnings.js';
import * as e from './errors.js';
import { validate_component } from '../shared/validate.js';
import { assign_nodes } from './dom/template.js';

/** @type {Set<string>} */
export const all_registered_events = new Set();

/** @type {Set<(events: Array<string>) => void>} */
export const root_event_handles = new Set();
import { run } from '../shared/utils.js';

/**
* This is normally true — block effects should run their intro transitions —
Expand All @@ -41,6 +40,21 @@ export function set_should_intro(value) {
should_intro = value;
}

/** @type {Array<() => void>} */
let on_init_error_handlers = [];
let mounting = false;

/**
* Push a handler to be called when an error occurs during initialization.
* If no initialization is happening, this is a noop.
* @param {() => void} handler
*/
export function push_init_error_handler(handler) {
if (mounting || hydrating) {
on_init_error_handlers.push(handler);
}
}

/**
* @param {Element} text
* @param {string} value
Expand Down Expand Up @@ -86,8 +100,15 @@ export function mount(component, options) {
}

const anchor = options.anchor ?? options.target.appendChild(empty());
// Don't flush previous effects to ensure order of outer effects stays consistent
return flush_sync(() => _mount(component, { ...options, anchor }), false);
let prev_mounting = mounting;
try {
mounting = true;
// Don't flush previous effects to ensure order of outer effects stays consistent
const result = flush_sync(() => _mount(component, { ...options, anchor }), false);
return result;
} finally {
mounting = prev_mounting;
}
}

/**
Expand Down Expand Up @@ -159,9 +180,6 @@ export function hydrate(component, options) {
}, false);
} catch (error) {
if (error === HYDRATION_ERROR) {
// TODO it's possible for event listeners to have been added and
// not removed, e.g. with `<svelte:window>` or `<svelte:document>`

if (options.recover === false) {
e.hydration_failed();
}
Expand Down Expand Up @@ -223,9 +241,19 @@ function _mount(Component, { target, anchor, props = {}, events, context, intro
event_handle(array_from(all_registered_events));
root_event_handles.add(event_handle);

const remove_event_handles = () => {
for (const event_name of registered_events) {
target.removeEventListener(event_name, handle_event_propagation);
document.removeEventListener(event_name, handle_event_propagation);
}
root_event_handles.delete(event_handle);
};

/** @type {Exports} */
// @ts-expect-error will be defined because the render effect runs synchronously
let component = undefined;
let prev_init_error_handlers = on_init_error_handlers;
on_init_error_handlers = [];

const unmount = effect_root(() => {
branch(() => {
Expand All @@ -245,8 +273,19 @@ function _mount(Component, { target, anchor, props = {}, events, context, intro
}

should_intro = intro;
// @ts-expect-error the public typings are not what the actual function looks like
component = Component(anchor, props) || {};

try {
// @ts-expect-error the public typings are not what the actual function looks like
component = Component(anchor, props) || {};
} catch (e) {
remove_event_handles();
on_init_error_handlers.forEach(run);

throw e;
} finally {
on_init_error_handlers = prev_init_error_handlers;
}

should_intro = true;

if (hydrating) {
Expand All @@ -261,12 +300,7 @@ function _mount(Component, { target, anchor, props = {}, events, context, intro
});

return () => {
for (const event_name of registered_events) {
target.removeEventListener(event_name, handle_event_propagation);
document.removeEventListener(event_name, handle_event_propagation);
}

root_event_handles.delete(event_handle);
remove_event_handles();
mounted_components.delete(component);
};
});
Expand Down
5 changes: 4 additions & 1 deletion packages/svelte/tests/runtime-legacy/shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,10 @@ export function runtime_suite(runes: boolean) {
if (config.skip_mode?.includes('hydrate')) return true;
}

if (variant === 'dom' && config.skip_mode?.includes('client')) {
if (
variant === 'dom' &&
(config.skip_mode?.includes('client') || (config.mode && !config.mode.includes('client')))
) {
return 'no-test';
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { flushSync } from 'svelte';
import { test } from '../../test';

export default test({
html: '<p><p>invalid</p></p>',
mode: ['hydrate'],
recover: true,
test({ assert, target, logs }) {
target.click();
flushSync();
assert.deepEqual(logs, ['body', 'document', 'window']);
}
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<svelte:window onclick={() => console.log('window')} />
<svelte:document onclick={() => console.log('document')} />
<svelte:body onclick={() => console.log('body')} />

<p>{@html '<p>invalid</p>'}</p>
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
<script>
throw new Error('boom');
</script>
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<script>
import Inner from './Inner.svelte';
</script>

<svelte:window onclick={() => console.log('window')} />
<svelte:document onclick={() => console.log('document')} />
<svelte:body onclick={() => console.log('body')} />

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

export default test({
mode: ['client'],
test({ assert, target, logs }) {
target.click();
flushSync();
assert.deepEqual(logs, []);
}
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<script>
import { mount, onMount } from 'svelte';
import Outer from './Outer.svelte';

let el;

onMount(() => {
try {
mount(Outer, { target: el });
} catch {}
});
</script>

<div bind:this={el}></div>