TagSpaces is an offline, open source, document manager with tagging support
chore: refactoring dom.ts
Ilian Sapundshievc9916ad20a19
diff --git a/src/renderer/utils/dom.ts b/src/renderer/utils/dom.tsindex c25ef9622..c78bf301a 100644--- a/src/renderer/utils/dom.ts+++ b/src/renderer/utils/dom.ts@@ -1,147 +1,189 @@import { getMimeType, getRelativeEntryPath } from '-/services/utils-io';-export function isVisibleOnScreen(element: any) {- const rectangle = element.getBoundingClientRect();- const isVisible =- rectangle.top >= 0 &&- rectangle.left >= 0 &&- rectangle.bottom <=- (window.innerHeight || document.documentElement.clientHeight) &&- rectangle.right <=- (window.innerWidth || document.documentElement.clientWidth);- return isVisible;+/**+ * Check if an element is visible on screen+ */+export function isVisibleOnScreen(element: HTMLElement | null): boolean {+ if (!element) return false;++ const rect = element.getBoundingClientRect();+ const viewportHeight =+ window.innerHeight || document.documentElement.clientHeight;+ const viewportWidth =+ window.innerWidth || document.documentElement.clientWidth;++ return (+ rect.top >= 0 &&+ rect.left >= 0 &&+ rect.bottom <= viewportHeight &&+ rect.right <= viewportWidth+ );}-export function getURLParameter(paramName: string, url?: string): string {- const intUrl = url || window.location.href;- const params = new URL(intUrl).searchParams;- let param = params.get(paramName);- // todo: temporal fix due to issue in the milkdown editor- if (param?.endsWith('\\')) {- param = param.substring(0, param.length - 1);+/**+ * Get URL parameter value by name+ */+export function getURLParameter(+ paramName: string,+ url?: string,+): string | null {+ try {+ const searchUrl = url || window.location.href;+ const param = new URL(searchUrl).searchParams.get(paramName);+ // Remove trailing backslash (temporal fix for milkdown editor issue)+ return param?.endsWith('\\') ? param.slice(0, -1) : param;+ } catch (e) {+ console.error('Invalid URL in getURLParameter:', e);+ return null;}- return param;}-export function clearAllURLParams() {+/**+ * Clear all URL parameters and keep only pathname+ */+export function clearAllURLParams(): void {window.history.pushState(null, null, window.location.pathname);}-export function clearURLParam(paramName) {+/**+ * Remove specific URL parameter+ */+export function clearURLParam(paramName: string): void {const url = new URL(window.location.href);- const params = new URLSearchParams(url.search);-- // Delete the foo parameter.- params.delete(paramName);- window.history.pushState(null, null, window.location.pathname + '?' + params);+ url.searchParams.delete(paramName);+ window.history.pushState(null, null, url.toString());}+/**+ * Update browser history with location and path parameters+ */export function updateHistory(locationUUID: string,locationPath: string,newDirectoryPath: string,newEntryPath?: string,-) {- const currentHref = new URL(window.location.href);- const params = new URLSearchParams(currentHref.search);- const currentLocationID = params.get('tslid');- const currentFolderPath = params.get('tsdpath');- const currentEntryPath = params.get('tsepath');- let diffLocation = false;- let diffFolderPath = false;- let diffEntryPath = false;-- if (locationUUID) {- let urlParams = '?';- const newEncLocationID = encodeURIComponent(locationUUID);- urlParams += 'tslid=' + newEncLocationID;- diffLocation = locationUUID !== currentLocationID;-- if (newDirectoryPath && newDirectoryPath.length > 0) {- const newRelDir = getRelativeEntryPath(locationPath, newDirectoryPath);- if (newRelDir) {- const newEncRelDir = encodeURIComponent(newRelDir);- urlParams += '&tsdpath=' + newEncRelDir;- }- diffFolderPath = newRelDir !== currentFolderPath;- }+): void {+ if (!locationUUID) return;- if (newEntryPath && newEntryPath.length > 0) {- const entryRelPath = getRelativeEntryPath(locationPath, newEntryPath);- if (entryRelPath) {- const newEncEntryPath = encodeURIComponent(entryRelPath);- urlParams += '&tsepath=' + newEncEntryPath;- }- diffEntryPath = entryRelPath !== currentEntryPath;- }+ const currentUrl = new URL(window.location.href);+ const currentParams = currentUrl.searchParams;+ const newParams = new URLSearchParams();++ // Build new URL parameters+ newParams.set('tslid', locationUUID);++ let hasChanges = locationUUID !== currentParams.get('tslid');- const localePar = getURLParameter('locale');- if (localePar && localePar.length > 1) {- urlParams += '&locale=' + localePar;+ // Add directory path if provided+ if (newDirectoryPath?.length > 0) {+ const relDir = getRelativeEntryPath(locationPath, newDirectoryPath);+ if (relDir) {+ newParams.set('tsdpath', relDir);+ hasChanges ||= relDir !== currentParams.get('tsdpath');}+ }- if (diffLocation || diffEntryPath || diffFolderPath) {- window.history.pushState(null, null, urlParams);+ // Add entry path if provided+ if (newEntryPath?.length > 0) {+ const relEntryPath = getRelativeEntryPath(locationPath, newEntryPath);+ if (relEntryPath) {+ newParams.set('tsepath', relEntryPath);+ hasChanges ||= relEntryPath !== currentParams.get('tsepath');}}++ // Preserve locale parameter+ const locale = currentParams.get('locale');+ if (locale?.length) {+ newParams.set('locale', locale);+ }++ // Only update if there are changes+ if (hasChanges) {+ const newUrl = `?${newParams.toString()}`;+ window.history.pushState(null, null, newUrl);+ }}+/**+ * Convert ArrayBuffer to Data URL+ */export function arrayBufferToDataURL(- arrayBuffer: any,+ arrayBuffer: ArrayBuffer,mime: string,): Promise<string> {- return new Promise((resolve) => {+ return new Promise((resolve, reject) => {const blob = new Blob([arrayBuffer], { type: mime });const reader = new FileReader();- reader.onload = function (event) {- const dataUrl = event.target?.result as string;+ reader.onload = () => {+ const dataUrl = reader.result as string;resolve(dataUrl);};+ reader.onerror = () => {+ reject(new Error('Failed to read array buffer'));+ };+reader.readAsDataURL(blob);});}-export function dataURLtoBlob(dataURI) {- const arr = dataURI.split(',');- const mime = arr[0].match(/:(.*?);/)[1];- const arrBuff = base64ToUint8Array(arr[1]).buffer;- return new window.Blob([arrBuff], { type: mime });+/**+ * Convert Data URL to Blob+ */+export function dataURLtoBlob(dataURI: string): Blob {+ const mimeMatch = dataURI.match(/:(.*?);/);+ if (!mimeMatch?.[1]) {+ throw new Error('Invalid data URI format');+ }++ const mime = mimeMatch[1];+ const commaIndex = dataURI.indexOf(',');+ const base64String = dataURI.slice(commaIndex + 1);+ const uint8Array = base64ToUint8Array(base64String);++ return new Blob([new Uint8Array(uint8Array)], { type: mime });}/**- * @param base64+ * Convert base64 string to Uint8Array*/-export function base64ToUint8Array(base64) {+export function base64ToUint8Array(base64: string): Uint8Array {// Find where the actual data starts (after the comma)// If no comma is found, assume the string is raw base64- const commaIndex = base64.indexOf(',');- const startOffset = commaIndex !== -1 ? commaIndex + 1 : 0;-- // atob can take a portion of a string via substring/slice- // Most modern engines optimize slice() to be more memory-efficient than split()- const binaryString = window.atob(base64.slice(startOffset));-- const len = binaryString.length;- const bytes = new Uint8Array(len);+ const startOffset = base64.indexOf(',') + 1;+ const binaryString = window.atob(+ startOffset > 0 ? base64.slice(startOffset) : base64,+ );- for (let i = 0; i < len; i++) {+ const bytes = new Uint8Array(binaryString.length);+ for (let i = 0; i < binaryString.length; i++) {bytes[i] = binaryString.charCodeAt(i);}-return bytes;}-export function generateClipboardLink(url, name?) {- const htmlLink = `<a href="${url}">${name ? name : url}</a>`;- const cbi = [+/**+ * Generate clipboard items with link in HTML and plain text formats+ */+export function generateClipboardLink(+ url: string,+ name?: string,+): ClipboardItem[] {+ if (!url) {+ throw new Error('URL is required');+ }++ const linkText = name || url;+ const htmlLink = `<a href="${url}">${linkText}</a>`;+ const htmlMime = getMimeType('html') || 'text/html';+ const txtMime = getMimeType('txt') || 'text/plain';++ return [new ClipboardItem({- [getMimeType('html')]: new Blob([htmlLink], {- type: getMimeType('html'),- }),- [getMimeType('txt')]: new Blob([url], { type: getMimeType('txt') }),+ [htmlMime]: new Blob([htmlLink], { type: htmlMime }),+ [txtMime]: new Blob([url], { type: txtMime }),}),];- return cbi;}