Skip to content

Commit

Permalink
Merge pull request #148 from Turbinya/refactor_right-clicks_handlers_…
Browse files Browse the repository at this point in the history
…on_files

perf: reduce the number of left-click event listeners on files
  • Loading branch information
kimlimjustin authored Oct 9, 2021
2 parents 9313f2e + e95c4a4 commit 3878a4a
Show file tree
Hide file tree
Showing 11 changed files with 60 additions and 94 deletions.
2 changes: 1 addition & 1 deletion src/Components/Drives/drives.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ const drivesToElements = (drives: Drive[], kBlockFormat = false): string => {
const driveName =
drive.mounted.split('/')[drive.mounted.split('/').length - 1]; // Get name of drive
result += `
<div class="pendrive file card-hover-effect" data-isdir="true" data-listenOpen data-path = "${getDriveBasePath(
<div class="pendrive file card-hover-effect" data-isdir="true" data-path = "${getDriveBasePath(
drive.mounted
)}">
<img src="${fileIcon(
Expand Down
12 changes: 6 additions & 6 deletions src/Components/Favorites/favorites.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,22 +9,22 @@ import getPath from "platform-folders"
const Favorites = ():string => {
const result = `<section class="home-section">
<h2 class="section-title">${Translate("Favorites")}</h2>
<div class="favorite file card-hover-effect" data-listenOpen data-isdir="true" data-path="${getPath("desktop")}">
<div class="favorite file card-hover-effect" data-isdir="true" data-path="${getPath("desktop")}">
<h3 class="favorite-title"><img src="${fileIcon('desktop', "favorites", false)}" alt="Desktop icon" class="favorite-icon">${Translate("Desktop")}</h3>
</div>
<div class="favorite file card-hover-effect" data-listenOpen data-isdir="true" data-path="${getPath("documents")}">
<div class="favorite file card-hover-effect" data-isdir="true" data-path="${getPath("documents")}">
<h3 class="favorite-title"><img src="${fileIcon('document', "favorites", false)}" alt="Document icon" class="favorite-icon">${Translate("Documents")}</h3>
</div>
<div class="favorite file card-hover-effect" data-listenOpen data-isdir="true" data-path="${getPath("downloads")}">
<div class="favorite file card-hover-effect" data-isdir="true" data-path="${getPath("downloads")}">
<h3 class="favorite-title"><img src="${fileIcon('download', "favorites", false)}" alt="Download icon" class="favorite-icon">${Translate("Downloads")}</h3>
</div>
<div class="favorite file card-hover-effect" data-listenOpen data-isdir="true" data-path="${getPath("pictures")}">
<div class="favorite file card-hover-effect" data-isdir="true" data-path="${getPath("pictures")}">
<h3 class="favorite-title"><img src="${fileIcon('picture', "favorites", false)}" alt="Pictures icon" class="favorite-icon">${Translate("Pictures")}</h3>
</div>
<div class="favorite file card-hover-effect" data-listenOpen data-isdir="true" data-path="${getPath("music")}">
<div class="favorite file card-hover-effect" data-isdir="true" data-path="${getPath("music")}">
<h3 class="favorite-title"><img src="${fileIcon('music', "favorites", false)}" alt="Music icon" class="favorite-icon">${Translate("Music")}</h3>
</div>
<div class="favorite file card-hover-effect" data-listenOpen data-isdir="true" data-path="${getPath("videos")}">
<div class="favorite file card-hover-effect" data-isdir="true" data-path="${getPath("videos")}">
<h3 class="favorite-title"><img src="${fileIcon('video', "favorites", false)}" alt="Video icon" class="favorite-icon">${Translate("Videos")}</h3>
</div></section>
`;
Expand Down
56 changes: 22 additions & 34 deletions src/Components/Files/File Operation/open.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,10 @@ const IGNORE_FILE = ['.', '..'];
let timeStarted:number;
let watcher:undefined|FSWatcher;

document.addEventListener('DOMContentLoaded', () => {
document.querySelector('#sidebar-nav').addEventListener('click', openFileHandler);
document.querySelector('#workspace').addEventListener('dblclick', openFileHandler);
})

/**
* Close dir watcher
Expand All @@ -44,7 +48,7 @@ const closeWatcher = ():void => {
* Get command to open a file with default app on various operating systems.
* @returns {string}
*/
const getCommandLine =():string => {
const getCommandLine = ():string => {
switch (process.platform) {
case 'darwin':
return 'open';
Expand All @@ -71,49 +75,37 @@ function openFileWithDefaultApp(file:string) :void{
* @param {any} e - event
* @returns {void}
*/
const openFileHandler = (e:Event):void => {
const openFileHandler = (e: Event): void => {

let element = e.target as HTMLElement;
while (!element.dataset.path) {
element = element.parentNode as HTMLElement
while(!element.dataset.path){
element = element.parentNode as HTMLElement;
}
const filePath = unescape(element.dataset.path)
if(element.id === "workspace") return;

const filePath = unescape(element.dataset.path);

// Open the file if it's not directory
if (element.dataset.isdir !== "true") {
if (element.dataset.isdir !== 'true') {
const recents = storage.get('recent')?.data;
openFileWithDefaultApp(filePath)
openFileWithDefaultApp(filePath);

// Push file into recent files
if (recents) {
if (recents.indexOf(filePath) !== -1) {
recents.push(recents.splice(recents.indexOf(filePath), 1)[0]);
storage.set('recent', recents)
storage.set('recent', recents);
} else {
storage.set('recent', [...recents, filePath])
storage.set('recent', [...recents, filePath]);
}
}
else storage.set('recent', [filePath])
} else {
storage.set('recent', [filePath]);
}
} else {
open(filePath)
open(filePath);
}
}

/**
* Listen elements and pass it into the handler
* @param {NodeListOf<HTMLElement>} elements - array of elements to be listened
* @returns {void}
*/
const listenOpen = (elements: NodeListOf<HTMLElement>):void => {
elements.forEach(element => {
if (document.getElementById("workspace").contains(element)) {
element.removeEventListener("dblclick", openFileHandler)
element.addEventListener("dblclick", openFileHandler)
} else {
element.removeEventListener("click", openFileHandler)
element.addEventListener("click", openFileHandler)
}
})
}

/**
* Display files into Xplorer main section
* @param {fileData[]} files - array of files of a directory
Expand Down Expand Up @@ -188,7 +180,6 @@ const displayFiles = async (files: fileData[], dir:string, options?: {reveal: bo

}
fileGrid.setAttribute("draggable", 'true')
fileGrid.setAttribute("data-listenOpen", '')
fileGrid.dataset.modifiedAt = String(dirent.modifiedAt);
fileGrid.dataset.createdAt = String(dirent.createdAt);
fileGrid.dataset.accessedAt = String(dirent.accessedAt);
Expand Down Expand Up @@ -216,7 +207,6 @@ const displayFiles = async (files: fileData[], dir:string, options?: {reveal: bo
updateTheme()
nativeDrag(document.querySelectorAll(".file"), dir)
SelectListener(document.querySelectorAll(".file"))
listenOpen(document.querySelectorAll("[data-listenOpen]")) // Listen to open the file
LAZY_LOAD()

InfoLog(`Open ${dir} within ${(Date.now() - timeStarted) / 1000}s`)
Expand All @@ -241,7 +231,6 @@ const open = async (dir:string, reveal?:boolean):Promise<void> => {
await changePosition(dir)
if (dir === "xplorer://Home") {
Home(() => {
listenOpen(document.querySelectorAll("[data-listenOpen]")) // Listen to open the file
SelectListener(document.querySelectorAll(".file"))
InfoLog(`Open ${dir} within ${(Date.now() - timeStarted) / 1000}s`)
console.log(`Open ${dir} within ${(Date.now() - timeStarted) / 1000}s`)
Expand Down Expand Up @@ -344,5 +333,4 @@ const open = async (dir:string, reveal?:boolean):Promise<void> => {
}
}


export { listenOpen, open, openFileWithDefaultApp, closeWatcher }
export { open, openFileWithDefaultApp, closeWatcher }
4 changes: 1 addition & 3 deletions src/Components/Files/File Preview/preview.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ const closePreviewFile = (): void => {
* @returns {void}
*/
const Preview = (filePath: string): void => {
const { listenOpen } = require('../File Operation/open'); //eslint-disable-line
closePreviewFile();
const previewElement = document.createElement('div');
previewElement.classList.add('preview');
Expand All @@ -42,7 +41,6 @@ const Preview = (filePath: string): void => {
${html}
`;

listenOpen(previewElement.querySelectorAll('[data-listenOpen]'));
document.querySelector<HTMLElement>('.main-box').scrollTop = 0;
document.querySelector<HTMLElement>('.main-box').style.overflowY =
'hidden';
Expand Down Expand Up @@ -95,7 +93,7 @@ const Preview = (filePath: string): void => {
});
} else if (IMAGE_TYPES.indexOf(path.extname(filePath)) !== -1) {
changePreview(
`<div class="preview-object" data-type="img"><img src="${filePath}" data-listenOpen data-path="${filePath}" /></div>`
`<div class="preview-object" data-type="img"><img src="${filePath}" data-path="${filePath}" /></div>`
);
} else if (VIDEO_TYPES.indexOf(path.extname(filePath)) !== -1) {
changePreview(
Expand Down
2 changes: 1 addition & 1 deletion src/Components/Layout/home.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ const homeFiles = (callback: cb) => {
file.isDir
} data-path = "${escape(
path.join(os.homedir(), file.name)
)}" data-listenOpen ${
)}" ${
isHiddenFile(path.join(os.homedir(), file.name))
? 'data-hidden-file'
: ''
Expand Down
2 changes: 1 addition & 1 deletion src/Components/Layout/layout.scss
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
flex-direction: column;
height: 100vh;
overflow: auto;
.sidebar-nav {
#sidebar-nav {
flex-grow: 1;
margin: 1rem 0;
padding: 15px 20px;
Expand Down
60 changes: 22 additions & 38 deletions src/Components/Layout/sidebar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,9 @@ interface Favorites {
}

const changeSidebar = (newElement: HTMLElement) => {
const { listenOpen } = require('../Files/File Operation/open'); //eslint-disable-line
const sidebarElement = document.body.querySelector('.sidebar');
sidebarElement.parentElement.replaceChild(newElement, sidebarElement);
updateTheme();
listenOpen(
document
.querySelector('.sidebar-nav')
.querySelectorAll('[data-listenOpen]')
); // Listen to open the file
return;
};

Expand Down Expand Up @@ -54,7 +48,7 @@ const createSidebar = (): void => {
} catch (_) {
isdir = true;
}
favoritesElement += `<span data-listenOpen data-path = "${
favoritesElement += `<span data-path = "${
favorite.path
}" data-isdir="${isdir}" class="sidebar-hover-effect sidebar-item"><img src="${fileIcon(
favorite.name,
Expand Down Expand Up @@ -106,7 +100,7 @@ const createSidebar = (): void => {
: drive.filesystem} (${drive.mounted})`
//prettier-ignore
: drive.mounted.split('/')[drive.mounted.split('/').length - 1]; // Get name of drive
drivesElement += `<span data-listenOpen data-path = "${getDriveBasePath(
drivesElement += `<span data-path = "${getDriveBasePath(
drive.mounted
)}" data-isdir="true" class="sidebar-hover-effect drive-item"><img src="${fileIcon(
drive.filesystem === 'Removable Disk' ? 'usb' : 'hard-disk',
Expand Down Expand Up @@ -150,30 +144,28 @@ const createSidebar = (): void => {

getDrivesElement().then((drivesElement) => {
// get drives element
const sidebarElement = document.createElement('div');
sidebarElement.classList.add('sidebar');
sidebarElement.innerHTML = `
<span class="xplorer-brand">Xplorer</span>
<div class="sidebar-nav">
${getFavoritesElement(_favorites)}
${drivesElement}
</div>
<div class="sidebar-setting-btn sidebar-hover-effect">
<div class="sidebar-setting-btn-inner">
<img src="${fileIcon(
'setting',
'sidebar',
false
)}" alt="Setting icon" class="sidebar-setting-btn-icon">
<span class="sidebar-setting-btn-text">${Translate(
'Settings'
)}</span>
</div>
</div>`;
const sidebarNavElement = document.querySelector('#sidebar-nav') as HTMLDivElement;
sidebarNavElement.innerHTML = `
${getFavoritesElement(_favorites)}
${drivesElement}
`

const sidebarElement = document.querySelector('.sidebar') as HTMLDivElement;
sidebarElement.insertAdjacentHTML(
'beforeend',
`<div class="sidebar-setting-btn sidebar-hover-effect">
<div class="sidebar-setting-btn-inner">
<img src="${fileIcon('setting', 'sidebar', false)}" alt="Setting icon" class="sidebar-setting-btn-icon" />
<span class="sidebar-setting-btn-text">
${Translate('Settings')}
</span>
</div>
</div>`
);

// Collapse section
sidebarElement
.querySelectorAll('.sidebar-nav-item-dropdown-btn')
sidebarElement.querySelectorAll('.sidebar-nav-item-dropdown-btn')
.forEach((btn) => {
btn.addEventListener('click', (e) => {
let sidebarNavItem = (e.target as Element).parentNode;
Expand Down Expand Up @@ -221,9 +213,6 @@ const createSidebar = (): void => {
if (_prevDrives === undefined) _prevDrives = _drives;
else {
if (_drives !== _prevDrives) {
const {
listenOpen,
} = require('../Files/File Operation/open'); //eslint-disable-line
const _newElement = document.createElement('div');
_newElement.innerHTML = _drives.trim();
document
Expand All @@ -233,11 +222,6 @@ const createSidebar = (): void => {
document.getElementById('sidebar-drives')
);
updateTheme();
listenOpen(
document
.getElementById('sidebar-drives')
.querySelectorAll('[data-listenOpen]')
);
document.body
.querySelector('.sidebar')
.querySelectorAll('.drive-item')
Expand Down
4 changes: 1 addition & 3 deletions src/Components/Layout/windowManager.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,15 @@
import { open } from '../Files/File Operation/open';
import storage from 'electron-json-storage-sync';
import { BrowserWindow } from '@electron/remote';
import createSidebar from './sidebar';
import { closePreviewFile } from '../Files/File Preview/preview';
import windowGUID from '../Constants/windowGUID';

/**
* Reload the page
* @returns {void}
*/
const reload = async (): Promise<void> => {
const reload = (): void => {
const tabs = storage.get(`tabs-${windowGUID}`)?.data;
await createSidebar();
open(tabs.tabs[tabs.focus].position);
closePreviewFile();
document.querySelector<HTMLElement>('.properties').style.animation =
Expand Down
3 changes: 0 additions & 3 deletions src/Components/Recent/recent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import { SelectListener } from '../Files/File Operation/select';
* @returns {Promise<void>}
*/
const Recent = async (): Promise<void> => {
const { listenOpen } = require('../Files/File Operation/open'); //eslint-disable-line
startLoading();
// Preference data
const layout =
Expand Down Expand Up @@ -71,7 +70,6 @@ const Recent = async (): Promise<void> => {
break;
}
fileGrid.setAttribute('draggable', 'true');
fileGrid.setAttribute('data-listenOpen', '');
fileGrid.dataset.path = escape(recent);
fileGrid.innerHTML = `
${preview}
Expand All @@ -86,7 +84,6 @@ const Recent = async (): Promise<void> => {
}
updateTheme();
SelectListener(document.querySelectorAll('.file'));
listenOpen(document.querySelectorAll('[data-listenOpen]')); // Listen to open the file
LAZY_LOAD();
}
stopLoading();
Expand Down
7 changes: 5 additions & 2 deletions src/Public/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,10 @@

