Skip to content

Commit

Permalink
feat: allow passing multiple filters in prop
Browse files Browse the repository at this point in the history
  • Loading branch information
posva committed Jun 29, 2023
1 parent f305def commit fb5fcda
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 9 deletions.
10 changes: 8 additions & 2 deletions src/GlobalEvents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ export const GlobalEventsImpl = defineComponent({
default: 'document',
},
filter: {
type: Function as PropType<EventFilter>,
type: [Function, Array] as PropType<EventFilter | EventFilter[]>,
default: () => () => true,
},

Expand Down Expand Up @@ -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)
Expand Down
27 changes: 20 additions & 7 deletions src/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 },
Expand All @@ -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()
Expand Down

0 comments on commit fb5fcda

Please # to comment.