perf(runtime-dom): cache modifier wrapper functions

close #8882
This commit is contained in:
Evan You 2023-11-30 19:00:00 +08:00
parent 4936d2e11a
commit da4a4fb5e8
1 changed files with 50 additions and 38 deletions

View File

@ -32,14 +32,20 @@ const modifierGuards: Record<
/** /**
* @private * @private
*/ */
export const withModifiers = (fn: Function, modifiers: string[]) => { export const withModifiers = (
return (event: Event, ...args: unknown[]) => { fn: Function & { _withMods?: Function },
for (let i = 0; i < modifiers.length; i++) { modifiers: string[]
const guard = modifierGuards[modifiers[i]] ) => {
if (guard && guard(event, modifiers)) return return (
} fn._withMods ||
return fn(event, ...args) (fn._withMods = (event: Event, ...args: unknown[]) => {
} for (let i = 0; i < modifiers.length; i++) {
const guard = modifierGuards[modifiers[i]]
if (guard && guard(event, modifiers)) return
}
return fn(event, ...args)
})
)
} }
// Kept for 2.x compat. // Kept for 2.x compat.
@ -57,7 +63,10 @@ const keyNames: Record<string, string | string[]> = {
/** /**
* @private * @private
*/ */
export const withKeys = (fn: Function, modifiers: string[]) => { export const withKeys = (
fn: Function & { _withKeys?: Function },
modifiers: string[]
) => {
let globalKeyCodes: LegacyConfig['keyCodes'] let globalKeyCodes: LegacyConfig['keyCodes']
let instance: ComponentInternalInstance | null = null let instance: ComponentInternalInstance | null = null
if (__COMPAT__) { if (__COMPAT__) {
@ -77,40 +86,43 @@ export const withKeys = (fn: Function, modifiers: string[]) => {
} }
} }
return (event: KeyboardEvent) => { return (
if (!('key' in event)) { fn._withKeys ||
return (fn._withKeys = (event: KeyboardEvent) => {
} if (!('key' in event)) {
return
}
const eventKey = hyphenate(event.key) const eventKey = hyphenate(event.key)
if (modifiers.some(k => k === eventKey || keyNames[k] === eventKey)) { if (modifiers.some(k => k === eventKey || keyNames[k] === eventKey)) {
return fn(event)
}
if (__COMPAT__) {
const keyCode = String(event.keyCode)
if (
compatUtils.isCompatEnabled(
DeprecationTypes.V_ON_KEYCODE_MODIFIER,
instance
) &&
modifiers.some(mod => mod == keyCode)
) {
return fn(event) return fn(event)
} }
if (globalKeyCodes) {
for (const mod of modifiers) { if (__COMPAT__) {
const codes = globalKeyCodes[mod] const keyCode = String(event.keyCode)
if (codes) { if (
const matches = isArray(codes) compatUtils.isCompatEnabled(
? codes.some(code => String(code) === keyCode) DeprecationTypes.V_ON_KEYCODE_MODIFIER,
: String(codes) === keyCode instance
if (matches) { ) &&
return fn(event) modifiers.some(mod => mod == keyCode)
) {
return fn(event)
}
if (globalKeyCodes) {
for (const mod of modifiers) {
const codes = globalKeyCodes[mod]
if (codes) {
const matches = isArray(codes)
? codes.some(code => String(code) === keyCode)
: String(codes) === keyCode
if (matches) {
return fn(event)
}
} }
} }
} }
} }
} })
} )
} }