From 83ce9b8e5c1ac9391a50814487ee8bcc2b1e3120 Mon Sep 17 00:00:00 2001 From: Alicia Sykes Date: Wed, 30 Mar 2022 21:54:01 +0100 Subject: [PATCH] :truck: Moves ClickOutside into directives directory --- src/directives/ClickOutside.js | 41 ++++++++++++++++++++++++++++++++++ src/main.js | 2 +- 2 files changed, 42 insertions(+), 1 deletion(-) create mode 100644 src/directives/ClickOutside.js diff --git a/src/directives/ClickOutside.js b/src/directives/ClickOutside.js new file mode 100644 index 00000000..86868c96 --- /dev/null +++ b/src/directives/ClickOutside.js @@ -0,0 +1,41 @@ +/** + * A Vue directive to trigger an event when the user + * clicks anywhere other than the specified elements + * Used to close context menus popup modals and tips + * Dashy: Licensed under MIT - (C) Alicia Sykes 2022 + */ + +const instances = []; // List of click event instances + +/* Trigger action when click anywhere, except target elem */ +function onDocumentClick(event, elem, action) { + const { target } = event; + if (elem !== target && !elem.contains(target)) { + action(event); + } +} + +export default { + /* Add event listeners */ + bind(element, binding) { + const elem = element; + elem.dataset.outsideClickIndex = instances.length; + + const action = binding.value; + const click = (event) => { + onDocumentClick(event, elem, action); + }; + + document.addEventListener('click', click); + document.addEventListener('touchstart', click); + instances.push(click); + }, + /* Remove event listeners */ + unbind(elem) { + if (!elem.dataset) return; + const index = elem.dataset.outsideClickIndex; + const handler = instances[index]; + document.removeEventListener('click', handler); + instances.splice(index, 1); + }, +}; diff --git a/src/main.js b/src/main.js index b212e6ab..5b79d619 100644 --- a/src/main.js +++ b/src/main.js @@ -16,9 +16,9 @@ import Dashy from '@/App.vue'; // Main Dashy Vue app import router from '@/router'; // Router, for navigation import store from '@/store'; // Store, for local state management import serviceWorker from '@/utils/InitServiceWorker'; // Service worker initialization -import clickOutside from '@/utils/ClickOutside'; // Directive for closing popups, modals, etc import { messages } from '@/utils/languages'; // Language texts import ErrorReporting from '@/utils/ErrorReporting'; // Error reporting initializer (off) +import clickOutside from '@/directives/ClickOutside'; // Directive for closing popups, modals, etc import { toastedOptions, tooltipOptions, language as defaultLanguage } from '@/utils/defaults'; import { initKeycloakAuth, isKeycloakEnabled } from '@/utils/KeycloakAuth';