Skip to content

Instantly share code, notes, and snippets.

@padcom
Last active June 20, 2018 00:54
Show Gist options
  • Save padcom/0a4e4699813d983fc76dfde29406f9e6 to your computer and use it in GitHub Desktop.
Save padcom/0a4e4699813d983fc76dfde29406f9e6 to your computer and use it in GitHub Desktop.
Vue implementation of defocuser (as a directive)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Dropdowns</title>
<script type="text/javascript" src="http://unpkg.com/vue"></script>
<style>
.label {
cursor: pointer;
user-select: none;
background-color: red;
}
.label:hover {
font-weight: bold;
}
.dropdown-content {
display: block;
position: absolute;
border: solid 1px rgb(185, 185, 185);
width: 100px;
height: 100px;
background-color: #eeeeee;
box-shadow: 1px 1px 5px gray;
}
</style>
</head>
<body>
<script>
class Defocuser {
constructor () {
this.elements = []
document.addEventListener('click', this.defocus('bubbling').bind(this), { capture: false })
document.addEventListener('click', this.defocus('capture').bind(this), { capture: true })
document.addEventListener('keydown', this.escape('bubbling').bind(this), { capture: false })
document.addEventListener('keydown', this.escape('capture').bind(this), { capture: true })
}
addElement (el, phase, callback) {
this.ensureDataStoreExistsInElement(el)
el.__defocus.event = callback || (() => {})
el.__defocus.observer = this.createMutationObserver(el)
el.__defocus.phase = phase
this.elements.unshift(el)
}
setSecondaryElement (el, secondary) {
this.ensureDataStoreExistsInElement(el)
el.__defocus.secondary = secondary
}
// event handlers
defocus (phase) {
return e => {
if (this.elements.length === 0 || !this.elements[0].__defocus || phase !== this.elements[0].__defocus.phase) {
return
}
const primary = this.elements[0]
const secondary = primary.__defocus.secondary
if (this.isElementOutsideElements(e.target, primary, secondary) && primary.__defocus.event) {
primary.__defocus.event()
}
}
}
escape (phase) {
return e => {
if (this.elements.length === 0 || !this.elements[0].__defocus || phase !== this.elements[0].__defocus.phase) {
return
}
if (e.code === 'Escape') {
const primary = this.elements[0]
primary.__defocus.event()
}
}
}
// private methods
isElementOutsideElements (el, primary, secondary) {
let element = el
while (element) {
if (element == primary || element == secondary) return false
element = element.parentNode
}
return true
}
ensureDataStoreExistsInElement(el) {
if (!el.__defocus) Object.defineProperty(el, '__defocus', { value: {} })
}
hasNodeRemovedEvent (el, events) {
return events.some(event => {
for (let i = 0; i < event.removedNodes.length; i++) {
if (event.removedNodes[i] == el) {
return true
}
}
})
}
removeElementFromStack (el) {
if (this.elements[0] != el) {
throw new Error('Top element is not the removed one')
}
this.elements.shift()
}
createMutationObserver (el) {
const observer = new MutationObserver(events => {
if (this.hasNodeRemovedEvent(el, events)) {
this.removeElementFromStack(el)
observer.disconnect()
}
})
observer.observe(el.parentNode, { childList: true })
return observer
}
}
let defocuser = null
const defocus = {
inserted (el, options) {
if (!defocuser) defocuser = new Defocuser()
defocuser.addElement(el, options.modifiers.capture ? 'capture' : 'bubbling', options.value || (() => {}))
}
}
const defocusSecondary = {
inserted (el, options) {
if (!defocuser) defocuser = new Defocuser()
defocuser.setSecondaryElement(el, options.value)
}
}
const DefocuserLibrary = {
defocus,
defocusSecondary,
install(Vue) {
Vue.directive('defocus', defocus)
Vue.directive('defocus-secondary', defocusSecondary)
}
}
Object.defineProperties(DefocuserLibrary, {
defocuser: {
get: function() {
return defocuser
}
}
})
if (typeof window !== 'undefined' && window.Vue) {
window.Vue.use(DefocuserLibrary)
}
console.log(DefocuserLibrary.defocuser)
</script>
<div id="app">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
<div class="dropdown" name="me">
<span class="label" ref="label" @click="toggle">click me!</span>
<div v-if="dropdown" class="dropdown-content" v-defocus.capture="close" v-defocus-secondary="$refs.label">
Hello, world!
</div>
</div>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</div>
<script>
new Vue({
el: '#app',
data: {
dropdown: false
},
methods: {
toggle () {
this.dropdown = !this.dropdown
},
close () {
this.dropdown = false
}
}
})
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment