Skip to content

feat: add support of handleEvent object listener #15856

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 5 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/rare-feet-hang.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'svelte': minor
---

feat: add support of handleEvent object as event listener
8 changes: 5 additions & 3 deletions packages/svelte/elements.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,11 @@ type Booleanish = boolean | 'true' | 'false';
// Event Handler Types
// ----------------------------------------------------------------------

type EventHandler<E extends Event = Event, T extends EventTarget = Element> = (
event: E & { currentTarget: EventTarget & T }
) => any;
type EventHandler<E extends Event = Event, T extends EventTarget = Element> =
| ((event: E & { currentTarget: EventTarget & T }) => any)
| {
handleEvent: (event: E & { currentTarget: EventTarget & T }) => any;
};

export type ClipboardEventHandler<T extends EventTarget> = EventHandler<ClipboardEvent, T>;
export type CompositionEventHandler<T extends EventTarget> = EventHandler<CompositionEvent, T>;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ export function build_event_handler(node, metadata, context) {
}

// wrap the handler in a function, so the expression is re-evaluated for each event
let call = b.call(b.member(handler, 'apply', false, true), b.this, b.id('$$args'));
let call = b.call('$.call_event_handler', handler, b.this, b.id('$$evt'), b.id('$$data'));

if (dev) {
const loc = locator(/** @type {number} */ (node.start));
Expand All @@ -165,15 +165,16 @@ export function build_event_handler(node, metadata, context) {
'$.apply',
b.thunk(handler),
b.this,
b.id('$$args'),
b.id('$$evt'),
b.id('$$data'),
b.id(context.state.analysis.name),
loc && b.array([b.literal(loc.line), b.literal(loc.column)]),
has_side_effects(node) && b.true,
remove_parens && b.true
);
}

return b.function(null, [b.rest(b.id('$$args'))], b.block([b.stmt(call)]));
return b.function(null, [b.id('$$evt'), b.rest(b.id('$$data'))], b.block([b.stmt(call)]));
}

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { DEV } from 'esm-env';
import { hydrating, set_hydrating } from '../hydration.js';
import { get_descriptors, get_prototype_of } from '../../../shared/utils.js';
import { create_event, delegate } from './events.js';
import { call_event_handler, create_event, delegate } from './events.js';
import { add_form_reset_listener, autofocus } from './misc.js';
import * as w from '../../warnings.js';
import { LOADING_ATTR_SYMBOL } from '#client/constants';
Expand Down Expand Up @@ -376,7 +376,7 @@ export function set_attributes(element, prev, next, css_hash, skip_warning = fal
* @param {Event} evt
*/
function handle(evt) {
current[key].call(this, evt);
call_event_handler(current[key], this, evt);
}

current[event_handle_key] = create_event(event_name, element, handle, opts);
Expand Down
50 changes: 36 additions & 14 deletions packages/svelte/src/internal/client/dom/elements/events.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import {
} from '../../runtime.js';
import { without_reactive_context } from './bindings/shared.js';

/** @typedef {((ev: Event, ...args: any) => void) | { handleEvent: (ev: Event, ...args: any) => void }} EventListenerWrapper */

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

Expand Down Expand Up @@ -45,10 +47,24 @@ export function replay_events(dom) {
}
}

/**
* @param {EventListenerWrapper | undefined} handler
* @param {EventTarget} current_target
* @param {Event} event
* @param {any[]} [data]
*/
export function call_event_handler(handler, current_target, event, data = []) {
if (typeof handler === 'function') {
handler.call(current_target, event, ...data);
} else {
handler?.handleEvent(event);
}
}

/**
* @param {string} event_name
* @param {EventTarget} dom
* @param {EventListener} [handler]
* @param {EventListenerOrEventListenerObject} [handler]
* @param {AddEventListenerOptions} [options]
*/
export function create_event(event_name, dom, handler, options = {}) {
Expand All @@ -61,8 +77,8 @@ export function create_event(event_name, dom, handler, options = {}) {
handle_event_propagation.call(dom, event);
}
if (!event.cancelBubble) {
return without_reactive_context(() => {
return handler?.call(this, event);
without_reactive_context(() => {
call_event_handler(handler, this, event);
});
}
}
Expand Down Expand Up @@ -93,7 +109,7 @@ export function create_event(event_name, dom, handler, options = {}) {
*
* @param {EventTarget} element
* @param {string} type
* @param {EventListener} handler
* @param {EventListenerOrEventListenerObject} handler
* @param {AddEventListenerOptions} [options]
*/
export function on(element, type, handler, options = {}) {
Expand All @@ -107,7 +123,7 @@ export function on(element, type, handler, options = {}) {
/**
* @param {string} event_name
* @param {Element} dom
* @param {EventListener} [handler]
* @param {EventListenerOrEventListenerObject} [handler]
* @param {boolean} [capture]
* @param {boolean} [passive]
* @returns {void}
Expand Down Expand Up @@ -245,9 +261,9 @@ export function handle_event_propagation(event) {
) {
if (is_array(delegated)) {
var [fn, ...data] = delegated;
fn.apply(current_target, [event, ...data]);
call_event_handler(fn, current_target, event, data);
} else {
delegated.call(current_target, event);
call_event_handler(delegated, current_target, event);
}
}
} catch (error) {
Expand Down Expand Up @@ -285,17 +301,19 @@ export function handle_event_propagation(event) {
/**
* In dev, warn if an event handler is not a function, as it means the
* user probably called the handler or forgot to add a `() =>`
* @param {() => (event: Event, ...args: any) => void} thunk
* @param {() => EventListenerWrapper} thunk
* @param {EventTarget} element
* @param {[Event, ...any]} args
* @param {Event} evt
* @param {any[]} data
* @param {any} component
* @param {[number, number]} [loc]
* @param {boolean} [remove_parens]
*/
export function apply(
thunk,
element,
args,
evt,
data,
component,
loc,
has_side_effects = false,
Expand All @@ -310,11 +328,15 @@ export function apply(
error = e;
}

if (typeof handler !== 'function' && (has_side_effects || handler != null || error)) {
if (
typeof handler !== 'function' &&
typeof handler?.handleEvent !== 'function' &&
(has_side_effects || handler != null || error)
) {
const filename = component?.[FILENAME];
const location = loc ? ` at ${filename}:${loc[0]}:${loc[1]}` : ` in ${filename}`;
const phase = args[0]?.eventPhase < Event.BUBBLING_PHASE ? 'capture' : '';
const event_name = args[0]?.type + phase;
const phase = evt?.eventPhase < Event.BUBBLING_PHASE ? 'capture' : '';
const event_name = evt?.type + phase;
const description = `\`${event_name}\` handler${location}`;
const suggestion = remove_parens ? 'remove the trailing `()`' : 'add a leading `() =>`';

Expand All @@ -324,5 +346,5 @@ export function apply(
throw error;
}
}
handler?.apply(element, args);
call_event_handler(handler, element, evt, data);
}
8 changes: 7 additions & 1 deletion packages/svelte/src/internal/client/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,13 @@ export {
STYLE
} from './dom/elements/attributes.js';
export { set_class } from './dom/elements/class.js';
export { apply, event, delegate, replay_events } from './dom/elements/events.js';
export {
apply,
call_event_handler,
event,
delegate,
replay_events
} from './dom/elements/events.js';
export { autofocus, remove_textarea_child } from './dom/elements/misc.js';
export { set_style } from './dom/elements/style.js';
export { animation, transition } from './dom/elements/transitions.js';
Expand Down
1 change: 1 addition & 0 deletions packages/svelte/src/internal/server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,7 @@ export function spread_attributes(attrs, css_hash, classes, styles, flags = 0) {
for (name in attrs) {
// omit functions, internal svelte properties and invalid attribute names
if (typeof attrs[name] === 'function') continue;
if (name[0] === 'o' && name[1] === 'n' && typeof attrs[name] === 'object') continue;
if (name[0] === '$' && name[1] === '$') continue; // faster than name.startsWith('$$')
if (INVALID_ATTR_NAME_CHAR_REGEX.test(name)) continue;

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

export default test({
mode: ['client'],

compileOptions: {
dev: true
},

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

b1.click();
flushSync();
assert.htmlEqual(target.innerHTML, '<button data-step="2">clicks: 2</button>');
assert.deepEqual(logs, []);
}
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<script>
let count = $state(0);

let onclick = $state({
handleEvent(ev) {
count += +ev.currentTarget.dataset.step;
}
});
</script>

<button data-step="2" {onclick}>
clicks: {count}
</button>
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { test } from '../../test';

export default test({
mode: ['client'],

compileOptions: {
dev: true
},

test({ assert, target, warnings, logs, errors }) {
const handler = (/** @type {any} */ e) => {
e.stopImmediatePropagation();
};

window.addEventListener('error', handler, true);

const [b1, b2, b3] = target.querySelectorAll('button');

b1.click();
b2.click();
b3.click();
assert.deepEqual(logs, []);
assert.deepEqual(warnings, [
'`click` handler at main.svelte:7:17 should be a function. Did you mean to add a leading `() =>`?',
'`click` handler at main.svelte:8:17 should be a function. Did you mean to add a leading `() =>`?',
'`click` handler at main.svelte:9:17 should be a function. Did you mean to add a leading `() =>`?'
]);
assert.include(errors[0], 'is not a function');
assert.include(errors[2], 'is not a function');
assert.include(errors[4], 'is not a function');

window.removeEventListener('error', handler, true);
}
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<script>
let empty = {};
let nully = { handleEvent: null };
let wrong = { handleEvent: "bad" };
</script>

<button onclick={empty}>click</button>
<button onclick={nully}>click</button>
<button onclick={wrong}>click</button>
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { test } from '../../test';

export default test({
test({ assert, target }) {
assert.htmlEqual(
target.innerHTML,
`<button>a</button><button>b</button><button>c</button><button>d</button>`
);
}
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<script>
const props = $props();
</script>

<button onclick={props.onclick}>c</button>
<button {...props}>d</button>
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<script>
import Child from "./child.svelte";

const onclick = {
handleEvent() {}
};
</script>

<button {onclick}>a</button>
<button {...{onclick}}>b</button>

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

export default test({
mode: ['client'],

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

buttons.forEach((b) => b.click());
flushSync();
buttons.forEach((b) => b.click());
flushSync();
buttons.forEach((b) => b.click());
flushSync();
assert.deepEqual(logs, [
'click',
true,
'click',
true,
'mutated',
true,
'mutated',
true,
'assigned',
true,
'assigned',
true
]);
assert.htmlEqual(target.innerHTML, '<button>a</button><button>b</button><button>next</button>');
}
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<script>
import { on } from 'svelte/events';

let onclick = $state.raw({
handleEvent(ev) {
console.log(ev.type, this === onclick);
}
});

function click2() {
console.log("mutated", this === onclick);
}

function click3() {
console.log("assigned", this === onclick);
}

let btn;
let step = 1;
$effect(() => {
return on(btn, 'click', () => {
switch (step) {
case 1: {
onclick.handleEvent = click2;
step = 2;
break;
}
case 2: {
onclick = { handleEvent: click3 };
}
}
});
});
</script>

<button {onclick}>a</button>
<button {...{onclick}}>b</button>
<button bind:this={btn}>next</button>