Skip to content

Adds event modifiers using | character #1641

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

Closed
wants to merge 4 commits into from
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
56 changes: 50 additions & 6 deletions src/compile/nodes/Element.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import validCalleeObjects from '../../utils/validCalleeObjects';
import reservedNames from '../../utils/reservedNames';
import fixAttributeCasing from '../../utils/fixAttributeCasing';
import { quoteNameIfNecessary, quotePropIfNecessary } from '../../utils/quoteIfNecessary';
import getEventModifiers from '../../utils/getEventModifiers';
import Compiler from '../Compiler';
import Node from './shared/Node';
import Block from '../dom/Block';
Expand All @@ -21,7 +22,45 @@ import mapChildren from './shared/mapChildren';
import { dimensions } from '../../utils/patterns';

// source: https://gist.github.com/ArjanSchouten/0b8574a6ad7f5065a5e7
const booleanAttributes = new Set('async autocomplete autofocus autoplay border challenge checked compact contenteditable controls default defer disabled formnovalidate frameborder hidden indeterminate ismap loop multiple muted nohref noresize noshade novalidate nowrap open readonly required reversed scoped scrolling seamless selected sortable spellcheck translate'.split(' '));
const booleanAttributes = new Set([
'async',
'autocomplete',
'autofocus',
'autoplay',
'border',
'challenge',
'checked',
'compact',
'contenteditable',
'controls',
'default',
'defer',
'disabled',
'formnovalidate',
'frameborder',
'hidden',
'indeterminate',
'ismap',
'loop',
'multiple',
'muted',
'nohref',
'noresize',
'noshade',
'novalidate',
'nowrap',
'open',
'readonly',
'required',
'reversed',
'scoped',
'scrolling',
'seamless',
'selected',
'sortable',
'spellcheck',
'translate'
]);

