From fb5fcdaff9a7b35671b09e52f1f4ad76c354ee72 Mon Sep 17 00:00:00 2001 From: Eduardo San Martin Morote Date: Thu, 29 Jun 2023 13:28:30 +0200 Subject: [PATCH] feat: allow passing multiple filters in prop --- src/GlobalEvents.ts | 10 ++++++++-- src/index.spec.ts | 27 ++++++++++++++++++++------- 2 files changed, 28 insertions(+), 9 deletions(-) diff --git a/src/GlobalEvents.ts b/src/GlobalEvents.ts index ae682e6..de02d4d 100644 --- a/src/GlobalEvents.ts +++ b/src/GlobalEvents.ts @@ -57,7 +57,7 @@ export const GlobalEventsImpl = defineComponent({ default: 'document', }, filter: { - type: Function as PropType, + type: [Function, Array] as PropType, default: () => () => true, }, @@ -106,7 +106,13 @@ export const GlobalEventsImpl = defineComponent({ const handlers: EventListener[] = listeners.map( (listener) => (event) => { - if (isActive.value && props.filter(event, listener, eventName)) { + const filters = Array.isArray(props.filter) + ? props.filter + : [props.filter] + if ( + isActive.value && + filters.every((filter) => filter(event, listener, eventName)) + ) { if (props.stop) event.stopPropagation() if (props.prevent) event.preventDefault() listener(event) diff --git a/src/index.spec.ts b/src/index.spec.ts index cba5289..776d60d 100644 --- a/src/index.spec.ts +++ b/src/index.spec.ts @@ -34,13 +34,7 @@ describe('GlobalEvents', () => { test('filter out events', () => { const onKeydown = vi.fn() - let called = false - // easy to test filter that calls only the filst event - const filter = () => { - const shouldCall = !called - called = true - return shouldCall - } + const filter = vi.fn().mockImplementationOnce(() => true) mount(GlobalEvents, { attrs: { onKeydown }, props: { filter }, @@ -56,6 +50,25 @@ describe('GlobalEvents', () => { expect(onKeydown).toHaveBeenCalledTimes(1) }) + test('multiple filters', () => { + const onKeydown = vi.fn() + const f1 = vi.fn().mockImplementationOnce(() => true) + const f2 = vi.fn().mockImplementationOnce(() => true) + mount(GlobalEvents, { + attrs: { onKeydown }, + props: { filter: [f1, f2] }, + }) + expect(onKeydown).not.toHaveBeenCalled() + + document.dispatchEvent(new Event('keydown')) + expect(onKeydown).toHaveBeenCalledTimes(1) + + document.dispatchEvent(new Event('keydown')) + document.dispatchEvent(new Event('keydown')) + document.dispatchEvent(new Event('keydown')) + expect(onKeydown).toHaveBeenCalledTimes(1) + }) + test('filter gets passed handler, and keyName', () => { const onKeydown = vi.fn() const filter = vi.fn()