<body>
<div class="container">
<div class="sidebar"></div>
<div class="sidebar">
<span class="xplorer-brand">Xplorer</span>
<div id="sidebar-nav"></div>
</div>
<div class="main">
<div class="topbar">
<div class="row">
Expand Down Expand Up @@ -76,7 +79,7 @@
<span class="loader"></span>
</div>
<div class="main-box">
<div id="workspace" data-path="Home"></div>
<div id="workspace" data-path="xplorer://Home"></div>
</div>
</div>
</div>
Expand Down
2 changes: 0 additions & 2 deletions src/preload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { ipcRenderer, webFrame } from 'electron';
import createSidebar from './Components/Layout/sidebar';
import { windowManager } from './Components/Layout/windowManager';
import Home from './Components/Layout/home';
import { listenOpen, open } from './Components/Files/File Operation/open';
import { ContextMenu } from './Components/ContextMenu/contextMenu';
import { createNewTab, Tab } from './Components/Layout/tab';
import { toggleHiddenFiles } from './Components/Functions/toggleHiddenFiles';
Expand Down Expand Up @@ -47,7 +46,6 @@ document.addEventListener('DOMContentLoaded', async () => {
let homeExecuted = false; // only execute home once
if (!homeExecuted) {
Home(() => {
listenOpen(document.querySelectorAll('[data-listenOpen]')); // Listen to open the file
SelectListener(document.querySelectorAll('.file'));
homeExecuted = true;
});
Expand Down

1 comment on commit 3878a4a

@vercel
Copy link

@vercel vercel bot commented on 3878a4a Oct 9, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.