Skip to content

Commit

Permalink
feat: detect click outside on iframe
Browse files Browse the repository at this point in the history
Clicks on iframe don't bubble, so they are undetected by our
`document.documentElement` listeners. Workarounds in the SO threads and
dev internet fall into 3 categories:
- add pseudo-elements cover ups on iframes;
- wrap iframes on an extra <div> and capture the click on it;
- window.onblur + document.activeElement combo;

The last one seemed the less intrusive:
- it doesn't block clicks on iframe content itself;
- it doesn't add extra DIVs which could cause layout issues;
- it keeps performance impact to a minimum;

How it works:
The gist is that a click on an iframe will move `focus` to it. Since
iframe has its own `window` our main app window will blur: on that event
we can then check if document.activeElement is an IFRAME and execute the
handler considering it a "faux click outside".

Implementation details:
- adds a custom `vco:faux-iframe-click` eventName id to the provided
  eventsNames array, this will be used to perform conditional logic:
  - bind `blur` event to window instead of document.documentElement;
  - use `onFauxIframeClick` instead of default `onEvent` as handler wrapper;
- `onFauxIframeClick` doens't require the event path logic checks as it
  only uses `document.activeElement` and simply wraps handler execution
  into a setTimeout to workaround an issue with Firefox, that only sets
  `activeElement` correctly after blur, on the next tick (event loop).

Caveats:
- Click outside will be triggered once on iframe. Subsequent clicks will
  not execute the handler untill focus has been moved back to main window.
  This is the "expected" behaviour as by clicking the iframe, focus will
  move to iframe contents — a different window. There might be way
  to workaround this, by triggering `window.focus()` at the end of the
  provided handler but that will break normal tab/focus flow, therefore
  not included by default.
- Moving focus to iframe via tab navigation also triggers `window.blur`
  consequently the click-outside handler.
  • Loading branch information
renatodeleao committed Aug 27, 2020
1 parent e56b509 commit e2e2bd1
Show file tree
Hide file tree
Showing 2 changed files with 103 additions and 22 deletions.
49 changes: 38 additions & 11 deletions src/v-click-outside.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,23 @@ function processDirectiveArguments(bindingValue) {
}
}

function execHandler({ event, handler, middleware }) {
if (middleware(event)) {
handler(event)
}
}

function onFauxIframeClick({ event, handler, middleware }) {
// Note: on firefox clicking on iframe triggers blur, but only on
// next event loop it becomes document.activeElement
// https://stackoverflow.com/q/2381336#comment61192398_23231136
setTimeout(() => {
if (document.activeElement.tagName === 'IFRAME') {
execHandler({ event, handler, middleware })
}
}, 0)
}

function onEvent({ el, event, handler, middleware }) {
// Note: composedPath is not supported on IE and Edge, more information here:
// https://developer.mozilla.org/en-US/docs/Web/API/Event/composedPath
Expand All @@ -37,9 +54,7 @@ function onEvent({ el, event, handler, middleware }) {
return
}

if (middleware(event)) {
handler(event)
}
execHandler({ event, handler, middleware })
}