export default class Element extends Node {
type: 'Element';
Expand Down Expand Up @@ -612,22 +651,27 @@ export default class Element extends Node {

const target = handler.shouldHoist ? 'this' : this.var;

// split by | to remove stop, prevent, pass, etc.
const eventName = handler.name.split('|')[0];

// get a name for the event handler that is globally unique
// if hoisted, locally unique otherwise
// if hoisted, locally unique otherwise.
const handlerName = (handler.shouldHoist ? compiler : block).getUniqueName(
`${handler.name.replace(/[^a-zA-Z0-9_$]/g, '_')}_handler`
`${eventName.replace(/[^a-zA-Z0-9_$]/g, '_')}_handler`
);

const component = block.alias('component'); // can't use #component, might be hoisted

const { bodyModifiers, optionModifiers } = getEventModifiers(handler.name);

// create the handler body
const handlerBody = deindent`
${handler.shouldHoist && (
handler.usesComponent || handler.usesContext
? `const { ${[handler.usesComponent && 'component', handler.usesContext && 'ctx'].filter(Boolean).join(', ')} } = ${target}._svelte;`
: null
)}

${bodyModifiers}
${handler.snippet ?
handler.snippet :
`${component}.fire("${handler.name}", event);`}
Expand Down Expand Up @@ -659,11 +703,11 @@ export default class Element extends Node {
}

block.builders.hydrate.addLine(
`@addListener(${this.var}, "${handler.name}", ${handlerName});`
`@addListener(${this.var}, "${eventName}", ${handlerName}, ${JSON.stringify(optionModifiers)});`
);

block.builders.destroy.addLine(
`@removeListener(${this.var}, "${handler.name}", ${handlerName});`
`@removeListener(${this.var}, "${eventName}", ${handlerName}, ${JSON.stringify(optionModifiers)});`
);
}
});
Expand Down
8 changes: 4 additions & 4 deletions src/shared/dom.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,12 +73,12 @@ export function createComment() {
return document.createComment('');
}

export function addListener(node, event, handler) {
node.addEventListener(event, handler, false);
export function addListener(node, event, handler, options) {
node.addEventListener(event, handler, options);
}

export function removeListener(node, event, handler) {
node.removeEventListener(event, handler, false);
export function removeListener(node, event, handler, options) {
node.removeEventListener(event, handler, options);
}

export function setAttribute(node, attribute, value) {
Expand Down
36 changes: 36 additions & 0 deletions src/utils/getEventModifiers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import EventHandler from '../compile/nodes/EventHandler';
import deindent from '../utils/deindent';

export default function getEventModifiers(handlerName: String) {
// Ignore first element because it's the event name, i.e. click
let modifiers = handlerName.split('|').slice(1);

let eventModifiers = modifiers.reduce((acc, m) => {
if (m === 'stopPropagation')
acc.bodyModifiers += 'event.stopPropagation();\n';
else if (m === 'preventDefault')
acc.bodyModifiers += 'event.preventDefault();\n';
else if (m === 'capture')
acc.optionModifiers[m] = true;
else if (m === 'once')
acc.optionModifiers[m] = true;
else if (m === 'passive')
acc.optionModifiers[m] = true;

return acc;
}, {
bodyModifiers: '',
optionModifiers: {
capture: false,
once: false,
passive: false,
}
});

if (eventModifiers.bodyModifiers !== '')
eventModifiers.bodyModifiers = deindent`
${eventModifiers.bodyModifiers}
`;

return eventModifiers;
}
13 changes: 13 additions & 0 deletions src/validate/html/validateEventHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import { Node } from '../../interfaces';

const validBuiltins = new Set(['set', 'fire', 'destroy']);

const validModifiers = new Set(['stopPropagation', 'preventDefault', 'capture', 'once', 'passive']);

export default function validateEventHandlerCallee(
validator: Validator,
attribute: Node,
Expand All @@ -22,6 +24,17 @@ export default function validateEventHandlerCallee(
});
}

const modifiers = attribute.name.split('|').slice(1);
if (
modifiers.length > 0 &&
modifiers.filter(m => !validModifiers.has(m)).length > 0
) {
validator.error(attribute, {
code: 'invalid-event-modifiers',
message: `Valid event modifiers are ${[...validModifiers].join(', ')}.`
});
}

const { name } = flattenReference(callee);

if (validCalleeObjects.has(name) || name === 'options') return;
Expand Down
8 changes: 4 additions & 4 deletions test/js/samples/input-files/expected-bundle.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,12 @@ function createElement(name) {
return document.createElement(name);
}

function addListener(node, event, handler) {
node.addEventListener(event, handler, false);
function addListener(node, event, handler, options) {
node.addEventListener(event, handler, options);
}

function removeListener(node, event, handler) {
node.removeEventListener(event, handler, false);
function removeListener(node, event, handler, options) {
node.removeEventListener(event, handler, options);
}

function setAttribute(node, attribute, value) {
Expand Down
8 changes: 4 additions & 4 deletions test/js/samples/input-range/expected-bundle.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,12 @@ function createElement(name) {
return document.createElement(name);
}

function addListener(node, event, handler) {
node.addEventListener(event, handler, false);
function addListener(node, event, handler, options) {
node.addEventListener(event, handler, options);
}

function removeListener(node, event, handler) {
node.removeEventListener(event, handler, false);
function removeListener(node, event, handler, options) {
node.removeEventListener(event, handler, options);
}

function setAttribute(node, attribute, value) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,12 @@ function createElement(name) {
return document.createElement(name);
}

function addListener(node, event, handler) {
node.addEventListener(event, handler, false);
function addListener(node, event, handler, options) {
node.addEventListener(event, handler, options);
}

function removeListener(node, event, handler) {
node.removeEventListener(event, handler, false);
function removeListener(node, event, handler, options) {
node.removeEventListener(event, handler, options);
}

function setAttribute(node, attribute, value) {
Expand Down
8 changes: 4 additions & 4 deletions test/js/samples/media-bindings/expected-bundle.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,12 @@ function createElement(name) {
return document.createElement(name);
}

function addListener(node, event, handler) {
node.addEventListener(event, handler, false);
function addListener(node, event, handler, options) {
node.addEventListener(event, handler, options);
}

function removeListener(node, event, handler) {
node.removeEventListener(event, handler, false);
function removeListener(node, event, handler, options) {
node.removeEventListener(event, handler, options);
}

function timeRangesToArray(ranges) {
Expand Down
15 changes: 15 additions & 0 deletions test/validator/samples/event-modifiers-invalid/errors.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
[{
"message": "Valid event modifiers are stopPropagation, preventDefault, capture, once, passive.",
"code": "invalid-event-modifiers",
"start": {
"line": 1,
"column": 8,
"character": 8
},
"end": {
"line": 1,
"column": 36,
"character": 36
},
"pos": 8
}]
1 change: 1 addition & 0 deletions test/validator/samples/event-modifiers-invalid/input.html
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<button on:click|stop|bad="doThat()"></button>