Просмотр исходного кода

refactor: reuse (add|remove)EventListener|isTouch

tophf 2 лет назад
Родитель
Сommit
1ed4bf710a

+ 1 - 1
src/background/utils/clipboard.js

@@ -16,7 +16,7 @@ addPublicCommands({
 
 document.body.appendChild(textarea);
 
-document.addEventListener('copy', e => {
+addEventListener('copy', e => {
   e.preventDefault();
   const { type, data } = clipboardData;
   e.clipboardData.setData(type || 'text/plain', data);

+ 2 - 2
src/common/keyboard.js

@@ -39,8 +39,8 @@ export function toggleTip(el) {
 }
 
 function bindKeys() {
-  document.addEventListener('focus', handleFocus, true);
-  document.addEventListener('blur', handleBlur, true);
+  addEventListener('focus', handleFocus, true);
+  addEventListener('blur', handleBlur, true);
   keyboardService.register('escape', handleEscape);
   keyboardService.register('c-[', handleEscape);
   keyboardService.register('enter', () => {

+ 2 - 2
src/common/router.js

@@ -35,8 +35,8 @@ function updateRoute(noConfirm) {
 }
 
 // popstate should be the first to ensure hashchange listeners see the correct lastRoute
-window.addEventListener('popstate', () => stack.pop());
-window.addEventListener('hashchange', () => updateRoute(), false);
+addEventListener('popstate', () => stack.pop());
+addEventListener('hashchange', () => updateRoute(), false);
 
 export function setRoute(hash, replace, noConfirm) {
   let hashString = `${hash}`;

+ 1 - 0
src/common/safe-globals.js

@@ -12,6 +12,7 @@ const {
   Error,
   Object,
   Promise,
+  addEventListener, removeEventListener,
   chrome,
   performance,
 } = global;

+ 2 - 2
src/common/ui/code.vue

@@ -306,7 +306,7 @@ export default {
       if (state) {
         this.cm?.focus();
       } else {
-        window.removeEventListener('keydown', this.onKeyDown);
+        removeEventListener('keydown', this.onKeyDown);
       }
     },
     /* reroute hotkeys back to CM when it isn't focused,
@@ -529,7 +529,7 @@ export default {
     });
     // pressing Tab key inside a line with no selection will reuse indent size
     if (!opts.tabSize) this.cm.options.tabSize = this.cm.options.indentUnit;
-    this.$refs.code.addEventListener('copy', this.onCopy);
+    this.$refs.code::addEventListener('copy', this.onCopy);
     this.onActive(true);
     hookSetting('editor', (newUserOpts) => {
       // Use defaults for keys that were present in the old userOpts but got deleted in newUserOpts

+ 1 - 0
src/common/ui/index.js

@@ -160,3 +160,4 @@ function vFocusFactory() {
  * ```
  */
 export const vFocus = vFocusFactory();
+export const isTouch = 'ontouchstart' in document;

+ 1 - 1
src/common/ui/message.vue

@@ -32,7 +32,7 @@ import { computed, nextTick, onMounted, ref } from 'vue';
 
 const dismissers = [];
 
-window.addEventListener('keydown', (e) => {
+addEventListener('keydown', (e) => {
   if (e.keyCode === 27 && dismissers.length) {
     e.stopImmediatePropagation();
     dismissers.pop()();

+ 2 - 1
src/common/ui/style/index.js

@@ -1,3 +1,4 @@
+import { isTouch } from '..';
 import options from '../../options';
 import './style.css';
 
@@ -66,6 +67,6 @@ options.hook((changes) => {
   }
 });
 
-if ('ontouchstart' in document) {
+if (isTouch) {
   document.documentElement.classList.add('touch');
 }

+ 14 - 13
src/options/utils/dragging.js

@@ -1,3 +1,4 @@
+import { isTouch } from '@/common/ui';
 
 const SCRIPT = '.script';
 const SCROLL_GAP = 50;
@@ -7,7 +8,6 @@ const ONE_FRAME_MS = 16;
 // touch-and-hold duration in ms before recognizing dragstart (needed to allow fling-scrolling)
 const LONGPRESS_DELAY = 500;
 
-const isTouch = 'ontouchstart' in document;
 const eventNames = isTouch
   ? { start: 'touchstart', move: 'touchmove', end: 'touchend' }
   : { start: 'dragstart', move: 'mousemove', end: 'mouseup' };
@@ -17,7 +17,6 @@ const noScroll = isTouch && Object.assign(document.createElement('div'), {
   className: 'dragging-noscroll',
 });
 const eventsToSuppress = ['scroll', 'mouseenter', 'mouseleave'];
-const { addEventListener: on, removeEventListener: off } = EventTarget.prototype;
 
 let dragged;
 let elements;
@@ -41,7 +40,9 @@ let xyCache;
 export default function toggleDragging(listEl, moveScript, state) {
   parent = listEl;
   parentOnDrop = moveScript;
-  parent::(state ? on : off)(eventNames.start, isTouch ? onTouchStart : onDragStart);
+  parent::(state ? addEventListener : removeEventListener)(
+    eventNames.start,
+    isTouch ? onTouchStart : onDragStart);
 }
 
 function onDrop() {
@@ -52,8 +53,8 @@ function onTouchStart(e) {
   if (!scriptFromEvent(e)) return;
   longPressEvent = e;
   longPressTimer = setTimeout(onTouchMoveDetect, LONGPRESS_DELAY, 'timer');
-  document::on(eventNames.move, onTouchMoveDetect);
-  document::on(eventNames.end, onTouchEndDetect);
+  addEventListener(eventNames.move, onTouchMoveDetect);
+  addEventListener(eventNames.end, onTouchEndDetect);
 }
 
 function onTouchMoveDetect(e) {
@@ -70,8 +71,8 @@ function onTouchMoveDetect(e) {
 
 function onTouchEndDetect() {
   clearTimeout(longPressTimer);
-  document::off(eventNames.move, onTouchMoveDetect);
-  document::off(eventNames.end, onTouchEndDetect);
+  removeEventListener(eventNames.move, onTouchMoveDetect);
+  removeEventListener(eventNames.end, onTouchEndDetect);
 }
 
 function onDragStart(e) {
@@ -97,8 +98,8 @@ function onDragStart(e) {
   dragged.style.width = `${rect.width}px`;
   parent.appendChild(dragged);
   if (isTouch) parent.insertAdjacentElement('afterBegin', noScroll);
-  document::on(eventNames.move, onDragMouseMove);
-  document::on(eventNames.end, onDragMouseUp);
+  addEventListener(eventNames.move, onDragMouseMove);
+  addEventListener(eventNames.end, onDragMouseUp);
 }
 
 function onDragMouseMove(e) {
@@ -120,8 +121,8 @@ function onDragMouseMove(e) {
 }
 
 function onDragMouseUp() {
-  document::off(eventNames.move, onDragMouseMove);
-  document::off(eventNames.end, onDragMouseUp);
+  removeEventListener(eventNames.move, onDragMouseMove);
+  removeEventListener(eventNames.end, onDragMouseUp);
   stopScrolling();
   dragged.remove();
   if (isTouch) noScroll.remove();
@@ -169,11 +170,11 @@ function doScroll() {
 
 function startScrolling() {
   scrollTimer = setInterval(doScroll, ONE_FRAME_MS);
-  eventsToSuppress.forEach(name => window::on(name, stopPropagation, true));
+  eventsToSuppress.forEach(name => addEventListener(name, stopPropagation, true));
 }
 
 function stopScrolling() {
-  eventsToSuppress.forEach(name => window::off(name, stopPropagation, true));
+  eventsToSuppress.forEach(name => removeEventListener(name, stopPropagation, true));
   if (scrollTimer) clearInterval(scrollTimer);
   scrollTimer = 0;
 }

+ 1 - 1
src/options/views/app.vue

@@ -67,7 +67,7 @@ function switchTab(step) {
   window.location.hash = switchTo?.name || '';
 }
 
-document.addEventListener('dragover', evt => {
+addEventListener('dragover', evt => {
   if (['', TAB_ABOUT, SCRIPTS].includes(store.route.hash)
     && /^application\/(zip|x-zip-compressed)$/.test(evt.dataTransfer.items[0]?.type)) {
     location.hash = `#${TAB_SETTINGS}`;

+ 1 - 1
src/options/views/edit/index.vue

@@ -156,7 +156,7 @@ const setupSavePosition = ({ id: curWndId, tabs }) => {
       });
     } else {
       // triggered on resizing only
-      window.addEventListener('resize', debounce(savePosition, 100));
+      addEventListener('resize', debounce(savePosition, 100));
       shouldSavePositionOnSave = true;
     }
   }

+ 1 - 1
src/options/views/edit/values.vue

@@ -152,7 +152,7 @@ export default {
     },
   },
   mounted() {
-    this.$refs.container.addEventListener('focusin', evt => {
+    this.$refs.container::addEventListener('focusin', evt => {
       keyboardService.setContext('edit', 'selectionEnd' in evt.target);
     });
   },

+ 3 - 3
src/options/views/tab-installed.vue

@@ -509,9 +509,9 @@ function bindKeys() {
   const handleFocus = () => {
     keyboardService.setContext('buttonFocus', document.activeElement?.tabIndex >= 0);
   };
-  document.addEventListener('focus', handleFocus, true);
+  addEventListener('focus', handleFocus, true);
   const disposeList = [
-    () => document.removeEventListener('focus', handleFocus, true),
+    () => removeEventListener('focus', handleFocus, true),
     ...IS_FIREFOX ? [
       keyboardService.register('tab', () => {
         handleTabNavigation(1);
@@ -665,7 +665,7 @@ export default {
         const style = getComputedStyle(document.documentElement);
         [columnsForCardsMode, columnsForTableMode] = ['cards', 'table']
           .map(type => style.getPropertyValue(`--columns-${type}`)?.split(',').map(Number).filter(Boolean) || []);
-        global.addEventListener('resize', adjustScriptWidth);
+        addEventListener('resize', adjustScriptWidth);
       }
       adjustScriptWidth();
       return bindKeys();

+ 1 - 1
src/options/views/tab-settings/vm-editor.vue

@@ -69,7 +69,7 @@ export default {
     this.revokers = null;
   },
   async mounted() {
-    this.$refs.editor.$el.addEventListener('dblclick', this.toggleBoolean);
+    this.$refs.editor.$el::addEventListener('dblclick', this.toggleBoolean);
     if (!this.revokers) {
       this.css = makeTextPreview(options.get(keyThemeCSS));
       this.revokers = [

+ 1 - 1
src/options/views/tab-settings/vm-import.vue

@@ -67,7 +67,7 @@ export default {
   },
   mounted() {
     const toggleDragDrop = initDragDrop(this.$refs.buttonImport);
-    window.addEventListener('hashchange', toggleDragDrop);
+    addEventListener('hashchange', toggleDragDrop);
     toggleDragDrop();
   },
 };