function bind(el, { value }) {
Expand All @@ -50,27 +65,39 @@ function bind(el, { value }) {
return
}

el[HANDLERS_PROPERTY] = events.map((eventName) => ({
event: eventName,
handler: (event) => onEvent({ event, el, handler, middleware }),
}))
// Note: keep events array immutable, since events value defaults to
// EVENTS variable reference.
el[HANDLERS_PROPERTY] = ['vco:faux-iframe-click', ...events].map(
(eventName, i) => {
const isForIframe = i === 0

return {
event: isForIframe ? 'blur' : eventName,
srcTarget: isForIframe ? window : document.documentElement,
handler: isForIframe
? (event) =>
onFauxIframeClick({ event, eventName, handler, middleware })
: (event) => onEvent({ event, el, handler, middleware }),
}
},
)

el[HANDLERS_PROPERTY].forEach(({ event, handler }) =>
el[HANDLERS_PROPERTY].forEach(({ event, srcTarget, handler }) =>
setTimeout(() => {
// Note: More info about this implementation can be found here:
// https://github.com/ndelvalle/v-click-outside/issues/137
if (!el[HANDLERS_PROPERTY]) {
return
}
document.documentElement.addEventListener(event, handler, false)
srcTarget.addEventListener(event, handler, false)
}, 0),
)
}

function unbind(el) {
const handlers = el[HANDLERS_PROPERTY] || []
handlers.forEach(({ event, handler }) =>
document.documentElement.removeEventListener(event, handler, false),
handlers.forEach(({ event, srcTarget, handler }) =>
srcTarget.removeEventListener(event, handler, false),
)
delete el[HANDLERS_PROPERTY]
}
Expand Down
76 changes: 65 additions & 11 deletions test/v-click-outside.test.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/* global jest describe it expect beforeEach beforeAll */
/* global jest describe it expect beforeEach afterEach beforeAll */

import { merge } from 'lodash'
import clickOutside from '../src/index'
Expand Down Expand Up @@ -49,6 +49,7 @@ describe('v-click-outside -> directive', () => {
describe('bind', () => {
beforeEach(() => {
document.documentElement.addEventListener = jest.fn()
window.addEventListener = jest.fn()
jest.useFakeTimers()
})

Expand All @@ -67,7 +68,9 @@ describe('v-click-outside -> directive', () => {
directive.bind(el, binding)
jest.runOnlyPendingTimers()

expect(el[HANDLERS_PROPERTY].length).toEqual(binding.value.events.length)
expect(el[HANDLERS_PROPERTY].length).toEqual(
binding.value.events.length + 1, // [vco:faux-iframe-click]
)

el[HANDLERS_PROPERTY].forEach((eventHandler) =>
expect(typeof eventHandler.handler).toEqual('function'),
Expand All @@ -76,6 +79,18 @@ describe('v-click-outside -> directive', () => {
expect(document.documentElement.addEventListener).toHaveBeenCalledTimes(
binding.value.events.length,
)

expect(window.addEventListener).toHaveBeenCalledTimes(1)
})

it('adds and event listener to the window, as click detection mechanism on iframes', () => {
const directive = createDirective()
const [el, binding] = createHookArguments()

directive.bind(el, binding)
jest.runOnlyPendingTimers()

expect(window.addEventListener).toHaveBeenCalledTimes(1)
})

it("doesn't do anything when binding value isActive attribute is false", () => {
Expand All @@ -87,6 +102,7 @@ describe('v-click-outside -> directive', () => {
jest.runOnlyPendingTimers()

expect(document.documentElement.addEventListener).toHaveBeenCalledTimes(0)
expect(window.addEventListener).toHaveBeenCalledTimes(0)
expect(el[HANDLERS_PROPERTY]).toBeUndefined()
})
})
Expand All @@ -95,6 +111,11 @@ describe('v-click-outside -> directive', () => {
beforeAll(() => {
jest.useFakeTimers()
document.documentElement.removeEventListener = jest.fn()
window.removeEventListener = jest.fn()
})

afterEach(() => {
jest.clearAllMocks()
})

it('removes event listeners attached to the element', () => {
Expand All @@ -103,17 +124,17 @@ describe('v-click-outside -> directive', () => {
const [el1, binding1] = createHookArguments()
directive.bind(el1, binding1)
jest.runOnlyPendingTimers()
expect(el1[HANDLERS_PROPERTY].length).toEqual(1)
expect(el1[HANDLERS_PROPERTY].length).toEqual(2)

const [el2, binding2] = createHookArguments()
directive.bind(el2, binding2)
jest.runOnlyPendingTimers()
expect(el2[HANDLERS_PROPERTY].length).toEqual(1)
expect(el2[HANDLERS_PROPERTY].length).toEqual(2)

const [el3, binding3] = createHookArguments()
directive.bind(el3, binding3)
jest.runOnlyPendingTimers()
expect(el3[HANDLERS_PROPERTY].length).toEqual(1)
expect(el3[HANDLERS_PROPERTY].length).toEqual(2)

const els = [el1, el2, el3]

Expand All @@ -125,6 +146,17 @@ describe('v-click-outside -> directive', () => {
document.documentElement.removeEventListener,
).toHaveBeenCalledTimes(3)
})

it('removes event listener attached to window', () => {
const directive = createDirective()
const [el, bindingValue] = createHookArguments()

directive.bind(el, bindingValue)
jest.runOnlyPendingTimers()

directive.unbind(el)
expect(window.removeEventListener).toHaveBeenCalledTimes(1)
})
})

describe('update', () => {
Expand All @@ -143,6 +175,8 @@ describe('v-click-outside -> directive', () => {
jest.useFakeTimers()
document.documentElement.addEventListener = jest.fn()
document.documentElement.removeEventListener = jest.fn()
window.addEventListener = jest.fn()
window.removeEventListener = jest.fn()
})

it('updates isActive binding value from true to true', () => {
Expand All @@ -152,22 +186,25 @@ describe('v-click-outside -> directive', () => {
directive.bind(el, binding)
jest.runOnlyPendingTimers()

expect(el[HANDLERS_PROPERTY].length).toEqual(1)
expect(el[HANDLERS_PROPERTY].length).toEqual(2)
expect(document.documentElement.addEventListener).toHaveBeenCalledTimes(
1,
)
expect(window.addEventListener).toHaveBeenCalledTimes(1)

binding.oldValue = binding.value
directive.update(el, binding)
jest.runOnlyPendingTimers()

expect(el[HANDLERS_PROPERTY].length).toEqual(1)
expect(el[HANDLERS_PROPERTY].length).toEqual(2)
expect(document.documentElement.addEventListener).toHaveBeenCalledTimes(
1,
)
expect(
document.documentElement.removeEventListener,
).toHaveBeenCalledTimes(0)
expect(window.addEventListener).toHaveBeenCalledTimes(1)
expect(window.removeEventListener).toHaveBeenCalledTimes(0)

const [, newBinding] = createHookArguments(undefined, {
value: { events: ['click'] },
Expand All @@ -176,13 +213,15 @@ describe('v-click-outside -> directive', () => {
directive.update(el, newBinding)
jest.runOnlyPendingTimers()

expect(el[HANDLERS_PROPERTY].length).toEqual(1)
expect(el[HANDLERS_PROPERTY].length).toEqual(2)
expect(document.documentElement.addEventListener).toHaveBeenCalledTimes(
2,
)
expect(
document.documentElement.removeEventListener,
).toHaveBeenCalledTimes(binding.value.events.length)
expect(window.addEventListener).toHaveBeenCalledTimes(2)
expect(window.removeEventListener).toHaveBeenCalledTimes(1)
})

it('updates is active binding value from true to false', () => {
Expand All @@ -192,10 +231,11 @@ describe('v-click-outside -> directive', () => {
directive.bind(el, binding)
jest.runOnlyPendingTimers()

expect(el[HANDLERS_PROPERTY].length).toEqual(1)
expect(el[HANDLERS_PROPERTY].length).toEqual(2)
expect(document.documentElement.addEventListener).toHaveBeenCalledTimes(
1,
)
expect(window.addEventListener).toHaveBeenCalledTimes(1)

binding.value.isActive = false
directive.update(el, binding)
Expand All @@ -208,6 +248,8 @@ describe('v-click-outside -> directive', () => {
expect(
document.documentElement.removeEventListener,
).toHaveBeenCalledTimes(1)
expect(window.addEventListener).toHaveBeenCalledTimes(1)
expect(window.removeEventListener).toHaveBeenCalledTimes(1)
})

it('updates is active binding value from false to true', () => {
Expand All @@ -226,19 +268,25 @@ describe('v-click-outside -> directive', () => {
expect(
document.documentElement.removeEventListener,
).toHaveBeenCalledTimes(0)
expect(window.addEventListener).toHaveBeenCalledTimes(0)
expect(window.removeEventListener).toHaveBeenCalledTimes(0)

binding.oldValue = { ...binding.value }
binding.value.isActive = true
directive.update(el, binding)
jest.runOnlyPendingTimers()
jest.runOnlyPendingTimers()

expect(el[HANDLERS_PROPERTY].length).toEqual(1)
expect(el[HANDLERS_PROPERTY].length).toEqual(2)
expect(document.documentElement.addEventListener).toHaveBeenCalledTimes(
1,
)
expect(window.addEventListener).toHaveBeenCalledTimes(1)
expect(
document.documentElement.removeEventListener,
).toHaveBeenCalledTimes(0)
expect(window.addEventListener).toHaveBeenCalledTimes(1)
expect(window.removeEventListener).toHaveBeenCalledTimes(0)

const [, newBinding] = createHookArguments(undefined, {
value: { events: ['click'] },
Expand All @@ -247,13 +295,15 @@ describe('v-click-outside -> directive', () => {
directive.update(el, newBinding)
jest.runOnlyPendingTimers()

expect(el[HANDLERS_PROPERTY].length).toEqual(1)
expect(el[HANDLERS_PROPERTY].length).toEqual(2)
expect(document.documentElement.addEventListener).toHaveBeenCalledTimes(
2,
)
expect(
document.documentElement.removeEventListener,
).toHaveBeenCalledTimes(binding.value.events.length)
expect(window.addEventListener).toHaveBeenCalledTimes(2)
expect(window.removeEventListener).toHaveBeenCalledTimes(1)
})

it('updates is active binding value from false to false', () => {
Expand All @@ -269,6 +319,8 @@ describe('v-click-outside -> directive', () => {
expect(document.documentElement.addEventListener).toHaveBeenCalledTimes(
0,
)
expect(window.addEventListener).toHaveBeenCalledTimes(0)
expect(window.removeEventListener).toHaveBeenCalledTimes(0)

directive.update(el, binding)
jest.runOnlyPendingTimers()
Expand All @@ -280,6 +332,8 @@ describe('v-click-outside -> directive', () => {
expect(
document.documentElement.removeEventListener,
).toHaveBeenCalledTimes(0)
expect(window.addEventListener).toHaveBeenCalledTimes(0)
expect(window.removeEventListener).toHaveBeenCalledTimes(0)
})
})
})
Expand Down

0 comments on commit e2e2bd1

Please sign in to comment.