Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perf: reduce the number of left-click event listeners on files #148

Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/Components/Drives/drives.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,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
59 changes: 23 additions & 36 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,36 @@ function openFileWithDefaultApp(file:string) :void{
* @param {any} e - event
* @returns {void}
*/
const openFileHandler = (e:Event):void => {
let element = e.target as HTMLElement;
while (!element.dataset.path) {
element = element.parentNode as HTMLElement
}
const filePath = unescape(element.dataset.path)
const openFileHandler = (e: Event): void => {
const target = e.target as HTMLElement

// Ignore workspace clicks
if (target.id === 'workspace') return

const element = target.dataset.path ? target : target.parentNode as HTMLElement,
filePath = unescape(element.dataset.path);

Copy link
Owner

Choose a reason for hiding this comment

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

Changing this introduce another bug, when you click exactly on a drive's name, a error came out,

Untitled_.Oct.8.2021.7_15.PM.mp4

this is because the target I clicked, pendrive-title is under pendrive-info div that is under the div that contains the dataset.path, could you please fix this?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Sorry, but today I changed my computer on which was Windows. Now i have a computer with Ubuntu. I didn't have such problems in Ubuntu. The computer with Windows will not be available to me for some time. So I cannot reliably verify that I have fixed it. So you can do it yourself or wait when I can.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

And I faced two problems on Ubuntu which I will now describe

Copy link
Owner

Choose a reason for hiding this comment

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

Ah okay, I'll fix it tonight (if I got time) or tomorrow

// 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 +179,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 +206,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 +230,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 +332,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 @@ -32,7 +32,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 @@ -45,7 +44,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 @@ -98,7 +96,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 @@ -104,7 +98,7 @@ const createSidebar = (): void => {
? `${drive.volumename || 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 @@ -148,30 +142,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 @@ -219,9 +211,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 @@ -231,11 +220,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
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
5 changes: 4 additions & 1 deletion 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
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 @@ -46,7 +45,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