TagSpaces is an offline, open source, document manager with tagging support
Creating new location do not change to the new folder (#2305)
Stanimir2b8641f21312
diff --git a/src/renderer/hooks/CurrentLocationContextProvider.tsx b/src/renderer/hooks/CurrentLocationContextProvider.tsxindex c2e418adb..b0a9402de 100644--- a/src/renderer/hooks/CurrentLocationContextProvider.tsx+++ b/src/renderer/hooks/CurrentLocationContextProvider.tsx@@ -356,7 +356,7 @@ export const CurrentLocationContextProvider = ({openAfterCreate = true,locationPosition: number = undefined,) {- allLocations.current = [...allLocations.current, location];+ //allLocations.current = [...allLocations.current, location];if (openAfterCreate) {openLocation(location);}@@ -369,9 +369,9 @@ export const CurrentLocationContextProvider = ({}function deleteLocationInt(locationId: string) {- allLocations.current = allLocations.current.filter(+ /* allLocations.current = allLocations.current.filter((l) => l.uuid !== locationId,- );+ );*/dispatch(LocationActions.deleteLocation(locationId));forceUpdate();}@@ -391,7 +391,7 @@ export const CurrentLocationContextProvider = ({return;}- // Create a copy of the array+ /* // Create a copy of the arrayconst newArray = [...allLocations.current];// Swap the location with the one above it@@ -399,7 +399,7 @@ export const CurrentLocationContextProvider = ({newArray[currentIndex] = newArray[currentIndex - 1];newArray[currentIndex - 1] = temp;- allLocations.current = newArray;+ allLocations.current = newArray;*/dispatch(LocationActions.moveLocationUp(locationUUID));}@@ -420,16 +420,16 @@ export const CurrentLocationContextProvider = ({) {return;}+ /*+ // Create a copy of the array+ const newArray = [...allLocations.current];- // Create a copy of the array- const newArray = [...allLocations.current];+ // Swap the location with the one below it+ const temp = newArray[currentIndex];+ newArray[currentIndex] = newArray[currentIndex + 1];+ newArray[currentIndex + 1] = temp;- // Swap the location with the one below it- const temp = newArray[currentIndex];- newArray[currentIndex] = newArray[currentIndex + 1];- newArray[currentIndex + 1] = temp;-- allLocations.current = newArray;+ allLocations.current = newArray;*/dispatch(LocationActions.moveLocationDown(locationUUID));}@@ -452,13 +452,13 @@ export const CurrentLocationContextProvider = ({if (currentIndex === -1) {throw new Error('Location not found');}+ /*+ // Remove the location from its current position+ const [location] = allLocations.current.splice(currentIndex, 1);- // Remove the location from its current position- const [location] = allLocations.current.splice(currentIndex, 1);-- // Insert the location at the specified new index- allLocations.current.splice(newIndex, 0, location);- allLocations.current = [...allLocations.current];+ // Insert the location at the specified new index+ allLocations.current.splice(newIndex, 0, location);+ allLocations.current = [...allLocations.current];*/dispatch(LocationActions.moveLocation(locationUUID, newIndex));}diff --git a/src/renderer/hooks/DirectoryContentContextProvider.tsx b/src/renderer/hooks/DirectoryContentContextProvider.tsxindex 97f23c245..96d621bfe 100644--- a/src/renderer/hooks/DirectoryContentContextProvider.tsx+++ b/src/renderer/hooks/DirectoryContentContextProvider.tsx@@ -43,7 +43,6 @@ import {import { TS } from '-/tagspaces.namespace';import { CommonLocation } from '-/utils/CommonLocation';import { arrayBufferToDataURL, updateHistory } from '-/utils/dom';-import { makeCancelable, useCancelable } from '-/utils/useCancelable';import useFirstRender from '-/utils/useFirstRender';import {cleanFrontDirSeparator,@@ -58,6 +57,7 @@ import {import { enhanceEntry, getUuid } from '@tagspaces/tagspaces-common/utils-io';import React, {createContext,+ useCallback,useEffect,useMemo,useReducer,@@ -65,6 +65,10 @@ import React, {} from 'react';import { useTranslation } from 'react-i18next';import { useDispatch, useSelector } from 'react-redux';+import {+ useCancelablePerLocation,+ makeCancelable,+} from '-/utils/useCancelablePerLocation';type DirectoryContentContextData = {currentLocationPath: string;@@ -216,6 +220,7 @@ export const DirectoryContentContextProvider = ({const {closeAllLocations,currentLocation,+ currentLocationId,findLocation,skipInitialDirList,getLocationPath,@@ -224,7 +229,6 @@ export const DirectoryContentContextProvider = ({const { metaActions, setReflectMetaActions } = useEditedEntryMetaContext();const { showNotification, hideNotifications } = useNotificationContext();const { selectedEntries, setSelectedEntries } = useSelectedEntriesContext();- const { signal, abort } = useCancelable();const currentLocationPath = useRef<string>('');//const useGenerateThumbnails = useSelector(getUseGenerateThumbnails);@@ -232,6 +236,8 @@ export const DirectoryContentContextProvider = ({const defaultPerspective = useSelector(getDefaultPerspective);const currentDirectoryEntries = useRef<TS.FileSystemEntry[]>([]);+ const { signal, abort, cancelAbort } =+ useCancelablePerLocation(currentLocationId);const searchQuery = useRef<TS.SearchQuery>({});const isSearchMode = useRef<boolean>(false);const manualPerspective = useRef<TS.PerspectiveType>('unspecified');@@ -243,7 +249,7 @@ export const DirectoryContentContextProvider = ({* undefined means no .ts folder exist*/const isMetaLoaded = useRef<boolean>(undefined);- const isLoading = useRef<boolean>(false);+ //const isLoading = useRef<boolean>(false);//const isMetaFolderExist = useRef<boolean>(undefined);const currentDirectoryPath = useRef<string>(undefined);const currentDirectoryFiles = useRef<TS.OrderVisibilitySettings[]>([]);@@ -310,19 +316,19 @@ export const DirectoryContentContextProvider = ({getLocationPath(currentLocation).then((locationPath) => {currentLocationPath.current = locationPath;if (!skipInitialDirList) {- if (isLoading.current) {+ /*if (isLoading.current) {//cancel loading KanBan S3 folders on location-folder changeabort();}- isLoading.current = true;+ isLoading.current = true;*/openDirectory(locationPath).then((success) => {manualPerspective.current = 'unspecified';- isLoading.current = false;+ //isLoading.current = false;return success;}).catch((ex) => {- isLoading.current = false;+ //isLoading.current = false;console.log('Error openDirectory:', ex);});}@@ -612,6 +618,7 @@ export const DirectoryContentContextProvider = ({}function setCurrentDirectoryEntries(dirEntries: TS.FileSystemEntry[]) {+ cancelAbort();if (dirEntries && dirEntries.length > 0) {currentDirectoryEntries.current = dirEntries; //[...dirEntries];forceUpdate();@@ -860,26 +867,40 @@ export const DirectoryContentContextProvider = ({* @param loadDirMeta* @param showHiddenEntries*/- function loadDirectoryContent(- directoryPath: string,- loadDirMeta = false,- showHiddenEntries = undefined,- ): Promise<TS.FileSystemEntry[]> {- // dispatch(actions.setIsLoading(true));+ const loadDirectoryContent = useCallback(+ (+ directoryPath: string,+ loadDirMeta = false,+ showHiddenEntries = undefined,+ ): Promise<TS.FileSystemEntry[]> => {+ if (selectedEntries.length > 0) {+ setSelectedEntries([]);+ }- if (selectedEntries.length > 0) {- setSelectedEntries([]);- }- if (loadDirMeta) {- return getDirMeta(directoryPath, currentLocation).then((meta) => {- if (meta) {- directoryMeta.current = meta;- } else {- directoryMeta.current = getDefaultDirMeta();- }- if (signal.aborted) {- return [];- }+ if (loadDirMeta) {+ return getDirMeta(directoryPath, currentLocation).then((meta) => {+ if (meta) {+ directoryMeta.current = meta;+ } else {+ directoryMeta.current = getDefaultDirMeta();+ }++ if (signal?.aborted) {+ return [];+ }++ return loadDirectoryContentInt(+ directoryPath,+ currentLocation,+ showHiddenEntries,+ ).then((entries) => {+ setCurrentDirectoryEntries(entries);+ return entries;+ });+ });+ } else {+ isMetaLoaded.current = false;+ directoryMeta.current = getDefaultDirMeta();return loadDirectoryContentInt(directoryPath,currentLocation,@@ -888,84 +909,67 @@ export const DirectoryContentContextProvider = ({setCurrentDirectoryEntries(entries);return entries;});- });- } else {- isMetaLoaded.current = false;- directoryMeta.current = getDefaultDirMeta();- return loadDirectoryContentInt(- directoryPath,- currentLocation,- showHiddenEntries,- ).then((entries) => {- setCurrentDirectoryEntries(entries);- return entries;- });- }- }+ }+ },+ [currentLocation, signal, selectedEntries, showUnixHiddenEntries],+ );- function loadDirectoryContentInt(- directoryPath: string,- location: CommonLocation,- showHiddenEntries = undefined,- ): Promise<TS.FileSystemEntry[]> {- showNotification(t('core:loading'), 'info', false);- const resultsLimit = {- maxLoops:- currentLocation && currentLocation.maxLoops- ? currentLocation.maxLoops- : AppConfig.maxLoops,- IsTruncated: false,- };- const promise = location- .listDirectoryPromise(- directoryPath,- [], // location.fullTextIndex ? ['extractTextContent'] : [],- currentLocation ? currentLocation.ignorePatternPaths : [],- resultsLimit,- )- .then((results) => {- if (signal.aborted) {+ const loadDirectoryContentInt = useCallback(+ (+ directoryPath: string,+ location: CommonLocation,+ showHiddenEntries = undefined,+ ): Promise<TS.FileSystemEntry[]> => {+ showNotification(t('core:loading'), 'info', false);++ const resultsLimit = {+ maxLoops: location?.maxLoops ?? AppConfig.maxLoops,+ IsTruncated: false,+ };++ const promise = location+ .listDirectoryPromise(+ directoryPath,+ [], // You can enhance this later for fullTextIndex+ location?.ignorePatternPaths ?? [],+ resultsLimit,+ )+ .then((results) => {+ if (signal?.aborted) return [];++ if (resultsLimit.IsTruncated) {+ openIsTruncatedConfirmDialog();+ }++ if (results !== undefined) {+ return loadDirectorySuccess(+ directoryPath,+ results,+ location,+ showHiddenEntries,+ );+ }return [];- }- if (resultsLimit.IsTruncated) {- openIsTruncatedConfirmDialog();- }- if (results !== undefined) {- // console.debug('app listDirectoryPromise resolved:' + results.length);- return loadDirectorySuccess(- directoryPath,- results,- location,- showHiddenEntries,- );- }- return [];- })- .catch((error) => {- // console.timeEnd('listDirectoryPromise');- return loadDirectoryFailure(error);- });- const cancelableFetch = makeCancelable(promise, signal);+ })+ .catch((error) => {+ return loadDirectoryFailure(error);+ });- return cancelableFetch- .then((response) => {- return response;- })- .catch((err) => {- if (err.name === 'AbortError') {- console.log('Upload was canceled');- } else {- console.error('Other error:', err);- }- return [];- });- /* return Promise.race([promise, uploadCancelled]).then(() => {- // useCancelable will call abort when unmounted. After listDirectoryPromise succeeded,- // we no longer care about that method of cancellation. Catch here to avoid an unhandled promise rejection.- uploadCancelled.catch(() => {});- return promise;- });*/- }+ const cancelableFetch = makeCancelable(promise, signal);++ return cancelableFetch+ .then((response) => response)+ .catch((err) => {+ if (err.name === 'AbortError') {+ console.log('cancelableFetch was canceled');+ } else {+ console.error('Other error:', err);+ }+ return [];+ });+ },+ [signal, showUnixHiddenEntries],+ );function clearDirectoryContent() {currentDirectoryPath.current = undefined;@@ -1085,17 +1089,18 @@ export const DirectoryContentContextProvider = ({showHiddenEntries !== undefined? showHiddenEntries: showUnixHiddenEntries;- dirEntries.map((entry) => {++ dirEntries.forEach((entry) => {if (!showHidden && entry.name.startsWith('.')) {- return true;+ return;}if (!showDirs && !entry.isFile) {- return true;+ return;}if (limit !== undefined && directoryContent.length >= limit) {- return true;+ return;}const enhancedEntry: TS.FileSystemEntry = enhanceEntry(@@ -1103,8 +1108,10 @@ export const DirectoryContentContextProvider = ({AppConfig.tagDelimiter,location?.getDirSeparator(),);- directoryContent.push({ ...enhancedEntry, locationID: location.uuid });- return true;+ directoryContent.push({+ ...enhancedEntry,+ locationID: location.uuid,+ });});return directoryContent;diff --git a/src/renderer/utils/useCancelable.ts b/src/renderer/utils/useCancelable.tsindex ccd6a42d9..c715d7723 100644--- a/src/renderer/utils/useCancelable.ts+++ b/src/renderer/utils/useCancelable.ts@@ -40,37 +40,3 @@ export const useCancelable = (): UseCancelableResult => {},};};--/**- * Wraps any Promise<T> so that it will reject with- * an AbortError when signal.abort() is called.- */-export function makeCancelable<T>(- promise: Promise<T>,- signal: AbortSignal,-): Promise<T> {- // 1) If already aborted, fail fast:- if (signal.aborted) {- return Promise.reject(new DOMException('Aborted', 'AbortError'));- }-- return new Promise<T>((resolve, reject) => {- // 2) Listener that rejects on abort:- const onAbort = () => {- reject(new DOMException('Aborted', 'AbortError'));- };-- signal.addEventListener('abort', onAbort, { once: true });-- // 3) When the real promise settles, clean up the abort listener:- promise- .then((value) => {- signal.removeEventListener('abort', onAbort);- resolve(value);- })- .catch((err) => {- signal.removeEventListener('abort', onAbort);- reject(err);- });- });-}diff --git a/src/renderer/utils/useCancelablePerLocation.ts b/src/renderer/utils/useCancelablePerLocation.tsnew file mode 100644index 000000000..05cae00fb--- /dev/null+++ b/src/renderer/utils/useCancelablePerLocation.ts@@ -0,0 +1,86 @@+/**+ * TagSpaces - universal file and folder organizer+ * Copyright (C) 2024-present TagSpaces GmbH+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License (version 3) as+ * published by the Free Software Foundation.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * https://usehooks-typescript.com/use-event-listener/+ * eslint-disable @typescript-eslint/ban-types+ */+import { useEffect, useRef } from 'react';++export function useCancelablePerLocation(locationUuid: string) {+ const controllerRef = useRef<AbortController | null>(null);++ useEffect(() => {+ if (locationUuid) {+ // Create a new AbortController for this location+ const controller = new AbortController();+ controllerRef.current = controller;++ return () => {+ // Cleanup: abort the fetch if the location changes or on unmount+ controller.abort();+ };+ } else {+ controllerRef.current = null;+ }+ }, [locationUuid]); // Re-run effect (and abort) only when UUID changes++ return {+ // Expose the signal and abort method for the current controller+ signal: controllerRef.current?.signal,+ abort: () => controllerRef.current?.abort(),+ cancelAbort: () => (controllerRef.current = null),+ };+}++/**+ * Wraps any Promise<T> so that it will reject with+ * an AbortError when signal.abort() is called.+ */+export function makeCancelable<T>(+ promise: Promise<T>,+ signal: AbortSignal,+): Promise<T> {+ // 1) If already aborted, fail fast:+ if (signal && signal.aborted) {+ return Promise.reject(new DOMException('Aborted', 'AbortError'));+ }++ return new Promise<T>((resolve, reject) => {+ // 2) Listener that rejects on abort:+ const onAbort = () => {+ reject(new DOMException('Aborted', 'AbortError'));+ };++ if (signal) {+ signal.addEventListener('abort', onAbort, { once: true });+ }++ // 3) When the real promise settles, clean up the abort listener:+ promise+ .then((value) => {+ if (signal) {+ signal.removeEventListener('abort', onAbort);+ }+ resolve(value);+ })+ .catch((err) => {+ if (signal) {+ signal.removeEventListener('abort', onAbort);+ }+ reject(err);+ });+ });+}