TagSpaces is an offline, open source, document manager with tagging support
Migration Redux to ContextProviders (#1989)
Stanimir8a6f801e9dc5
diff --git a/.github/workflows/pull_request.yml b/.github/workflows/pull_request.ymlindex 63508d928..d72053f64 100644--- a/.github/workflows/pull_request.yml+++ b/.github/workflows/pull_request.yml@@ -78,7 +78,7 @@ jobs:- name: Checkout TagspacesProuses: actions/checkout@v2with:- ref: develop+ ref: refactoring-directoryContentrepository: tagspaces/tagspacesprotoken: ${{ secrets.CHECKOUT_TSPRO }}path: extensions/tagspacesprodiff --git a/app/components/DirectoryListView.tsx b/app/components/DirectoryListView.tsxindex a8ac9679d..27f07ff92 100644--- a/app/components/DirectoryListView.tsx+++ b/app/components/DirectoryListView.tsx@@ -14,16 +14,14 @@ import { extractContainingDirectoryPath } from '@tagspaces/tagspaces-common/pathimport { getShowUnixHiddenEntries } from '-/reducers/settings';import AppConfig from '-/AppConfig';import { TS } from '-/tagspaces.namespace';-import {- actions as AppActions,- AppDispatch,- getCurrentLocationId-} from '-/reducers/app';+import { actions as AppActions, AppDispatch } from '-/reducers/app';import { ParentFolderIcon } from '-/components/CommonIcons';import { getLocations } from '-/reducers/locations';import PlatformIO from '-/services/platform-facade';import { Pro } from '-/pro';import { useTranslation } from 'react-i18next';+import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';+import { useLocationIndexContext } from '-/hooks/useLocationIndexContext';interface Props {setTargetDir: (dirPath: string) => void;@@ -32,10 +30,13 @@ interface Props {function DirectoryListView(props: Props) {const { currentDirectoryPath, setTargetDir } = props;const { t } = useTranslation();+ const { watchForChanges } = useLocationIndexContext();+ const { currentLocation } = useCurrentLocationContext();const locations: Array<TS.Location> = useSelector(getLocations);- const currentLocationId: string = useSelector(getCurrentLocationId);const showUnixHiddenEntries: boolean = useSelector(getShowUnixHiddenEntries);- const chosenLocationId = useRef<string>(currentLocationId);+ const chosenLocationId = useRef<string>(+ currentLocation ? currentLocation.uuid : undefined+ );const chosenDirectory = useRef<string>(currentDirectoryPath);const [directoryContent, setDirectoryContent] = useState<TS.FileSystemEntry[]@@ -47,7 +48,9 @@ function DirectoryListView(props: Props) {);if (chosenLocation) {const path =- chosenLocation.uuid === currentLocationId && currentDirectoryPath+ currentLocation &&+ chosenLocation.uuid === currentLocation.uuid &&+ currentDirectoryPath? currentDirectoryPath: chosenLocation.path;listDirectory(path);@@ -68,10 +71,10 @@ function DirectoryListView(props: Props) {};function getDirLocations() {- const currentLocation = locations.find(+ const chosenLocation = locations.find(location => location.uuid === chosenLocationId.current);- if (currentLocation.type !== locationType.TYPE_LOCAL) {+ if (chosenLocation.type !== locationType.TYPE_LOCAL) {return null;}return (@@ -181,7 +184,7 @@ function DirectoryListView(props: Props) {callback: newDirPath => {listDirectory(chosenDirectory.current);setTargetDir(newDirPath);- dispatch(AppActions.watchForChanges());+ watchForChanges();},reflect: false})diff --git a/app/components/DirectoryTreeView.tsx b/app/components/DirectoryTreeView.tsxindex a38b45bec..96b6330e6 100644--- a/app/components/DirectoryTreeView.tsx+++ b/app/components/DirectoryTreeView.tsx@@ -28,6 +28,8 @@ import TargetTableMoveFileBox from '-/components/TargetTableMoveFileBox';import { TS } from '-/tagspaces.namespace';import { actions as AppActions, AppDispatch } from '-/reducers/app';import { getShowUnixHiddenEntries } from '-/reducers/settings';+import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';+import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';interface Props {classes: any;@@ -45,6 +47,9 @@ export interface DirectoryTreeViewRef {const DirectoryTreeView = forwardRef((props: Props, ref: Ref<DirectoryTreeViewRef>) => {const { classes, location, handleFileMoveDrop } = props;+ const { openDirectory } = useDirectoryContentContext();+ const { changeLocation } = useCurrentLocationContext();+const [data, setData] = useState(undefined);const [isExpanded, setExpanded] = useState(false);const showUnixHiddenEntries = useSelector(getShowUnixHiddenEntries);@@ -162,9 +167,8 @@ const DirectoryTreeView = forwardRef(PlatformIO.enableObjectStoreSupport(subDir).then(() => {loadSubDirectories(subDir);- dispatch(AppActions.changeLocation(subDir));- dispatch(AppActions.loadDirectoryContent(subDir.path, true, true));- return true;+ changeLocation(subDir);+ return openDirectory(subDir.path);}).catch(error => {console.log('enableObjectStoreSupport', error);@@ -172,8 +176,8 @@ const DirectoryTreeView = forwardRef(} else if (subDir.type === locationType.TYPE_LOCAL) {PlatformIO.disableObjectStoreSupport();loadSubDirectories(subDir);- dispatch(AppActions.changeLocation(subDir));- dispatch(AppActions.loadDirectoryContent(subDir.path, true, true));+ changeLocation(subDir);+ openDirectory(subDir.path);}};diff --git a/app/components/EditDescription.tsx b/app/components/EditDescription.tsxindex 1316e4b0a..61c20c0da 100644--- a/app/components/EditDescription.tsx+++ b/app/components/EditDescription.tsx@@ -3,11 +3,11 @@ import { styled, useTheme } from '@mui/material/styles';import Typography from '@mui/material/Typography';import { MilkdownEditor, MilkdownRef } from '@tagspaces/tagspaces-md';import { useTranslation } from 'react-i18next';-import { useSelector } from 'react-redux';-import { getDirectoryPath, OpenedEntry } from '-/reducers/app';+import { OpenedEntry } from '-/reducers/app';import { useDescriptionContext } from '-/hooks/useDescriptionContext';import { useOpenedEntryContext } from '-/hooks/useOpenedEntryContext';import EditDescriptionButtons from '-/components/EditDescriptionButtons';+import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';const PREFIX = 'EditDescription';@@ -29,11 +29,11 @@ function EditDescription() {const { t } = useTranslation();const theme = useTheme();const { openedEntries } = useOpenedEntryContext();- const openedFile: OpenedEntry = openedEntries[0];- const currentFolder = useSelector(getDirectoryPath);- const fileDescriptionRef = useRef<MilkdownRef>(null);+ const { currentDirectoryPath } = useDirectoryContentContext();const { description, setDescription } = useDescriptionContext();+ const openedFile: OpenedEntry = openedEntries[0];+ const fileDescriptionRef = useRef<MilkdownRef>(null);const [editMode, setEditMode] = useState<boolean>(false);const descriptionFocus = useRef<boolean>(false);const descriptionButtonsRef = useRef(null);@@ -124,7 +124,7 @@ function EditDescription() {readOnly={!editMode}lightMode={false}excludePlugins={!editMode ? ['menu', 'upload'] : []}- currentFolder={currentFolder}+ currentFolder={currentDirectoryPath}/></>)}diff --git a/app/components/EditDescriptionButtons.tsx b/app/components/EditDescriptionButtons.tsxindex 549024f42..16c7491d3 100644--- a/app/components/EditDescriptionButtons.tsx+++ b/app/components/EditDescriptionButtons.tsx@@ -5,10 +5,9 @@ import { ProTooltip } from '-/components/HelperComponents';import { Pro } from '-/pro';import { convertMarkDown } from '-/services/utils-io';import { useTranslation } from 'react-i18next';-import { useSelector } from 'react-redux';-import { getDirectoryPath } from '-/reducers/app';import { useDescriptionContext } from '-/hooks/useDescriptionContext';import ConfirmDialog from '-/components/dialogs/ConfirmDialog';+import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';const PREFIX = 'EditDescriptionButtons';@@ -41,13 +40,13 @@ const EditDescriptionButtons: React.FC<Props> = ({setEditMode}) => {const { t } = useTranslation();- const currentFolder = useSelector(getDirectoryPath);const {description,isSaveDescriptionConfirmOpened,setSaveDescriptionConfirmOpened,saveDescription} = useDescriptionContext();+ const { currentDirectoryPath } = useDirectoryContentContext();const [isDescriptionChanged, descriptionChanged] = useState<boolean>(false);React.useImperativeHandle(buttonsRef, () => ({@@ -64,12 +63,12 @@ const EditDescriptionButtons: React.FC<Props> = ({const printHTML = () => {const sanitizedDescription = description- ? convertMarkDown(description, currentFolder)+ ? convertMarkDown(description, currentDirectoryPath): t('core:addMarkdownDescription');const printWin = window.open('', 'PRINT', 'height=400,width=600');printWin.document.write(- '<html><head><title>' + currentFolder + ' description</title>'+ '<html><head><title>' + currentDirectoryPath + ' description</title>');printWin.document.write('</head><body >');printWin.document.write(sanitizedDescription);diff --git a/app/components/EntryContainer.tsx b/app/components/EntryContainer.tsxindex 5756970ba..59814dfa1 100644--- a/app/components/EntryContainer.tsx+++ b/app/components/EntryContainer.tsx@@ -36,7 +36,6 @@ import Box from '@mui/material/Box';import ButtonGroup from '@mui/material/ButtonGroup';import { CancelIcon, CloseEditIcon } from '-/components/CommonIcons';import { getUuid } from '@tagspaces/tagspaces-common/utils-io';-import { buffer } from '@tagspaces/tagspaces-common/misc';import AppConfig from '-/AppConfig';import {extractContainingDirectoryPath,@@ -52,28 +51,23 @@ import {isRevisionsEnabled,getEntryContainerTab} from '-/reducers/settings';-import {- OpenedEntry,- NotificationTypes,- isReadOnlyMode,- actions as AppActions,- getDirectoryPath,- AppDispatch-} from '-/reducers/app';+import { OpenedEntry, AppDispatch } from '-/reducers/app';import useEventListener from '-/utils/useEventListener';import { TS } from '-/tagspaces.namespace';import FileView from '-/components/FileView';import { Pro } from '-/pro';import { Switch } from '@mui/material';-import useFirstRender from '-/utils/useFirstRender';import ResolveConflictDialog from '-/components/dialogs/ResolveConflictDialog';-import { styled, useTheme } from '@mui/material/styles';+import { useTheme } from '@mui/material/styles';import EntryContainerTabs from '-/components/EntryContainerTabs';import EntryContainerNav from '-/components/EntryContainerNav';import EntryContainerTitle from '-/components/EntryContainerTitle';import { useTranslation } from 'react-i18next';import { useDescriptionContext } from '-/hooks/useDescriptionContext';import { useOpenedEntryContext } from '-/hooks/useOpenedEntryContext';+import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';+import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';+import { useNotificationContext } from '-/hooks/useNotificationContext';//const defaultSplitSize = '7.86%'; // '7.2%'; // 103;// const bufferedSplitResize = buffer({@@ -95,12 +89,17 @@ function EntryContainer() {reloadOpenedFile} = useOpenedEntryContext();const { saveDescription } = useDescriptionContext();+ const {+ readOnlyMode,+ switchLocationTypeByID,+ switchCurrentLocationType+ } = useCurrentLocationContext();+ const { openDirectory, currentDirectoryPath } = useDirectoryContentContext();+ const { showNotification } = useNotificationContext();const tabIndex = useSelector(getEntryContainerTab);- const currentDirectoryPath = useSelector(getDirectoryPath);const fileEditHistoryKey = useSelector((state: any) => state.settings[historyKeys.fileEditKey]);- const readOnlyMode = useSelector(isReadOnlyMode);const keyBindings = useSelector(getKeyBindingObject);const desktopMode = useSelector(isDesktopMode);const revisionsEnabled = useSelector(isRevisionsEnabled);@@ -311,9 +310,7 @@ function EntryContainer() {if (data.message) {message = message + ': ' + data.message;}- dispatch(- AppActions.showNotification(message, NotificationTypes.default)- );+ showNotification(message);break;case 'saveDocument':savingFile(data.force !== undefined ? data.force : false);@@ -351,7 +348,7 @@ function EntryContainer() {// if (!this.state.currentEntry.isFile) {// textFilePath += '/index.html';// }- dispatch(AppActions.switchLocationTypeByID(openedFile.locationId)).then(+ switchLocationTypeByID(openedFile.locationId).then(currentLocationId => {PlatformIO.loadTextFilePromise(textFilePath,@@ -392,19 +389,11 @@ function EntryContainer() {theme.palette.mode);}- if (currentLocationId) {- return dispatch(- AppActions.switchCurrentLocationType(currentLocationId)- );- }+ return switchCurrentLocationType();}).catch(err => {console.warn('Error loading text content ' + err);- if (currentLocationId) {- return dispatch(- AppActions.switchCurrentLocationType(currentLocationId)- );- }+ return switchCurrentLocationType();});});@@ -531,23 +520,19 @@ function EntryContainer() {};const override = (): Promise<boolean> => {- return dispatch(- AppActions.switchLocationTypeByID(openedFile.locationId)- ).then(currentLocationId =>+ return switchLocationTypeByID(openedFile.locationId).then(() =>PlatformIO.getPropertiesPromise(openedFile.path).then((entryProp: TS.FileSystemEntry) =>save({ ...openedFile, lmdt: entryProp.lmdt }).then(() =>- dispatch(AppActions.switchCurrentLocationType(currentLocationId))+ switchCurrentLocationType())));};const saveAs = (newFilePath: string): Promise<boolean> => {- return dispatch(- AppActions.switchLocationTypeByID(openedFile.locationId)- ).then(currentLocationId =>+ return switchLocationTypeByID(openedFile.locationId).then(() =>PlatformIO.copyFilePromise(openedFile.path, newFilePath).then(() =>PlatformIO.getPropertiesPromise(newFilePath).then((entryProp: TS.FileSystemEntry) =>@@ -560,18 +545,15 @@ function EntryContainer() {entryProp.path);if (currentDirectoryPath === openedFileDir) {- dispatch(- AppActions.loadDirectoryContent(openedFileDir, true, true)- ); /*+ openDirectory(openedFileDir);+ /*updateOpenedFile(openedFile.path, {...openedFile,editMode: false,shouldReload: !openedFile.shouldReload});*/}- return dispatch(- AppActions.switchCurrentLocationType(currentLocationId)- );+ return switchCurrentLocationType();})))@@ -579,12 +561,8 @@ function EntryContainer() {};const saveFile = (): Promise<boolean> => {- return dispatch(- AppActions.switchLocationTypeByID(openedFile.locationId)- ).then(currentLocationId =>- save(openedFile).then(() =>- dispatch(AppActions.switchCurrentLocationType(currentLocationId))- )+ return switchLocationTypeByID(openedFile.locationId).then(() =>+ save(openedFile).then(() => switchCurrentLocationType()));};@@ -641,18 +619,14 @@ function EntryContainer() {}const editOpenedFile = () => {- dispatch(AppActions.switchLocationTypeByID(openedFile.locationId)).then(- currentLocationId => {- updateOpenedFile(openedFile.path, {- id: '',- ...openedFile,- editMode: true,- shouldReload: undefined- }).then(() => {- dispatch(AppActions.switchCurrentLocationType(currentLocationId));- });- }- );+ switchLocationTypeByID(openedFile.locationId).then(() => {+ updateOpenedFile(openedFile.path, {+ id: '',+ ...openedFile,+ editMode: true,+ shouldReload: undefined+ }).then(() => switchCurrentLocationType());+ });};/*const setPercent = (p: number | undefined) => {@@ -702,24 +676,17 @@ function EntryContainer() {const toggleAutoSave = (event: React.ChangeEvent<HTMLInputElement>) => {const autoSave = event.target.checked;if (Pro && Pro.MetaOperations) {- dispatch(AppActions.switchLocationTypeByID(openedFile.locationId)).then(- currentLocationId => {- Pro.MetaOperations.saveFsEntryMeta(openedFile.path, {- autoSave- }).then(entryMeta => {- updateOpenedFile(openedFile.path, entryMeta).then(() => {- dispatch(AppActions.switchCurrentLocationType(currentLocationId));- });- });- }- );+ switchLocationTypeByID(openedFile.locationId).then(currentLocationId => {+ Pro.MetaOperations.saveFsEntryMeta(openedFile.path, {+ autoSave+ }).then(entryMeta => {+ updateOpenedFile(openedFile.path, entryMeta).then(() =>+ switchCurrentLocationType()+ );+ });+ });} else {- dispatch(- AppActions.showNotification(- t('core:thisFunctionalityIsAvailableInPro'),- NotificationTypes.default- )- );+ showNotification(t('core:thisFunctionalityIsAvailableInPro'));}};diff --git a/app/components/EntryContainerMenu.tsx b/app/components/EntryContainerMenu.tsxindex 7435ebdd8..5b6e01eb7 100644--- a/app/components/EntryContainerMenu.tsx+++ b/app/components/EntryContainerMenu.tsx@@ -16,8 +16,6 @@ import {import {actions as AppActions,AppDispatch,- isReadOnlyMode,- NotificationTypes,OpenedEntry} from '-/reducers/app';import { useDispatch, useSelector } from 'react-redux';@@ -38,6 +36,9 @@ import ConfirmDialog from '-/components/dialogs/ConfirmDialog';import { isDesktopMode } from '-/reducers/settings';import { useTranslation } from 'react-i18next';import { useOpenedEntryContext } from '-/hooks/useOpenedEntryContext';+import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';+import { useFsActionsContext } from '-/hooks/useFsActionsContext';+import { useNotificationContext } from '-/hooks/useNotificationContext';interface Props {anchorEl: null | HTMLElement;@@ -61,8 +62,10 @@ function EntryContainerMenu(props: Props) {} = props;const { t } = useTranslation();// const theme = useTheme();- const { toggleEntryFullWidth } = useOpenedEntryContext();- const readOnlyMode = useSelector(isReadOnlyMode);+ const { toggleEntryFullWidth, openLink } = useOpenedEntryContext();+ const { readOnlyMode } = useCurrentLocationContext();+ const { deleteFile } = useFsActionsContext();+ const { showNotification } = useNotificationContext();const desktopMode = useSelector(isDesktopMode);const dispatch: AppDispatch = useDispatch();@@ -115,12 +118,7 @@ function EntryContainerMenu(props: Props) {downloadCordova(openedEntry.url, entryName);} else {console.log('Can only download HTTP/HTTPS URIs');- dispatch(- AppActions.showNotification(- t('core:cantDownloadLocalFile'),- NotificationTypes.default- )- );+ showNotification(t('core:cantDownloadLocalFile'));}} else {const downloadLink = document.getElementById('downloadFile');@@ -155,9 +153,9 @@ function EntryContainerMenu(props: Props) {const navigateToFolder = () => {if (openedEntry.isFile) {- dispatch(AppActions.openLink(sharingParentFolderLink));+ openLink(sharingParentFolderLink);} else {- dispatch(AppActions.openLink(sharingLink));+ openLink(sharingLink);}handleClose();};@@ -177,7 +175,7 @@ function EntryContainerMenu(props: Props) {if (openedEntry.isFile) {dispatch(AppActions.openFileNatively(openedEntry.path));} else {- dispatch(AppActions.openDirectory(openedEntry.path));+ PlatformIO.openDirectory(openedEntry.path);}}handleClose();@@ -483,9 +481,7 @@ function EntryContainerMenu(props: Props) {}confirmCallback={result => {if (result) {- dispatch(- AppActions.deleteFile(openedEntry.path, openedEntry.uuid)- );+ return deleteFile(openedEntry.path, openedEntry.uuid);}}}cancelDialogTID="cancelSaveBeforeCloseDialog"diff --git a/app/components/EntryContainerTabs.tsx b/app/components/EntryContainerTabs.tsxindex 3b2bfed60..a0f0eda90 100644--- a/app/components/EntryContainerTabs.tsx+++ b/app/components/EntryContainerTabs.tsx@@ -25,12 +25,10 @@ import Box from '@mui/material/Box';import {actions as AppActions,AppDispatch,- isReadOnlyMode,OpenedEntry} from '-/reducers/app';import Revisions from '-/components/Revisions';import EntryProperties from '-/components/EntryProperties';-import { TS } from '-/tagspaces.namespace';import {actions as SettingsActions,getEntryContainerTab,@@ -124,7 +122,6 @@ function EntryContainerTabs(props: EntryContainerTabsProps) {const { t } = useTranslation();const theme = useTheme();const tabIndex = useSelector(getEntryContainerTab);- const readOnlyMode = useSelector(isReadOnlyMode);const tileServer = useSelector(getMapTileServer);const desktopMode = useSelector(isDesktopMode);const dispatch: AppDispatch = useDispatch();@@ -154,9 +151,6 @@ function EntryContainerTabs(props: EntryContainerTabsProps) {}// Create functions that dispatch actions- const handleRenameFile = (filePath: string, newFilePath: string) =>- dispatch(AppActions.renameFile(filePath, newFilePath));-const handleChange = (event: React.SyntheticEvent, newValue: number) => {dispatch(SettingsActions.setEntryContainerTab(newValue));openPanel();@@ -225,12 +219,7 @@ function EntryContainerTabs(props: EntryContainerTabsProps) {</StyledTabs></Box><TsTabPanel value={selectedTabIndex} index={0}>- <EntryProperties- key={openedFile.path}- renameFile={handleRenameFile}- isReadOnlyMode={readOnlyMode}- tileServer={tileServer}- />+ <EntryProperties key={openedFile.path} tileServer={tileServer} /></TsTabPanel><TsTabPanel value={selectedTabIndex} index={1}><EditDescription />diff --git a/app/components/EntryContainerTitle.tsx b/app/components/EntryContainerTitle.tsxindex 9b41eec54..644821da3 100644--- a/app/components/EntryContainerTitle.tsx+++ b/app/components/EntryContainerTitle.tsx@@ -24,18 +24,12 @@ import {extractFileName,extractDirectoryName} from '@tagspaces/tagspaces-common/paths';-import {- actions as AppActions,- AppDispatch,- NotificationTypes,- OpenedEntry-} from '-/reducers/app';import Tooltip from '-/components/Tooltip';import PlatformIO from '-/services/platform-facade';import { FolderIcon, MoreMenuIcon } from '-/components/CommonIcons';import AppConfig from '-/AppConfig';import EntryContainerMenu from '-/components/EntryContainerMenu';-import { useDispatch, useSelector } from 'react-redux';+import { useSelector } from 'react-redux';import { getLocations } from '-/reducers/locations';import Box from '@mui/material/Box';import { dataTidFormat } from '-/services/test';@@ -47,6 +41,7 @@ import TagsPreview from '-/components/TagsPreview';import { Pro } from '-/pro';import { useTranslation } from 'react-i18next';import { useOpenedEntryContext } from '-/hooks/useOpenedEntryContext';+import { useNotificationContext } from '-/hooks/useNotificationContext';const FileBadge = styled('span')(({ theme }) => ({color: 'white',@@ -73,8 +68,8 @@ function EntryContainerTitle(props: Props) {sharingLink,sharingParentFolderLink} = useOpenedEntryContext();+ const { showNotification } = useNotificationContext();const openedFile = openedEntries[0];- const dispatch: AppDispatch = useDispatch();const locations = useSelector(getLocations);const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);const [ignored, forceUpdate] = useReducer(x => x + 1, 0);@@ -91,13 +86,10 @@ function EntryContainerTitle(props: Props) {}forceUpdate();} else {- dispatch(- AppActions.showNotification(- t('core:toggleBookmark') +- ' - ' +- t('thisFunctionalityIsAvailableInPro'),- NotificationTypes.default- )+ showNotification(+ t('core:toggleBookmark') ++ ' - ' ++ t('thisFunctionalityIsAvailableInPro'));}};diff --git a/app/components/EntryProperties.tsx b/app/components/EntryProperties.tsxindex e12fa5b05..59be4ad22 100644--- a/app/components/EntryProperties.tsx+++ b/app/components/EntryProperties.tsx@@ -101,6 +101,9 @@ import { useTranslation } from 'react-i18next';import { useOpenedEntryContext } from '-/hooks/useOpenedEntryContext';import { useTaggingActionsContext } from '-/hooks/useTaggingActionsContext';import { useFsActionsContext } from '-/hooks/useFsActionsContext';+import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';+import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';+import { useNotificationContext } from '-/hooks/useNotificationContext';const PREFIX = 'EntryProperties';@@ -190,13 +193,6 @@ const BgndImgChooserDialog =interface Props {locations: Array<TS.Location>;- renameFile: (path: string, nextPath: string) => Promise<boolean>;- showNotification: (message: string) => void;- updateThumbnailUrl: (path: string, thumbUrl: string) => void;- switchLocationType: (locationId: string) => Promise<string | null>;- switchCurrentLocationType: (currentLocationId: string) => Promise<boolean>;- isReadOnlyMode: boolean;- // currentDirectoryPath: string | null;tagDelimiter: string;tileServer: TS.MapTileServer;lastBackgroundImageChange: any;@@ -223,8 +219,20 @@ function EntryProperties(props: Props) {updateOpenedFile,sharingLink} = useOpenedEntryContext();- const { renameDirectory } = useFsActionsContext();+ const { renameDirectory, renameFile } = useFsActionsContext();const { addTags, removeTags, removeAllTags } = useTaggingActionsContext();+ const {+ currentDirectoryPath,+ updateThumbnailUrl,+ setDirectoryMeta+ } = useDirectoryContentContext();+ const {+ switchLocationTypeByID,+ switchCurrentLocationType,+ readOnlyMode+ } = useCurrentLocationContext();+ const { showNotification } = useNotificationContext();+const fileNameRef = useRef<HTMLInputElement>(null);const sharingLinkRef = useRef<HTMLInputElement>(null);// const fileDescriptionRef = useRef<MilkdownRef>(null);@@ -323,46 +331,36 @@ function EntryProperties(props: Props) {const renameEntry = () => {if (editName !== undefined) {- const { renameFile } = props;-const path = extractContainingDirectoryPath(currentEntry.current.path,PlatformIO.getDirSeparator());const nextPath = path + PlatformIO.getDirSeparator() + editName;- props- .switchLocationType(openedEntry.locationId)- .then(currentLocationId => {- if (currentEntry.current.isFile) {- renameFile(currentEntry.current.path, nextPath)- .then(() => {- props.switchCurrentLocationType(currentLocationId);- return true;- })- .catch(() => {- props.switchCurrentLocationType(currentLocationId);- fileNameRef.current.value = entryName;- });- } else {- renameDirectory(currentEntry.current.path, editName)- .then(newDirPath => {- props.switchCurrentLocationType(currentLocationId);- return true;- })- .catch(() => {- props.switchCurrentLocationType(currentLocationId);- fileNameRef.current.value = entryName;- });- }- });+ switchLocationTypeByID(openedEntry.locationId).then(currentLocationId => {+ if (currentEntry.current.isFile) {+ renameFile(currentEntry.current.path, nextPath)+ .then(() => switchCurrentLocationType())+ .catch(() => {+ switchCurrentLocationType();+ fileNameRef.current.value = entryName;+ });+ } else {+ renameDirectory(currentEntry.current.path, editName)+ .then(newDirPath => switchCurrentLocationType())+ .catch(() => {+ switchCurrentLocationType();+ fileNameRef.current.value = entryName;+ });+ }+ });setEditName(undefined);}};const activateEditNameField = () => {- if (props.isReadOnlyMode) {+ if (readOnlyMode) {setEditName(undefined);return;}@@ -386,7 +384,7 @@ function EntryProperties(props: Props) {const toggleThumbFilesDialog = () => {if (!Pro) {- props.showNotification(t('core:thisFunctionalityIsAvailableInPro'));+ showNotification(t('core:thisFunctionalityIsAvailableInPro'));return true;}if (!currentEntry.current.editMode && editName === undefined) {@@ -396,7 +394,7 @@ function EntryProperties(props: Props) {const toggleBgndImgDialog = () => {if (!Pro) {- props.showNotification(t('core:thisFunctionalityIsAvailableInPro'));+ showNotification(t('core:thisFunctionalityIsAvailableInPro'));return true;}if (!currentEntry.current.editMode && editName === undefined) {@@ -406,14 +404,13 @@ function EntryProperties(props: Props) {const setThumb = (filePath, thumbFilePath) => {if (filePath !== undefined) {- return props- .switchLocationType(openedEntry.locationId)- .then(currentLocationId => {+ return switchLocationTypeByID(openedEntry.locationId).then(+ currentLocationId => {if (PlatformIO.haveObjectStoreSupport() ||PlatformIO.haveWebDavSupport()) {- props.updateThumbnailUrl(+ updateThumbnailUrl(currentEntry.current.path,PlatformIO.getURLforPath(thumbFilePath));@@ -421,7 +418,7 @@ function EntryProperties(props: Props) {}/*return replaceThumbnailURLPromise(filePath, thumbFilePath).then(objUrl => {*/- props.updateThumbnailUrl(+ updateThumbnailUrl(currentEntry.current.path,thumbFilePath// objUrl.tmbPath@@ -429,38 +426,33 @@ function EntryProperties(props: Props) {? '?' + props.lastThumbnailImageChange: '')*/);- return props.switchCurrentLocationType(currentLocationId);- /*})- .catch(err => {- props.switchCurrentLocationType();- console.warn('Error replaceThumbnailURLPromise ' + err);- props.showNotification('Error replacing thumbnail');- });*/- });+ return switchCurrentLocationType();+ }+ );} else {// reset Thumbnailreturn getThumbnailURLPromise(currentEntry.current.path).then(objUrl => {- props.updateThumbnailUrl(currentEntry.current.path, objUrl.tmbPath);+ updateThumbnailUrl(currentEntry.current.path, objUrl.tmbPath);return true;}).catch(err => {console.warn('Error getThumbnailURLPromise ' + err);- props.showNotification('Error reset Thumbnail');+ showNotification('Error reset Thumbnail');});}};const toggleBackgroundColorPicker = () => {- if (props.isReadOnlyMode) {+ if (readOnlyMode) {return;}if (!Pro) {- props.showNotification(t('core:thisFunctionalityIsAvailableInPro'));+ showNotification(t('core:thisFunctionalityIsAvailableInPro'));return;}if (!Pro.MetaOperations) {- props.showNotification(t('Saving color not supported'));+ showNotification(t('Saving color not supported'));return;}setDisplayColorPicker(!displayColorPicker);@@ -472,17 +464,20 @@ function EntryProperties(props: Props) {color = 'transparent';}currentEntry.current.color = color;- props.switchLocationType(openedEntry.locationId).then(currentLocationId => {+ switchLocationTypeByID(openedEntry.locationId).then(currentLocationId => {Pro.MetaOperations.saveFsEntryMeta(currentEntry.current.path, { color }).then(entryMeta => {- // if (props.entryPath === props.currentDirectoryPath) {+ if (currentEntry.current.path === currentDirectoryPath) {+ setDirectoryMeta(entryMeta);+ }+ // for KanBanprops.setLastBackgroundColorChange(currentEntry.current.path,new Date().getTime());// todo handle LastBackgroundColorChange and skip updateOpenedFileupdateOpenedFile(currentEntry.current.path, entryMeta).then(() =>- props.switchCurrentLocationType(currentLocationId)+ switchCurrentLocationType());/* } else {@@ -491,9 +486,9 @@ function EntryProperties(props: Props) {return true;}).catch(error => {- props.switchCurrentLocationType(currentLocationId);+ switchCurrentLocationType();console.warn('Error saving color for folder ' + error);- props.showNotification(t('Error saving color for folder'));+ showNotification(t('Error saving color for folder'));});});};@@ -528,7 +523,7 @@ function EntryProperties(props: Props) {};*/const handleChange = (name: string, value: Array<TS.Tag>, action: string) => {- props.switchLocationType(openedEntry.locationId).then(currentLocationId => {+ switchLocationTypeByID(openedEntry.locationId).then(currentLocationId => {if (action === 'remove-value') {if (!value) {// no tags left in the select element@@ -537,18 +532,18 @@ function EntryProperties(props: Props) {id: '',tags: []}).then(() => {- props.switchCurrentLocationType(currentLocationId);+ switchCurrentLocationType();});});} else {- removeTags([currentEntry.current.path], value).then(() => {- props.switchCurrentLocationType(currentLocationId);- });+ removeTags([currentEntry.current.path], value).then(() =>+ switchCurrentLocationType()+ );}} else if (action === 'clear') {- removeAllTags([currentEntry.current.path]).then(() => {- props.switchCurrentLocationType(currentLocationId);- });+ removeAllTags([currentEntry.current.path]).then(() =>+ switchCurrentLocationType()+ );} else {// create-option or select-optionconst tags =@@ -561,14 +556,12 @@ function EntryProperties(props: Props) {));return addTags([currentEntry.current.path], tags).then(() =>- props.switchCurrentLocationType(currentLocationId)+ switchCurrentLocationType());}});};- const { isReadOnlyMode } = props;-if (!currentEntry ||!currentEntry.current.path ||@@ -656,7 +649,7 @@ function EntryProperties(props: Props) {}).catch(error => {console.warn('Error saving perspective for folder ' + error);- props.showNotification(t('Error saving perspective for folder'));+ showNotification(t('Error saving perspective for folder'));});};@@ -716,7 +709,7 @@ function EntryProperties(props: Props) {readOnly: editName === undefined,endAdornment: (<InputAdornment position="end">- {!isReadOnlyMode && !currentEntry.current.editMode && (+ {!readOnlyMode && !currentEntry.current.editMode && (<div style={{ textAlign: 'right' }}>{editName !== undefined ? (<div>@@ -784,11 +777,11 @@ function EntryProperties(props: Props) {label={t('core:fileTags')}dataTid="PropertiesTagsSelectTID"placeholderText={t('core:dropHere')}- isReadOnlyMode={+ /*isReadOnlyMode={isReadOnlyMode ||currentEntry.current.editMode ||editName !== undefined- }+ }*/tags={currentEntry.current.tags}tagMode="default"handleChange={handleChange}@@ -969,7 +962,7 @@ function EntryProperties(props: Props) {),endAdornment: (<InputAdornment position="end">- {!isReadOnlyMode &&+ {!readOnlyMode &&!currentEntry.current.editMode &&editName === undefined && (<Button@@ -1026,7 +1019,7 @@ function EntryProperties(props: Props) {const promise = navigator.clipboard.writeText(sharingLink);- props.showNotification(t('core:linkCopied'));+ showNotification(t('core:linkCopied'));}}>{t('core:copy')}@@ -1187,7 +1180,7 @@ function EntryProperties(props: Props) {spacing={1}style={{ alignItems: 'center' }}>- {!isReadOnlyMode &&+ {!readOnlyMode &&!currentEntry.current.editMode &&editName === undefined && (<ProTooltip tooltip={t('changeThumbnail')}>@@ -1245,7 +1238,7 @@ function EntryProperties(props: Props) {spacing={1}style={{ alignItems: 'center' }}>- {!isReadOnlyMode &&+ {!readOnlyMode &&!currentEntry.current.editMode &&editName === undefined && (<ProTooltip tooltip={t('changeBackgroundImage')}>@@ -1341,10 +1334,7 @@ function EntryProperties(props: Props) {open={showSharingLinkDialog}onClose={() => setShowSharingLinkDialog(false)}path={currentEntry.current.path}- // showNotification={props.showNotification}locationId={currentEntry.current.locationId}- switchCurrentLocationType={props.switchCurrentLocationType}- switchLocationType={props.switchLocationType}/>)}{BgndImgChooserDialog && (@@ -1403,12 +1393,8 @@ function mapStateToProps(state) {function mapActionCreatorsToProps(dispatch) {return bindActionCreators({- switchLocationType: LocationActions.switchLocationType,- switchCurrentLocationType: AppActions.switchCurrentLocationType,setLastBackgroundColorChange: AppActions.setLastBackgroundColorChange,- setSelectedEntries: AppActions.setSelectedEntries,- updateThumbnailUrl: AppActions.updateThumbnailUrl,- showNotification: AppActions.showNotification+ setSelectedEntries: AppActions.setSelectedEntries},dispatch);diff --git a/app/components/FileUploadContainer.tsx b/app/components/FileUploadContainer.tsxindex a4f1a1f7b..415aa1156 100644--- a/app/components/FileUploadContainer.tsx+++ b/app/components/FileUploadContainer.tsx@@ -20,7 +20,7 @@ import React, { forwardRef, Ref, useImperativeHandle, useRef } from 'react';import { useDispatch } from 'react-redux';import { TS } from '-/tagspaces.namespace';import { actions as AppActions, AppDispatch } from '-/reducers/app';-import IOActions from '-/reducers/io-actions';+import { useIOActionsContext } from '-/hooks/useIOActionsContext';interface Props {id: string;@@ -36,6 +36,7 @@ const FileUploadContainer = forwardRef((props: Props, ref: Ref<FileUploadContainerRef>) => {const dispatch: AppDispatch = useDispatch();const { id, directoryPath } = props;+ const { uploadFilesAPI } = useIOActionsContext();const onUploadProgress = (progress, abort, fileName) => {dispatch(AppActions.onUploadProgress(progress, abort, fileName));@@ -86,12 +87,10 @@ const FileUploadContainer = forwardRef(// const file = selection.currentTarget.files[0];dispatch(AppActions.resetProgress());dispatch(AppActions.toggleUploadDialog());- dispatch(- IOActions.uploadFilesAPI(- Array.from(selection.currentTarget.files),- directoryPath,- onUploadProgress- )+ uploadFilesAPI(+ Array.from(selection.currentTarget.files),+ directoryPath,+ onUploadProgress).then((fsEntries: Array<TS.FileSystemEntry>) => {dispatch(AppActions.reflectCreateEntries(fsEntries));diff --git a/app/components/FileView.tsx b/app/components/FileView.tsxindex fd07936fd..1d35ed11a 100644--- a/app/components/FileView.tsx+++ b/app/components/FileView.tsx@@ -17,14 +17,12 @@*/import React, { MutableRefObject } from 'react';-import { useSelector } from 'react-redux';import { rgbToHex, useTheme } from '@mui/material/styles';import CloseIcon from '@mui/icons-material/Close';import { OpenedEntry } from '-/reducers/app';import useEventListener from '-/utils/useEventListener';-import { getSearchQuery } from '-/reducers/location-index';-import { TS } from '-/tagspaces.namespace';import { useTranslation } from 'react-i18next';+import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';interface Props {openedFile: OpenedEntry;@@ -39,7 +37,6 @@ interface Props {function FileView(props: Props) {const { i18n } = useTranslation();const theme = useTheme();- const searchQuery = useSelector(getSearchQuery);const {openedFile,fileViewer,@@ -50,6 +47,8 @@ function FileView(props: Props) {eventID} = props; // .openedFiles[0];+ const { searchQuery } = useDirectoryContentContext();+useEventListener('toggle-resume', () => {if (fileViewer &&diff --git a/app/components/FolderContainer.tsx b/app/components/FolderContainer.tsxindex 61e92cfc4..bc0345efd 100644--- a/app/components/FolderContainer.tsx+++ b/app/components/FolderContainer.tsx@@ -16,16 +16,15 @@**/-import React, { useCallback, useEffect, useState } from 'react';+import React, { useCallback, useState } from 'react';import { useTheme } from '@mui/material/styles';-import { connect, useSelector } from 'react-redux';+import { connect } from 'react-redux';import { bindActionCreators } from 'redux';import IconButton from '@mui/material/IconButton';import Box from '@mui/material/Box';import CircularProgress from '@mui/material/CircularProgress';import Tooltip from '-/components/Tooltip';import Typography from '@mui/material/Typography';-import InputAdornment from '@mui/material/InputAdornment';import ToggleButton from '@mui/material/ToggleButton';import ToggleButtonGroup from '@mui/material/ToggleButtonGroup';import AppConfig from '-/AppConfig';@@ -37,16 +36,9 @@ import {} from '-/reducers/settings';import {actions as AppActions,- getDirectoryContent,- isReadOnlyMode,- getCurrentDirectoryPerspective,getSelectedEntries,- getProgress,- isSearchMode,- getLastSearchTimestamp,- getDirectoryPath+ getProgress} from '../reducers/app';-import LoadingLazy from '../components/LoadingLazy';import {GoBackIcon,GoForwardIcon,@@ -57,140 +49,36 @@ import { Pro } from '../pro';import RenameEntryDialog from '-/components/dialogs/RenameEntryDialog';import { TS } from '-/tagspaces.namespace';import PathBreadcrumbs from './PathBreadcrumbs';-import { enhanceOpenedEntry } from '-/services/utils-io';-import {- actions as LocationIndexActions,- getSearchQuery-} from '-/reducers/location-index';import { PerspectiveIDs, AvailablePerspectives } from '-/perspectives';-import MainSearchField from '-/components/MainSearchField';// import LoadingAnimation from '-/components/LoadingAnimation';import SearchBox from '-/components/SearchBox';-import useFirstRender from '-/utils/useFirstRender';import { useTranslation } from 'react-i18next';-import { SortedDirContextProvider } from '-/perspectives/grid-perspective/hooks/SortedDirContextProvider';import { useOpenedEntryContext } from '-/hooks/useOpenedEntryContext';--const GridPerspective = React.lazy(() =>- import(- /* webpackChunkName: "GridPerspective" */ '../perspectives/grid-perspective'- )-);-function GridPerspectiveAsync(props) {- return (- <React.Suspense fallback={<LoadingLazy />}>- <SortedDirContextProvider>- <GridPerspective {...props} />- </SortedDirContextProvider>- </React.Suspense>- );-}--const ListPerspective = React.lazy(() =>- import(/* webpackChunkName: "ListPerspective" */ '../perspectives/list')-);-function ListPerspectiveAsync(props) {- return (- <React.Suspense fallback={<LoadingLazy />}>- <SortedDirContextProvider>- <ListPerspective {...props} />- </SortedDirContextProvider>- </React.Suspense>- );-}--let GalleryPerspective = React.Fragment;-if (Pro && Pro.Perspectives && Pro.Perspectives.GalleryPerspective) {- // GalleryPerspective = React.lazy(() => import(/* webpackChunkName: "GalleryPerspective" */ '../node_modules/@tagspaces/pro/modules/perspectives/gallery'));-- GalleryPerspective = Pro.Perspectives.GalleryPerspective;-}-function GalleryPerspectiveAsync(props) {- return (- <React.Suspense fallback={<LoadingLazy />}>- <GalleryPerspective {...props} />- </React.Suspense>- );-}--let MapiquePerspective = React.Fragment;-if (Pro && Pro.Perspectives && Pro.Perspectives.MapiquePerspective) {- // MapiquePerspective = React.lazy(() => import(/* webpackChunkName: "MapiquePerspective" */ '../node_modules/@tagspaces/pro/modules/perspectives/mapique'));- MapiquePerspective = Pro.Perspectives.MapiquePerspective;-}-function MapiquePerspectiveAsync(props) {- return (- <React.Suspense fallback={<LoadingLazy />}>- <MapiquePerspective {...props} />- </React.Suspense>- );-}--let KanBanPerspective = React.Fragment;-if (Pro && Pro.Perspectives && Pro.Perspectives.KanBanPerspective) {- KanBanPerspective = Pro.Perspectives.KanBanPerspective;-}-function KanBanPerspectiveAsync(props) {- return (- <React.Suspense fallback={<LoadingLazy />}>- <KanBanPerspective {...props} />- </React.Suspense>- );-}--const WelcomePanel = React.lazy(() =>- import(/* webpackChunkName: "WelcomePanel" */ './WelcomePanel')-);-function WelcomePanelAsync(props) {- return (- <React.Suspense fallback={<LoadingLazy />}>- <WelcomePanel {...props} />- </React.Suspense>- );-}+import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';+import RenderPerspective from '-/components/RenderPerspective';+import { useLocationIndexContext } from '-/hooks/useLocationIndexContext';interface Props {- settings: any;- directoryContent: Array<TS.FileSystemEntry>;- renameFile: () => void;- reflectCreateEntry: (path: string, isFile: boolean) => void;- loadParentDirectoryContent: () => void;setSelectedEntries: (selectedEntries: Array<Object>) => void;- isReadOnlyMode: boolean;isDesktopMode: boolean;- showNotification: (content: string) => void;toggleDrawer?: () => void;toggleProTeaser: (slidePage?: string) => void;drawerOpened: boolean;- setCurrentDirectoryPerspective: (perspective: string) => void;maxSearchResults: number;defaultPerspective: string;- currentDirectoryPerspective: string;- updateCurrentDirEntry: (path: string, entry: Object) => void;- setCurrentDirectoryColor: (color: string) => void;selectedEntries: Array<TS.FileSystemEntry>;toggleUploadDialog: () => void;progress?: Array<any>;- searchQuery: TS.SearchQuery;- setSearchQuery: (searchQuery: TS.SearchQuery) => void;- enterSearchMode: () => void;- exitSearchMode: () => void;goBack: () => void;goForward: () => void;- lastSearchTimestamp: number;- isSearchMode: boolean;- openMoveCopyFilesDialog: () => void;}function FolderContainer(props: Props) {const {- directoryContent,toggleDrawer,toggleProTeaser,isDesktopMode,- currentDirectoryPerspective,setSelectedEntries,- reflectCreateEntry,defaultPerspective,goBack,goForward@@ -199,40 +87,15 @@ function FolderContainer(props: Props) {const { t } = useTranslation();const theme = useTheme();const { openedEntries } = useOpenedEntryContext();- const havePrevOpenedFile = React.useRef<boolean>(false);- const firstRender = useFirstRender();- const currentDirectoryPath = useSelector(getDirectoryPath) || '';-- // TODO rethink to move this in openedEntryContextProvider- useEffect(() => {- if (- !firstRender &&- havePrevOpenedFile.current &&- props.selectedEntries.length < 2- ) {- if (openedEntries.length > 0) {- const openedFile = openedEntries[0];- if (openedFile.path === currentDirectoryPath) {- if (openedFile.color) {- props.setCurrentDirectoryColor(openedFile.color);- } else if (openedFile.color === undefined) {- props.setCurrentDirectoryColor(undefined);- }- if (openedFile.perspective) {- props.setCurrentDirectoryPerspective(openedFile.perspective);- }- } else {- // update openedFile meta in grid perspective list (like description)- const currentEntry = enhanceOpenedEntry(- openedFile,- props.settings.tagDelimiter- );- props.updateCurrentDirEntry(openedFile.path, currentEntry);- }- }- }- havePrevOpenedFile.current = openedEntries.length > 0;- }, [openedEntries]);+ const {+ setSearchQuery,+ currentDirectoryEntries,+ currentDirectoryPath,+ currentDirectoryPerspective,+ setCurrentDirectoryPerspective,+ enterSearchMode,+ isSearchMode+ } = useDirectoryContentContext();/*** reflect update openedFile from perspective@@ -254,7 +117,7 @@ function FolderContainer(props: Props) {}}, [props.editedEntryPaths]);*/- const [isRenameEntryDialogOpened, setIsRenameEntryDialogOpened] = useState<+ const [isRenameEntryDialogOpened, setRenameEntryDialogOpened] = useState<boolean>(false);@@ -266,69 +129,14 @@ function FolderContainer(props: Props) {}const showWelcomePanel =- !currentDirectoryPath &&- directoryContent.length < 1 &&- !(props.isSearchMode && props.lastSearchTimestamp);+ !currentDirectoryPath && currentDirectoryEntries.length < 1;+ // && !(isSearchMode && props.lastSearchTimestamp);const openRenameEntryDialog = useCallback(- () => setIsRenameEntryDialogOpened(true),+ () => setRenameEntryDialogOpened(true),[]);- const renderPerspective = () => {- if (showWelcomePanel) {- return AppConfig.showWelcomePanel ? <WelcomePanelAsync /> : null;- }- if (currentPerspective === PerspectiveIDs.LIST) {- return (- <ListPerspectiveAsync- openRenameEntryDialog={openRenameEntryDialog}- currentDirectoryPath={currentDirectoryPath}- />- );- }- if (Pro && currentPerspective === PerspectiveIDs.GALLERY) {- return (- <GalleryPerspectiveAsync- directoryContent={props.directoryContent}- lastSearchTimestamp={props.lastSearchTimestamp}- currentDirectoryPath={currentDirectoryPath}- switchPerspective={switchPerspective}- />- );- }- if (Pro && currentPerspective === PerspectiveIDs.MAPIQUE) {- return (- <MapiquePerspectiveAsync- directoryContent={props.directoryContent}- lastSearchTimestamp={props.lastSearchTimestamp}- currentDirectoryPath={currentDirectoryPath}- switchPerspective={switchPerspective}- />- );- }- if (Pro && currentPerspective === PerspectiveIDs.KANBAN) {- return (- <KanBanPerspectiveAsync- directoryContent={props.directoryContent}- lastSearchTimestamp={props.lastSearchTimestamp}- openRenameEntryDialog={openRenameEntryDialog}- loadParentDirectoryContent={props.loadParentDirectoryContent}- renameFile={props.renameFile}- currentDirectoryPath={currentDirectoryPath}- switchPerspective={switchPerspective}- />- );- }-- return (- <GridPerspectiveAsync- openRenameEntryDialog={openRenameEntryDialog}- currentDirectoryPath={currentDirectoryPath}- />- );- };-function CircularProgressWithLabel(prop) {return (<Box position="relative" display="inline-flex">@@ -371,7 +179,7 @@ function FolderContainer(props: Props) {perspectiveId === PerspectiveIDs.GRID ||perspectiveId === PerspectiveIDs.LIST) {- props.setCurrentDirectoryPerspective(perspectiveId);+ setCurrentDirectoryPerspective(perspectiveId);} else if (perspectiveId === PerspectiveIDs.GALLERY) {toggleProTeaser(PerspectiveIDs.GALLERY);} else if (perspectiveId === PerspectiveIDs.MAPIQUE) {@@ -403,14 +211,9 @@ function FolderContainer(props: Props) {);});- const toggleSearchMode = () => {- if (props.isSearchMode) {- props.setSearchQuery({});- props.exitSearchMode();- } else {- props.setSearchQuery({ textQuery: '' });- props.enterSearchMode();- }+ const openSearchMode = () => {+ setSearchQuery({ textQuery: '' });+ enterSearchMode();};const openSearchKeyBinding = AppConfig.isElectron@@ -475,12 +278,9 @@ function FolderContainer(props: Props) {</IconButton></Tooltip>)}- {props.isSearchMode ? (+ {isSearchMode ? (/* todo rethink if open props is needed */- <SearchBox- open={props.isSearchMode}- textQuery={props.searchQuery.textQuery}- />+ <SearchBox open={isSearchMode} />) : (<><div@@ -516,7 +316,7 @@ function FolderContainer(props: Props) {}}/> */}<Tooltip title={t('core:searchTitle') + openSearchKeyBinding}>- <IconButton data-tid="toggleSearch" onClick={toggleSearchMode}>+ <IconButton data-tid="toggleSearch" onClick={openSearchMode}><SearchIcon /></IconButton></Tooltip>@@ -538,12 +338,8 @@ function FolderContainer(props: Props) {<PathBreadcrumbsswitchPerspective={switchPerspective}setSelectedEntries={setSelectedEntries}- reflectCreateEntry={reflectCreateEntry}isDesktopMode={isDesktopMode}- openRenameDirectoryDialog={() =>- setIsRenameEntryDialogOpened(true)- }- openMoveCopyFilesDialog={props.openMoveCopyFilesDialog}+ openRenameDirectoryDialog={() => setRenameEntryDialogOpened(true)}/></>)}@@ -555,11 +351,11 @@ function FolderContainer(props: Props) {}}>{/*<LoadingAnimation />*/}- {renderPerspective()}+ <RenderPerspective openRenameEntryDialog={openRenameEntryDialog} />{isRenameEntryDialogOpened && (<RenameEntryDialogopen={isRenameEntryDialogOpened}- onClose={() => setIsRenameEntryDialogOpened(false)}+ onClose={() => setRenameEntryDialogOpened(false)}/>)}</div>@@ -589,20 +385,11 @@ function FolderContainer(props: Props) {function mapStateToProps(state) {return {- settings: state.settings,selectedEntries: getSelectedEntries(state),- directoryContent: getDirectoryContent(state),- currentDirectoryPerspective: getCurrentDirectoryPerspective(state),- //searchResultCount: getSearchResultCount(state),maxSearchResults: getMaxSearchResults(state),isDesktopMode: getDesktopMode(state),- isReadOnlyMode: isReadOnlyMode(state),progress: getProgress(state),- searchQuery: getSearchQuery(state),- defaultPerspective: getDefaultPerspective(state),- //editedEntryPaths: getEditedEntryPaths(state),- lastSearchTimestamp: getLastSearchTimestamp(state),- isSearchMode: isSearchMode(state)+ defaultPerspective: getDefaultPerspective(state)};}@@ -610,36 +397,17 @@ function mapActionCreatorsToProps(dispatch) {return bindActionCreators({toggleUploadDialog: AppActions.toggleUploadDialog,- renameFile: AppActions.renameFile,- reflectCreateEntry: AppActions.reflectCreateEntry,- loadParentDirectoryContent: AppActions.loadParentDirectoryContent,- setSelectedEntries: AppActions.setSelectedEntries,- showNotification: AppActions.showNotification,- setCurrentDirectoryPerspective: AppActions.setCurrentDirectoryPerspective,- updateCurrentDirEntry: AppActions.updateCurrentDirEntry,- setCurrentDirectoryColor: AppActions.setCurrentDirectoryColor,- enterSearchMode: AppActions.enterSearchMode,- exitSearchMode: AppActions.exitSearchMode,- setSearchQuery: LocationIndexActions.setSearchQuery+ setSelectedEntries: AppActions.setSelectedEntries},dispatch);}const areEqual = (prevProp: Props, nextProp: Props) =>- nextProp.settings.currentTheme === prevProp.settings.currentTheme &&nextProp.drawerOpened === prevProp.drawerOpened &&nextProp.isDesktopMode === prevProp.isDesktopMode &&- nextProp.currentDirectoryPerspective ===- prevProp.currentDirectoryPerspective &&/* this props is set before currentDirectoryEntries is loaded and will reload FolderContainer */- JSON.stringify(nextProp.progress) === JSON.stringify(prevProp.progress) &&- JSON.stringify(nextProp.directoryContent) ===- JSON.stringify(prevProp.directoryContent) &&- JSON.stringify(nextProp.searchQuery) ===- JSON.stringify(prevProp.searchQuery) &&- nextProp.lastSearchTimestamp === prevProp.lastSearchTimestamp &&- nextProp.isSearchMode === prevProp.isSearchMode;+ JSON.stringify(nextProp.progress) === JSON.stringify(prevProp.progress);export default connect(mapStateToProps,diff --git a/app/components/LocationManager.tsx b/app/components/LocationManager.tsxindex 9addd0820..acbb6acfa 100644--- a/app/components/LocationManager.tsx+++ b/app/components/LocationManager.tsx@@ -31,6 +31,7 @@ import { TS } from '-/tagspaces.namespace';import PlatformIO from '-/services/platform-facade';import { classes, SidePanel } from '-/components/SidePanels.css';import { useTranslation } from 'react-i18next';+import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';const CreateEditLocationDialog = React.lazy(() =>import(@@ -61,11 +62,16 @@ type SubFolder = {function LocationManager(props: Props) {const { t } = useTranslation();const dispatch: AppDispatch = useDispatch();+ const {+ addLocations,+ editLocation,+ selectedLocation+ } = useCurrentLocationContext();const locations: Array<TS.Location> = useSelector(getLocations);// const loading: boolean = useSelector(isLoading);//const language: string = useSelector(getCurrentLanguage);const fileInputRef = useRef<HTMLInputElement>(null);- const [selectedLocation, setSelectedLocation] = useState<TS.Location>(null);+ //const selectedLocation = useRef<TS.Location>(null);const [isEditLocationDialogOpened, setEditLocationDialogOpened] = useState<boolean>(false);@@ -85,13 +91,9 @@ function LocationManager(props: Props) {const ImportLocationsDialog =Pro && Pro.UI ? Pro.UI.ImportLocationsDialog : false;- useEffect(() => {- if (locations.length < 1) {- // init locations- dispatch(LocationActions.setDefaultLocations(t));- }- }, [locations]);-+ /*function setSelectedLocation(location: TS.Location) {+ selectedLocation.current = location;+ }*/function handleFileInputChange(selection: any) {const target = selection.currentTarget;const file = target.files[0];@@ -201,8 +203,8 @@ function LocationManager(props: Props) {setDeleteLocationDialogOpened={setDeleteLocationDialogOpened}- selectedLocation={selectedLocation}- setSelectedLocation={setSelectedLocation}+ /*selectedLocation={selectedLocation.current}+ setSelectedLocation={setSelectedLocation}*//></div>)}@@ -225,10 +227,8 @@ function LocationManager(props: Props) {<CreateEditLocationDialogAsyncopen={isEditLocationDialogOpened}onClose={() => setEditLocationDialogOpened(false)}- location={selectedLocation}- editLocation={location =>- dispatch(LocationActions.editLocation(location))- }+ /*location={selectedLocation.current}*/+ editLocation={location => editLocation(location)}/>)}{isDeleteLocationDialogOpened && (@@ -241,7 +241,7 @@ function LocationManager(props: Props) {})}confirmCallback={result => {if (result && selectedLocation) {- dispatch(LocationActions.removeLocation(selectedLocation));+ dispatch(LocationActions.deleteLocation(selectedLocation));}}}cancelDialogTID="cancelDeleteLocationDialog"@@ -260,7 +260,7 @@ function LocationManager(props: Props) {open={Boolean(importFile)}onClose={() => setImportFile(undefined)}importFile={importFile}- addLocations={loc => dispatch(LocationActions.addLocations(loc))}+ addLocations={loc => addLocations(loc)}locations={locations}/>)}diff --git a/app/components/LocationView.tsx b/app/components/LocationView.tsxindex f7c261aee..16ad9acbd 100644--- a/app/components/LocationView.tsx+++ b/app/components/LocationView.tsx@@ -16,8 +16,8 @@**/-import React, { useRef, useState } from 'react';-import { useDispatch, useSelector } from 'react-redux';+import React, { useRef } from 'react';+import { useDispatch } from 'react-redux';import Tooltip from '-/components/Tooltip';import ListItem from '@mui/material/ListItem';import ListItemIcon from '@mui/material/ListItemIcon';@@ -29,16 +29,10 @@ import { LocalLocationIcon, CloudLocationIcon } from '-/components/CommonIcons';import DefaultLocationIcon from '@mui/icons-material/Highlight';import { locationType } from '@tagspaces/tagspaces-common/misc';import AppConfig from '-/AppConfig';-import {- actions as AppActions,- AppDispatch,- getCurrentLocationId,- isReadOnlyMode-} from '../reducers/app';+import { actions as AppActions, AppDispatch } from '../reducers/app';import PlatformIO from '../services/platform-facade';import TargetMoveFileBox from './TargetMoveFileBox';import DragItemTypes from './DragItemTypes';-import IOActions from '../reducers/io-actions';import DirectoryTreeView, {DirectoryTreeViewRef} from '-/components/DirectoryTreeView';@@ -46,35 +40,44 @@ import LocationContextMenu from '-/components/menus/LocationContextMenu';import { TS } from '-/tagspaces.namespace';import { classes, SidePanel } from '-/components/SidePanels.css';import { useTranslation } from 'react-i18next';+import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';+import { useNotificationContext } from '-/hooks/useNotificationContext';+import { useIOActionsContext } from '-/hooks/useIOActionsContext';interface Props {location: TS.Location;hideDrawer?: () => void;setEditLocationDialogOpened: (open: boolean) => void;setDeleteLocationDialogOpened: (open: boolean) => void;- selectedLocation: TS.Location;- setSelectedLocation: (loc: TS.Location) => void;}function LocationView(props: Props) {const { t } = useTranslation();++ const { moveFiles, uploadFiles } = useIOActionsContext();+ const {+ openLocation,+ currentLocation,+ readOnlyMode,+ setSelectedLocation,+ locationDirectoryContextMenuAnchorEl,+ setLocationDirectoryContextMenuAnchorEl+ } = useCurrentLocationContext();+ const { reloadDirectory } = useIOActionsContext();+ const { showNotification } = useNotificationContext();const directoryTreeRef = useRef<DirectoryTreeViewRef>(null);- const [+ /* const [locationDirectoryContextMenuAnchorEl,setLocationDirectoryContextMenuAnchorEl- ] = useState<null | HTMLElement>(null);+ ] = useState<null | HTMLElement>(null);*/const dispatch: AppDispatch = useDispatch();- const currentLocationId: string = useSelector(getCurrentLocationId);- const readOnlyMode = useSelector(isReadOnlyMode);const {location,hideDrawer,- setSelectedLocation,setEditLocationDialogOpened,- setDeleteLocationDialogOpened,- selectedLocation+ setDeleteLocationDialogOpened} = props;const isCloudLocation = location.type === locationType.TYPE_CLOUD;@@ -89,21 +92,13 @@ function LocationView(props: Props) {};const handleLocationClick = () => {- if (location.uuid === currentLocationId) {+ if (currentLocation && location.uuid === currentLocation.uuid) {// the same location click-- dispatch(- AppActions.loadDirectoryContent(- PlatformIO.getLocationPath(location),- true,- true- )- );+ reloadDirectory(PlatformIO.getLocationPath(location));} else {// this.directoryTreeRef[location.uuid].loadSubDir(location, 1);dispatch(AppActions.setSelectedEntries([]));- dispatch(AppActions.exitSearchMode());- dispatch(AppActions.openLocation(location));+ openLocation(location);if (hideDrawer) {hideDrawer();}@@ -114,11 +109,11 @@ function LocationView(props: Props) {directoryTreeRef.current.closeLocation();};- const handleLocationContextMenuClick = (event: any) => {+ const handleLocationContextMenuClick = (event: any, chosenLocation) => {event.preventDefault();event.stopPropagation();+ setSelectedLocation(chosenLocation);setLocationDirectoryContextMenuAnchorEl(event.currentTarget);- setSelectedLocation(location);};const onUploadProgress = (progress, response) => {@@ -143,33 +138,15 @@ function LocationView(props: Props) {arrPath.push(path);}if (readOnlyMode) {- dispatch(- AppActions.showNotification(- t('core:dndDisabledReadOnlyMode'),- 'error',- true- )- );+ showNotification(t('core:dndDisabledReadOnlyMode'), 'error', true);return;}if (!AppConfig.isWin && !path.startsWith('/')) {- dispatch(- AppActions.showNotification(- t('Moving file not possible'),- 'error',- true- )- );+ showNotification(t('Moving file not possible'), 'error', true);return;}if (AppConfig.isWin && !path.substr(1).startsWith(':')) {- dispatch(- AppActions.showNotification(- t('Moving file not possible'),- 'error',- true- )- );+ showNotification(t('Moving file not possible'), 'error', true);return;}let targetPath = item.path;@@ -187,9 +164,7 @@ function LocationView(props: Props) {.then(() => {dispatch(AppActions.resetProgress());dispatch(AppActions.toggleUploadDialog());- dispatch(- IOActions.uploadFiles(arrPath, targetPath, onUploadProgress)- )+ uploadFiles(arrPath, targetPath, onUploadProgress).then((fsEntries: Array<TS.FileSystemEntry>) => {dispatch(AppActions.reflectCreateEntries(fsEntries));return true;@@ -204,7 +179,7 @@ function LocationView(props: Props) {});} else if (targetLocation.type === locationType.TYPE_LOCAL) {PlatformIO.disableObjectStoreSupport();- dispatch(IOActions.moveFiles(arrPath, targetPath));+ moveFiles(arrPath, targetPath);}dispatch(AppActions.setSelectedEntries([]));}@@ -253,25 +228,18 @@ function LocationView(props: Props) {<LocationContextMenusetEditLocationDialogOpened={setEditLocationDialogOpened}setDeleteLocationDialogOpened={setDeleteLocationDialogOpened}- selectedLocation={selectedLocation}- locationDirectoryContextMenuAnchorEl={- locationDirectoryContextMenuAnchorEl- }- setLocationDirectoryContextMenuAnchorEl={- setLocationDirectoryContextMenuAnchorEl- }closeLocationTree={closeLocationTree}/>)}<ListItemdata-tid={'location_' + location.name.replace(/ /g, '_')}className={- currentLocationId === location.uuid+ currentLocation && currentLocation.uuid === location.uuid? classes.listItemSelected: classes.listItem}onClick={handleLocationClick}- onContextMenu={event => handleLocationContextMenuClick(event)}+ onContextMenu={event => handleLocationContextMenuClick(event, location)}><ListItemIcon// onClick={(e) => {@@ -320,8 +288,10 @@ function LocationView(props: Props) {aria-haspopup="true"edge="end"data-tid={'locationMoreButton_' + location.name}- onClick={event => handleLocationContextMenuClick(event)}- onContextMenu={event => handleLocationContextMenuClick(event)}+ onClick={event => handleLocationContextMenuClick(event, location)}+ onContextMenu={event =>+ handleLocationContextMenuClick(event, location)+ }size="large">{location.isDefault && (@@ -344,4 +314,4 @@ function LocationView(props: Props) {);}-export default React.memo(LocationView);+export default LocationView;diff --git a/app/components/PathBreadcrumbs.tsx b/app/components/PathBreadcrumbs.tsxindex bbc491f41..a286db7b3 100644--- a/app/components/PathBreadcrumbs.tsx+++ b/app/components/PathBreadcrumbs.tsx@@ -29,17 +29,11 @@ import {extractShortDirectoryName} from '@tagspaces/tagspaces-common/paths';import DirectoryMenu from './menus/DirectoryMenu';-import { TS } from '-/tagspaces.namespace';import { LocalLocationIcon, CloudLocationIcon } from '-/components/CommonIcons';import { locationType } from '@tagspaces/tagspaces-common/misc';import { useTranslation } from 'react-i18next';-import { useDispatch, useSelector } from 'react-redux';-import { getCurrentLocation } from '-/reducers/locations';-import {- actions as AppActions,- AppDispatch,- getDirectoryPath-} from '-/reducers/app';+import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';+import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';const StyledBreadcrumb = styled(Chip)(({ theme }) => {const backgroundColor =@@ -79,18 +73,16 @@ const StyledBreadcrumbs = styled(Breadcrumbs)(({ theme }) => {interface Props {switchPerspective: (perspectiveId: string) => void;setSelectedEntries: (selectedEntries: Array<Object>) => void;- reflectCreateEntry: (path: string, isFile: boolean) => void;openRenameDirectoryDialog: () => void;- openMoveCopyFilesDialog: () => void;isDesktopMode: boolean;}function PathBreadcrumbs(props: Props) {const { t } = useTranslation();- const dispatch: AppDispatch = useDispatch();+ //const dispatch: AppDispatch = useDispatch();+ const { openDirectory, currentDirectoryPath } = useDirectoryContentContext();+ const { currentLocation } = useCurrentLocationContext();let pathParts: Array<string> = [];- const currentLocation = useSelector(getCurrentLocation);- const currentDirectoryPath = useSelector(getDirectoryPath);const [directoryContextMenuAnchorEl,@@ -99,9 +91,7 @@ function PathBreadcrumbs(props: Props) {const {setSelectedEntries,- reflectCreateEntry,openRenameDirectoryDialog,- openMoveCopyFilesDialog,isDesktopMode} = props;@@ -188,9 +178,7 @@ function PathBreadcrumbs(props: Props) {href="#"label={folderName}icon={index === 0 && locationTypeIcon}- onClick={() =>- dispatch(AppActions.loadDirectoryContent(pathPart, false, true))- }+ onClick={() => openDirectory(pathPart)}/></Tooltip>);@@ -249,10 +237,9 @@ function PathBreadcrumbs(props: Props) {open={Boolean(directoryContextMenuAnchorEl)}onClose={closeDirectoryMenu}anchorEl={directoryContextMenuAnchorEl}+ perspectiveMode={false}directoryPath={currentDirectoryPath}openRenameDirectoryDialog={openRenameDirectoryDialog}- openMoveCopyFilesDialog={openMoveCopyFilesDialog}- reflectCreateEntry={reflectCreateEntry}/></>);diff --git a/app/components/RenderHistory.tsx b/app/components/RenderHistory.tsxindex ab1b28349..c0bea7ed0 100644--- a/app/components/RenderHistory.tsx+++ b/app/components/RenderHistory.tsx@@ -33,13 +33,8 @@ import IconButton from '@mui/material/IconButton';import { RemoveIcon, HistoryIcon } from '-/components/CommonIcons';import { dataTidFormat } from '-/services/test';import { useTranslation } from 'react-i18next';-import { useDispatch, useSelector } from 'react-redux';-import {- actions as AppActions,- AppDispatch,- getCurrentLocationId-} from '-/reducers/app';import { useOpenedEntryContext } from '-/hooks/useOpenedEntryContext';+import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';interface Props {historyKey: string;@@ -50,16 +45,12 @@ interface Props {}function RenderHistory(props: Props) {const { t } = useTranslation();- const dispatch: AppDispatch = useDispatch();- const { openEntry } = useOpenedEntryContext();- const currentLocationId = useSelector(getCurrentLocationId);+ // const dispatch: AppDispatch = useDispatch();+ const { openEntry, openLink } = useOpenedEntryContext();+ const { openLocationById, currentLocation } = useCurrentLocationContext();const { historyKey, items, update, maxItems, showDelete = true } = props;- const openLinkDispatch = link =>- dispatch(AppActions.openLink(link, { fullWidth: false }));-- const openLocationByIdDispatch = locationId =>- dispatch(AppActions.openLocationById(locationId));+ const openLinkDispatch = link => openLink(link, { fullWidth: false });return (<>@@ -85,9 +76,9 @@ function RenderHistory(props: Props) {onClick={() =>Pro.history.openItem(item,- currentLocationId,+ currentLocation && currentLocation.uuid,openLinkDispatch,- openLocationByIdDispatch,+ openLocationById,openEntry)}diff --git a/app/components/RenderPerspective.tsx b/app/components/RenderPerspective.tsxnew file mode 100644index 000000000..3e2b8144e--- /dev/null+++ b/app/components/RenderPerspective.tsx@@ -0,0 +1,172 @@+/**+ * TagSpaces - universal file and folder organizer+ * Copyright (C) 2017-present TagSpaces UG (haftungsbeschraenkt)+ *+ * 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/>.+ *+ */++import React from 'react';++import AppConfig from '-/AppConfig';++import { Pro } from '-/pro';+import { PerspectiveIDs } from '-/perspectives';+import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';+import { useSelector } from 'react-redux';+import { getDefaultPerspective } from '-/reducers/settings';+import LoadingLazy from '-/components/LoadingLazy';+import { SortedDirContextProvider } from '-/perspectives/grid-perspective/hooks/SortedDirContextProvider';+import { PaginationContextProvider } from '-/hooks/PaginationContextProvider';+import { ThumbGenerationContextProvider } from '-/hooks/ThumbGenerationContextProvider';++const GridPerspective = React.lazy(() =>+ import(+ /* webpackChunkName: "GridPerspective" */ '../perspectives/grid-perspective'+ )+);+function GridPerspectiveAsync(props) {+ return (+ <React.Suspense fallback={<LoadingLazy />}>+ <SortedDirContextProvider>+ <PaginationContextProvider>+ <ThumbGenerationContextProvider>+ <GridPerspective {...props} />+ </ThumbGenerationContextProvider>+ </PaginationContextProvider>+ </SortedDirContextProvider>+ </React.Suspense>+ );+}++const ListPerspective = React.lazy(() =>+ import(/* webpackChunkName: "ListPerspective" */ '../perspectives/list')+);+function ListPerspectiveAsync(props) {+ return (+ <React.Suspense fallback={<LoadingLazy />}>+ <SortedDirContextProvider>+ <PaginationContextProvider>+ <ThumbGenerationContextProvider>+ <ListPerspective {...props} />+ </ThumbGenerationContextProvider>+ </PaginationContextProvider>+ </SortedDirContextProvider>+ </React.Suspense>+ );+}++let GalleryPerspective = React.Fragment;+if (Pro && Pro.Perspectives && Pro.Perspectives.GalleryPerspective) {+ // GalleryPerspective = React.lazy(() => import(/* webpackChunkName: "GalleryPerspective" */ '../node_modules/@tagspaces/pro/modules/perspectives/gallery'));++ GalleryPerspective = Pro.Perspectives.GalleryPerspective;+}+function GalleryPerspectiveAsync(props) {+ return (+ <React.Suspense fallback={<LoadingLazy />}>+ <ThumbGenerationContextProvider>+ <GalleryPerspective {...props} />+ </ThumbGenerationContextProvider>+ </React.Suspense>+ );+}++let MapiquePerspective = React.Fragment;+if (Pro && Pro.Perspectives && Pro.Perspectives.MapiquePerspective) {+ // MapiquePerspective = React.lazy(() => import(/* webpackChunkName: "MapiquePerspective" */ '../node_modules/@tagspaces/pro/modules/perspectives/mapique'));+ MapiquePerspective = Pro.Perspectives.MapiquePerspective;+}+function MapiquePerspectiveAsync(props) {+ return (+ <React.Suspense fallback={<LoadingLazy />}>+ <ThumbGenerationContextProvider>+ <MapiquePerspective {...props} />+ </ThumbGenerationContextProvider>+ </React.Suspense>+ );+}++let KanBanPerspective = React.Fragment;+if (Pro && Pro.Perspectives && Pro.Perspectives.KanBanPerspective) {+ KanBanPerspective = Pro.Perspectives.KanBanPerspective;+}+function KanBanPerspectiveAsync(props) {+ return (+ <React.Suspense fallback={<LoadingLazy />}>+ <ThumbGenerationContextProvider>+ <KanBanPerspective {...props} />+ </ThumbGenerationContextProvider>+ </React.Suspense>+ );+}++const WelcomePanel = React.lazy(() =>+ import(/* webpackChunkName: "WelcomePanel" */ './WelcomePanel')+);+function WelcomePanelAsync(props) {+ return (+ <React.Suspense fallback={<LoadingLazy />}>+ <WelcomePanel {...props} />+ </React.Suspense>+ );+}++interface Props {+ openRenameEntryDialog: () => void;+}++function RenderPerspective(props: Props) {+ const { openRenameEntryDialog } = props;+ const {+ currentDirectoryEntries,+ currentDirectoryPath,+ currentDirectoryPerspective+ } = useDirectoryContentContext();++ const defaultPerspective = useSelector(getDefaultPerspective);++ let currentPerspective =+ currentDirectoryPerspective || defaultPerspective || PerspectiveIDs.GRID;++ if (currentPerspective === PerspectiveIDs.UNSPECIFIED) {+ currentPerspective = defaultPerspective;+ }++ const showWelcomePanel =+ !currentDirectoryPath && currentDirectoryEntries.length < 1;++ if (showWelcomePanel) {+ return AppConfig.showWelcomePanel ? <WelcomePanelAsync /> : null;+ }+ if (currentPerspective === PerspectiveIDs.LIST) {+ return (+ <ListPerspectiveAsync openRenameEntryDialog={openRenameEntryDialog} />+ );+ }+ if (Pro && currentPerspective === PerspectiveIDs.GALLERY) {+ return <GalleryPerspectiveAsync />;+ }+ if (Pro && currentPerspective === PerspectiveIDs.MAPIQUE) {+ return <MapiquePerspectiveAsync />;+ }+ if (Pro && currentPerspective === PerspectiveIDs.KANBAN) {+ return (+ <KanBanPerspectiveAsync openRenameEntryDialog={openRenameEntryDialog} />+ );+ }++ return <GridPerspectiveAsync openRenameEntryDialog={openRenameEntryDialog} />;+}++export default RenderPerspective;diff --git a/app/components/SearchAutocomplete.tsx b/app/components/SearchAutocomplete.tsxindex 6d60d9806..43c84ec9c 100644--- a/app/components/SearchAutocomplete.tsx+++ b/app/components/SearchAutocomplete.tsx@@ -27,17 +27,7 @@ import IconButton from '@mui/material/IconButton';import ClearSearchIcon from '@mui/icons-material/Close';import AdvancedSearchIcon from '@mui/icons-material/TuneOutlined';import DropDownIcon from '@mui/icons-material/ArrowDropDownOutlined';-import {- actions as AppActions,- AppDispatch,- getDirectoryPath,- isSearchMode-} from '../reducers/app';-import {- actions as LocationIndexActions,- isIndexing,- getSearchQuery-} from '../reducers/location-index';+import { actions as AppActions, AppDispatch } from '../reducers/app';import {getMaxSearchResults,getShowUnixHiddenEntries@@ -63,7 +53,7 @@ import {SearchOptionType,SearchQueryComposition} from '-/components/SearchOptions';-import { getCurrentLocation, getLocations } from '-/reducers/locations';+import { getLocations } from '-/reducers/locations';import CloseIcon from '@mui/icons-material/Close';import { getTagLibrary } from '-/services/taglibrary-utils';import { getSearches } from '-/reducers/searches';@@ -72,6 +62,10 @@ import { dataTidFormat } from '-/services/test';import { useTheme } from '@mui/material/styles';import { useTranslation } from 'react-i18next';import { useOpenedEntryContext } from '-/hooks/useOpenedEntryContext';+import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';+import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';+import { useNotificationContext } from '-/hooks/useNotificationContext';+import { useLocationIndexContext } from '-/hooks/useLocationIndexContext';interface Props {style?: any;@@ -93,23 +87,33 @@ interface Props {function SearchAutocomplete(props: Props) {const { t } = useTranslation();const theme = useTheme();- const { openEntry } = useOpenedEntryContext();+ const { openEntry, openLink } = useOpenedEntryContext();+ const {+ currentLocation,+ changeLocationByID,+ switchLocationTypeByID,+ openLocationById+ } = useCurrentLocationContext();+ const {+ currentDirectoryPath,+ exitSearchMode,+ openCurrentDirectory,+ searchQuery,+ setSearchQuery+ } = useDirectoryContentContext();+ const {+ watchForChanges,+ isIndexing,+ searchAllLocations,+ searchLocationIndex+ } = useLocationIndexContext();const dispatch: AppDispatch = useDispatch();- const indexing = useSelector(isIndexing);- const searchQuery: TS.SearchQuery = useSelector(getSearchQuery);- // const isDesktop = useSelector(isDesktopMode);- const currentDirectory = useSelector(getDirectoryPath);const maxSearchResults = useSelector(getMaxSearchResults);const showUnixHiddenEntries = useSelector(getShowUnixHiddenEntries);const locations: TS.Location[] = useSelector(getLocations);- const currentLocation: TS.Location = useSelector(getCurrentLocation);- const searchMode: boolean = useSelector(isSearchMode);const searches: Array<TS.SearchQuery> = useSelector(getSearches);- const openLinkDispatch = (link, options) =>- dispatch(AppActions.openLink(link, options));- const openLocationByIdDispatch = locationId =>- dispatch(AppActions.openLocationById(locationId));+ const openLinkDispatch = (link, options) => openLink(link, options);const { setTextQuery, textQuery, open, setAnchorSearch } = props;// const [, forceUpdate] = useReducer(x => x + 1, 0);@@ -166,16 +170,16 @@ function SearchAutocomplete(props: Props) {// const mainSearchField = useRef<HTMLInputElement>(null);const isOpen = useRef<boolean>(true);- const firstRender = useFirstRender();+ // const firstRender = useFirstRender();const historyKeys = Pro && Pro.history ? Pro.history.historyKeys : {};- useEffect(() => {+ /*useEffect(() => {if (!firstRender) {if (!searchMode) {clearSearch();}}- }, [searchMode]);+ }, [searchMode]);*//* let searchBoxingName = t('location');if (searchBoxing === 'global') {@@ -325,9 +329,9 @@ function SearchAutocomplete(props: Props) {textQuery: txtQuery};if (searchBoxing === 'global') {- dispatch(LocationIndexActions.searchAllLocations(sQuery));+ searchAllLocations(sQuery);} else {- dispatch(LocationIndexActions.searchLocationIndex(sQuery));+ searchLocationIndex(sQuery);}}} /*else {@@ -435,9 +439,10 @@ function SearchAutocomplete(props: Props) {}const clearSearch = () => {resetValues([]);- dispatch(LocationIndexActions.setSearchQuery({}));- dispatch(AppActions.exitSearchMode());- dispatch(AppActions.watchForChanges());+ setSearchQuery({});+ exitSearchMode();+ watchForChanges();+ openCurrentDirectory();};function removeActionsFromQuery(@@ -595,7 +600,7 @@ function SearchAutocomplete(props: Props) {tagPlaceLong,// tagPlaceRadius,maxSearchResults: maxSearchResults,- currentDirectory: currentDirectory,+ currentDirectory: currentDirectoryPath,forceIndexing: forceIndexing.current,showUnixHiddenEntries: showUnixHiddenEntries,executeSearch: true@@ -604,7 +609,7 @@ function SearchAutocomplete(props: Props) {clearSearch();} else {console.log('Search object: ' + JSON.stringify(sQuery));- dispatch(LocationIndexActions.setSearchQuery(sQuery));+ setSearchQuery(sQuery);}};@@ -947,11 +952,11 @@ function SearchAutocomplete(props: Props) {}actions.push(option);} else if (option.action === ExecActions.OPEN_LOCATION) {- dispatch(AppActions.exitSearchMode());+ exitSearchMode();// isOpen.current = false;searchOptions.current = getSearchOptions();currentOptions.current = undefined;- openLocationByIdDispatch(option.id);+ openLocationById(option.id);return [];} else if (isAction(option.action, SearchActions.FILTER)) {actions.push(option);@@ -983,14 +988,10 @@ function SearchAutocomplete(props: Props) {} else if (option.action === ExecActions.OPEN_HISTORY) {if (option.searchQuery) {if (option.id) {- dispatch(AppActions.switchLocationTypeByID(option.id)).then(- () => {- dispatch(AppActions.changeLocationByID(option.id));- dispatch(- LocationIndexActions.setSearchQuery(option.searchQuery)- );- }- );+ switchLocationTypeByID(option.id).then(() => {+ changeLocationByID(option.id);+ setSearchQuery(option.searchQuery);+ });} else {}} else if (Pro && Pro.history) {@@ -1002,9 +1003,9 @@ function SearchAutocomplete(props: Props) {};Pro.history.openItem(item,- currentLocation.uuid,+ currentLocation && currentLocation.uuid,openLinkDispatch,- openLocationByIdDispatch,+ openLocationById,openEntry);}@@ -1022,9 +1023,9 @@ function SearchAutocomplete(props: Props) {};Pro.history.openItem(item,- currentLocation.uuid,+ currentLocation && currentLocation.uuid,openLinkDispatch,- openLocationByIdDispatch,+ openLocationById,openEntry);}@@ -1033,9 +1034,7 @@ function SearchAutocomplete(props: Props) {isOpen.current = false;return [];} else if (option.action === ExecActions.OPEN_SAVED_SEARCHES) {- dispatch(- LocationIndexActions.setSearchQuery(JSON.parse(option.fullName))- );+ setSearchQuery(JSON.parse(option.fullName));searchOptions.current = getSearchOptions();currentOptions.current = undefined;isOpen.current = false;@@ -1086,15 +1085,13 @@ function SearchAutocomplete(props: Props) {actionValues.current,SearchQueryComposition.TAG_NOT);- dispatch(- LocationIndexActions.setSearchQuery({- ...searchQuery,- tagsAND,- tagsOR,- tagsNOT,- executeSearch: false- })- );+ setSearchQuery({+ ...searchQuery,+ tagsAND,+ tagsOR,+ tagsNOT,+ executeSearch: false+ });setTextQuery('');if (hasOptionsChanged) {changeOptions(option.action);@@ -1108,13 +1105,11 @@ function SearchAutocomplete(props: Props) {const id = setActionLabel(SearchQueryComposition.TYPE, option);if (id) {fileTypes.current = option.descr.split(', ');- dispatch(- LocationIndexActions.setSearchQuery({- ...searchQuery,- fileTypes: fileTypes.current,- executeSearch: false- })- );+ setSearchQuery({+ ...searchQuery,+ fileTypes: fileTypes.current,+ executeSearch: false+ });}if (hasOptionsChanged) {changeOptions(option.action);@@ -1129,13 +1124,11 @@ function SearchAutocomplete(props: Props) {const id = setActionLabel(SearchQueryComposition.SIZE, option);if (id) {fileSize.current = id;- dispatch(- LocationIndexActions.setSearchQuery({- ...searchQuery,- fileSize: id,- executeSearch: false- })- );+ setSearchQuery({+ ...searchQuery,+ fileSize: id,+ executeSearch: false+ });}if (hasOptionsChanged) {changeOptions(option.action);@@ -1155,13 +1148,11 @@ function SearchAutocomplete(props: Props) {);if (id) {lastModified.current = id;- dispatch(- LocationIndexActions.setSearchQuery({- ...searchQuery,- lastModified: id,- executeSearch: false- })- );+ setSearchQuery({+ ...searchQuery,+ lastModified: id,+ executeSearch: false+ });}if (hasOptionsChanged) {changeOptions(option.action);@@ -1176,13 +1167,11 @@ function SearchAutocomplete(props: Props) {const id = setActionLabel(SearchQueryComposition.SCOPE, option);if (id) {setSearchBoxing(scope[id]);- dispatch(- LocationIndexActions.setSearchQuery({- ...searchQuery,- searchBoxing: scope[id],- executeSearch: false- })- );+ setSearchQuery({+ ...searchQuery,+ searchBoxing: scope[id],+ executeSearch: false+ });}if (hasOptionsChanged) {changeOptions(option.action);@@ -1196,13 +1185,11 @@ function SearchAutocomplete(props: Props) {const id = setActionLabel(SearchQueryComposition.ACCURACY, option);if (id) {searchType.current = accuracy[id];- dispatch(- LocationIndexActions.setSearchQuery({- ...searchQuery,- searchType: accuracy[id],- executeSearch: false- })- );+ setSearchQuery({+ ...searchQuery,+ searchType: accuracy[id],+ executeSearch: false+ });}if (hasOptionsChanged) {changeOptions(option.action);@@ -1674,12 +1661,12 @@ function SearchAutocomplete(props: Props) {);}}/>- <Tooltip title={indexing ? t('searchDisabledWhileIndexing') : ''}>+ <Tooltip title={isIndexing ? t('searchDisabledWhileIndexing') : ''}><Buttonid="searchButton"variant="outlined"size="small"- disabled={indexing}+ disabled={isIndexing}style={{marginRight: 10,marginLeft: 10,diff --git a/app/components/SearchBox.tsx b/app/components/SearchBox.tsxindex c1e4f8e89..56992bab2 100644--- a/app/components/SearchBox.tsx+++ b/app/components/SearchBox.tsx@@ -16,22 +16,26 @@**/-import React, { useState, useRef } from 'react';+import React, { useState } from 'react';import Popover from '@mui/material/Popover';import SearchPopover from '-/components/SearchPopover';import SearchAutocomplete from '-/components/SearchAutocomplete';+import { useLocationIndexContext } from '-/hooks/useLocationIndexContext';+import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';interface Props {open: boolean;- textQuery: string;}function SearchBox(props: Props) {+ const { searchQuery } = useDirectoryContentContext();const [anchorSearch, setAnchorSearch] = useState<HTMLButtonElement | null>(null);- // todo replace with props.setSearchQuery- const [textQuery, setTextQuery] = useState<string>(props.textQuery || '');++ const [textQuery, setTextQuery] = useState<string>(+ searchQuery.textQuery || ''+ );return (<>diff --git a/app/components/SearchPopover.tsx b/app/components/SearchPopover.tsxindex c1b4405a9..b549bb566 100644--- a/app/components/SearchPopover.tsx+++ b/app/components/SearchPopover.tsx@@ -17,19 +17,16 @@*/import React, { useReducer, useRef, useState } from 'react';-import { bindActionCreators } from 'redux';-import { connect } from 'react-redux';+import { useSelector } from 'react-redux';import { LocalizationProvider, DatePicker } from '@mui/x-date-pickers';-import DateFnsUtils from '@date-io/date-fns';+/*import DateFnsUtils from '@date-io/date-fns';*/import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns';import Box from '@mui/material/Box';-import format from 'date-fns/format';import Typography from '@mui/material/Typography';import MenuItem from '@mui/material/MenuItem';import Tooltip from '-/components/Tooltip';import Button from '@mui/material/Button';import Grid from '@mui/material/Grid';-import Input from '@mui/material/Input';import OutlinedInput from '@mui/material/OutlinedInput';import TextField from '@mui/material/TextField';import InputLabel from '@mui/material/InputLabel';@@ -41,25 +38,17 @@ import ToggleButton from '@mui/material/ToggleButton';import ToggleButtonGroup from '@mui/material/ToggleButtonGroup';import { mergeWithExtractedTags } from '@tagspaces/tagspaces-common/misc';import TagsSelect from './TagsSelect';-import { actions as AppActions, getDirectoryPath } from '../reducers/app';-import {- actions as LocationIndexActions,- isIndexing,- getSearchQuery-} from '../reducers/location-index';import {getMaxSearchResults,getShowUnixHiddenEntries} from '-/reducers/settings';import { FileTypeGroups, haveSearchFilters } from '-/services/search';import { Pro } from '../pro';-import { formatDateTime, extractTimePeriod } from '-/utils/dates';import { parseGeoLocation, parseLatLon } from '-/utils/geo';import { getSearches } from '-/reducers/searches';import { TS } from '-/tagspaces.namespace';import { ProLabel, BetaLabel, ProTooltip } from '-/components/HelperComponents';import Links from '-/content/links';-import GlobalSearch from '-/services/search-index';import {CreateFileIcon,FolderIcon,@@ -82,27 +71,14 @@ import { openURLExternally } from '-/services/utils-io';import { useTheme } from '@mui/material/styles';import { classes, SidePanel } from '-/components/SidePanels.css';import { useTranslation } from 'react-i18next';+import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';+import { useLocationIndexContext } from '-/hooks/useLocationIndexContext';const SaveSearchDialog = Pro && Pro.UI ? Pro.UI.SaveSearchDialog : false;interface Props {style?: any;- loadDirectoryContent: (- path: string,- generateThumbnails: boolean,- loadDirMeta?: boolean- ) => void;hideDrawer?: () => void;- searchQuery: TS.SearchQuery; // () => any;- setSearchResults: (entries: Array<any>) => void;- exitSearchMode: () => void;- setSearchQuery: (searchQuery: TS.SearchQuery) => void;- currentDirectory: string;- maxSearchResults: number;- indexing: boolean;- searches: Array<TS.SearchQuery>;- showUnixHiddenEntries: boolean;- // openSearchPanel: () => void;onClose: () => void;textQuery: string;setTextQuery: (value: string) => void;@@ -111,24 +87,31 @@ interface Props {function SearchPopover(props: Props) {const { t } = useTranslation();const theme = useTheme();+ const {+ openCurrentDirectory,+ currentDirectoryPath,+ searchQuery,+ setSearchQuery,+ exitSearchMode+ } = useDirectoryContentContext();+ const { getIndex, isIndexing } = useLocationIndexContext();const [, forceUpdate] = useReducer(x => x + 1, 0);- // const textQuery = useRef<string>(props.searchQuery.textQuery);- // const tagsAND = useRef<Array<TS.Tag>>(props.searchQuery.tagsAND);+ const maxSearchResults = useSelector(getMaxSearchResults);+ const searches = useSelector(getSearches);+ const showUnixHiddenEntries = useSelector(getShowUnixHiddenEntries);+ // const textQuery = useRef<string>(searchQuery.textQuery);+ // const tagsAND = useRef<Array<TS.Tag>>(searchQuery.tagsAND);const fileTypes = useRef<Array<string>>(- props.searchQuery.fileTypes- ? props.searchQuery.fileTypes- : FileTypeGroups.any+ searchQuery.fileTypes ? searchQuery.fileTypes : FileTypeGroups.any);- const searchBoxing = props.searchQuery.searchBoxing- ? props.searchQuery.searchBoxing+ const searchBoxing = searchQuery.searchBoxing+ ? searchQuery.searchBoxing: 'location';// useRef<'fuzzy' | 'semistrict' | 'strict'>(- const searchType = props.searchQuery.searchType- ? props.searchQuery.searchType- : 'fuzzy';+ const searchType = searchQuery.searchType ? searchQuery.searchType : 'fuzzy';const lastModified = useRef<string>(- props.searchQuery.lastModified ? props.searchQuery.lastModified : ''+ searchQuery.lastModified ? searchQuery.lastModified : '');const [saveSearchDialogOpened, setSaveSearchDialogOpened] = useState<TS.SearchQuery@@ -137,25 +120,25 @@ function SearchPopover(props: Props) {// const tagTimePeriodHelper = useRef<string>(' ');const [tagPlace, setTagPlace] = useState<string>(' ');const [tagPlaceHelper, setTagPlaceHelper] = useState<string>(' ');- const tagTimePeriodFrom = props.searchQuery.tagTimePeriodFrom // useRef<number | null>(- ? props.searchQuery.tagTimePeriodFrom+ const tagTimePeriodFrom = searchQuery.tagTimePeriodFrom // useRef<number | null>(+ ? searchQuery.tagTimePeriodFrom: null;- const tagTimePeriodTo = props.searchQuery.tagTimePeriodTo //useRef<number | null>(- ? props.searchQuery.tagTimePeriodTo+ const tagTimePeriodTo = searchQuery.tagTimePeriodTo //useRef<number | null>(+ ? searchQuery.tagTimePeriodTo: null;const [tagPlaceLat, setTagPlaceLat] = useState<number | null>(null);const [tagPlaceLong, setTagPlaceLong] = useState<number | null>(null);// const [tagPlaceRadius, setTagPlaceRadius] = useState<number>(0);const forceIndexing = useRef<boolean>(- props.searchQuery.forceIndexing ? props.searchQuery.forceIndexing : false+ searchQuery.forceIndexing ? searchQuery.forceIndexing : false);const fileSize = useRef<string>(- props.searchQuery.fileSize ? props.searchQuery.fileSize : ''+ searchQuery.fileSize ? searchQuery.fileSize : '');/*useEffect(() => {- props.setTextQuery(props.searchQuery.textQuery);- }, [props.searchQuery]);*/+ props.setTextQuery(searchQuery.textQuery);+ }, [searchQuery]);*/const handleFileTypeChange = (event: React.ChangeEvent<HTMLInputElement>) => {const { target } = event;@@ -164,14 +147,13 @@ function SearchPopover(props: Props) {if (name === 'fileTypes') {const types = JSON.parse(value);fileTypes.current = types;- const searchQuery = {- ...props.searchQuery,+ setSearchQuery({+ ...searchQuery,searchBoxing: searchBoxing,fileTypes: types,- showUnixHiddenEntries: props.showUnixHiddenEntries,+ showUnixHiddenEntries,executeSearch: false- };- props.setSearchQuery(searchQuery);+ });}};@@ -181,15 +163,14 @@ function SearchPopover(props: Props) {if (name === 'fileSize') {fileSize.current = value;- const searchQuery = {- ...props.searchQuery,++ setSearchQuery({+ ...searchQuery,searchBoxing: searchBoxing,fileSize: value,- showUnixHiddenEntries: props.showUnixHiddenEntries,+ showUnixHiddenEntries,executeSearch: false- };-- props.setSearchQuery(searchQuery);+ });}};@@ -201,14 +182,13 @@ function SearchPopover(props: Props) {if (name === 'lastModified') {lastModified.current = value;- const searchQuery = {- ...props.searchQuery,+ setSearchQuery({+ ...searchQuery,searchBoxing: searchBoxing,lastModified: value,- showUnixHiddenEntries: props.showUnixHiddenEntries,+ showUnixHiddenEntries,executeSearch: false- };- props.setSearchQuery(searchQuery);+ });}};@@ -218,7 +198,7 @@ function SearchPopover(props: Props) {const { target } = event;const { value } = target;- const savedSearch = props.searches.find(search => search.uuid === value);+ const savedSearch = searches.find(search => search.uuid === value);if (!savedSearch) {return true;}@@ -246,11 +226,11 @@ function SearchPopover(props: Props) {tagTimePeriod.current = ttPeriod;}*/- props.setSearchQuery({+ setSearchQuery({...savedSearch,tagTimePeriodFrom: savedSearch.tagTimePeriodFrom,tagTimePeriodTo: savedSearch.tagTimePeriodTo,- showUnixHiddenEntries: props.showUnixHiddenEntries+ showUnixHiddenEntries});};@@ -266,37 +246,37 @@ function SearchPopover(props: Props) {if (reason === 'remove-value') {if (name === 'tagsAND') {searchQuery = {- ...props.searchQuery,- tagsAND: removeTags(props.searchQuery.tagsAND, value)+ ...searchQuery,+ tagsAND: removeTags(searchQuery.tagsAND, value)};} else if (name === 'tagsNOT') {searchQuery = {- ...props.searchQuery,- tagsNOT: removeTags(props.searchQuery.tagsNOT, value)+ ...searchQuery,+ tagsNOT: removeTags(searchQuery.tagsNOT, value)};} else if (name === 'tagsOR') {searchQuery = {- ...props.searchQuery,- tagsOR: removeTags(props.searchQuery.tagsOR, value)+ ...searchQuery,+ tagsOR: removeTags(searchQuery.tagsOR, value)};}} else {// eslint-disable-next-line no-lonely-ifif (name === 'tagsAND') {- searchQuery = { ...props.searchQuery, tagsAND: value };+ searchQuery = { ...searchQuery, tagsAND: value };} else if (name === 'tagsNOT') {- searchQuery = { ...props.searchQuery, tagsNOT: value };+ searchQuery = { ...searchQuery, tagsNOT: value };} else if (name === 'tagsOR') {- searchQuery = { ...props.searchQuery, tagsOR: value };+ searchQuery = { ...searchQuery, tagsOR: value };}}if (!haveSearchFilters(searchQuery)) {clearSearch();} else {- props.setSearchQuery({+ setSearchQuery({...searchQuery,searchBoxing: searchBoxing,- showUnixHiddenEntries: props.showUnixHiddenEntries,+ showUnixHiddenEntries,executeSearch: false});}@@ -369,14 +349,6 @@ function SearchPopover(props: Props) {}};- function openCurrentDirectory() {- if (props.currentDirectory) {- props.loadDirectoryContent(props.currentDirectory, false, true);- } else {- props.exitSearchMode();- }- }-const clearSearch = () => {props.setTextQuery('');//searchBoxing.current = 'location';@@ -394,31 +366,31 @@ function SearchPopover(props: Props) {// setTagPlaceRadius(0);forceIndexing.current = false;fileSize.current = '';- props.setSearchQuery({});- props.exitSearchMode();- openCurrentDirectory();+ setSearchQuery({});+ exitSearchMode();props.onClose();+ openCurrentDirectory();};const saveSearch = (isNew = true) => {const tagsAND = mergeWithExtractedTags(props.textQuery,- props.searchQuery.tagsAND,+ searchQuery.tagsAND,'+');const tagsOR = mergeWithExtractedTags(props.textQuery,- props.searchQuery.tagsOR,+ searchQuery.tagsOR,'|');const tagsNOT = mergeWithExtractedTags(props.textQuery,- props.searchQuery.tagsNOT,+ searchQuery.tagsNOT,'-');setSaveSearchDialogOpened({- uuid: isNew ? undefined : props.searchQuery.uuid,- title: props.searchQuery.title,+ uuid: isNew ? undefined : searchQuery.uuid,+ title: searchQuery.title,textQuery: props.textQuery,tagsAND,tagsOR,@@ -433,8 +405,8 @@ function SearchPopover(props: Props) {tagPlaceLat,tagPlaceLong,// tagPlaceRadius,- maxSearchResults: props.maxSearchResults,- currentDirectory: props.currentDirectory,+ maxSearchResults: maxSearchResults,+ currentDirectory: currentDirectoryPath,forceIndexing: forceIndexing.current});};@@ -444,12 +416,11 @@ function SearchPopover(props: Props) {boxing: 'location' | 'folder' | 'global') => {if (boxing !== null) {- const searchQuery = {- ...props.searchQuery,+ setSearchQuery({+ ...searchQuery,searchBoxing: boxing,executeSearch: false- };- props.setSearchQuery(searchQuery);+ });/*searchBoxing.current = boxing;forceUpdate();*/@@ -461,12 +432,11 @@ function SearchPopover(props: Props) {type: 'fuzzy' | 'semistrict' | 'strict') => {if (type !== null) {- const searchQuery = {- ...props.searchQuery,+ setSearchQuery({+ ...searchQuery,searchType: type,executeSearch: false- };- props.setSearchQuery(searchQuery);+ });/*searchType.current = type;forceUpdate();*/@@ -476,20 +446,20 @@ function SearchPopover(props: Props) {const executeSearch = () => {const tagsAND = mergeWithExtractedTags(props.textQuery,- props.searchQuery.tagsAND,+ searchQuery.tagsAND,'+');const tagsOR = mergeWithExtractedTags(props.textQuery,- props.searchQuery.tagsOR,+ searchQuery.tagsOR,'|');const tagsNOT = mergeWithExtractedTags(props.textQuery,- props.searchQuery.tagsNOT,+ searchQuery.tagsNOT,'-');- const searchQuery: TS.SearchQuery = {+ const query: TS.SearchQuery = {textQuery: props.textQuery,tagsAND,tagsOR,@@ -504,21 +474,18 @@ function SearchPopover(props: Props) {tagPlaceLat,tagPlaceLong,// tagPlaceRadius,- maxSearchResults: props.maxSearchResults,- currentDirectory: props.currentDirectory,+ maxSearchResults: maxSearchResults,+ currentDirectory: currentDirectoryPath,forceIndexing: forceIndexing.current,- showUnixHiddenEntries: props.showUnixHiddenEntries,+ showUnixHiddenEntries,executeSearch: true};console.log('Search object: ' + JSON.stringify(searchQuery));- props.setSearchQuery(searchQuery);+ setSearchQuery(query);props.onClose();};- const { indexing } = props;- const indexStatus = GlobalSearch.getInstance().getIndex()- ? GlobalSearch.getInstance().getIndex().length + ' indexed entries'- : '';+ const indexStatus = getIndex() ? getIndex().length + ' indexed entries' : '';return (<SidePanelstyle={{@@ -583,17 +550,17 @@ function SearchPopover(props: Props) {<Selectname="savedSearch"labelId="saved-searches"- disabled={indexing || !Pro}+ disabled={isIndexing || !Pro}onChange={handleSavedSearchChange}displayEmptyfullWidth- value={props.searchQuery.uuid ? props.searchQuery.uuid : -1}+ value={searchQuery.uuid ? searchQuery.uuid : -1}><MenuItem value={-1} style={{ display: 'none' }} />- {props.searches.length < 1 && (+ {searches.length < 1 && (<MenuItem>{t('noSavedSearches')}</MenuItem>)}- {props.searches.map(search => (+ {searches.map(search => (<MenuItem key={search.uuid} value={search.uuid}><span style={{ width: '100%' }}>{search.title}</span></MenuItem>@@ -609,7 +576,7 @@ function SearchPopover(props: Props) {width: '100%'}}>- {props.searchQuery.uuid && (+ {searchQuery.uuid && (<Tooltip title={t('editSavedSearchTitle')}><IconButtondata-tid="editSearchBtnTID"@@ -643,7 +610,7 @@ function SearchPopover(props: Props) {/></Grid></Grid>- <FormControl className={classes.formControl} disabled={indexing}>+ <FormControl className={classes.formControl} disabled={isIndexing}><ToggleButtonGrouponChange={switchSearchBoxing}size="small"@@ -669,7 +636,7 @@ function SearchPopover(props: Props) {</ToggleButton></ToggleButtonGroup></FormControl>- <FormControl className={classes.formControl} disabled={indexing}>+ <FormControl className={classes.formControl} disabled={isIndexing}><ToggleButtonGrouponChange={switchSearchType}size="small"@@ -694,7 +661,7 @@ function SearchPopover(props: Props) {</ToggleButton></ToggleButtonGroup></FormControl>- <FormControl className={classes.formControl} disabled={indexing}>+ <FormControl className={classes.formControl} disabled={isIndexing}><ToggleButtonGrouponChange={() => {forceIndexing.current = !forceIndexing.current;@@ -717,33 +684,33 @@ function SearchPopover(props: Props) {</ToggleButton></ToggleButtonGroup></FormControl>- <FormControl className={classes.formControl} disabled={indexing}>+ <FormControl className={classes.formControl} disabled={isIndexing}><TagsSelectdataTid="searchTagsAndTID"placeholderText={t('core:selectTags')}label={t('core:mustContainTheseTags')}- tags={props.searchQuery.tagsAND}+ tags={searchQuery.tagsAND}handleChange={handleTagFieldChange}tagSearchType="tagsAND"tagMode="remove"/></FormControl>- <FormControl className={classes.formControl} disabled={indexing}>+ <FormControl className={classes.formControl} disabled={isIndexing}><TagsSelectdataTid="searchTagsOrTID"placeholderText={t('core:selectTags')}- tags={props.searchQuery.tagsOR}+ tags={searchQuery.tagsOR}label={t('core:atLeastOneOfTheseTags')}handleChange={handleTagFieldChange}tagSearchType="tagsOR"tagMode="remove"/></FormControl>- <FormControl className={classes.formControl} disabled={indexing}>+ <FormControl className={classes.formControl} disabled={isIndexing}><TagsSelectdataTid="searchTagsNotTID"placeholderText={t('core:selectTags')}- tags={props.searchQuery.tagsNOT}+ tags={searchQuery.tagsNOT}label={t('core:noneOfTheseTags')}handleChange={handleTagFieldChange}tagSearchType="tagsNOT"@@ -752,7 +719,7 @@ function SearchPopover(props: Props) {</FormControl><FormControlclassName={classes.formControl}- disabled={indexing || !Pro}+ disabled={isIndexing || !Pro}><ProTooltip tooltip={t('filterByTypTooltip')}><InputLabel htmlFor="file-type">{t('core:fileType')}</InputLabel>@@ -875,7 +842,7 @@ function SearchPopover(props: Props) {</FormControl><FormControlclassName={classes.formControl}- disabled={indexing || !Pro}+ disabled={isIndexing || !Pro}><ProTooltip tooltip={t('filterBySizeTooltip')}><InputLabel@@ -929,7 +896,7 @@ function SearchPopover(props: Props) {</FormControl><FormControlclassName={classes.formControl}- disabled={indexing || !Pro}+ disabled={isIndexing || !Pro}><ProTooltip tooltip={t('filterByLastModifiedDateTooltip')}><InputLabel@@ -967,39 +934,37 @@ function SearchPopover(props: Props) {<ProTooltip tooltip={t('enterTimePeriodTooltip')}><LocalizationProviderdateAdapter={AdapterDateFns}- utils={DateFnsUtils}+ /*utils={DateFnsUtils}*/><Box position="relative" display="inline-flex"><DatePickerlabel={t('enterTagTimePeriodFrom')}- disabled={indexing || !Pro}+ disabled={isIndexing || !Pro}inputFormat="yyyy-MM-dd"- value={tagTimePeriodFrom}+ value={new Date(tagTimePeriodFrom)}onChange={(fromDataTime: Date) => {if (fromDataTime) {- const searchQuery = {- ...props.searchQuery,+ setSearchQuery({+ ...searchQuery,tagTimePeriodFrom: fromDataTime.getTime(),executeSearch: false- };- props.setSearchQuery(searchQuery);+ });}}}renderInput={params => <TextField {...params} />}/><DatePickerlabel={t('enterTagTimePeriodTo')}- disabled={indexing || !Pro}+ disabled={isIndexing || !Pro}inputFormat="yyyy-MM-dd"- value={tagTimePeriodTo}+ value={new Date(tagTimePeriodTo)}onChange={(toDataTime: Date) => {if (toDataTime) {- const searchQuery = {- ...props.searchQuery,+ setSearchQuery({+ ...searchQuery,tagTimePeriodTo: toDataTime.getTime(),executeSearch: false- };- props.setSearchQuery(searchQuery);+ });}}}renderInput={params => (@@ -1083,13 +1048,13 @@ function SearchPopover(props: Props) {{t('resetBtn')}</Button><Button- disabled={indexing}+ disabled={isIndexing}variant="contained"id="searchButtonAdvTID"onClick={executeSearch}size="small">- {indexing ? 'Search disabled while indexing' : t('searchTitle')}+ {isIndexing ? 'Search disabled while indexing' : t('searchTitle')}</Button></div></div>@@ -1099,9 +1064,9 @@ function SearchPopover(props: Props) {onClose={(searchQuery: TS.SearchQuery) => {setSaveSearchDialogOpened(undefined);if (searchQuery) {- props.setSearchQuery({+ setSearchQuery({...searchQuery,- showUnixHiddenEntries: props.showUnixHiddenEntries+ showUnixHiddenEntries});}}}@@ -1113,39 +1078,4 @@ function SearchPopover(props: Props) {);}-function mapStateToProps(state) {- return {- indexing: isIndexing(state),- searchQuery: getSearchQuery(state),- currentDirectory: getDirectoryPath(state),- maxSearchResults: getMaxSearchResults(state),- searches: getSearches(state),- showUnixHiddenEntries: getShowUnixHiddenEntries(state)- };-}--function mapDispatchToProps(dispatch) {- return bindActionCreators(- {- setSearchQuery: LocationIndexActions.setSearchQuery,- createLocationsIndexes: LocationIndexActions.createLocationsIndexes,- loadDirectoryContent: AppActions.loadDirectoryContent,- setSearchResults: AppActions.setSearchResults,- exitSearchMode: AppActions.exitSearchMode- },- dispatch- );-}--const areEqual = (prevProp, nextProp) =>- nextProp.indexing === prevProp.indexing &&- nextProp.searchQuery === prevProp.searchQuery &&- nextProp.textQuery === prevProp.textQuery &&- nextProp.currentDirectory === prevProp.currentDirectory &&- JSON.stringify(nextProp.searches) === JSON.stringify(prevProp.searches) &&- JSON.stringify(nextProp.classes) === JSON.stringify(prevProp.classes);--export default connect(- mapStateToProps,- mapDispatchToProps-)(React.memo(SearchPopover, areEqual));+export default SearchPopover;diff --git a/app/components/StoredSearches.tsx b/app/components/StoredSearches.tsxindex f15275d51..e1c9a95a6 100644--- a/app/components/StoredSearches.tsx+++ b/app/components/StoredSearches.tsx@@ -30,10 +30,6 @@ import ArrowDownIcon from '@mui/icons-material/KeyboardArrowDown';import ArrowRightIcon from '@mui/icons-material/KeyboardArrowRight';import Typography from '@mui/material/Typography';import ListItem from '@mui/material/ListItem';-import {- actions as LocationIndexActions,- getSearchQuery-} from '-/reducers/location-index';import {actions as SettingsActions,getFileEditHistory,@@ -47,20 +43,17 @@ import { Pro } from '../pro';import { actions as SearchActions, getSearches } from '-/reducers/searches';import { TS } from '-/tagspaces.namespace';import SearchMenu from '-/components/menus/SearchMenu';-import { actions as AppActions } from '-/reducers/app';import HistoryMenu from '-/components/menus/HistoryMenu';import BookmarksMenu from '-/components/menus/BookmarksMenu';import { classes, SidePanel } from '-/components/SidePanels.css';import { useTranslation } from 'react-i18next';import RenderHistory from '-/components/RenderHistory';+import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';+import { useLocationIndexContext } from '-/hooks/useLocationIndexContext';interface Props {style?: any;- searchQuery: TS.SearchQuery;- setSearchQuery: (searchQuery: TS.SearchQuery) => void;searches: Array<TS.SearchQuery>;- // searchLocationIndex: (searchQuery: TS.SearchQuery) => void;- // searchAllLocations: (searchQuery: TS.SearchQuery) => void;showUnixHiddenEntries: boolean;addSearches: (searches: Array<TS.SearchQuery>) => void;reduceHeightBy: number;@@ -81,6 +74,7 @@ const historyKeys = Pro && Pro.history ? Pro.history.historyKeys : {};function StoredSearches(props: Props) {const { t } = useTranslation();+ const { setSearchQuery } = useDirectoryContentContext();const [saveSearchDialogOpened, setSaveSearchDialogOpened] = useState<TS.SearchQuery>(undefined);@@ -135,9 +129,10 @@ function StoredSearches(props: Props) {return true;}- props.setSearchQuery({+ setSearchQuery({...savedSearch,- showUnixHiddenEntries: props.showUnixHiddenEntries+ showUnixHiddenEntries: props.showUnixHiddenEntries,+ executeSearch: true});};@@ -531,7 +526,7 @@ function StoredSearches(props: Props) {onClose={(searchQuery: TS.SearchQuery) => {setSaveSearchDialogOpened(undefined);if (searchQuery) {- props.setSearchQuery({+ setSearchQuery({...searchQuery,showUnixHiddenEntries: props.showUnixHiddenEntries});@@ -583,7 +578,6 @@ function StoredSearches(props: Props) {function mapStateToProps(state) {return {- searchQuery: getSearchQuery(state),searches: getSearches(state),showUnixHiddenEntries: getShowUnixHiddenEntries(state),storedSearchesVisible: getStoredSearchesVisible(state),@@ -598,7 +592,6 @@ function mapDispatchToProps(dispatch) {return bindActionCreators({addSearches: SearchActions.addSearches,- setSearchQuery: LocationIndexActions.setSearchQuery,setStoredSearchesVisible: SettingsActions.setStoredSearchesVisible,setShowBookmarks: SettingsActions.setShowBookmarks,setFileOpenHistory: SettingsActions.setFileOpenHistory,@@ -616,7 +609,6 @@ const areEqual = (prevProp, nextProp) =>nextProp.folderOpenHistory === prevProp.folderOpenHistory &&nextProp.fileEditHistory === prevProp.fileEditHistory &&nextProp.indexing === prevProp.indexing &&- nextProp.searchQuery === prevProp.searchQuery &&nextProp.currentDirectory === prevProp.currentDirectory &&nextProp.indexedEntriesCount === prevProp.indexedEntriesCount &&JSON.stringify(nextProp.searches) === JSON.stringify(prevProp.searches);diff --git a/app/components/TagContainer.tsx b/app/components/TagContainer.tsxindex c27398449..ccfde3c1f 100644--- a/app/components/TagContainer.tsx+++ b/app/components/TagContainer.tsx@@ -32,7 +32,6 @@ import TagContainerMenu from '-/components/TagContainerMenu';interface Props {tag: TS.Tag;- isReadOnlyMode?: boolean;tagGroup?: TS.TagGroup;handleTagMenu?: (event: Object,diff --git a/app/components/TagContainerMenu.tsx b/app/components/TagContainerMenu.tsxindex eb10d5653..4643ccd40 100644--- a/app/components/TagContainerMenu.tsx+++ b/app/components/TagContainerMenu.tsx@@ -20,8 +20,8 @@ import React from 'react';import { useSelector } from 'react-redux';import MoreVertIcon from '@mui/icons-material/MoreVert';import RemoveTagIcon from '@mui/icons-material/Close';-import { isReadOnlyMode } from '-/reducers/app';import { TS } from '-/tagspaces.namespace';+import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';interface Props {tag: TS.Tag;@@ -31,7 +31,7 @@ interface Props {}function TagContainerMenu(props: Props) {- const readOnlyMode = useSelector(isReadOnlyMode);+ const { readOnlyMode } = useCurrentLocationContext();const { deleteIcon, tag, handleRemoveTag, tagMode } = props;if (readOnlyMode) {return <div style={{ width: 10 }} />;diff --git a/app/components/TagLibrary.tsx b/app/components/TagLibrary.tsxindex 59a9cebf4..e7e5a2d6c 100644--- a/app/components/TagLibrary.tsx+++ b/app/components/TagLibrary.tsx@@ -42,12 +42,10 @@ import {getTagTextColor} from '../reducers/settings';import {- actions as AppActions,AppDispatch,getSelectedEntries,- isReadOnlyMode,isTagLibraryChanged-} from '../reducers/app';+} from '-/reducers/app';import SmartTags from '../reducers/smart-tags';import EditTagDialog from '-/components/dialogs/EditTagDialog';import { TS } from '-/tagspaces.namespace';@@ -76,6 +74,7 @@ import { classes, SidePanel } from '-/components/SidePanels.css';import { useTranslation } from 'react-i18next';import { useOpenedEntryContext } from '-/hooks/useOpenedEntryContext';import { useTaggingActionsContext } from '-/hooks/useTaggingActionsContext';+import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';interface Props {style?: any;@@ -85,13 +84,17 @@ interface Props {function TagLibrary(props: Props) {const { t } = useTranslation();const { addTags } = useTaggingActionsContext();+ const {+ switchLocationTypeByID,+ switchCurrentLocationType,+ readOnlyMode+ } = useCurrentLocationContext();const dispatch: AppDispatch = useDispatch();const tagBackgroundColor = useSelector(getTagColor);const tagTextColor = useSelector(getTagTextColor);const selectedEntries: Array<TS.FileSystemEntry> = useSelector(getSelectedEntries);- const readOnly = useSelector(isReadOnlyMode);const tagGroupCollapsed: Array<string> = useSelector(getTagGroupCollapsed);const locations: Array<TS.Location> = useSelector(getLocations);const saveTagInLocation: boolean = useSelector(getSaveTagInLocation);@@ -272,7 +275,7 @@ function TagLibrary(props: Props) {tagGroup.expanded = !(tagGroupCollapsed && tagGroupCollapsed.includes(tagGroup.uuid));- const isReadOnly = tagGroup.readOnly || isTagLibraryReadOnly;+return (<div key={tagGroup.uuid}><TagGroupTitleDnD@@ -285,13 +288,13 @@ function TagLibrary(props: Props) {toggleTagGroup={toggleTagGroupDispatch}locations={locations}tagGroupCollapsed={tagGroupCollapsed}- isReadOnly={isReadOnly}+ isReadOnly={tagGroup.readOnly || isTagLibraryReadOnly}/><Collapse in={tagGroup.expanded} unmountOnExit><TagGroupContainer taggroup={tagGroup}>{tagGroup.children &&tagGroup.children.map((tag: TS.Tag, idx) => {- if (readOnly) {+ if (readOnlyMode) {return (<TagContainerkey={tagGroup.uuid + tag.title}@@ -437,14 +440,10 @@ function TagLibrary(props: Props) {l => l.uuid === entry.locationId);if (location) {- dispatch(LocationActions.switchLocationType(location.uuid)).then(- currentLocationId => {- setTagGroups(createTagGroup(entry, tagGroups, location));- dispatch(- AppActions.switchCurrentLocationType(currentLocationId)- );- }- );+ switchLocationTypeByID(location.uuid).then(currentLocationId => {+ setTagGroups(createTagGroup(entry, tagGroups, location));+ switchCurrentLocationType();+ });} else {setTagGroups(createTagGroup(entry, tagGroups));}diff --git a/app/components/TagsSelect.tsx b/app/components/TagsSelect.tsxindex d25044b41..fb3935387 100644--- a/app/components/TagsSelect.tsx+++ b/app/components/TagsSelect.tsx@@ -27,6 +27,7 @@ import TagContainer from '-/components/TagContainer';import { getUuid } from '@tagspaces/tagspaces-common/utils-io';import { getAllTags } from '-/services/taglibrary-utils';import { Box } from '@mui/material';+import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';/*const styles: any = (theme: any) => ({root: {@@ -75,7 +76,6 @@ interface Props {handleChange?: (param1: any, param2: any, param3?: any) => void;// allTags?: TS.Tag[];tagMode?: 'default' | 'display' | 'remove';- isReadOnlyMode?: boolean;placeholderText?: string;selectedEntryPath?: string;autoFocus?: boolean;@@ -83,6 +83,7 @@ interface Props {}function TagsSelect(props: Props) {+ const { readOnlyMode } = useCurrentLocationContext();const [tagMenuAnchorEl, setTagMenuAnchorEl] = useState<null | HTMLElement>(null);@@ -98,8 +99,7 @@ function TagsSelect(props: Props) {selectedEntryPath,autoFocus = false,tags = [],- tagMode,- isReadOnlyMode+ tagMode} = props;function handleTagChange(@@ -107,7 +107,7 @@ function TagsSelect(props: Props) {selectedTags: Array<TS.Tag>,reason: string) {- if (!isReadOnlyMode) {+ if (!readOnlyMode) {if (reason === 'selectOption') {props.handleChange(props.tagSearchType, selectedTags, reason);} else if (reason === 'createOption') {@@ -183,9 +183,9 @@ function TagsSelect(props: Props) {<Box sx={{ flexGrow: 1 }}><Autocompletedata-tid={props.dataTid}- disabled={isReadOnlyMode}+ disabled={readOnlyMode}multiple- options={!props.isReadOnlyMode ? allTags.current : []}+ options={!readOnlyMode ? allTags.current : []}getOptionLabel={(option: TS.Tag) => option.title}freeSoloautoSelect@@ -197,7 +197,6 @@ function TagsSelect(props: Props) {value.map((option: TS.Tag, index: number) => (<TagContainerkey={selectedEntryPath + option + index}- isReadOnlyMode={isReadOnlyMode}tag={option}tagMode={tagMode}handleTagMenu={handleTagMenu}@@ -207,11 +206,7 @@ function TagsSelect(props: Props) {}renderOption={(props, option) => (<Box component="li" {...props}>- <TagContainer- isReadOnlyMode={true}- tag={option}- tagMode={tagMode}- />+ <TagContainer tag={option} tagMode={tagMode} /></Box>)}renderInput={params => (diff --git a/app/components/TargetFileBox.tsx b/app/components/TargetFileBox.tsxindex c6cab900c..57802db9a 100644--- a/app/components/TargetFileBox.tsx+++ b/app/components/TargetFileBox.tsx@@ -23,15 +23,13 @@ import { useTranslation } from 'react-i18next';import AppConfig from '-/AppConfig';import PlatformIO from '-/services/platform-facade';import { useDispatch, useSelector } from 'react-redux';-import {- actions as AppActions,- AppDispatch,- getDirectoryPath,- isReadOnlyMode-} from '-/reducers/app';-import IOActions from '-/reducers/io-actions';+import { actions as AppActions, AppDispatch } from '-/reducers/app';import { TS } from '-/tagspaces.namespace';import { Identifier } from 'dnd-core';+import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';+import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';+import { useNotificationContext } from '-/hooks/useNotificationContext';+import { useIOActionsContext } from '-/hooks/useIOActionsContext';type DragItem = { files: File[]; items: DataTransferItemList };type DragProps = { isActive: boolean; handlerId: Identifier | null };@@ -45,9 +43,11 @@ interface Props {function TargetFileBox(props: Props) {const { t } = useTranslation();const dispatch: AppDispatch = useDispatch();+ const { readOnlyMode } = useCurrentLocationContext();+ const { currentDirectoryPath } = useDirectoryContentContext();+ const { uploadFilesAPI } = useIOActionsContext();+ const { showNotification } = useNotificationContext();const ref = useRef<HTMLDivElement>(null);- const readOnlyMode = useSelector(isReadOnlyMode);- const directoryPath = useSelector(getDirectoryPath);const { setMoveCopyDialogOpened } = props;const onUploadProgress = (progress, abort, fileName) => {@@ -56,24 +56,16 @@ function TargetFileBox(props: Props) {const handleCopyFiles = (files: Array<File>) => {if (readOnlyMode) {- dispatch(- AppActions.showNotification(- t('core:dndDisabledReadOnlyMode'),- 'error',- true- )- );+ showNotification(t('core:dndDisabledReadOnlyMode'), 'error', true);return Promise.reject(t('core:dndDisabledReadOnlyMode'));}if (files) {console.log('Dropped files: ' + JSON.stringify(files));- if (!directoryPath) {- dispatch(- AppActions.showNotification(- 'Importing files failed, because no folder is opened in TagSpaces!',- 'error',- true- )+ if (!currentDirectoryPath) {+ showNotification(+ 'Importing files failed, because no folder is opened in TagSpaces!',+ 'error',+ true);return Promise.reject(new Error(@@ -83,9 +75,7 @@ function TargetFileBox(props: Props) {}dispatch(AppActions.resetProgress());dispatch(AppActions.toggleUploadDialog());- return dispatch(- IOActions.uploadFilesAPI(files, directoryPath, onUploadProgress)- )+ return uploadFilesAPI(files, currentDirectoryPath, onUploadProgress).then((fsEntries: Array<TS.FileSystemEntry>) => {dispatch(AppActions.reflectCreateEntries(fsEntries));return true;@@ -118,7 +108,7 @@ function TargetFileBox(props: Props) {isActive: m.isOver({ shallow: true }) && m.canDrop()})}),- [directoryPath]+ [currentDirectoryPath]);drop(ref);diff --git a/app/components/dialogs/CreateDirectoryDialog.tsx b/app/components/dialogs/CreateDirectoryDialog.tsxindex ab3efb02e..4bd201fb0 100644--- a/app/components/dialogs/CreateDirectoryDialog.tsx+++ b/app/components/dialogs/CreateDirectoryDialog.tsx@@ -17,7 +17,7 @@*/import React, { useState, useEffect, useRef } from 'react';-import { useDispatch, useSelector } from 'react-redux';+import { useSelector } from 'react-redux';import Button from '@mui/material/Button';import TextField from '@mui/material/TextField';import DialogActions from '@mui/material/DialogActions';@@ -26,17 +26,12 @@ import DialogTitle from '@mui/material/DialogTitle';import FormControl from '@mui/material/FormControl';import FormHelperText from '@mui/material/FormHelperText';import Dialog from '@mui/material/Dialog';-import {- actions as AppActions,- AppDispatch,- getDirectoryPath-} from '-/reducers/app';import { joinPaths } from '@tagspaces/tagspaces-common/paths';import DialogCloseButton from '-/components/dialogs/DialogCloseButton';import PlatformIO from '-/services/platform-facade';import { useTranslation } from 'react-i18next';-import { useOpenedEntryContext } from '-/hooks/useOpenedEntryContext';import { useFsActionsContext } from '-/hooks/useFsActionsContext';+import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';interface Props {open: boolean;@@ -49,11 +44,12 @@ interface Props {function CreateDirectoryDialog(props: Props) {const { t } = useTranslation();const { createDirectory } = useFsActionsContext();+ const { currentDirectoryPath } = useDirectoryContentContext();+const [inputError, setInputError] = useState(false);const isFirstRun = useRef(true);const [disableConfirmButton, setDisableConfirmButton] = useState(true);const [name, setName] = useState('');- const currentDirectoryPath = useSelector(getDirectoryPath);const { open, onClose, selectedDirectoryPath, reflect } = props;useEffect(() => {diff --git a/app/components/dialogs/CreateEditLocationDialog.tsx b/app/components/dialogs/CreateEditLocationDialog.tsxindex 3cd225a32..16b6aa014 100644--- a/app/components/dialogs/CreateEditLocationDialog.tsx+++ b/app/components/dialogs/CreateEditLocationDialog.tsx@@ -61,15 +61,10 @@ import { TS } from '-/tagspaces.namespace';import DialogCloseButton from '-/components/dialogs/DialogCloseButton';import InfoIcon from '-/components/InfoIcon';import { ProLabel, BetaLabel, ProTooltip } from '-/components/HelperComponents';-import { actions as LocationActions, getLocations } from '-/reducers/locations';-import {- NotificationTypes,- actions as AppActions,- AppDispatch-} from '-/reducers/app';+import { getLocations } from '-/reducers/locations';+import { AppDispatch } from '-/reducers/app';import { getPersistTagsInSidecarFile, isDevMode } from '-/reducers/settings';import ConfirmDialog from '-/components/dialogs/ConfirmDialog';-import { actions as LocationIndexActions } from '-/reducers/location-index';import PlatformIO from '-/services/platform-facade';import WebdavForm from '-/components/dialogs/WebdavForm';import { useTheme } from '@mui/material/styles';@@ -79,6 +74,9 @@ import { getUuid } from '@tagspaces/tagspaces-common/utils-io';import { ExpandIcon } from '-/components/CommonIcons';import MaxLoopsSelect from '-/components/dialogs/MaxLoopsSelect';import { useTranslation } from 'react-i18next';+import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';+import { useNotificationContext } from '-/hooks/useNotificationContext';+import { useLocationIndexContext } from '-/hooks/useLocationIndexContext';const PREFIX = 'CreateEditLocationDialog';@@ -94,7 +92,7 @@ const StyledDialog = styled(Dialog)(({ theme }) => ({}));interface Props {- location?: TS.Location;+ /*location?: TS.Location;*/open: boolean;onClose: () => void;classes: any;@@ -103,13 +101,16 @@ interface Props {function CreateEditLocationDialog(props: Props) {const { t } = useTranslation();- const dispatch: AppDispatch = useDispatch();++ const { showNotification } = useNotificationContext();+ const { createLocationIndex } = useLocationIndexContext();+ const { addLocation, selectedLocation } = useCurrentLocationContext();const isPersistTagsInSidecar = useSelector(getPersistTagsInSidecarFile);const locations: Array<TS.Location> = useSelector(getLocations);const devMode: boolean = useSelector(isDevMode);const IgnorePatternDialog =Pro && Pro.UI ? Pro.UI.IgnorePatternDialog : false;- const { location } = props;+ /*const { location } = props;*/const [showSecretAccessKey, setShowSecretAccessKey] = useState<boolean>(false);@@ -117,82 +118,96 @@ function CreateEditLocationDialog(props: Props) {const [errorTextPath, setErrorTextPath] = useState<boolean>(false);const [errorTextName, setErrorTextName] = useState<boolean>(false);const [name, setName] = useState<string>(- location && location.name ? location.name : ''+ selectedLocation && selectedLocation.name ? selectedLocation.name : '');const [username, setUserName] = useState<string>(- location && location.username ? location.username : ''+ selectedLocation && selectedLocation.username+ ? selectedLocation.username+ : '');const [password, setPassword] = useState<string>(- location && location.password ? location.password : ''+ selectedLocation && selectedLocation.password+ ? selectedLocation.password+ : '');let defaultIndexAge = AppConfig.maxIndexAge;- if (location && location.maxIndexAge && location.maxIndexAge > 0) {- const maxIndexAsString = location.maxIndexAge + '';+ if (+ selectedLocation &&+ selectedLocation.maxIndexAge &&+ selectedLocation.maxIndexAge > 0+ ) {+ const maxIndexAsString = selectedLocation.maxIndexAge + '';defaultIndexAge = parseInt(maxIndexAsString, 10);}const [maxIndexAge, setMaxIndexAge] = useState<number>(defaultIndexAge);let defaultMaxLoops = AppConfig.maxLoops;- if (location && location.maxLoops && location.maxLoops > 0) {- const maxLoopsAsString = location.maxLoops + '';+ if (+ selectedLocation &&+ selectedLocation.maxLoops &&+ selectedLocation.maxLoops > 0+ ) {+ const maxLoopsAsString = selectedLocation.maxLoops + '';defaultMaxLoops = parseInt(maxLoopsAsString, 10);}const [maxLoops, setMaxLoops] = useState<number>(defaultMaxLoops);const [storeName, setStoreName] = useState<string>(- location && location.name ? location.name : ''+ selectedLocation && selectedLocation.name ? selectedLocation.name : '');const [path, setPath] = useState<string>(- location && (location.path || location.paths)- ? location.path || location.paths[0]+ selectedLocation && (selectedLocation.path || selectedLocation.paths)+ ? selectedLocation.path || selectedLocation.paths[0]: '');const [storePath, setStorePath] = useState<string>(- location && (location.path || location.paths)- ? location.path || location.paths[0]+ selectedLocation && (selectedLocation.path || selectedLocation.paths)+ ? selectedLocation.path || selectedLocation.paths[0]: '');const [endpointURL, setEndpointURL] = useState<string>(- location ? location.endpointURL : ''+ selectedLocation ? selectedLocation.endpointURL : '');const [authType, setAuthType] = useState<string>('password');const [isDefault, setIsDefault] = useState<boolean>(- location ? location.isDefault : false+ selectedLocation ? selectedLocation.isDefault : false);const [isReadOnly, setIsReadOnly] = useState<boolean>(- location ? location.isReadOnly : false+ selectedLocation ? selectedLocation.isReadOnly : false);const [watchForChanges, setWatchForChanges] = useState<boolean>(- location ? location.watchForChanges : false+ selectedLocation ? selectedLocation.watchForChanges : false);const [disableIndexing, setIndexDisable] = useState<boolean>(- location ? location.disableIndexing : false+ selectedLocation ? selectedLocation.disableIndexing : false);const [fullTextIndex, setFullTextIndex] = useState<boolean>(- location ? location.fullTextIndex : false+ selectedLocation ? selectedLocation.fullTextIndex : false);const [accessKeyId, setAccessKeyId] = useState<string>(- location ? location.accessKeyId : ''+ selectedLocation ? selectedLocation.accessKeyId : '');const [secretAccessKey, setSecretAccessKey] = useState<string>(- location ? location.secretAccessKey : ''+ selectedLocation ? selectedLocation.secretAccessKey : '');const [sessionToken, setSessionToken] = useState<string>(- location ? location.sessionToken : undefined+ selectedLocation ? selectedLocation.sessionToken : undefined);const [bucketName, setBucketName] = useState<string>(- location ? location.bucketName : ''+ selectedLocation ? selectedLocation.bucketName : '');const [persistTagsInSidecarFile, setPersistTagsInSidecarFile] = useState<boolean | null>(- location && location.persistTagsInSidecarFile !== undefined- ? location.persistTagsInSidecarFile+ selectedLocation && selectedLocation.persistTagsInSidecarFile !== undefined+ ? selectedLocation.persistTagsInSidecarFile: null // props.isPersistTagsInSidecar);- const [region, setRegion] = useState<string>(location ? location.region : '');+ const [region, setRegion] = useState<string>(+ selectedLocation ? selectedLocation.region : ''+ );let defaultType;- if (location) {- defaultType = location.type;+ if (selectedLocation) {+ defaultType = selectedLocation.type;} else if (AppConfig.isWeb) {defaultType = locationType.TYPE_CLOUD;} else {@@ -200,7 +215,7 @@ function CreateEditLocationDialog(props: Props) {}const [type, setType] = useState<string>(defaultType);const [newuuid, setNewUuid] = useState<string>(- location ? location.uuid : getUuid()+ selectedLocation ? selectedLocation.uuid : getUuid());const [cloudErrorTextName, setCloudErrorTextName] = useState<boolean>(false);const [webdavErrorUrl, setWebdavErrorUrl] = useState<boolean>(false);@@ -212,7 +227,7 @@ function CreateEditLocationDialog(props: Props) {>(false);const [ignorePatternPaths, setIgnorePatternPaths] = useState<Array<string>>(- location ? location.ignorePatternPaths : undefined+ selectedLocation ? selectedLocation.ignorePatternPaths : undefined);const [isIgnorePatternDialogOpen, setIgnorePatternDialogOpen] = useState<@@ -270,12 +285,7 @@ function CreateEditLocationDialog(props: Props) {if (!locations.some(ln => ln.uuid === newId)) {setNewUuid(newId);} else {- dispatch(- AppActions.showNotification(- 'Location with this ID already exists',- NotificationTypes.error- )- );+ showNotification('Location with this ID already exists', 'error');}}/**@@ -364,7 +374,7 @@ function CreateEditLocationDialog(props: Props) {let loc;if (type === locationType.TYPE_LOCAL) {loc = {- uuid: props.location ? props.location.uuid : newuuid,+ uuid: selectedLocation ? selectedLocation.uuid : newuuid,type,name,path,@@ -379,7 +389,7 @@ function CreateEditLocationDialog(props: Props) {};} else if (type === locationType.TYPE_WEBDAV) {loc = {- uuid: props.location ? props.location.uuid : newuuid,+ uuid: selectedLocation ? selectedLocation.uuid : newuuid,type,authType,name,@@ -397,7 +407,7 @@ function CreateEditLocationDialog(props: Props) {};} else if (type === locationType.TYPE_CLOUD) {loc = {- uuid: props.location ? props.location.uuid : newuuid,+ uuid: selectedLocation ? selectedLocation.uuid : newuuid,type,name: storeName,path: storePath,@@ -423,8 +433,8 @@ function CreateEditLocationDialog(props: Props) {loc = { ...loc, persistTagsInSidecarFile };}- if (!props.location) {- dispatch(LocationActions.addLocation(loc));+ if (!selectedLocation) {+ addLocation(loc);} else if (props.editLocation) {loc.newuuid = newuuid;props.editLocation(loc);@@ -507,11 +517,11 @@ function CreateEditLocationDialog(props: Props) {}const currentTagsSetting =- props.location && props.location.persistTagsInSidecarFile !== null- ? location.persistTagsInSidecarFile+ selectedLocation && selectedLocation.persistTagsInSidecarFile !== null+ ? selectedLocation.persistTagsInSidecarFile: isPersistTagsInSidecar;- const disableLocationTypeSwitch: boolean = props.location !== undefined;+ const disableLocationTypeSwitch: boolean = selectedLocation !== undefined;const theme = useTheme();const fullScreen = useMediaQuery(theme.breakpoints.down('md'));@@ -534,7 +544,7 @@ function CreateEditLocationDialog(props: Props) {}}><DialogTitle>- {props.location+ {selectedLocation? t('core:editLocationTitle'): t('core:createLocationTitle')}<DialogCloseButton@@ -625,7 +635,7 @@ function CreateEditLocationDialog(props: Props) {</>}/>- {isFullTextIndexConfirmDialogOpened && location && (+ {isFullTextIndexConfirmDialogOpened && selectedLocation && (<ConfirmDialogopen={isFullTextIndexConfirmDialogOpened}onClose={() => {@@ -635,9 +645,7 @@ function CreateEditLocationDialog(props: Props) {content={t('core:fullTextIndexRegenerate')}confirmCallback={result => {if (result) {- dispatch(- LocationIndexActions.createLocationIndex(location)- );+ createLocationIndex(selectedLocation);} else {setFullTextIndexConfirmDialogOpened(false);}@@ -972,7 +980,7 @@ function CreateEditLocationDialog(props: Props) {onClose={() => setIgnorePatternDialogOpen(false)}ignorePatternPaths={ignorePatternPaths}setIgnorePatternPaths={setIgnorePatternPaths}- locationPath={PlatformIO.getLocationPath(location)}+ locationPath={PlatformIO.getLocationPath(selectedLocation)}/>)}</>diff --git a/app/components/dialogs/FilePreviewDialog.tsx b/app/components/dialogs/FilePreviewDialog.tsxindex eb5e95814..50efdc62a 100644--- a/app/components/dialogs/FilePreviewDialog.tsx+++ b/app/components/dialogs/FilePreviewDialog.tsx@@ -38,6 +38,7 @@ import useEventListener from '-/utils/useEventListener';import PlatformIO from '-/services/platform-facade';import AppConfig from '-/AppConfig';import { actions as LocationActions } from '-/reducers/locations';+import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';interface Props {open: boolean;@@ -47,7 +48,11 @@ interface Props {function FilePreviewDialog(props: Props) {const { open = false, onClose, fsEntry } = props;- const dispatch: AppDispatch = useDispatch();+ //const dispatch: AppDispatch = useDispatch();+ const {+ switchLocationTypeByID,+ switchCurrentLocationType+ } = useCurrentLocationContext();const supportedFileTypes = useSelector(getSupportedFileTypes);const currentTheme = useSelector(getCurrentTheme);const fileViewer: MutableRefObject<HTMLIFrameElement> = useRef<@@ -106,9 +111,7 @@ function FilePreviewDialog(props: Props) {fileViewer.current.contentWindow.setTheme(currentTheme);}*/- dispatch(- LocationActions.switchLocationType(openedFile.locationId)- ).then((currentLocationId: string) => {+ switchLocationTypeByID(openedFile.locationId).then(() => {PlatformIO.loadTextFilePromise(textFilePath,data.preview ? data.preview : false@@ -147,19 +150,11 @@ function FilePreviewDialog(props: Props) {currentTheme);}- if (currentLocationId) {- dispatch(- AppActions.switchCurrentLocationType(currentLocationId)- );- }+ return switchCurrentLocationType();}).catch(err => {console.warn('Error loading text content ' + err);- if (currentLocationId) {- dispatch(- AppActions.switchCurrentLocationType(currentLocationId)- );- }+ return switchCurrentLocationType();});});break;diff --git a/app/components/dialogs/FileUploadDialog.tsx b/app/components/dialogs/FileUploadDialog.tsxindex 381adaefd..67bb6cc7b 100644--- a/app/components/dialogs/FileUploadDialog.tsx+++ b/app/components/dialogs/FileUploadDialog.tsx@@ -34,15 +34,14 @@ import DraggablePaper from '-/components/DraggablePaper';import {actions as AppActions,AppDispatch,- getCurrentDirectoryPerspective,- getDirectoryPath,getProgress} from '-/reducers/app';import { extractFileName } from '@tagspaces/tagspaces-common/paths';import DialogCloseButton from '-/components/dialogs/DialogCloseButton';import { PerspectiveIDs } from '-/perspectives';-import { getCurrentLocation } from '-/reducers/locations';import { useTranslation } from 'react-i18next';+import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';+import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';interface Props {open: boolean;@@ -54,12 +53,14 @@ function FileUploadDialog(props: Props) {const { open = false, title, onClose } = props;const { t } = useTranslation();const dispatch: AppDispatch = useDispatch();++ const {+ loadDirectoryContent,+ currentDirectoryPerspective,+ currentDirectoryPath+ } = useDirectoryContentContext();+ const { currentLocation } = useCurrentLocationContext();const progress = useSelector(getProgress);- const currentDirectoryPerspective = useSelector(- getCurrentDirectoryPerspective- );- const currentDirectoryPath = useSelector(getDirectoryPath);- const currentLocation = useSelector(getCurrentLocation);const targetPath = React.useRef<string>(getTargetPath());@@ -238,9 +239,7 @@ function FileUploadDialog(props: Props) {onClose();dispatch(AppActions.clearUploadDialog());if (currentDirectoryPerspective === PerspectiveIDs.GRID) {- dispatch(- AppActions.loadDirectoryContent(currentDirectoryPath, false)- );+ loadDirectoryContent(currentDirectoryPath, false);}}}color="primary"diff --git a/app/components/dialogs/IsTruncatedConfirmDialog.tsx b/app/components/dialogs/IsTruncatedConfirmDialog.tsxindex aaa9287d6..5fb479422 100644--- a/app/components/dialogs/IsTruncatedConfirmDialog.tsx+++ b/app/components/dialogs/IsTruncatedConfirmDialog.tsx@@ -16,7 +16,7 @@**/-import React, { useState } from 'react';+import React from 'react';import Button from '@mui/material/Button';import DialogActions from '@mui/material/DialogActions';import DialogContent from '@mui/material/DialogContent';@@ -28,22 +28,13 @@ import { locationType } from '@tagspaces/tagspaces-common/misc';import DialogCloseButton from '-/components/dialogs/DialogCloseButton';import MaxLoopsSelect from '-/components/dialogs/MaxLoopsSelect';import AppConfig from '-/AppConfig';-import { TS } from '-/tagspaces.namespace';-import { useDispatch, useSelector } from 'react-redux';-import {- actions as LocationActions,- getCurrentLocation-} from '-/reducers/locations';-import {- actions as AppActions,- AppDispatch,- getDirectoryPath-} from '-/reducers/app';import Typography from '@mui/material/Typography';import InfoIcon from '-/components/InfoIcon';import FormControlLabel from '@mui/material/FormControlLabel';import PlatformIO from '-/services/platform-facade';import { useTranslation } from 'react-i18next';+import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';+import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';interface Props {open: boolean;@@ -53,13 +44,17 @@ interface Props {function IsTruncatedConfirmDialog(props: Props) {const { open, onClose } = props;const { t } = useTranslation();- const dispatch: AppDispatch = useDispatch();- const location: TS.Location = useSelector(getCurrentLocation);- const currentDirectoryPath = useSelector(getDirectoryPath);++ const { openDirectory, currentDirectoryPath } = useDirectoryContentContext();+ const { currentLocation, editLocation } = useCurrentLocationContext();let defaultMaxLoops = AppConfig.maxLoops;- if (location && location.maxLoops && location.maxLoops > 0) {- const maxLoopsAsString = location.maxLoops + '';+ if (+ currentLocation &&+ currentLocation.maxLoops &&+ currentLocation.maxLoops > 0+ ) {+ const maxLoopsAsString = currentLocation.maxLoops + '';defaultMaxLoops = parseInt(maxLoopsAsString, 10);}//const [maxLoops, setMaxLoops] = useState<number>(defaultMaxLoops);@@ -67,23 +62,17 @@ function IsTruncatedConfirmDialog(props: Props) {function changeMaxLoops(event: React.ChangeEvent<HTMLInputElement>) {const loops = event.target.value;if (loops) {- dispatch(- LocationActions.editLocation(- {- ...location,- maxLoops: parseInt(loops, 10)- },- false- )+ editLocation(+ {+ ...currentLocation,+ maxLoops: parseInt(loops, 10)+ },+ false);onClose();- if (location.type === locationType.TYPE_CLOUD) {- PlatformIO.enableObjectStoreSupport(location)- .then(() =>- dispatch(- AppActions.loadDirectoryContent(currentDirectoryPath, true, true)- )- )+ if (currentLocation.type === locationType.TYPE_CLOUD) {+ PlatformIO.enableObjectStoreSupport(currentLocation)+ .then(() => openDirectory(currentDirectoryPath)).catch(error => {console.log('enableObjectStoreSupport', error);});diff --git a/app/components/dialogs/LinkGeneratorDialog.tsx b/app/components/dialogs/LinkGeneratorDialog.tsxindex aafa7f408..c549ec553 100644--- a/app/components/dialogs/LinkGeneratorDialog.tsx+++ b/app/components/dialogs/LinkGeneratorDialog.tsx@@ -36,6 +36,8 @@ import PlatformIO from '-/services/platform-facade';import { actions } from '-/reducers/app';import Links from '-/content/links';import { useTranslation } from 'react-i18next';+import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';+import { useNotificationContext } from '-/hooks/useNotificationContext';const PREFIX = 'LinkGeneratorDialog';@@ -56,10 +58,7 @@ interface Props {open: boolean;onClose: () => void;path: string;- // showNotification: (message: string) => void;locationId?: string;- switchLocationType?: (locationId: string) => Promise<string | null>;- switchCurrentLocationType?: (currentLocationId: string) => Promise<boolean>;}const QRTextField = TextField;@@ -67,7 +66,11 @@ const QRTextField = TextField;function LinkGeneratorDialog(props: Props) {const { open, onClose, path } = props;const { t } = useTranslation();- const dispatch = useDispatch();+ const { showNotification } = useNotificationContext();+ const {+ switchLocationTypeByID,+ switchCurrentLocationType+ } = useCurrentLocationContext();const linkValidityDuration = useRef<number>(60 * 15);const signedLink = useRef<string>(undefined);const [ignored, forceUpdate] = useReducer(x => x + 1, 0);@@ -79,22 +82,22 @@ function LinkGeneratorDialog(props: Props) {}, []);function setSignedLink() {- if (props.switchLocationType) {- props.switchLocationType(props.locationId).then(currentLocationId => {- signedLink.current = PlatformIO.getURLforPath(- path,- linkValidityDuration.current- );- forceUpdate();- props.switchCurrentLocationType(currentLocationId);- });- } else {+ //if (switchLocationType) {+ switchLocationTypeByID(props.locationId).then(currentLocationId => {signedLink.current = PlatformIO.getURLforPath(path,linkValidityDuration.current);forceUpdate();- }+ return switchCurrentLocationType();+ });+ /*} else {+ signedLink.current = PlatformIO.getURLforPath(+ path,+ linkValidityDuration.current+ );+ forceUpdate();+ }*/}return (@@ -146,9 +149,7 @@ function LinkGeneratorDialog(props: Props) {navigator.clipboard.writeText(signedLink.current).then(() => {- dispatch(- actions.showNotification(t('core:linkCopied'))- );+ showNotification(t('core:linkCopied'));});}}color="primary"diff --git a/app/components/dialogs/MoveCopyFilesDialog.tsx b/app/components/dialogs/MoveCopyFilesDialog.tsxindex 2dcff277a..8fb463835 100644--- a/app/components/dialogs/MoveCopyFilesDialog.tsx+++ b/app/components/dialogs/MoveCopyFilesDialog.tsx@@ -14,14 +14,12 @@ import Dialog from '@mui/material/Dialog';import { FolderIcon, FileIcon } from '-/components/CommonIcons';import DraggablePaper from '-/components/DraggablePaper';import PlatformIO from '-/services/platform-facade';-import IOActions from '-/reducers/io-actions';import DialogCloseButton from '-/components/dialogs/DialogCloseButton';import { useTheme } from '@mui/material/styles';import useMediaQuery from '@mui/material/useMediaQuery';import {actions as AppActions,AppDispatch,- getDirectoryPath,getSelectedEntries} from '-/reducers/app';import { TS } from '-/tagspaces.namespace';@@ -34,6 +32,8 @@ import {checkFilesExistPromise} from '-/services/utils-io';import { useTranslation } from 'react-i18next';+import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';+import { useIOActionsContext } from '-/hooks/useIOActionsContext';interface Props {open: boolean;@@ -45,11 +45,12 @@ interface Props {function MoveCopyFilesDialog(props: Props) {const { t } = useTranslation();const dispatch: AppDispatch = useDispatch();+ const { currentDirectoryPath } = useDirectoryContentContext();+ const { copyFiles, copyDirs, moveFiles, moveDirs } = useIOActionsContext();const selectedEntries: Array<TS.FileSystemEntry> = useSelector(getSelectedEntries);- const currentDirectoryPath: string | null = useSelector(getDirectoryPath);const [targetPath, setTargetPath] = useState(currentDirectoryPath ? currentDirectoryPath : '');@@ -147,19 +148,11 @@ function MoveCopyFilesDialog(props: Props) {dispatch(AppActions.resetProgress());dispatch(AppActions.toggleUploadDialog('copyEntriesTitle'));if (selectedFiles.length > 0) {- dispatch(- IOActions.copyFiles(selectedFiles, targetPath, onUploadProgress)- );+ copyFiles(selectedFiles, targetPath, onUploadProgress);setTargetPath('');}if (selectedDirs.length > 0) {- dispatch(- IOActions.copyDirs(- getEntriesCount(selectedDirs),- targetPath,- onUploadProgress- )- );+ copyDirs(getEntriesCount(selectedDirs), targetPath, onUploadProgress);}onClose(true);}@@ -170,19 +163,13 @@ function MoveCopyFilesDialog(props: Props) {function handleMoveFiles() {if (selectedFiles.length > 0) {- dispatch(IOActions.moveFiles(selectedFiles, targetPath));+ moveFiles(selectedFiles, targetPath);setTargetPath('');}if (selectedDirs.length > 0) {dispatch(AppActions.resetProgress());dispatch(AppActions.toggleUploadDialog('moveEntriesTitle'));- dispatch(- IOActions.moveDirs(- getEntriesCount(selectedDirs),- targetPath,- onUploadProgress- )- );+ moveDirs(getEntriesCount(selectedDirs), targetPath, onUploadProgress);}onClose(true);}diff --git a/app/components/dialogs/MoveOrCopyFilesDialog.tsx b/app/components/dialogs/MoveOrCopyFilesDialog.tsxindex 2a7a07a35..92c45d124 100644--- a/app/components/dialogs/MoveOrCopyFilesDialog.tsx+++ b/app/components/dialogs/MoveOrCopyFilesDialog.tsx@@ -40,12 +40,7 @@ import DraggablePaper from '-/components/DraggablePaper';import DialogCloseButton from '-/components/dialogs/DialogCloseButton';import AppConfig from '-/AppConfig';import { useTranslation } from 'react-i18next';-import {- actions as AppActions,- AppDispatch,- getDirectoryPath-} from '-/reducers/app';-import { useDispatch, useSelector } from 'react-redux';+import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';interface Props {open: boolean;@@ -58,9 +53,10 @@ function MoveOrCopyFilesDialog(props: Props) {const { t } = useTranslation();const theme = useTheme();- const dispatch: AppDispatch = useDispatch();++ const { openDirectory, currentDirectoryPath } = useDirectoryContentContext();+ // const dispatch: AppDispatch = useDispatch();const fullScreen = useMediaQuery(theme.breakpoints.down('md'));- const directoryPath = useSelector(getDirectoryPath);const handleMoveCopyFiles = (files: Array<File>, move = false) => {const promises = [];@@ -69,7 +65,7 @@ function MoveOrCopyFilesDialog(props: Props) {promises.push(PlatformIO.renameFilePromise(file.path,- directoryPath + AppConfig.dirSeparator + file.name+ currentDirectoryPath + AppConfig.dirSeparator + file.name).then(() => true).catch(error => {@@ -80,7 +76,7 @@ function MoveOrCopyFilesDialog(props: Props) {promises.push(PlatformIO.copyFilePromise(file.path,- directoryPath + AppConfig.dirSeparator + file.name+ currentDirectoryPath + AppConfig.dirSeparator + file.name).then(() => true).catch(error => {@@ -90,9 +86,7 @@ function MoveOrCopyFilesDialog(props: Props) {}}Promise.all(promises)- .then(() =>- dispatch(AppActions.loadDirectoryContent(directoryPath, true, true))- )+ .then(() => openDirectory(currentDirectoryPath)).catch(error => {console.log('promises', error);});diff --git a/app/components/dialogs/OpenLinkDialog.tsx b/app/components/dialogs/OpenLinkDialog.tsxindex 092752fce..6f952b354 100644--- a/app/components/dialogs/OpenLinkDialog.tsx+++ b/app/components/dialogs/OpenLinkDialog.tsx@@ -29,15 +29,16 @@ import DialogCloseButton from '-/components/dialogs/DialogCloseButton';// import useMediaQuery from '@mui/material/useMediaQuery';import InfoIcon from '-/components/InfoIcon';import { useTranslation } from 'react-i18next';+import { useOpenedEntryContext } from '-/hooks/useOpenedEntryContext';interface Props {open: boolean;onClose: () => void;- openLink: (url: string, options?: any) => void;}function OpenLinkDialog(props: Props) {const { t } = useTranslation();+ const { openLink } = useOpenedEntryContext();const [inputError, setInputError] = useState(false);const [disableConfirmButton, setDisableConfirmButton] = useState(true);const [linkURL, setLinkURL] = useState('');@@ -66,7 +67,7 @@ function OpenLinkDialog(props: Props) {function onConfirm() {if (!disableConfirmButton && linkURL) {- props.openLink(linkURL, { fullWidth: false });+ openLink(linkURL, { fullWidth: false });resetState();props.onClose();}diff --git a/app/components/dialogs/RenameEntryDialog.tsx b/app/components/dialogs/RenameEntryDialog.tsxindex 999cdc534..213fc3a83 100644--- a/app/components/dialogs/RenameEntryDialog.tsx+++ b/app/components/dialogs/RenameEntryDialog.tsx@@ -36,15 +36,14 @@ import AppConfig from '-/AppConfig';import {actions as AppActions,AppDispatch,- getDirectoryPath,getLastSelectedEntry} from '-/reducers/app';import PlatformIO from '-/services/platform-facade';import DialogCloseButton from '-/components/dialogs/DialogCloseButton';import { dirNameValidation, fileNameValidation } from '-/services/utils-io';import { useTranslation } from 'react-i18next';-import { useOpenedEntryContext } from '-/hooks/useOpenedEntryContext';import { useFsActionsContext } from '-/hooks/useFsActionsContext';+import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';interface Props {open: boolean;@@ -54,16 +53,11 @@ interface Props {function RenameEntryDialog(props: Props) {const { open, onClose } = props;const { t } = useTranslation();- const { renameDirectory } = useFsActionsContext();- const currentDirectoryPath = useSelector(getDirectoryPath);+ const { renameDirectory, renameFile } = useFsActionsContext();+ const { currentDirectoryPath } = useDirectoryContentContext();const [inputError, setInputError] = useState<boolean>(false);const disableConfirmButton = useRef<boolean>(true);const lastSelectedEntry = useSelector(getLastSelectedEntry);- const dispatch: AppDispatch = useDispatch();-- const renameFile = (source, target) => {- dispatch(AppActions.renameFile(source, target));- };let defaultName = '';let originPath;@@ -144,6 +138,7 @@ function RenameEntryDialog(props: Props) {const onConfirm = () => {if (!disableConfirmButton.current) {+ onClose();if (isFile) {const fileDirectory = extractContainingDirectoryPath(lastSelectedEntry.path,@@ -151,11 +146,10 @@ function RenameEntryDialog(props: Props) {);const newFilePath =fileDirectory + PlatformIO.getDirSeparator() + name.current;- renameFile(originPath, newFilePath);+ return renameFile(originPath, newFilePath);} else {- renameDirectory(originPath, name.current);+ return renameDirectory(originPath, name.current);}- onClose();}};diff --git a/app/components/dialogs/components/CreateDirectory.tsx b/app/components/dialogs/components/CreateDirectory.tsxindex c5566d221..c477d9b69 100644--- a/app/components/dialogs/components/CreateDirectory.tsx+++ b/app/components/dialogs/components/CreateDirectory.tsx@@ -24,13 +24,7 @@ import Button from '@mui/material/Button';import ButtonGroup from '@mui/material/ButtonGroup';import Grid from '@mui/material/Grid';import AppConfig from '-/AppConfig';-import {- actions as AppActions,- AppDispatch,- NotificationTypes-} from '-/reducers/app';-import IOActions from '-/reducers/io-actions';-import { TS } from '-/tagspaces.namespace';+import { actions as AppActions, AppDispatch } from '-/reducers/app';import PlatformIO from '-/services/platform-facade';import Tooltip from '-/components/Tooltip';import TextField from '@mui/material/TextField';@@ -40,6 +34,8 @@ import FileUploadContainer, {FileUploadContainerRef} from '-/components/FileUploadContainer';import { useTranslation } from 'react-i18next';+import { useIOActionsContext } from '-/hooks/useIOActionsContext';+import { useNotificationContext } from '-/hooks/useNotificationContext';const PREFIX = 'CreateDirectory';@@ -62,6 +58,8 @@ interface Props {function CreateDirectory(props: Props) {const { onClose, tidPrefix } = props;const { t } = useTranslation();+ const { downloadFile } = useIOActionsContext();+ const { showNotification } = useNotificationContext();const fileUploadContainerRef = useRef<FileUploadContainerRef>(null);const dispatch: AppDispatch = useDispatch();@@ -122,14 +120,12 @@ function CreateDirectory(props: Props) {if (PlatformIO.haveObjectStoreSupport() || AppConfig.isElectron) {dispatch(AppActions.resetProgress());dispatch(AppActions.toggleUploadDialog());- dispatch(- IOActions.downloadFile(- fileUrl.current,- targetDirectoryPath +- PlatformIO.getDirSeparator() +- decodeURIComponent(fileName),- onUploadProgress- )+ downloadFile(+ fileUrl.current,+ targetDirectoryPath ++ PlatformIO.getDirSeparator() ++ decodeURIComponent(fileName),+ onUploadProgress).then(() => {if (PlatformIO.haveObjectStoreSupport()) {@@ -142,13 +138,7 @@ function CreateDirectory(props: Props) {dispatch(AppActions.setProgress(fileUrl.current, -1, t('core:errorCORS')));- dispatch(- AppActions.showNotification(- 'downloadFile error' + e.message,- NotificationTypes.error,- true- )- );+ showNotification('downloadFile error' + e.message, 'error', true);});} else {saveAs(fileUrl.current, decodeURIComponent(fileName));diff --git a/app/components/dialogs/components/CreateFile.tsx b/app/components/dialogs/components/CreateFile.tsxindex f49ceebf0..e58956227 100644--- a/app/components/dialogs/components/CreateFile.tsx+++ b/app/components/dialogs/components/CreateFile.tsx@@ -18,20 +18,14 @@import React, { useReducer, useRef, useState } from 'react';import { styled } from '@mui/material/styles';-import { useSelector, useDispatch } from 'react-redux';+import { useSelector } from 'react-redux';import Button from '@mui/material/Button';import ButtonGroup from '@mui/material/ButtonGroup';import Typography from '@mui/material/Typography';import Grid from '@mui/material/Grid';import { formatDateTime4Tag } from '@tagspaces/tagspaces-common/misc';import AppConfig from '-/AppConfig';-import {- actions as AppActions,- getDirectoryPath,- AppDispatch-} from '-/reducers/app';import { getFirstRWLocation } from '-/reducers/locations';-import { TS } from '-/tagspaces.namespace';import Tooltip from '-/components/Tooltip';import TextField from '@mui/material/TextField';import FormHelperText from '@mui/material/FormHelperText';@@ -39,8 +33,9 @@ import { FormControl } from '@mui/material';import { fileNameValidation } from '-/services/utils-io';import { useTargetPathContext } from '-/components/dialogs/hooks/useTargetPathContext';import { useTranslation } from 'react-i18next';-import { useTaggingActionsContext } from '-/hooks/useTaggingActionsContext';import { useOpenedEntryContext } from '-/hooks/useOpenedEntryContext';+import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';+import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';const PREFIX = 'CreateFile';@@ -65,11 +60,13 @@ function CreateFile(props: Props) {const { onClose, tidPrefix } = props;const { t } = useTranslation();- const dispatch: AppDispatch = useDispatch();- const firstRWLocation = useSelector(getFirstRWLocation);- const currentDirectoryPath: string | null = useSelector(getDirectoryPath);+ //const dispatch: AppDispatch = useDispatch();+ const { openLocation } = useCurrentLocationContext();+ const { currentDirectoryPath } = useDirectoryContentContext();const { targetDirectoryPath } = useTargetPathContext();+ const firstRWLocation = useSelector(getFirstRWLocation);+const fileName = useRef<string>('note' +AppConfig.beginTagContainer +@@ -93,7 +90,7 @@ function CreateFile(props: Props) {function loadLocation() {if (!currentDirectoryPath && firstRWLocation) {- dispatch(AppActions.openLocation(firstRWLocation));+ openLocation(firstRWLocation);}}diff --git a/app/components/dialogs/components/TargetPath.tsx b/app/components/dialogs/components/TargetPath.tsxindex e8a96af84..006004107 100644--- a/app/components/dialogs/components/TargetPath.tsx+++ b/app/components/dialogs/components/TargetPath.tsx@@ -17,17 +17,16 @@*/import React from 'react';-import { useSelector } from 'react-redux';import Typography from '@mui/material/Typography';import Grid from '@mui/material/Grid';-import { getCurrentLocation } from '-/reducers/locations';import { InfoIcon } from '-/components/CommonIcons';import { useTargetPathContext } from '-/components/dialogs/hooks/useTargetPathContext';import { useTranslation } from 'react-i18next';+import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';function TargetPath() {const { t } = useTranslation();- const currentLocation = useSelector(getCurrentLocation);+ const { currentLocation } = useCurrentLocationContext();const { targetDirectoryPath } = useTargetPathContext();return (diff --git a/app/components/dialogs/hooks/TargetPathContextProvider.tsx b/app/components/dialogs/hooks/TargetPathContextProvider.tsxindex f8a8e6a76..1e115176f 100644--- a/app/components/dialogs/hooks/TargetPathContextProvider.tsx+++ b/app/components/dialogs/hooks/TargetPathContextProvider.tsx@@ -18,13 +18,10 @@import React, { createContext, useMemo } from 'react';import { useSelector } from 'react-redux';-import {- getDirectoryPath,- getSelectedEntries,- getCurrentDirectoryPerspective-} from '-/reducers/app';+import { getSelectedEntries } from '-/reducers/app';import { getFirstRWLocation } from '-/reducers/locations';import { PerspectiveIDs } from '-/perspectives';+import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';type TargetPathContextData = {targetDirectoryPath: string;@@ -43,10 +40,10 @@ export const TargetPathContextProvider = ({}: TargetPathContextProviderProps) => {const firstRWLocation = useSelector(getFirstRWLocation);const selectedEntries = useSelector(getSelectedEntries);- const currentDirectoryPath = useSelector(getDirectoryPath);- const currentDirectoryPerspective = useSelector(- getCurrentDirectoryPerspective- );+ const {+ currentDirectoryPerspective,+ currentDirectoryPath+ } = useDirectoryContentContext();const context = useMemo(() => {let targetDirectoryPath = currentDirectoryPath;diff --git a/app/components/dialogs/settings/SettingsExtensions.tsx b/app/components/dialogs/settings/SettingsExtensions.tsxindex e9401d4f2..59a63da56 100644--- a/app/components/dialogs/settings/SettingsExtensions.tsx+++ b/app/components/dialogs/settings/SettingsExtensions.tsx@@ -35,15 +35,18 @@ import {AppDispatch,getExtensions} from '-/reducers/app';-import IOActions from '-/reducers/io-actions';import { TS } from '-/tagspaces.namespace';import PlatformIO from '-/services/platform-facade';import ConfirmDialog from '-/components/dialogs/ConfirmDialog';import InfoIcon from '-/components/InfoIcon';import { useTranslation } from 'react-i18next';+import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';+import { useIOActionsContext } from '-/hooks/useIOActionsContext';function SettingsExtensions() {const { t } = useTranslation();+ const { switchCurrentLocationType } = useCurrentLocationContext();+ const { uploadFilesAPI } = useIOActionsContext();const fileInputRef = useRef<HTMLInputElement>(null);const [removeExtDialogOpened, setRemoveExtDialogOpened] = useState<TS.Extension@@ -66,14 +69,7 @@ function SettingsExtensions() {PlatformIO.disableWebdavSupport();const destinationPath =dataDir + PlatformIO.getDirSeparator() + 'tsplugins';- dispatch(- IOActions.uploadFilesAPI(- files,- destinationPath,- onUploadProgress,- false- )- )+ uploadFilesAPI(files, destinationPath, onUploadProgress, false).then((fsEntries: Array<TS.FileSystemEntry>) => {const targetPath =destinationPath +@@ -87,12 +83,12 @@ function SettingsExtensions() {return Promise.all(promises).then(paths => {PlatformIO.loadExtensions();paths.forEach(path => PlatformIO.deleteFilePromise(path));- return dispatch(AppActions.switchCurrentLocationType());+ return switchCurrentLocationType();});}).catch(error => {console.log('uploadFiles', error);- return dispatch(AppActions.switchCurrentLocationType());+ return switchCurrentLocationType();});});};diff --git a/app/components/menus/DirectoryMenu.tsx b/app/components/menus/DirectoryMenu.tsxindex 4c59f5ab2..2eba154bf 100644--- a/app/components/menus/DirectoryMenu.tsx+++ b/app/components/menus/DirectoryMenu.tsx@@ -33,23 +33,25 @@ import PlatformIO from '-/services/platform-facade';import {actions as AppActions,AppDispatch,- getDirectoryPath,- getLastSelectedEntryPath,- getSelectedEntries,- isReadOnlyMode+ getSelectedEntries} from '-/reducers/app';import FileUploadContainer, {FileUploadContainerRef} from '-/components/FileUploadContainer';import { TS } from '-/tagspaces.namespace';-import { getRelativeEntryPath } from '-/services/utils-io';+import { getRelativeEntryPath, toFsEntry } from '-/services/utils-io';import { PerspectiveIDs } from '-/perspectives';import PlatformFacade from '-/services/platform-facade';import { getDirectoryMenuItems } from '-/perspectives/common/DirectoryMenuItems';-import { getCurrentLocation, getLocations } from '-/reducers/locations';+import { getLocations } from '-/reducers/locations';import { useTranslation } from 'react-i18next';import { useOpenedEntryContext } from '-/hooks/useOpenedEntryContext';import { useTaggingActionsContext } from '-/hooks/useTaggingActionsContext';+import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';+import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';+import { useNotificationContext } from '-/hooks/useNotificationContext';+import { useIOActionsContext } from '-/hooks/useIOActionsContext';+import { useLocationIndexContext } from '-/hooks/useLocationIndexContext';interface Props {open: boolean;@@ -58,11 +60,10 @@ interface Props {anchorEl: Element;directoryPath: string;openAddRemoveTagsDialog?: () => void;- reflectCreateEntry?: (path: string, isFile: boolean) => void;switchPerspective?: (perspectiveId: string) => void;perspectiveMode?: boolean;openRenameDirectoryDialog: () => void;- openMoveCopyFilesDialog: () => void;+ openMoveCopyFilesDialog?: () => void;mouseX?: number;mouseY?: number;}@@ -71,6 +72,15 @@ function DirectoryMenu(props: Props) {const { t } = useTranslation();const { openEntry } = useOpenedEntryContext();const { addTags } = useTaggingActionsContext();+ const { currentLocation, readOnlyMode } = useCurrentLocationContext();+ const { showNotification } = useNotificationContext();+ const {+ openDirectory,+ currentDirectoryPath,+ setCurrentDirectoryPerspective+ } = useDirectoryContentContext();+ const { reloadDirectory } = useIOActionsContext();+ const { reflectCreateEntry } = useLocationIndexContext();const fileUploadContainerRef = useRef<FileUploadContainerRef>(null);const {open,@@ -78,36 +88,23 @@ function DirectoryMenu(props: Props) {anchorEl,mouseX,mouseY,- directoryPath,openAddRemoveTagsDialog,openMoveCopyFilesDialog,openRenameDirectoryDialog,- switchPerspective+ switchPerspective,+ perspectiveMode} = props;- const currentLocation: TS.Location = useSelector(getCurrentLocation);+ const directoryPath = props.directoryPath || currentDirectoryPath;const selectedEntries: Array<TS.FileSystemEntry> = useSelector(getSelectedEntries);const locations: Array<TS.Location> = useSelector(getLocations);- const currentDirectoryPath = useSelector(getDirectoryPath);- const lastSelectedEntryPath = useSelector(getLastSelectedEntryPath);- const readOnlyMode = useSelector(isReadOnlyMode);const dispatch: AppDispatch = useDispatch();- const loadDirectoryContent = (path, generateThumbnails, loadDirMeta) => {- return dispatch(- AppActions.loadDirectoryContent(path, generateThumbnails, loadDirMeta)- );- };-const toggleCreateDirectoryDialog = () => {dispatch(AppActions.toggleCreateDirectoryDialog());};- const reflectCreateEntry = (path, isFile) => {- dispatch(AppActions.reflectCreateEntry(path, isFile));- };-const toggleNewFileDialog = () => {dispatch(AppActions.toggleNewFileDialog());};@@ -124,42 +121,37 @@ function DirectoryMenu(props: Props) {dispatch(AppActions.setSelectedEntries(selectedEntries));};- const showNotification = (text, notificationType?, autohide?) => {- dispatch(AppActions.showNotification(text, notificationType, autohide));- };-const toggleProTeaser = slidePage => {dispatch(AppActions.toggleProTeaser(slidePage));};- const setCurrentDirectoryPerspective = perspective => {- dispatch(AppActions.setCurrentDirectoryPerspective(perspective));- };-function generateFolderLink() {- const entryFromIndex = selectedEntries[0]['locationID'];- const locationID = entryFromIndex- ? selectedEntries[0]['locationID']- : currentLocation.uuid;- const entryPath = selectedEntries[0].path;+ let locationID = currentLocation.uuid;+ let entryPath = currentDirectoryPath;+ if (selectedEntries && selectedEntries.length > 0) {+ if (selectedEntries[0]['locationID']) {+ locationID = selectedEntries[0]['locationID'];+ }+ entryPath = selectedEntries[0].path;+ }const tmpLoc = locations.find(location => location.uuid === locationID);const relativePath = getRelativeEntryPath(tmpLoc, entryPath);return generateSharingLink(locationID, undefined, relativePath);}function copySharingLink() {- if (selectedEntries && selectedEntries.length === 1) {- const sharingLink = generateFolderLink();- navigator.clipboard- .writeText(sharingLink)- .then(() => {- showNotification(t('core:sharingLinkCopied'));- return true;- })- .catch(() => {- showNotification(t('core:sharingLinkFailed'));- });- }+ //if (selectedEntries && selectedEntries.length === 1) {+ const sharingLink = generateFolderLink();+ navigator.clipboard+ .writeText(sharingLink)+ .then(() => {+ showNotification(t('core:sharingLinkCopied'));+ return true;+ })+ .catch(() => {+ showNotification(t('core:sharingLinkFailed'));+ });+ //}}/* const [@@ -167,12 +159,8 @@ function DirectoryMenu(props: Props) {setIsCreateDirectoryDialogOpened] = useState(false);*/- function reloadDirectory() {- return loadDirectoryContent(directoryPath, true, true);- }-- function openDirectory() {- return loadDirectoryContent(directoryPath, true, true);+ function openDir() {+ return openDirectory(directoryPath);}function showProperties() {@@ -243,17 +231,17 @@ function DirectoryMenu(props: Props) {}function showInFileManager() {- dispatch(AppActions.openDirectory(directoryPath));+ PlatformIO.openDirectory(directoryPath);}function openInNewWindow() {// onClose();- if (selectedEntries && selectedEntries.length === 1) {- const sharingLink = generateFolderLink();- const newInstanceLink =- window.location.href.split('?')[0] + '?' + sharingLink.split('?')[1];- PlatformIO.createNewInstance(newInstanceLink);- }+ //if (selectedEntries && selectedEntries.length === 1) {+ const sharingLink = generateFolderLink();+ const newInstanceLink =+ window.location.href.split('?')[0] + '?' + sharingLink.split('?')[1];+ PlatformIO.createNewInstance(newInstanceLink);+ //}}function addExistingFile() {@@ -285,7 +273,6 @@ Do you want to continue?`)};Pro.MacTagsImport.importTags(directoryPath, entryCallback).then(() => {- // loadDirectoryContent(directoryPath); // TODO after first import tags is not imported without reloadDirContenttoggleProgressDialog();console.log('Import tags succeeded ' + directoryPath);showNotification(@@ -342,7 +329,8 @@ Do you want to continue?`)'default',true);- reflectCreateEntry(newFilePath, true);+ reflectCreateEntry(toFsEntry(newFilePath, true));+ dispatch(AppActions.reflectCreateEntry(newFilePath, true));return true;}).catch(error => {@@ -416,11 +404,11 @@ Do you want to continue?`)const menuItems = getDirectoryMenuItems(currentLocation,selectedEntries.length,- lastSelectedEntryPath !== currentDirectoryPath,+ perspectiveMode, // lastSelectedEntryPath !== currentDirectoryPath,readOnlyMode,onClose,t,- openDirectory,+ openDir,reloadDirectory,openRenameDirectoryDialog,openMoveCopyFilesDialog,diff --git a/app/components/menus/EntryTagMenu.tsx b/app/components/menus/EntryTagMenu.tsxindex 561d32a77..aa48aac14 100644--- a/app/components/menus/EntryTagMenu.tsx+++ b/app/components/menus/EntryTagMenu.tsx@@ -27,16 +27,14 @@ import ListItemText from '@mui/material/ListItemText';import Menu from '@mui/material/Menu';import MenuItem from '@mui/material/MenuItem';import ConfirmDialog from '../dialogs/ConfirmDialog';-import { actions as LocationIndexActions } from '-/reducers/location-index';import { getMaxSearchResults } from '-/reducers/settings';-import {- actions as AppActions,- AppDispatch,- isReadOnlyMode-} from '-/reducers/app';+import { actions as AppActions, AppDispatch } from '-/reducers/app';import { TS } from '-/tagspaces.namespace';import { useTranslation } from 'react-i18next';import { useTaggingActionsContext } from '-/hooks/useTaggingActionsContext';+import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';+import { useLocationIndexContext } from '-/hooks/useLocationIndexContext';+import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';interface Props {open: boolean;@@ -60,15 +58,12 @@ function EntryTagMenu(props: Props) {const removeTagsProps = props.removeTags;const { t } = useTranslation();+ const { setSearchQuery } = useDirectoryContentContext();const { removeTags } = useTaggingActionsContext();+ const { readOnlyMode } = useCurrentLocationContext();const [isDeleteTagDialogOpened, setIsDeleteTagDialogOpened] = useState(false);const dispatch: AppDispatch = useDispatch();const maxSearchResults: number = useSelector(getMaxSearchResults);- const readOnlyMode = useSelector(isReadOnlyMode);-- const setSearchQuery = searchQuery => {- dispatch(LocationIndexActions.setSearchQuery(searchQuery));- };const toggleEditTagDialog = tag => {dispatch(AppActions.toggleEditTagDialog(tag));diff --git a/app/components/menus/FileMenu.tsx b/app/components/menus/FileMenu.tsxindex 735b0c0e7..0b0c84f2e 100644--- a/app/components/menus/FileMenu.tsx+++ b/app/components/menus/FileMenu.tsx@@ -52,11 +52,7 @@ import {} from '-/services/utils-io';import { Pro } from '-/pro';import { TS } from '-/tagspaces.namespace';-import {- actions as AppActions,- AppDispatch,- isReadOnlyMode-} from '-/reducers/app';+import { actions as AppActions, AppDispatch } from '-/reducers/app';import { useSelector, useDispatch } from 'react-redux';import { supportedImgs } from '-/services/thumbsgenerator';import { getPrefixTagContainer } from '-/reducers/settings';@@ -65,10 +61,13 @@ import {DeleteIcon,LinkIcon} from '-/components/CommonIcons';-import { getCurrentLocation, getLocations } from '-/reducers/locations';+import { getLocations } from '-/reducers/locations';import PropertiesIcon from '@mui/icons-material/Info';import { useTranslation } from 'react-i18next';import { useOpenedEntryContext } from '-/hooks/useOpenedEntryContext';+import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';+import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';+import { useNotificationContext } from '-/hooks/useNotificationContext';interface Props {anchorEl: Element;@@ -112,9 +111,10 @@ function FileMenu(props: Props) {const { t } = useTranslation();const dispatch: AppDispatch = useDispatch();const { openEntry } = useOpenedEntryContext();- const currentLocation: TS.Location = useSelector(getCurrentLocation);+ const { openDirectory } = useDirectoryContentContext();+ const { showNotification } = useNotificationContext();+ const { currentLocation, readOnlyMode } = useCurrentLocationContext();const locations: Array<TS.Location> = useSelector(getLocations);- const readOnlyMode = useSelector(isReadOnlyMode);const prefixTagContainer = useSelector(getPrefixTagContainer);function generateFileLink() {@@ -142,11 +142,11 @@ function FileMenu(props: Props) {navigator.clipboard.writeText(sharingLink).then(() => {- dispatch(AppActions.showNotification(t('core:sharingLinkCopied')));+ showNotification(t('core:sharingLinkCopied'));return true;}).catch(() => {- dispatch(AppActions.showNotification(t('core:sharingLinkFailed')));+ showNotification(t('core:sharingLinkFailed'));});}}@@ -175,13 +175,11 @@ function FileMenu(props: Props) {onClose();setFolderThumbnailPromise(selectedFilePath, t).then((directoryPath: string) => {- dispatch(- AppActions.showNotification('Thumbnail created for: ' + directoryPath)- );+ showNotification('Thumbnail created for: ' + directoryPath);return true;}).catch(error => {- dispatch(AppActions.showNotification('Thumbnail creation failed.'));+ showNotification('Thumbnail creation failed.');console.warn('Error setting Thumb for entry: ' + selectedFilePath,error@@ -207,15 +205,11 @@ function FileMenu(props: Props) {dispatch(AppActions.setLastBackgroundImageChange(path, new Date().getTime()));- dispatch(- AppActions.showNotification(- 'Background created for: ' + directoryPath- )- );+ showNotification('Background created for: ' + directoryPath);return true;}).catch(error => {- dispatch(AppActions.showNotification('Background creation failed.'));+ showNotification('Background creation failed.');console.warn('Error setting Background for entry: ' + selectedFilePath,error@@ -264,14 +258,12 @@ function FileMenu(props: Props) {if (onDuplicateFile) {onDuplicateFile(dirPath);} else {- dispatch(AppActions.loadDirectoryContent(dirPath, true, true));+ openDirectory(dirPath);}return true;}).catch(error => {- dispatch(- AppActions.showNotification('Error creating duplicate: ', error)- );+ showNotification('Error creating duplicate: ', error);});}}@@ -283,10 +275,7 @@ function FileMenu(props: Props) {selectedFilePath,PlatformIO.getDirSeparator());- dispatch(AppActions.exitSearchMode());- return dispatch(- AppActions.loadDirectoryContent(parentFolder, false, true)- );+ return openDirectory(parentFolder);}}@@ -384,7 +373,7 @@ function FileMenu(props: Props) {onClick={() => {onClose();if (selectedFilePath) {- dispatch(AppActions.showInFileManager(selectedFilePath));+ PlatformIO.showInFileManager(selectedFilePath);}}}>diff --git a/app/components/menus/LocationContextMenu.tsx b/app/components/menus/LocationContextMenu.tsxindex 22dced722..22ba7e2ad 100644--- a/app/components/menus/LocationContextMenu.tsx+++ b/app/components/menus/LocationContextMenu.tsx@@ -17,7 +17,7 @@*/import React from 'react';-import { useSelector, useDispatch } from 'react-redux';+import { useDispatch } from 'react-redux';import { getUuid } from '@tagspaces/tagspaces-common/utils-io';import { generateSharingLink } from '@tagspaces/tagspaces-common/paths';import ListItemText from '@mui/material/ListItemText';@@ -35,43 +35,37 @@ import OpenFolderNativelyIcon from '@mui/icons-material/Launch';import { OpenNewWindowIcon, CloseIcon } from '-/components/CommonIcons';import { locationType } from '@tagspaces/tagspaces-common/misc';import AppConfig from '-/AppConfig';-import {- actions as LocationActions,- getLocationPosition-} from '-/reducers/locations';-import { actions as LocationIndexActions } from '-/reducers/location-index';+import { actions as LocationActions } from '-/reducers/locations';import { actions as AppActions, AppDispatch } from '-/reducers/app';-import { TS } from '-/tagspaces.namespace';import PlatformIO from '-/services/platform-facade';import { useTranslation } from 'react-i18next';+import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';+import { useLocationIndexContext } from '-/hooks/useLocationIndexContext';interface Props {setEditLocationDialogOpened: (open: boolean) => void;setDeleteLocationDialogOpened: (open: boolean) => void;- selectedLocation: TS.Location;closeLocationTree: () => void;- locationDirectoryContextMenuAnchorEl: HTMLElement;- setLocationDirectoryContextMenuAnchorEl: (el: HTMLElement) => void;}function LocationContextMenu(props: Props) {const {- selectedLocation,setEditLocationDialogOpened,setDeleteLocationDialogOpened,- setLocationDirectoryContextMenuAnchorEl,- closeLocationTree,- locationDirectoryContextMenuAnchorEl+ closeLocationTree} = props;const { t } = useTranslation();- const dispatch: AppDispatch = useDispatch();- const locationPosition = useSelector(state =>- getLocationPosition(state, selectedLocation.uuid)- );- const createLocationIndex = location => {- dispatch(LocationIndexActions.createLocationIndex(location));- };+ const {+ addLocation,+ closeLocation,+ getLocationPosition,+ selectedLocation,+ locationDirectoryContextMenuAnchorEl,+ setLocationDirectoryContextMenuAnchorEl+ } = useCurrentLocationContext();+ const { createLocationIndex } = useLocationIndexContext();+ const dispatch: AppDispatch = useDispatch();const moveLocationUp = locationId => {dispatch(LocationActions.moveLocationUp(locationId));@@ -81,20 +75,6 @@ function LocationContextMenu(props: Props) {dispatch(LocationActions.moveLocationDown(locationId));};- const showInFileManager = path => {- dispatch(AppActions.showInFileManager(path));- };-- const closeLocation = locationId => {- dispatch(AppActions.closeLocation(locationId));- };-- const addLocation = (location, openAfterCreate, locationPosition) => {- dispatch(- LocationActions.addLocation(location, openAfterCreate, locationPosition)- );- };-const indexLocation = () => {setLocationDirectoryContextMenuAnchorEl(null);createLocationIndex(selectedLocation);@@ -106,6 +86,7 @@ function LocationContextMenu(props: Props) {};const duplicateLocation = () => {+ const locationPosition = getLocationPosition(selectedLocation.uuid);addLocation({...selectedLocation,@@ -140,7 +121,7 @@ function LocationContextMenu(props: Props) {const showInFileManagerInt = () => {setLocationDirectoryContextMenuAnchorEl(null);- showInFileManager(PlatformIO.getLocationPath(selectedLocation));+ PlatformIO.showInFileManager(PlatformIO.getLocationPath(selectedLocation));};const closeLocationInt = () => {diff --git a/app/components/menus/LocationManagerMenu.tsx b/app/components/menus/LocationManagerMenu.tsxindex 4016254c2..d56ecd307 100644--- a/app/components/menus/LocationManagerMenu.tsx+++ b/app/components/menus/LocationManagerMenu.tsx@@ -32,13 +32,14 @@ import MoreVertIcon from '@mui/icons-material/MoreVert';import { useDispatch } from 'react-redux';import AppConfig from '-/AppConfig';import { Pro } from '../../pro';-import { actions as AppActions, AppDispatch } from '-/reducers/app';+import { AppDispatch } from '-/reducers/app';import Links from '-/content/links';import { ProLabel } from '-/components/HelperComponents';-import { actions as LocationIndexActions } from '-/reducers/location-index';import { OpenLinkIcon, HelpIcon } from '-/components/CommonIcons';import { openURLExternally } from '-/services/utils-io';import { useTranslation } from 'react-i18next';+import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';+import { useLocationIndexContext } from '-/hooks/useLocationIndexContext';interface Props {classes: any;@@ -57,6 +58,9 @@ function LocationManagerMenu(props: Props) {toggleOpenLinkDialog} = props;const { t } = useTranslation();++ const { createLocationsIndexes } = useLocationIndexContext();+ const { closeAllLocations } = useCurrentLocationContext();const [locationManagerMenuAnchorEl,setLocationManagerMenuAnchorEl@@ -153,7 +157,7 @@ function LocationManagerMenu(props: Props) {data-tid="locationManagerMenuCloseAll"onClick={() => {setLocationManagerMenuAnchorEl(null);- dispatch(AppActions.closeAllLocations());+ closeAllLocations();}}><ListItemIcon>@@ -169,7 +173,7 @@ function LocationManagerMenu(props: Props) {data-tid="updateAllLocationIndexes"onClick={() => {setLocationManagerMenuAnchorEl(null);- dispatch(LocationIndexActions.createLocationsIndexes());+ createLocationsIndexes();}}><ListItemIcon>diff --git a/app/components/menus/LocationMenu.tsx b/app/components/menus/LocationMenu.tsxindex 2d7c468d2..24e2bb310 100644--- a/app/components/menus/LocationMenu.tsx+++ b/app/components/menus/LocationMenu.tsx@@ -17,7 +17,7 @@*/import React, { useState } from 'react';-import { useSelector, useDispatch } from 'react-redux';+import { useSelector } from 'react-redux';import Menu from '@mui/material/Menu';import MenuItem from '@mui/material/MenuItem';import { LocalLocationIcon, CloudLocationIcon } from '-/components/CommonIcons';@@ -29,14 +29,10 @@ import IconButton from '@mui/material/IconButton';import ArrowDropDownIcon from '@mui/icons-material/ArrowDropDown';import { locationType } from '@tagspaces/tagspaces-common/misc';import { getLocations } from '-/reducers/locations';-import {- actions as AppActions,- AppDispatch,- getCurrentLocationId-} from '-/reducers/app';import { TS } from '-/tagspaces.namespace';import { useTheme } from '@mui/material/styles';import { useTranslation } from 'react-i18next';+import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';interface Props {menuAnchorEl?: Element;@@ -45,21 +41,14 @@ interface Props {function LocationMenu(props: Props) {const { t } = useTranslation();const theme = useTheme();- const dispatch: AppDispatch = useDispatch();+ const { openLocation, currentLocation } = useCurrentLocationContext();+ //const dispatch: AppDispatch = useDispatch();const locations: Array<TS.Location> = useSelector(getLocations);- const currentLocationId: string | null = useSelector(getCurrentLocationId);const [locationChooserMenuAnchorEl,setLocationChooserMenuAnchorEl] = useState<null | HTMLElement>(null);- let currentLocation;- if (currentLocationId && locations) {- currentLocation = locations.find(- (location: TS.Location) => location.uuid === currentLocationId- );- }-const locationIcon =currentLocation && currentLocation.type === locationType.TYPE_CLOUD ? (<CloudLocationIcon />@@ -120,7 +109,7 @@ function LocationMenu(props: Props) {data-tid="folderContainerMenuOpenLocation"key={location.uuid}onClick={() => {- dispatch(AppActions.openLocation(location));+ openLocation(location);setLocationChooserMenuAnchorEl(null);}}style={diff --git a/app/components/menus/SavedSearchesMenu.tsx b/app/components/menus/SavedSearchesMenu.tsxindex be13ff813..0758638f8 100644--- a/app/components/menus/SavedSearchesMenu.tsx+++ b/app/components/menus/SavedSearchesMenu.tsx@@ -21,10 +21,11 @@ import { useSelector, useDispatch } from 'react-redux';import Menu from '@mui/material/Menu';import MenuItem from '@mui/material/MenuItem';import { getSearches } from '-/reducers/searches';-import { actions as LocationIndexActions } from '-/reducers/location-index';import { getShowUnixHiddenEntries } from '-/reducers/settings';import { AppDispatch } from '-/reducers/app';import { useTranslation } from 'react-i18next';+import { useLocationIndexContext } from '-/hooks/useLocationIndexContext';+import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';interface Props {open: boolean;@@ -35,11 +36,9 @@ interface Props {function SavedSearchesMenu(props: Props) {const { open, onClose, anchorEl } = props;const { t } = useTranslation();- const dispatch: AppDispatch = useDispatch();+ const { setSearchQuery } = useDirectoryContentContext();const searches = useSelector(state => getSearches(state));- const showUnixHiddenEntries = useSelector(state =>- getShowUnixHiddenEntries(state)- );+ const showUnixHiddenEntries = useSelector(getShowUnixHiddenEntries);const handleSavedSearchClick = (uuid: string) => {const savedSearch = searches.find(search => search.uuid === uuid);@@ -47,12 +46,10 @@ function SavedSearchesMenu(props: Props) {return true;}- dispatch(- LocationIndexActions.setSearchQuery({- ...savedSearch,- showUnixHiddenEntries: showUnixHiddenEntries- })- );+ setSearchQuery({+ ...savedSearch,+ showUnixHiddenEntries: showUnixHiddenEntries+ });};const menuItems = searches.length ? (diff --git a/app/components/menus/TagGroupMenu.tsx b/app/components/menus/TagGroupMenu.tsxindex 337baa50e..f4f34bdff 100644--- a/app/components/menus/TagGroupMenu.tsx+++ b/app/components/menus/TagGroupMenu.tsx@@ -32,12 +32,13 @@ import CollectTagsIcon from '@mui/icons-material/Voicemail';import Menu from '@mui/material/Menu';import MenuItem from '@mui/material/MenuItem';import { getMaxSearchResults } from '-/reducers/settings';-import { actions as LocationIndexActions } from '-/reducers/location-index';import { actions as AppActions, AppDispatch } from '-/reducers/app';import { TS } from '-/tagspaces.namespace';import InfoIcon from '-/components/InfoIcon';import { useTranslation } from 'react-i18next';import { useTaggingActionsContext } from '-/hooks/useTaggingActionsContext';+import { useLocationIndexContext } from '-/hooks/useLocationIndexContext';+import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';interface Props {classes?: any;@@ -71,6 +72,7 @@ function TagGroupMenu(props: Props) {const { t } = useTranslation();const { collectTagsFromLocation } = useTaggingActionsContext();+ const { setSearchQuery } = useDirectoryContentContext();const dispatch: AppDispatch = useDispatch();const maxSearchResults = useSelector(getMaxSearchResults);@@ -108,13 +110,11 @@ function TagGroupMenu(props: Props) {function showFilesWithTags() {if (selectedTagGroupEntry) {// openSearchPanel();- dispatch(- LocationIndexActions.setSearchQuery({- tagsOR: selectedTagGroupEntry.children,- maxSearchResults: maxSearchResults,- executeSearch: true- })- );+ setSearchQuery({+ tagsOR: selectedTagGroupEntry.children,+ maxSearchResults: maxSearchResults,+ executeSearch: true+ });}handleCloseTagGroupMenu();}diff --git a/app/components/menus/TagLibraryMenu.tsx b/app/components/menus/TagLibraryMenu.tsxindex dc932697a..3cdcac830 100644--- a/app/components/menus/TagLibraryMenu.tsx+++ b/app/components/menus/TagLibraryMenu.tsx@@ -35,6 +35,7 @@ import { Pro } from '-/pro';import { openURLExternally } from '-/services/utils-io';import { actions as AppActions, AppDispatch } from '-/reducers/app';import { useTranslation } from 'react-i18next';+import { useNotificationContext } from '-/hooks/useNotificationContext';interface Props {classes?: any;@@ -50,7 +51,7 @@ interface Props {function TagLibraryMenu(props: Props) {const { t } = useTranslation();- const dispatch: AppDispatch = useDispatch();+ const { showNotification } = useNotificationContext();const fileInput = useRef<HTMLInputElement>(null);const tagGroupsImported = useRef([]);// const [tagGroups, setTagGroups] = useState(null);@@ -89,22 +90,10 @@ function TagLibraryMenu(props: Props) {tagGroupsImported.current = jsonObj.tagGroups;setIsImportExportTagGroupDialogOpened(true);} else {- dispatch(- AppActions.showNotification(- t('core:invalidImportFile'),- 'warning',- true- )- );+ showNotification(t('core:invalidImportFile'), 'warning', true);}} catch (e) {- dispatch(- AppActions.showNotification(- t('core:invalidImportFile'),- 'warning',- true- )- );+ showNotification(t('core:invalidImportFile'), 'warning', true);}};reader.readAsText(file);diff --git a/app/components/menus/TagMenu.tsx b/app/components/menus/TagMenu.tsxindex 7bb27dd34..dbb2fe1c5 100644--- a/app/components/menus/TagMenu.tsx+++ b/app/components/menus/TagMenu.tsx@@ -26,17 +26,14 @@ import ListItemIcon from '@mui/material/ListItemIcon';import ListItemText from '@mui/material/ListItemText';import Menu from '@mui/material/Menu';import MenuItem from '@mui/material/MenuItem';-import { actions as LocationIndexActions } from '-/reducers/location-index';import { getMaxSearchResults } from '-/reducers/settings';-import {- AppDispatch,- getSelectedEntries,- isReadOnlyMode-} from '-/reducers/app';+import { AppDispatch, getSelectedEntries } from '-/reducers/app';import { TS } from '-/tagspaces.namespace';import { useTranslation } from 'react-i18next';-import { useOpenedEntryContext } from '-/hooks/useOpenedEntryContext';import { useTaggingActionsContext } from '-/hooks/useTaggingActionsContext';+import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';+import { useLocationIndexContext } from '-/hooks/useLocationIndexContext';+import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';const isTagLibraryReadOnly =window.ExtTagLibrary && window.ExtTagLibrary.length > 0;@@ -61,21 +58,19 @@ function TagMenu(props: Props) {} = props;const { t } = useTranslation();- const dispatch: AppDispatch = useDispatch();const { addTags } = useTaggingActionsContext();- const readOnlyMode = useSelector(isReadOnlyMode);+ const { readOnlyMode } = useCurrentLocationContext();+ const { setSearchQuery } = useDirectoryContentContext();const maxSearchResults: number = useSelector(getMaxSearchResults);const selectedEntries = useSelector(getSelectedEntries);function showFilesWithThisTag() {if (selectedTag) {- dispatch(- LocationIndexActions.setSearchQuery({- tagsAND: [selectedTag],- maxSearchResults: maxSearchResults,- executeSearch: true- })- );+ setSearchQuery({+ tagsAND: [selectedTag],+ maxSearchResults: maxSearchResults,+ executeSearch: true+ });}onClose();}diff --git a/app/containers/MainPage.tsx b/app/containers/MainPage.tsxindex d951bec46..7231eda2c 100644--- a/app/containers/MainPage.tsx+++ b/app/containers/MainPage.tsx@@ -19,9 +19,7 @@import React, { useEffect, useReducer, useRef, useState } from 'react';import clsx from 'clsx';import { bindActionCreators } from 'redux';-import { connect, useSelector } from 'react-redux';-//import { translate } from 'react-i18next';-//import { initReactI18next } from 'react-i18next';+import { connect } from 'react-redux';import SwipeableDrawer from '@mui/material/SwipeableDrawer';import Drawer from '@mui/material/Drawer';import { HotKeys } from 'react-hotkeys';@@ -45,7 +43,6 @@ import {} from '../reducers/settings';import {actions as AppActions,- isGeneratingThumbs,isAboutDialogOpened,isOnboardingDialogOpened,isKeysDialogOpened,@@ -62,7 +59,6 @@ import {isNewFileDialogOpened,isSettingsDialogOpened,isOpenLinkDialogOpened,- isReadOnlyMode,isProgressOpened,isDeleteMultipleEntriesDialogOpened,isImportKanBanDialogOpened,@@ -76,7 +72,6 @@ import TargetFileBox from '../components/TargetFileBox';import LoadingLazy from '../components/LoadingLazy';import withDnDContext from '-/containers/withDnDContext';import CustomDragLayer from '-/components/CustomDragLayer';-import IOActions from '-/reducers/io-actions';import FileUploadDialog from '-/components/dialogs/FileUploadDialog';import ProgressDialog from '-/components/dialogs/ProgressDialog';import useEventListener from '-/utils/useEventListener';@@ -84,7 +79,6 @@ import ConfirmDialog from '-/components/dialogs/ConfirmDialog';import { TS } from '-/tagspaces.namespace';import PageNotification from '-/containers/PageNotification';import listen from '-/containers/RendererListener';-import { actions as LocationIndexActions } from '-/reducers/location-index';import MoveOrCopyFilesDialog from '-/components/dialogs/MoveOrCopyFilesDialog';import { Pro } from '-/pro';import NewFileDialog from '-/components/dialogs/NewFileDialog';@@ -92,9 +86,9 @@ import IsTruncatedConfirmDialog from '-/components/dialogs/IsTruncatedConfirmDiaimport { styled, useTheme } from '@mui/material/styles';import { useTranslation } from 'react-i18next';import { DescriptionContextProvider } from '-/hooks/DescriptionContextProvider';-import { TaggingActionsContextProvider } from '-/hooks/TaggingActionsContextProvider';import { useOpenedEntryContext } from '-/hooks/useOpenedEntryContext';import { useFsActionsContext } from '-/hooks/useFsActionsContext';+import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';const drawerWidth = 320;const body = document.getElementsByTagName('body')[0];@@ -139,9 +133,6 @@ interface Props {isFirstRun: boolean;setFirstRun: (isFirstRun: boolean) => void;isDesktopMode: boolean;- isGeneratingThumbs: boolean;- // setGeneratingThumbnails: (isGenerating: boolean) => void;- isReadOnlyMode: boolean;isSettingsDialogOpened: boolean;isNewEntryDialogOpened: boolean;isNewFileDialogOpened: boolean;@@ -164,9 +155,7 @@ interface Props {isEditTagDialogOpened: boolean;keyBindings: any;toggleEditTagDialog: (tag: TS.Tag) => void;- loadParentDirectoryContent: () => void;- openLink: (linkURL: string, options?: any) => void;- saveFile: () => void; // needed by electron-menus+ //saveFile: () => void; // needed by electron-menussetZoomResetApp: () => void; // needed by electron-menussetZoomInApp: () => void; // needed by electron-menussetZoomOutApp: () => void; // needed by electron-menus@@ -199,25 +188,13 @@ interface Props {isTagLibraryPanelOpened: boolean;isSearchPanelOpened: boolean;isHelpFeedbackPanelOpened: boolean;- showNotification: (- text: string,- notificationType?: string,- autohide?: boolean- ) => void;reflectCreateEntries: (fsEntries: Array<TS.FileSystemEntry>) => void;- uploadFilesAPI: (- files: Array<File>,- destination: string,- onUploadProgress?: (progress: Progress, response: any) => void- ) => any;onUploadProgress: (progress: Progress, response: any) => void;isDeleteMultipleEntriesDialogOpened: boolean;isImportKanBanDialogOpened: boolean;toggleDeleteMultipleEntriesDialog: () => void;selectedEntries: Array<any>;- deleteFile: (path: string, uuid: string) => void;user: CognitoUserInterface;- setSearchQuery: (searchQuery: TS.SearchQuery) => void;}const CreateEditLocationDialog = React.lazy(() =>@@ -341,6 +318,7 @@ function MainPage(props: Props) {const { t } = useTranslation();const { deleteDirectory } = useFsActionsContext();const {+ openLink,openedEntries,isEntryInFullWidth,openFsEntry,@@ -348,6 +326,14 @@ function MainPage(props: Props) {openNextFile,openPrevFile} = useOpenedEntryContext();++ const { deleteFile } = useFsActionsContext();++ const {+ loadParentDirectoryContent,+ enterSearchMode,+ exitSearchMode+ } = useDirectoryContentContext();const theme = useTheme();const percent = useRef<number | undefined>(undefined);const [ignored, forceUpdate] = useReducer(x => x + 1, 0);@@ -392,7 +378,7 @@ function MainPage(props: Props) {window.addEventListener('popstate',() => {- props.openLink(window.location.href, { fullWidth: false });+ openLink(window.location.href, { fullWidth: false });},{ once: true });@@ -406,7 +392,7 @@ function MainPage(props: Props) {window.addEventListener('popstate',() => {- props.openLink(window.location.href, { fullWidth: false });+ openLink(window.location.href, { fullWidth: false });// console.log(// '>>> last href: ' + decodeURIComponent(window.location.href)// );@@ -472,7 +458,7 @@ function MainPage(props: Props) {};const keyBindingHandlers = {- openParentDirectory: props.loadParentDirectoryContent,+ openParentDirectory: loadParentDirectoryContent,toggleShowHiddenEntries: props.toggleShowUnixHiddenEntries,showLocationManager: () => {props.openLocationManagerPanel();@@ -482,8 +468,8 @@ function MainPage(props: Props) {props.openTagLibraryPanel();setDrawerOpened(true);},- openSearch: () => props.setSearchQuery({ textQuery: '' }), // props.openSearchPanel,- closeSearch: () => props.setSearchQuery({}),+ openSearch: () => enterSearchMode(),+ closeSearch: () => exitSearchMode(),showHelp: () => {props.openHelpFeedbackPanel();setDrawerOpened(true);@@ -517,8 +503,7 @@ function MainPage(props: Props) {toggleOpenLinkDialog,toggleProTeaser,setFirstRun,- mainSplitSize,- openLink+ mainSplitSize} = props;const { FILE } = NativeTypes;@@ -573,9 +558,9 @@ function MainPage(props: Props) {drawerOpened={drawerOpened}goBack={goBack}goForward={goForward}- openMoveCopyFilesDialog={() =>+ /*openMoveCopyFilesDialog={() =>setMoveCopyDialogOpened(props.selectedEntries)- }+ }*//>{isFileOpened && (<DescriptionContextProvider>@@ -593,167 +578,165 @@ function MainPage(props: Props) {keyMap={keyMap}style={{ height: '100%' }}>- <TaggingActionsContextProvider>- <MoveOrCopyFilesDialog- open={moveCopyDialogOpened !== undefined}- onClose={() => {- setMoveCopyDialogOpened(undefined);+ <MoveOrCopyFilesDialog+ open={moveCopyDialogOpened !== undefined}+ onClose={() => {+ setMoveCopyDialogOpened(undefined);+ }}+ selectedFiles={moveCopyDialogOpened}+ />+ {props.isLocationDialogOpened && (+ <CreateEditLocationDialogAsync+ open={props.isLocationDialogOpened}+ onClose={toggleLocationDialog}+ />+ )}+ {props.isAboutDialogOpened && (+ <AboutDialogAsync+ open={props.isAboutDialogOpened}+ toggleLicenseDialog={toggleLicenseDialog}+ toggleThirdPartyLibsDialog={toggleThirdPartyLibsDialog}+ onClose={toggleAboutDialog}+ />+ )}+ {props.isKeysDialogOpened && (+ <KeyboardDialogAsync+ open={props.isKeysDialogOpened}+ onClose={toggleKeysDialog}+ />+ )}+ {props.isLicenseDialogOpened && (+ <LicenseDialogAsync+ open={props.isLicenseDialogOpened}+ onClose={(event, reason) => {+ if (reason === 'backdropClick' || reason === 'escapeKeyDown') {+ return true;+ }+ setFirstRun(false);+ toggleLicenseDialog();}}- selectedFiles={moveCopyDialogOpened}/>- {props.isLocationDialogOpened && (- <CreateEditLocationDialogAsync- open={props.isLocationDialogOpened}- onClose={toggleLocationDialog}- />- )}- {props.isAboutDialogOpened && (- <AboutDialogAsync- open={props.isAboutDialogOpened}- toggleLicenseDialog={toggleLicenseDialog}- toggleThirdPartyLibsDialog={toggleThirdPartyLibsDialog}- onClose={toggleAboutDialog}- />- )}- {props.isKeysDialogOpened && (- <KeyboardDialogAsync- open={props.isKeysDialogOpened}- onClose={toggleKeysDialog}- />- )}- {props.isLicenseDialogOpened && (- <LicenseDialogAsync- open={props.isLicenseDialogOpened}- onClose={(event, reason) => {- if (reason === 'backdropClick' || reason === 'escapeKeyDown') {- return true;- }- setFirstRun(false);- toggleLicenseDialog();- }}- />- )}- {props.isOnboardingDialogOpened && (- <OnboardingDialogAsync- open={props.isOnboardingDialogOpened}- onClose={toggleOnboardingDialog}- />- )}- {props.isThirdPartyLibsDialogOpened && (- <ThirdPartyLibsDialogAsync- open={props.isThirdPartyLibsDialogOpened}- onClose={toggleThirdPartyLibsDialog}- />- )}- {props.isEditTagDialogOpened && (- <EditEntryTagDialogAsync- open={props.isEditTagDialogOpened}- onClose={() => toggleEditTagDialog(undefined)}- />- )}- {props.isOpenLinkDialogOpened && (- <OpenLinkDialogAsync- open={props.isOpenLinkDialogOpened}- onClose={toggleOpenLinkDialog}- openLink={openLink}- />- )}- {props.isProTeaserVisible && (- <ProTeaserDialogAsync- open={props.isProTeaserVisible}- onClose={toggleProTeaser}- />- )}- {props.isUploadProgressDialogOpened !== undefined && (- <FileUploadDialog- open={true}- onClose={toggleUploadDialog}- title={props.isUploadProgressDialogOpened}- />- )}- {props.isTruncatedConfirmDialogOpened && (- <IsTruncatedConfirmDialog- open={true}- onClose={props.toggleTruncatedConfirmDialog}- />- )}- {props.isProgressDialogOpened && (- <ProgressDialog- open={props.isProgressDialogOpened}- onClose={toggleProgressDialog}- />- )}- {props.isCreateDirectoryOpened !== null && (- <CreateDirectoryDialog- open={true}- onClose={toggleCreateDirectoryDialog}- selectedDirectoryPath={props.isCreateDirectoryOpened?.rootDirPath}- callback={props.isCreateDirectoryOpened?.callback}- reflect={props.isCreateDirectoryOpened?.reflect}- />- )}- <NewEntryDialog- open={props.isNewEntryDialogOpened}- onClose={toggleNewEntryDialog}+ )}+ {props.isOnboardingDialogOpened && (+ <OnboardingDialogAsync+ open={props.isOnboardingDialogOpened}+ onClose={toggleOnboardingDialog}/>- {props.isNewFileDialogOpened && (- <NewFileDialog- open={props.isNewFileDialogOpened}- onClose={toggleNewFileDialog}- />- )}- <SettingsDialog- open={props.isSettingsDialogOpened}- onClose={toggleSettingsDialog}+ )}+ {props.isThirdPartyLibsDialogOpened && (+ <ThirdPartyLibsDialogAsync+ open={props.isThirdPartyLibsDialogOpened}+ onClose={toggleThirdPartyLibsDialog}/>- {KanBanImportDialog && props.selectedEntries[0] && (- <KanBanImportDialog- open={props.isImportKanBanDialogOpened}- onClose={props.toggleImportKanBanDialog}- />- )}- {props.isDeleteMultipleEntriesDialogOpened && (- <ConfirmDialog- open={props.isDeleteMultipleEntriesDialogOpened}- onClose={() => props.toggleDeleteMultipleEntriesDialog()}- title={t('core:deleteConfirmationTitle')}- content={t('core:deleteConfirmationContent')}- list={props.selectedEntries.map(fsEntry => fsEntry.name)}- confirmCallback={result => {- if (result && props.selectedEntries) {- const deletePromises = props.selectedEntries.map(fsEntry => {- if (fsEntry.isFile) {- return props.deleteFile(fsEntry.path, fsEntry.uuid);- }- return deleteDirectory(fsEntry.path);+ )}+ {props.isEditTagDialogOpened && (+ <EditEntryTagDialogAsync+ open={props.isEditTagDialogOpened}+ onClose={() => toggleEditTagDialog(undefined)}+ />+ )}+ {props.isOpenLinkDialogOpened && (+ <OpenLinkDialogAsync+ open={props.isOpenLinkDialogOpened}+ onClose={toggleOpenLinkDialog}+ />+ )}+ {props.isProTeaserVisible && (+ <ProTeaserDialogAsync+ open={props.isProTeaserVisible}+ onClose={toggleProTeaser}+ />+ )}+ {props.isUploadProgressDialogOpened !== undefined && (+ <FileUploadDialog+ open={true}+ onClose={toggleUploadDialog}+ title={props.isUploadProgressDialogOpened}+ />+ )}+ {props.isTruncatedConfirmDialogOpened && (+ <IsTruncatedConfirmDialog+ open={true}+ onClose={props.toggleTruncatedConfirmDialog}+ />+ )}+ {props.isProgressDialogOpened && (+ <ProgressDialog+ open={props.isProgressDialogOpened}+ onClose={toggleProgressDialog}+ />+ )}+ {props.isCreateDirectoryOpened !== null && (+ <CreateDirectoryDialog+ open={true}+ onClose={toggleCreateDirectoryDialog}+ selectedDirectoryPath={props.isCreateDirectoryOpened?.rootDirPath}+ callback={props.isCreateDirectoryOpened?.callback}+ reflect={props.isCreateDirectoryOpened?.reflect}+ />+ )}+ <NewEntryDialog+ open={props.isNewEntryDialogOpened}+ onClose={toggleNewEntryDialog}+ />+ {props.isNewFileDialogOpened && (+ <NewFileDialog+ open={props.isNewFileDialogOpened}+ onClose={toggleNewFileDialog}+ />+ )}+ <SettingsDialog+ open={props.isSettingsDialogOpened}+ onClose={toggleSettingsDialog}+ />+ {KanBanImportDialog && props.selectedEntries[0] && (+ <KanBanImportDialog+ open={props.isImportKanBanDialogOpened}+ onClose={props.toggleImportKanBanDialog}+ />+ )}+ {props.isDeleteMultipleEntriesDialogOpened && (+ <ConfirmDialog+ open={props.isDeleteMultipleEntriesDialogOpened}+ onClose={() => props.toggleDeleteMultipleEntriesDialog()}+ title={t('core:deleteConfirmationTitle')}+ content={t('core:deleteConfirmationContent')}+ list={props.selectedEntries.map(fsEntry => fsEntry.name)}+ confirmCallback={result => {+ if (result && props.selectedEntries) {+ const deletePromises = props.selectedEntries.map(fsEntry => {+ if (fsEntry.isFile) {+ return deleteFile(fsEntry.path, fsEntry.uuid);+ }+ return deleteDirectory(fsEntry.path);+ });+ Promise.all(deletePromises)+ .then(delResult => {+ // console.debug(delResult);+ if (delResult.some(del => del)) {+ props.setSelectedEntries([]);+ } // TODO else { remove only deleted from setSelectedEntries}+ return true;+ })+ .catch(err => {+ console.warn('Deleting file failed', err);});- Promise.all(deletePromises)- .then(delResult => {- // console.debug(delResult);- if (delResult.some(del => del)) {- props.setSelectedEntries([]);- } // TODO else { remove only deleted from setSelectedEntries}- return true;- })- .catch(err => {- console.warn('Deleting file failed', err);- });- }- }}- cancelDialogTID="cancelDeleteFileDialog"- confirmDialogTID="confirmDeleteFileDialog"- confirmDialogContentTID="confirmDeleteDialogContent"- />- )}- <PageNotification />- <div- style={{- backgroundColor: theme.palette.background.default,- height: '100%'+ }}}- >- <style>- {`+ cancelDialogTID="cancelDeleteFileDialog"+ confirmDialogTID="confirmDeleteFileDialog"+ confirmDialogContentTID="confirmDeleteDialogContent"+ />+ )}+ <PageNotification />+ <div+ style={{+ backgroundColor: theme.palette.background.default,+ height: '100%'+ }}+ >+ <style>+ {`body { background-color: ${theme.palette.background.default} !important;}@@ -779,44 +762,43 @@ function MainPage(props: Props) {flex-direction: column;}`}- </style>- {props.isDesktopMode || (AppConfig.isAmplify && !props.user) ? (- <TargetFileBox- accepts={[FILE]}- setMoveCopyDialogOpened={setMoveCopyDialogOpened}+ </style>+ {props.isDesktopMode || (AppConfig.isAmplify && !props.user) ? (+ <TargetFileBox+ accepts={[FILE]}+ setMoveCopyDialogOpened={setMoveCopyDialogOpened}+ >+ <CustomDragLayer />+ <Drawer variant="persistent" anchor="left" open={drawerOpened}>+ <MobileNavigation width={drawerWidth} />+ </Drawer>+ <main+ className={clsx(classes.content, {+ [classes.contentShift]: !drawerOpened+ })}>- <CustomDragLayer />- <Drawer variant="persistent" anchor="left" open={drawerOpened}>- <MobileNavigation width={drawerWidth} />- </Drawer>- <main- className={clsx(classes.content, {- [classes.contentShift]: !drawerOpened- })}- >- {renderContainers()}- </main>- </TargetFileBox>- ) : (- <>- <SwipeableDrawer- open={drawerOpened}- onClose={() => setDrawerOpened(false)}- onOpen={() => setDrawerOpened(true)}- hysteresis={0.1}- disableBackdropTransition={!AppConfig.isIOS}- disableDiscovery={AppConfig.isIOS}- >- <MobileNavigation- width={drawerWidth}- hideDrawer={() => setDrawerOpened(false)}- />- </SwipeableDrawer>{renderContainers()}- </>- )}- </div>- </TaggingActionsContextProvider>+ </main>+ </TargetFileBox>+ ) : (+ <>+ <SwipeableDrawer+ open={drawerOpened}+ onClose={() => setDrawerOpened(false)}+ onOpen={() => setDrawerOpened(true)}+ hysteresis={0.1}+ disableBackdropTransition={!AppConfig.isIOS}+ disableDiscovery={AppConfig.isIOS}+ >+ <MobileNavigation+ width={drawerWidth}+ hideDrawer={() => setDrawerOpened(false)}+ />+ </SwipeableDrawer>+ {renderContainers()}+ </>+ )}+ </div></HotKeys></Root>);@@ -840,8 +822,6 @@ function mapStateToProps(state) {isOpenLinkDialogOpened: isOpenLinkDialogOpened(state),isProTeaserVisible: isProTeaserVisible(state),isProgressDialogOpened: isProgressOpened(state),- isReadOnlyMode: isReadOnlyMode(state),- isGeneratingThumbs: isGeneratingThumbs(state),isDesktopMode: getDesktopMode(state),keyBindings: getKeyBindingObject(state),mainSplitSize: getMainVerticalSplitSize(state),@@ -861,7 +841,6 @@ function mapStateToProps(state) {function mapDispatchToProps(dispatch) {return bindActionCreators({- loadParentDirectoryContent: AppActions.loadParentDirectoryContent,toggleCreateDirectoryDialog: AppActions.toggleCreateDirectoryDialog,toggleUploadDialog: AppActions.toggleUploadDialog,toggleProgressDialog: AppActions.toggleProgressDialog,@@ -869,8 +848,7 @@ function mapDispatchToProps(dispatch) {toggleEditTagDialog: AppActions.toggleEditTagDialog,toggleTruncatedConfirmDialog: AppActions.toggleTruncatedConfirmDialog,onUploadProgress: AppActions.onUploadProgress,- saveFile: AppActions.saveFile,- openLink: AppActions.openLink,+ //saveFile: AppActions.saveFile,setZoomResetApp: SettingsActions.setZoomResetApp,setZoomInApp: SettingsActions.setZoomInApp,setZoomOutApp: SettingsActions.setZoomOutApp,@@ -890,7 +868,6 @@ function mapDispatchToProps(dispatch) {setSelectedEntries: AppActions.setSelectedEntries,toggleShowUnixHiddenEntries: SettingsActions.toggleShowUnixHiddenEntries,setMainVerticalSplitSize: SettingsActions.setMainVerticalSplitSize,- showNotification: AppActions.showNotification,reflectCreateEntries: AppActions.reflectCreateEntries,openLocationManagerPanel: AppActions.openLocationManagerPanel,openTagLibraryPanel: AppActions.openTagLibraryPanel,@@ -900,9 +877,6 @@ function mapDispatchToProps(dispatch) {toggleDeleteMultipleEntriesDialog:AppActions.toggleDeleteMultipleEntriesDialog,setFirstRun: SettingsActions.setFirstRun,- uploadFilesAPI: IOActions.uploadFilesAPI,- deleteFile: AppActions.deleteFile,- setSearchQuery: LocationIndexActions.setSearchQuery,addExtensions: AppActions.addExtensions,addSupportedFileTypes: SettingsActions.addSupportedFileTypes},@@ -932,7 +906,6 @@ const areEqual = (prevProp, nextProp) =>nextProp.isOpenLinkDialogOpened === prevProp.isOpenLinkDialogOpened &&nextProp.isProTeaserVisible === prevProp.isProTeaserVisible &&nextProp.isProgressDialogOpened === prevProp.isProgressDialogOpened &&- nextProp.isReadOnlyMode === prevProp.isReadOnlyMode &&nextProp.isSearchPanelOpened === prevProp.isSearchPanelOpened &&nextProp.isSettingsDialogOpened === prevProp.isSettingsDialogOpened &&nextProp.isTagLibraryPanelOpened === prevProp.isTagLibraryPanelOpened &&diff --git a/app/containers/PageNotification.tsx b/app/containers/PageNotification.tsxindex 1c43b1ead..39d7372b7 100644--- a/app/containers/PageNotification.tsx+++ b/app/containers/PageNotification.tsx@@ -18,8 +18,8 @@import React from 'react';import { bindActionCreators } from 'redux';-import { connect } from 'react-redux';-import { emphasize, styled, Theme } from '@mui/material/styles';+import { useDispatch, useSelector } from 'react-redux';+import { styled } from '@mui/material/styles';import Snackbar from '@mui/material/Snackbar';import Button from '@mui/material/Button';import IconButton from '@mui/material/IconButton';@@ -27,36 +27,15 @@ import CloseIcon from '@mui/icons-material/Close';import { getLastPublishedVersion } from '-/reducers/settings';import {actions as AppActions,- getNotificationStatus,- isGeneratingThumbs,+ AppDispatch,isUpdateAvailable} from '../reducers/app';-import {- actions as LocationIndexActions,- isIndexing-} from '../reducers/location-index';import { Pro } from '../pro';import Links from '-/content/links';import { openURLExternally } from '-/services/utils-io';-import Chip from '@mui/material/Chip';import { useTranslation } from 'react-i18next';--interface Props {- notificationStatus: any;- isIndexing: boolean;- isGeneratingThumbs: boolean;- showNotification: (- text: string,- notificationType?: string,- autohide?: boolean- ) => void;- hideNotifications: () => void;- cancelDirectoryIndexing: () => void;- isUpdateAvailable: boolean;- lastPublishedVersion: string;- setUpdateAvailable: (isUpdateAvailable: boolean) => void;- setGeneratingThumbnails: (isGenerating: boolean) => void;-}+import { useNotificationContext } from '-/hooks/useNotificationContext';+import { useLocationIndexContext } from '-/hooks/useLocationIndexContext';const TSNotification = styled(Snackbar)(({ theme }) => {return {@@ -68,10 +47,22 @@ const TSNotification = styled(Snackbar)(({ theme }) => {};}) as typeof Snackbar;-function PageNotification(props: Props) {+function PageNotification() {const { t } = useTranslation();+ const dispatch: AppDispatch = useDispatch();+ const {+ isGeneratingThumbs,+ setGeneratingThumbs,+ notificationStatus,+ showNotification,+ hideNotifications+ } = useNotificationContext();+ const { isIndexing, cancelDirectoryIndexing } = useLocationIndexContext();+ const updateAvailable = useSelector(isUpdateAvailable);+ const lastPublishedVersion = useSelector(getLastPublishedVersion);+const skipRelease = () => {- props.setUpdateAvailable(false);+ dispatch(AppActions.setUpdateAvailable(false));};const openChangelogPage = () => {@@ -80,39 +71,39 @@ function PageNotification(props: Props) {const getLatestVersion = () => {if (Pro) {- props.showNotification(t('core:getLatestVersionPro'), 'default', false);+ showNotification(t('core:getLatestVersionPro'), 'default', false);} else {openURLExternally(Links.links.downloadURL, true);}- props.setUpdateAvailable(false);+ dispatch(AppActions.setUpdateAvailable(false));};return (<><TSNotification- data-tid={props.notificationStatus.tid}+ data-tid={notificationStatus.tid}anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}- open={props.notificationStatus.visible}- onClose={() => props.hideNotifications()}- autoHideDuration={props.notificationStatus.autohide ? 3000 : undefined}- message={props.notificationStatus.text}+ open={notificationStatus.visible}+ onClose={() => hideNotifications()}+ autoHideDuration={notificationStatus.autohide ? 3000 : undefined}+ message={notificationStatus.text}action={[<IconButton- data-tid={'close' + props.notificationStatus.tid}+ data-tid={'close' + notificationStatus.tid}key="close"aria-label={t('core:closeButton')}color="inherit"- onClick={() => props.hideNotifications()}+ onClick={() => hideNotifications()}size="large"><CloseIcon /></IconButton>]}/>- {props.isGeneratingThumbs && (+ {isGeneratingThumbs && (<TSNotificationanchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}- open={props.isGeneratingThumbs}+ open={isGeneratingThumbs}autoHideDuration={undefined}message={t('core:loadingOrGeneratingThumbnails')}action={[@@ -120,7 +111,7 @@ function PageNotification(props: Props) {key="closeButton"aria-label={t('core:closeButton')}color="inherit"- onClick={() => props.setGeneratingThumbnails(false)}+ onClick={() => setGeneratingThumbs(false)}size="large"><CloseIcon />@@ -130,7 +121,7 @@ function PageNotification(props: Props) {)}<TSNotificationanchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}- open={props.isIndexing}+ open={isIndexing}autoHideDuration={undefined}message="Indexing"action={[@@ -138,7 +129,7 @@ function PageNotification(props: Props) {key="cancelIndexButton"color="secondary"size="small"- onClick={props.cancelDirectoryIndexing}+ onClick={() => cancelDirectoryIndexing()}data-tid="cancelDirectoryIndexing">{t('core:cancelIndexing')}@@ -147,9 +138,9 @@ function PageNotification(props: Props) {/><TSNotificationanchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}- open={props.isUpdateAvailable}+ open={updateAvailable}autoHideDuration={undefined}- message={'Version ' + props.lastPublishedVersion + ' available.'}+ message={'Version ' + lastPublishedVersion + ' available.'}action={[<Buttonkey="laterButton"@@ -181,37 +172,4 @@ function PageNotification(props: Props) {);}-function mapStateToProps(state) {- return {- notificationStatus: getNotificationStatus(state),- isIndexing: isIndexing(state),- isUpdateAvailable: isUpdateAvailable(state),- lastPublishedVersion: getLastPublishedVersion(state),- isGeneratingThumbs: isGeneratingThumbs(state)- };-}--function mapDispatchToProps(dispatch) {- return bindActionCreators(- {- showNotification: AppActions.showNotification,- hideNotifications: AppActions.hideNotifications,- cancelDirectoryIndexing: LocationIndexActions.cancelDirectoryIndexing,- setUpdateAvailable: AppActions.setUpdateAvailable,- setGeneratingThumbnails: AppActions.setGeneratingThumbnails- },- dispatch- );-}--const areEqual = (prevProp, nextProp) =>- JSON.stringify(nextProp.notificationStatus) ===- JSON.stringify(prevProp.notificationStatus) &&- nextProp.isIndexing === prevProp.isIndexing &&- nextProp.isGeneratingThumbs === prevProp.isGeneratingThumbs &&- nextProp.isUpdateAvailable === prevProp.isUpdateAvailable;--export default connect(- mapStateToProps,- mapDispatchToProps-)(React.memo(PageNotification, areEqual));+export default PageNotification;diff --git a/app/containers/Root.tsx b/app/containers/Root.tsxindex 9362a49aa..aae3825ac 100644--- a/app/containers/Root.tsx+++ b/app/containers/Root.tsx@@ -28,6 +28,12 @@ import TsAuth from '-/containers/TsAuth';import init from '-/services/i18nInit';import { FsActionsContextProvider } from '-/hooks/FsActionsContextProvider';import { OpenedEntryContextProvider } from '-/hooks/OpenedEntryContextProvider';+import { DirectoryContentContextProvider } from '-/hooks/DirectoryContentContextProvider';+import { CurrentLocationContextProvider } from '-/hooks/CurrentLocationContextProvider';+import { NotificationContextProvider } from '-/hooks/NotificationContextProvider';+import { IOActionsContextProvider } from '-/hooks/IOActionsContextProvider';+import { TaggingActionsContextProvider } from '-/hooks/TaggingActionsContextProvider';+import { LocationIndexContextProvider } from '-/hooks/LocationIndexContextProvider';type RootType = {store: Store<{}>;@@ -47,11 +53,23 @@ export default function Root({ store, persistor }: RootType) {let appContent = (<App>- <OpenedEntryContextProvider>- <FsActionsContextProvider>- <MainPage />- </FsActionsContextProvider>- </OpenedEntryContextProvider>+ <NotificationContextProvider>+ <CurrentLocationContextProvider>+ <DirectoryContentContextProvider>+ <LocationIndexContextProvider>+ <OpenedEntryContextProvider>+ <FsActionsContextProvider>+ <IOActionsContextProvider>+ <TaggingActionsContextProvider>+ <MainPage />+ </TaggingActionsContextProvider>+ </IOActionsContextProvider>+ </FsActionsContextProvider>+ </OpenedEntryContextProvider>+ </LocationIndexContextProvider>+ </DirectoryContentContextProvider>+ </CurrentLocationContextProvider>+ </NotificationContextProvider></App>);diff --git a/app/hooks/CurrentLocationContextProvider.tsx b/app/hooks/CurrentLocationContextProvider.tsxnew file mode 100644index 000000000..7a5fca59f--- /dev/null+++ b/app/hooks/CurrentLocationContextProvider.tsx@@ -0,0 +1,405 @@+/**+ * TagSpaces - universal file and folder organizer+ * Copyright (C) 2023-present TagSpaces UG (haftungsbeschraenkt)+ *+ * 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/>.+ *+ */++import React, {+ createContext,+ useEffect,+ useMemo,+ useRef,+ useState+} from 'react';+import { useDispatch, useSelector } from 'react-redux';+import { actions as AppActions, AppDispatch } from '-/reducers/app';+import { TS } from '-/tagspaces.namespace';+import { useTranslation } from 'react-i18next';+import {+ actions as LocationActions,+ getDefaultLocationId,+ getLocations+} from '-/reducers/locations';+import PlatformIO from '-/services/platform-facade';+import { setLocationType } from '-/services/utils-io';+import { clearAllURLParams, getURLParameter } from '-/utils/dom';+import { Pro } from '-/pro';+import { locationType } from '@tagspaces/tagspaces-common/misc';+import { getUuid } from '@tagspaces/tagspaces-common/utils-io';+import { useNotificationContext } from '-/hooks/useNotificationContext';+import { getPersistTagsInSidecarFile } from '-/reducers/settings';++type CurrentLocationContextData = {+ currentLocation: TS.Location;+ readOnlyMode: boolean;+ skipInitialDirList: boolean;+ persistTagsInSidecarFile: boolean;+ changeLocation: (location: TS.Location) => void;+ editLocation: (location: TS.Location, openAfterEdit?: boolean) => void;+ addLocation: (+ location: TS.Location,+ openAfterCreate?: boolean,+ locationPosition?: number+ ) => void;+ addLocations: (arrLocations: Array<TS.Location>, override?: boolean) => void;+ openLocation: (location: TS.Location, skipInitialDirList?: boolean) => void;+ closeLocation: (locationId: string) => void;+ closeAllLocations: () => void;+ switchCurrentLocationType: () => Promise<boolean>;+ switchLocationTypeByID: (locationId: string) => Promise<boolean>;+ changeLocationByID: (locationId: string) => void;+ openLocationById: (locationId: string, skipInitialDirList?: boolean) => void;+ selectedLocation: TS.Location;+ setSelectedLocation: (location: TS.Location) => void;+ getLocationPosition: (locationId: string) => number;+ locationDirectoryContextMenuAnchorEl: null | HTMLElement;+ setLocationDirectoryContextMenuAnchorEl: (el: HTMLElement) => void;+};++export const CurrentLocationContext = createContext<CurrentLocationContextData>(+ {+ currentLocation: undefined,+ readOnlyMode: false,+ skipInitialDirList: false,+ persistTagsInSidecarFile: true,+ changeLocation: () => {},+ editLocation: () => {},+ addLocation: () => {},+ addLocations: () => {},+ openLocation: () => {},+ closeLocation: () => {},+ closeAllLocations: () => {},+ switchCurrentLocationType: () => Promise.resolve(false),+ switchLocationTypeByID: () => Promise.resolve(false),+ changeLocationByID: () => {},+ openLocationById: () => {},+ selectedLocation: undefined,+ setSelectedLocation: () => {},+ getLocationPosition: () => 0,+ locationDirectoryContextMenuAnchorEl: undefined,+ setLocationDirectoryContextMenuAnchorEl: () => {}+ }+);++export type CurrentLocationContextProviderProps = {+ children: React.ReactNode;+};++export const CurrentLocationContextProvider = ({+ children+}: CurrentLocationContextProviderProps) => {+ const dispatch: AppDispatch = useDispatch();+ const { t } = useTranslation();+ const { showNotification } = useNotificationContext();++ const [currentLocation, setCurrentLocation] = useState<TS.Location>(+ undefined+ );+ const selectedLocation = useRef<TS.Location>(undefined);+ const skipInitialDirList = useRef<boolean>(false);+ const [+ locationDirectoryContextMenuAnchorEl,+ setLocationDirectoryContextMenuAnchorEl+ ] = useState<null | HTMLElement>(null);++ const locations: TS.Location[] = useSelector(getLocations);+ const defaultLocationId = useSelector(getDefaultLocationId);+ const settingsPersistTagsInSidecarFile: boolean = useSelector(+ getPersistTagsInSidecarFile+ );++ useEffect(() => {+ if (!currentLocation && defaultLocationId && defaultLocationId.length > 0) {+ const openDefaultLocation =+ !getURLParameter('tslid') &&+ !getURLParameter('tsdpath') &&+ !getURLParameter('tsepath') &&+ !getURLParameter('cmdopen');+ if (openDefaultLocation) {+ openLocationById(defaultLocationId);+ }+ }+ }, []);++ useEffect(() => {+ if (locations.length < 1) {+ // init locations+ setDefaultLocations();+ } else {+ // check if current location exist (or is removed)+ if (currentLocation) {+ const location = locations.find(+ location => location.uuid === currentLocation.uuid+ );+ if (!location) {+ closeLocation(currentLocation.uuid);+ }+ }+ }+ }, [locations]);++ function setSelectedLocation(location: TS.Location) {+ selectedLocation.current = location;+ }++ function setDefaultLocations() {+ PlatformIO.getDevicePaths()+ .then(devicePaths => {+ if (devicePaths) {+ Object.keys(devicePaths).forEach(key => {+ addLocation(+ {+ uuid: getUuid(),+ type: locationType.TYPE_LOCAL,+ name: t(('core:' + key) as any) as string,+ path: devicePaths[key] as string,+ isDefault: false, // AppConfig.isWeb && devicePaths[key] === '/files/', // Used for the web ts demo+ isReadOnly: false,+ disableIndexing: false+ },+ false+ );+ });+ }+ return true;+ })+ .catch(ex => console.error(ex));+ }++ function addLocation(+ location: TS.Location,+ openAfterCreate = true,+ locationPosition: number = undefined+ ) {+ dispatch(LocationActions.createLocation(location, locationPosition));+ if (openAfterCreate) {+ openLocation(location);+ }+ }+ /**+ * @param arrLocations+ * @param override = true - if location exist override else skip+ */+ function addLocations(arrLocations: Array<TS.Location>, override = true) {+ arrLocations.forEach((newLocation: TS.Location, idx, array) => {+ const locationExist: boolean = locations.some(+ location => location.uuid === newLocation.uuid+ );+ const isLast = idx === array.length - 1;+ if (!locationExist) {+ addLocation(newLocation, isLast);+ } else if (override) {+ editLocation(newLocation, isLast);+ }+ });+ }++ function editLocation(location: TS.Location, openAfterEdit = true) {+ dispatch(LocationActions.changeLocation(location));+ if (PlatformIO.haveObjectStoreSupport()) {+ // disableObjectStoreSupport to revoke objectStoreAPI cached object+ PlatformIO.disableObjectStoreSupport();+ }+ if (PlatformIO.haveWebDavSupport()) {+ // disableWebdavSupport to revoke cached object+ PlatformIO.disableWebdavSupport();+ }+ if (openAfterEdit) {+ /*+ * check if location uuid is changed+ */+ if (+ location.newuuid !== undefined &&+ location.newuuid !== location.uuid+ ) {+ openLocation({ ...location, uuid: location.newuuid });+ } else {+ openLocation(location);+ }+ // dispatch(AppActions.setReadOnlyMode(location.isReadOnly || false));+ }+ }++ const readOnlyMode: boolean = useMemo(+ () => currentLocation && currentLocation.isReadOnly,+ [currentLocation]+ );++ const persistTagsInSidecarFile: boolean = useMemo(() => {+ const locationPersistTagsInSidecarFile =+ currentLocation && currentLocation.persistTagsInSidecarFile;+ if (locationPersistTagsInSidecarFile !== undefined) {+ return locationPersistTagsInSidecarFile;+ }+ return settingsPersistTagsInSidecarFile;+ }, [currentLocation]);++ function changeLocation(location: TS.Location) {+ if (!currentLocation || location.uuid !== currentLocation.uuid) {+ setCurrentLocation(location);+ }+ }++ function changeLocationByID(locationId: string) {+ if (!currentLocation || locationId !== currentLocation.uuid) {+ const location = locations.find(location => location.uuid === locationId);+ if (location) {+ setCurrentLocation(location);+ }+ }+ }++ function switchLocationTypeByID(locationId: string) {+ const location = locations.find(location => location.uuid === locationId);+ return switchLocationType(location);+ }++ /**+ * @param location+ * return Promise<currentLocationId> if location is changed or null if location and type is changed+ */+ function switchLocationType(location: TS.Location) {+ if (currentLocation === undefined) {+ return setLocationType(location).then(() => null);+ }+ if (location.uuid !== currentLocation.uuid) {+ if (location.type !== currentLocation.type) {+ return setLocationType(location).then(() => null);+ } else {+ // handle the same location type but different location+ // dispatch(actions.setCurrentLocationId(location.uuid));+ return setLocationType(location).then(() => currentLocation.uuid);+ }+ }+ return Promise.resolve(null);+ }++ function switchCurrentLocationType() {+ return setLocationType(currentLocation);+ }++ function openLocationById(locationId: string, skipInitDirList?: boolean) {+ const location = locations.find(location => location.uuid === locationId);+ if (location) {+ openLocation(location, skipInitDirList);+ }+ }++ function openLocation(+ location: TS.Location,+ skipInitDirList: boolean = false+ ) {+ if (Pro && Pro.Watcher) {+ Pro.Watcher.stopWatching();+ }+ skipInitialDirList.current = skipInitDirList;+ if (location.type === locationType.TYPE_CLOUD) {+ PlatformIO.enableObjectStoreSupport(location)+ .then(() => {+ showNotification(+ t('core:connectedtoObjectStore' as any) as string,+ 'default',+ true+ );+ //dispatch(AppActions.setReadOnlyMode(location.isReadOnly || false));+ changeLocation(location);+ return true;+ })+ .catch(e => {+ console.log('connectedtoObjectStoreFailed', e);+ showNotification(+ t('core:connectedtoObjectStoreFailed' as any) as string,+ 'warning',+ true+ );+ PlatformIO.disableObjectStoreSupport();+ });+ } else {+ if (location.type === locationType.TYPE_WEBDAV) {+ PlatformIO.enableWebdavSupport(location);+ } else {+ PlatformIO.disableObjectStoreSupport();+ PlatformIO.disableWebdavSupport();+ }+ //dispatch(AppActions.setReadOnlyMode(location.isReadOnly || false));+ changeLocation(location);+ }+ }++ function closeLocation(locationId: string) {+ if (currentLocation && currentLocation.uuid === locationId) {+ locations.map(location => {+ if (location.uuid === locationId) {+ // location needed evtl. to unwatch many loc. root folders if available+ setCurrentLocation(undefined);+ dispatch(AppActions.setSelectedEntries([]));+ }+ clearAllURLParams();+ return true;+ });+ }+ }++ function closeAllLocations() {+ // location needed evtl. to unwatch many loc. root folders if available+ setCurrentLocation(undefined);+ dispatch(AppActions.setSelectedEntries([]));+ clearAllURLParams();+ return true;+ }++ function getLocationPosition(locationId: string): number {+ return locations.findIndex(location => location.uuid === locationId);+ }++ function isCurrentLocation(uuid: string) {+ return currentLocation && currentLocation.uuid === uuid;+ }++ const context = useMemo(() => {+ return {+ currentLocation,+ readOnlyMode,+ skipInitialDirList: skipInitialDirList.current,+ persistTagsInSidecarFile,+ changeLocation,+ addLocation,+ addLocations,+ editLocation,+ openLocation,+ closeLocation,+ closeAllLocations,+ switchCurrentLocationType,+ switchLocationTypeByID,+ changeLocationByID,+ openLocationById,+ selectedLocation: selectedLocation.current,+ locationDirectoryContextMenuAnchorEl,+ setLocationDirectoryContextMenuAnchorEl,+ setSelectedLocation,+ getLocationPosition+ };+ }, [+ currentLocation,+ skipInitialDirList.current,+ locationDirectoryContextMenuAnchorEl+ ]);++ return (+ <CurrentLocationContext.Provider value={context}>+ {children}+ </CurrentLocationContext.Provider>+ );+};diff --git a/app/hooks/DescriptionContextProvider.tsx b/app/hooks/DescriptionContextProvider.tsxindex 046787744..b776c3793 100644--- a/app/hooks/DescriptionContextProvider.tsx+++ b/app/hooks/DescriptionContextProvider.tsx@@ -27,12 +27,13 @@ import { useDispatch, useSelector } from 'react-redux';import {actions as AppActions,AppDispatch,- isReadOnlyMode,OpenedEntry} from '-/reducers/app';import { Pro } from '-/pro';import { useTranslation } from 'react-i18next';import { useOpenedEntryContext } from '-/hooks/useOpenedEntryContext';+import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';+import { useNotificationContext } from '-/hooks/useNotificationContext';type DescriptionContextData = {description: string;@@ -58,14 +59,19 @@ export const DescriptionContextProvider = ({children}: DescriptionContextProviderProps) => {const { t } = useTranslation();+ const dispatch: AppDispatch = useDispatch();const {openedEntries,addToEntryContainer,updateOpenedFile,reloadOpenedFile} = useOpenedEntryContext();- const dispatch: AppDispatch = useDispatch();- const readOnlyMode = useSelector(isReadOnlyMode);+ const {+ switchLocationTypeByID,+ switchCurrentLocationType,+ readOnlyMode+ } = useCurrentLocationContext();+ const { showNotification } = useNotificationContext();const openedFile = useRef<OpenedEntry>(openedEntries[0]);const isChanged = useRef<boolean>(false);const [@@ -98,36 +104,29 @@ export const DescriptionContextProvider = ({return;}if (!Pro) {- dispatch(- AppActions.showNotification(t('core:thisFunctionalityIsAvailableInPro'))- );+ showNotification(t('core:thisFunctionalityIsAvailableInPro'));return;}if (!Pro.MetaOperations) {- dispatch(- AppActions.showNotification(t('Saving description not supported'))- );+ showNotification(t('Saving description not supported'));return;}if (openedFile.current.description !== undefined) {//forceUpdate();//setDescriptionChanged(false);if (openedFile.current.locationId) {- dispatch(- AppActions.switchLocationTypeByID(openedFile.current.locationId)- ).then(currentLocationId => {- saveMetaData()- .then(() =>- dispatch(AppActions.switchCurrentLocationType(currentLocationId))- )- .catch(error => {- console.warn('Error saving description ' + error);- dispatch(AppActions.switchCurrentLocationType(currentLocationId));- dispatch(- AppActions.showNotification(t('Error saving description'))- );- });- });+ switchLocationTypeByID(openedFile.current.locationId).then(+ currentLocationId => {+ saveMetaData()+ .then(() => switchCurrentLocationType())+ .catch(error => {+ console.warn('Error saving description ' + error);+ switchCurrentLocationType().then(() =>+ showNotification(t('Error saving description'))+ );+ });+ }+ );} else {console.debug('openedFile:' +diff --git a/app/hooks/DirectoryContentContextProvider.tsx b/app/hooks/DirectoryContentContextProvider.tsxnew file mode 100644index 000000000..10005d1b3--- /dev/null+++ b/app/hooks/DirectoryContentContextProvider.tsx@@ -0,0 +1,722 @@+/**+ * TagSpaces - universal file and folder organizer+ * Copyright (C) 2023-present TagSpaces UG (haftungsbeschraenkt)+ *+ * 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/>.+ *+ */++import React, {+ createContext,+ useEffect,+ useMemo,+ useReducer,+ useRef,+ useState+} from 'react';+import { useDispatch, useSelector } from 'react-redux';+import { locationType } from '@tagspaces/tagspaces-common/misc';+import {+ actions as AppActions,+ AppDispatch,+ getEditedEntryPaths,+ getSelectedEntries+} from '-/reducers/app';+import { TS } from '-/tagspaces.namespace';+import { useTranslation } from 'react-i18next';+import {+ extractFileName,+ extractFileExtension,+ extractTagsAsObjects,+ extractParentDirectoryPath,+ getMetaFileLocationForDir,+ normalizePath,+ getMetaDirectoryPath+} from '@tagspaces/tagspaces-common/paths';+import PlatformIO from '-/services/platform-facade';+import { loadJSONFile, merge, updateFsEntries } from '-/services/utils-io';+import AppConfig from '-/AppConfig';+import { PerspectiveIDs } from '-/perspectives';+import { updateHistory } from '-/utils/dom';+import { getShowUnixHiddenEntries } from '-/reducers/settings';+import { enhanceEntry, getUuid } from '@tagspaces/tagspaces-common/utils-io';+import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';+import useFirstRender from '-/utils/useFirstRender';+import { useNotificationContext } from '-/hooks/useNotificationContext';+import { loadCurrentDirMeta } from '-/services/meta-loader';++type DirectoryContentContextData = {+ currentDirectoryEntries: TS.FileSystemEntry[];+ directoryMeta: TS.FileSystemEntryMeta;+ currentDirectoryPerspective: string;+ currentDirectoryPath: string;+ /**+ * used for reorder files in KanBan+ */+ currentDirectoryFiles: TS.OrderVisibilitySettings[];+ /**+ * used for reorder dirs in KanBan+ */+ currentDirectoryDirs: TS.OrderVisibilitySettings[];+ //isMetaLoaded: boolean;+ isMetaFolderExist: boolean;+ searchQuery: TS.SearchQuery;+ isSearchMode: boolean;+ setSearchQuery: (sQuery: TS.SearchQuery) => void;+ loadParentDirectoryContent: () => void;+ loadDirectoryContent: (+ directoryPath: string,+ loadDirMeta?: boolean+ ) => Promise<TS.FileSystemEntry[]>;+ enhanceDirectoryContent: (+ dirEntries,+ isCloudLocation,+ showDirs?: boolean,+ limit?: number,+ getDirMeta?: boolean,+ generateThumbnails?: boolean+ ) => any;+ openDirectory: (dirPath: string) => Promise<boolean>;+ openCurrentDirectory: () => Promise<boolean>;+ clearDirectoryContent: () => void;+ setCurrentDirectoryPerspective: (perspective: string) => void;+ setCurrentDirectoryColor: (color: string) => void;+ setCurrentDirectoryDirs: (dirs: TS.OrderVisibilitySettings[]) => void;+ setCurrentDirectoryFiles: (files: TS.OrderVisibilitySettings[]) => void;+ updateCurrentDirEntry: (path: string, entry: TS.FileSystemEntry) => void;+ updateCurrentDirEntries: (dirEntries: TS.FileSystemEntry[]) => void;+ updateThumbnailUrl: (filePath: string, thumbUrl: string) => void;+ setDirectoryMeta: (meta: TS.FileSystemEntryMeta) => void;+ setSearchResults: (entries: TS.FileSystemEntry[]) => void;+ appendSearchResults: (entries: TS.FileSystemEntry[]) => void;+ enterSearchMode: () => void;+ exitSearchMode: () => void;+};++export const DirectoryContentContext = createContext<+ DirectoryContentContextData+>({+ currentDirectoryEntries: [],+ directoryMeta: undefined,+ currentDirectoryPerspective: undefined,+ currentDirectoryPath: undefined,+ currentDirectoryFiles: [],+ currentDirectoryDirs: [],+ //isMetaLoaded: undefined,+ isMetaFolderExist: false,+ searchQuery: {},+ isSearchMode: false,+ setSearchQuery: () => {},+ loadParentDirectoryContent: () => {},+ loadDirectoryContent: undefined,+ enhanceDirectoryContent: () => {},+ openDirectory: undefined,+ openCurrentDirectory: undefined,+ clearDirectoryContent: () => {},+ setCurrentDirectoryPerspective: () => {},+ setCurrentDirectoryColor: () => {},+ setCurrentDirectoryDirs: () => {},+ setCurrentDirectoryFiles: () => {},+ updateCurrentDirEntry: () => {},+ updateCurrentDirEntries: () => {},+ updateThumbnailUrl: () => {},+ setDirectoryMeta: () => {},+ setSearchResults: () => {},+ appendSearchResults: () => {},+ enterSearchMode: () => {},+ exitSearchMode: () => {}+});++export type DirectoryContentContextProviderProps = {+ children: React.ReactNode;+};++export const DirectoryContentContextProvider = ({+ children+}: DirectoryContentContextProviderProps) => {+ const dispatch: AppDispatch = useDispatch();+ const { t } = useTranslation();+ const {+ closeAllLocations,+ currentLocation,+ skipInitialDirList+ } = useCurrentLocationContext();+ const { showNotification, hideNotifications } = useNotificationContext();+ const selectedEntries = useSelector(getSelectedEntries);+ //const useGenerateThumbnails = useSelector(getUseGenerateThumbnails);+ const showUnixHiddenEntries = useSelector(getShowUnixHiddenEntries);+ const editedEntryPaths = useSelector(getEditedEntryPaths);+ //const enableWS = useSelector(getEnableWS);++ const [currentDirectoryEntries, setCurrentDirectoryEntries] = useState<+ TS.FileSystemEntry[]+ >([]);+ const searchQuery = useRef<TS.SearchQuery>({});+ const isSearchMode = useRef<boolean>(false);+ /**+ * if search is performed = timestamp otherwise undefined+ */+ const lastSearchTimestamp = useRef<number>(undefined);+ const directoryMeta = useRef<TS.FileSystemEntryMeta>({ id: getUuid() });+ /**+ * isMetaLoaded boolean if thumbs and description from meta are loaded+ * is using why directoryMeta can be loaded but empty+ * undefined means no .ts folder exist+ */+ const isMetaLoaded = useRef<boolean>(undefined);+ const isMetaFolderExist = useRef<boolean>(undefined);+ const currentDirectoryPath = useRef<string>(undefined);+ const currentPerspective = useRef<string>(PerspectiveIDs.UNSPECIFIED);+ const currentDirectoryFiles = useRef<TS.OrderVisibilitySettings[]>([]);+ const currentDirectoryDirs = useRef<TS.OrderVisibilitySettings[]>([]);+ const firstRender = useFirstRender();+ const [ignored, forceUpdate] = useReducer(x => x + 1, 0, undefined);++ useEffect(() => {+ if (currentLocation) {+ if (!skipInitialDirList) {+ openDirectory(PlatformIO.getLocationPath(currentLocation));+ }+ } else {+ clearDirectoryContent();+ exitSearchMode();+ }+ }, [currentLocation]);++ /**+ * HANDLE REFLECT_RENAME_ENTRY+ */+ useEffect(() => {+ if (!firstRender && editedEntryPaths && editedEntryPaths.length > 0) {+ let action;+ for (const editedEntryPath of editedEntryPaths) {+ action = editedEntryPath.action;+ }+ if (action === 'rename') {+ const oldFilePath = editedEntryPaths[0].path;+ const newFilePath = editedEntryPaths[1].path;+ const entry = currentDirectoryEntries.find(e => e.path === oldFilePath);+ if (entry) {+ const fileNameTags = entry.isFile+ ? extractTagsAsObjects(+ newFilePath,+ AppConfig.tagDelimiter,+ PlatformIO.getDirSeparator()+ )+ : []; // dirs dont have tags in filename+ const newEntry = {+ ...entry,+ path: newFilePath,+ name: extractFileName(newFilePath, PlatformIO.getDirSeparator()),+ extension: extractFileExtension(+ newFilePath,+ PlatformIO.getDirSeparator()+ ),+ tags: [+ ...entry.tags.filter(tag => tag.type !== 'plain'), //'sidecar'), // add only sidecar tags+ ...fileNameTags+ ]+ };+ const newDirectoryEntries = currentDirectoryEntries.map(entry =>+ entry.path === oldFilePath ? newEntry : entry+ );+ /*if (searchMode.current) {+ GlobalSearch.getInstance().setResults(newDirectoryEntries);+ } else {*/+ setCurrentDirectoryEntries(newDirectoryEntries);+ //}+ }+ } else if (action === 'delete') {+ const filePath = editedEntryPaths[0].path;+ const newDirectoryEntries = currentDirectoryEntries.filter(+ entry => entry.path !== filePath+ );++ /*if (searchMode.current) {+ GlobalSearch.getInstance().setResults(newDirectoryEntries);+ } else {*/+ setCurrentDirectoryEntries(newDirectoryEntries);+ }+ }+ }, [editedEntryPaths]);++ function exitSearchMode() {+ isSearchMode.current = false;+ forceUpdate();+ }++ function enterSearchMode() {+ isSearchMode.current = true;+ forceUpdate();+ }++ function setSearchResults(searchResults: TS.FileSystemEntry[]) {+ setCurrentDirectoryEntries(searchResults);+ }++ function appendSearchResults(searchResults: TS.FileSystemEntry[]) {+ const newSearchResults = searchResults.filter(+ result =>+ !currentDirectoryEntries.some(entry => entry.path === result.path)+ );+ if (newSearchResults.length > 0) {+ setSearchResults([...currentDirectoryEntries, ...newSearchResults]);+ }+ }++ function loadParentDirectoryContent() {+ if (isSearchMode.current) {+ exitSearchMode();+ }+ const currentLocationPath = normalizePath(currentLocation.path);++ // dispatch(actions.setIsLoading(true));++ if (currentDirectoryPath.current) {+ const parentDirectory = extractParentDirectoryPath(+ currentDirectoryPath.current,+ PlatformIO.getDirSeparator()+ );+ // console.log('parentDirectory: ' + parentDirectory + ' - currentLocationPath: ' + currentLocationPath);+ if (parentDirectory.includes(currentLocationPath)) {+ openDirectory(parentDirectory);+ } else {+ showNotification(t('core:parentDirNotInLocation'), 'warning', true);+ // dispatch(actions.setIsLoading(false));+ }+ } else {+ showNotification(t('core:firstOpenaFolder'), 'warning', true);+ // dispatch(actions.setIsLoading(false));+ }+ }++ const updateCurrentDirEntry = useMemo(() => {+ return (path: string, entry: any) => {+ const entryUpdated = { ...entry, ...(!entry.path && { path: path }) };+ /*if (searchMode.current) {+ const results = updateFsEntries(+ GlobalSearch.getInstance().getResults(),+ [entryUpdated]+ );+ GlobalSearch.getInstance().setResults(results);+ } else {*/+ setCurrentDirectoryEntries(+ updateFsEntries(currentDirectoryEntries, [entryUpdated])+ );+ };+ }, [currentDirectoryEntries]);++ const getMergedEntries = (entries1, entries2) => {+ if (entries1 && entries1.length > 0) {+ return entries1.map(currentEntry => {+ const updatedEntries = entries2.filter(+ newEntry => newEntry && newEntry.path === currentEntry.path+ );+ if (updatedEntries && updatedEntries.length > 0) {+ const updatedEntry = updatedEntries.reduce(+ (prevValue, currentValue) =>+ merge(currentValue, prevValue) as TS.FileSystemEntry+ );+ return merge(updatedEntry, currentEntry);+ }+ return currentEntry;+ });+ }+ return entries2;+ };++ function updateCurrentDirEntries(+ dirEntries: TS.FileSystemEntry[],+ currentDirEntries?: TS.FileSystemEntry[]+ ) {+ if (dirEntries) {+ const entries = dirEntries.filter(e => e !== undefined);+ if (entries.length > 0) {+ const currDirEntries = currentDirEntries+ ? currentDirEntries+ : currentDirectoryEntries;+ if (currDirEntries && currDirEntries.length > 0) {+ setCurrentDirectoryEntries(getMergedEntries(currDirEntries, entries));+ } else {+ setCurrentDirectoryEntries(entries);+ }+ }+ }+ }++ function updateThumbnailUrl(filePath: string, thumbUrl: string) {+ const dirEntries = currentDirectoryEntries.map(entry => {+ if (entry.path === filePath) {+ return { ...entry, thumbPath: thumbUrl };+ }+ return entry;+ });+ setCurrentDirectoryEntries(dirEntries);+ }++ function loadDirectoryContent(+ directoryPath: string,+ loadDirMeta = false+ ): Promise<TS.FileSystemEntry[]> {+ // console.debug('loadDirectoryContent:' + directoryPath);+ window.walkCanceled = false;++ // dispatch(actions.setIsLoading(true));++ if (selectedEntries.length > 0) {+ dispatch(AppActions.setSelectedEntries([]));+ }+ if (loadDirMeta) {+ const metaDirectory = getMetaDirectoryPath(directoryPath);+ return PlatformIO.checkDirExist(metaDirectory).then(exist => {+ if (exist) {+ isMetaFolderExist.current = true;+ const metaFilePath = getMetaFileLocationForDir(+ directoryPath,+ PlatformIO.getDirSeparator()+ );+ return loadJSONFile(metaFilePath)+ .then(fsEntryMeta => {+ isMetaLoaded.current = true;+ return loadDirectoryContentInt(+ directoryPath,+ fsEntryMeta+ // description: getDescriptionPreview(fsEntryMeta.description, 200)+ );+ })+ .catch(err => {+ console.debug(+ 'Error loading meta of:' + directoryPath + ' ' + err+ );+ isMetaLoaded.current = false;+ return loadDirectoryContentInt(directoryPath);+ });+ } else {+ isMetaFolderExist.current = false;+ return loadDirectoryContentInt(directoryPath);+ }+ });+ } else {+ isMetaLoaded.current = false;+ return loadDirectoryContentInt(directoryPath);+ }+ }++ function loadDirectoryContentInt(+ directoryPath: string,+ fsEntryMeta?: TS.FileSystemEntryMeta+ ): Promise<TS.FileSystemEntry[]> {+ showNotification(t('core:loading'), 'info', false);+ const resultsLimit = {+ maxLoops:+ currentLocation && currentLocation.maxLoops+ ? currentLocation.maxLoops+ : AppConfig.maxLoops,+ IsTruncated: false+ };+ return PlatformIO.listDirectoryPromise(+ directoryPath,+ [],+ /*fsEntryMeta &&+ fsEntryMeta.perspective &&+ (fsEntryMeta.perspective === PerspectiveIDs.KANBAN ||+ fsEntryMeta.perspective === PerspectiveIDs.GALLERY)+ ? [] //'extractThumbPath']+ : [], // mode,*/+ currentLocation ? currentLocation.ignorePatternPaths : [],+ resultsLimit+ )+ .then(results => {+ if (resultsLimit.IsTruncated) {+ //OPEN ISTRUNCATED dialog+ dispatch(AppActions.toggleTruncatedConfirmDialog());+ }+ updateHistory(currentLocation, directoryPath);+ if (results !== undefined) {+ // console.debug('app listDirectoryPromise resolved:' + results.length);+ return loadDirectorySuccess(directoryPath, results, fsEntryMeta);+ }+ /*dispatch(+ AppActions.updateCurrentDirectoryPerspective(+ fsEntryMeta ? fsEntryMeta.perspective : undefined+ )+ );*/+ return [];+ })+ .catch(error => {+ // console.timeEnd('listDirectoryPromise');+ return loadDirectoryFailure(error);+ /*dispatch(+ AppActions.updateCurrentDirectoryPerspective(+ fsEntryMeta ? fsEntryMeta.perspective : undefined+ )+ );*/+ });+ }++ function clearDirectoryContent() {+ currentDirectoryPath.current = undefined;+ setCurrentDirectoryEntries([]);+ }++ function openCurrentDirectory(): Promise<boolean> {+ if (currentDirectoryPath.current) {+ return openDirectory(currentDirectoryPath.current);+ }+ return Promise.resolve(false);+ }++ function openDirectory(dirPath: string): Promise<boolean> {+ if (dirPath) {+ return loadDirectoryContent(dirPath, true).then(dirEntries => {+ if (dirEntries) {+ return loadCurrentDirMeta(dirPath, dirEntries).then(entries => {+ updateCurrentDirEntries(entries, dirEntries);+ return true;+ });+ }+ });+ }+ return Promise.resolve(false);+ }++ function loadDirectorySuccess(+ directoryPath: string,+ dirEntries: TS.FileSystemEntry[],+ dirMeta?: TS.FileSystemEntryMeta+ ): TS.FileSystemEntry[] {+ hideNotifications(['error']);++ if (dirMeta) {+ directoryMeta.current = dirMeta;+ if (dirMeta.perspective) {+ currentPerspective.current = dirMeta.perspective;+ } else {+ currentPerspective.current = PerspectiveIDs.UNSPECIFIED;+ }+ if (dirMeta.customOrder) {+ if (dirMeta.customOrder.files) {+ currentDirectoryFiles.current = dirMeta.customOrder.files;+ }+ if (dirMeta.customOrder.folders) {+ currentDirectoryDirs.current = dirMeta.customOrder.folders;+ }+ }+ } else {+ currentPerspective.current = PerspectiveIDs.UNSPECIFIED;+ }+ const directoryContent = enhanceDirectoryContent(+ dirEntries,+ currentLocation && currentLocation.type === locationType.TYPE_CLOUD,+ true+ );++ isSearchMode.current = false;++ if (+ currentDirectoryPath.current &&+ currentDirectoryPath.current.startsWith('./')+ ) {+ // relative paths+ currentDirectoryPath.current = PlatformIO.resolveFilePath(+ currentDirectoryPath.current+ );+ } else {+ currentDirectoryPath.current = directoryPath;+ }+ setCurrentDirectoryEntries(directoryContent);+ return directoryContent;+ }++ function loadDirectoryFailure(error?: any) {+ console.error('Error loading directory: ', error);+ //hideNotifications();++ showNotification(+ t('core:errorLoadingFolder') + ': ' + error.message,+ 'warning',+ false+ );+ closeAllLocations();+ return [];+ }++ function setCurrentDirectoryColor(color: string) {+ if (directoryMeta) {+ directoryMeta.current.color = color;+ }+ }++ function enhanceDirectoryContent(+ dirEntries,+ isCloudLocation,+ showDirs = true,+ limit = undefined+ ) {+ const directoryContent = [];+ dirEntries.map(entry => {+ if (!showUnixHiddenEntries && entry.name.startsWith('.')) {+ return true;+ }++ if (!showDirs && !entry.isFile) {+ return true;+ }++ if (limit !== undefined && directoryContent.length >= limit) {+ return true;+ }++ /*if (getDirMeta && !entry.isFile) {+ dirsMetaPromises.push(getEnhancedDir(entry));+ }*/++ const enhancedEntry: TS.FileSystemEntry = enhanceEntry(+ entry,+ AppConfig.tagDelimiter,+ PlatformIO.getDirSeparator()+ );+ directoryContent.push(enhancedEntry);+ /*if (+ // Enable thumb generation by+ generateThumbnails &&+ !AppConfig.isWeb && // not in webdav mode+ !PlatformIO.haveObjectStoreSupport() && // not in object store mode+ !PlatformIO.haveWebDavSupport() && // not in webdav mode+ enhancedEntry.isFile && // only for files+ genThumbnails() // enabled in the settings+ ) {+ // const isPDF = enhancedEntry.path.endsWith('.pdf');+ if (+ isWorkerAvailable &&+ supportedImgsWS.includes(enhancedEntry.extension)+ ) {+ // !isPDF) {+ tmbGenerationList.push(enhancedEntry.path);+ } else if (+ supportedImgs.includes(enhancedEntry.extension) ||+ supportedContainers.includes(enhancedEntry.extension) ||+ supportedText.includes(enhancedEntry.extension) ||+ supportedMisc.includes(enhancedEntry.extension) ||+ supportedVideos.includes(enhancedEntry.extension)+ ) {+ tmbGenerationPromises.push(+ getThumbnailURLPromise(enhancedEntry.path)+ );+ } else {+ console.log(+ 'Unsupported thumbgeneration ext:' + enhancedEntry.extension+ );+ }+ }*/+ return true;+ });++ return directoryContent;+ /*return {+ directoryContent,+ tmbGenerationPromises,+ tmbGenerationList,+ dirsMetaPromises+ };*/+ }++ function setCurrentDirectoryPerspective(+ perspective: string,+ reload: boolean = true+ ) {+ currentPerspective.current = perspective;+ if (reload) {+ forceUpdate();+ }+ }++ /*const currentDirectoryPerspective: string = useMemo(+ () => currentPerspective.current,+ [currentDirectoryPath.current, currentPerspective.current]+ );*/++ function setCurrentDirectoryDirs(dirs: TS.OrderVisibilitySettings[]) {+ currentDirectoryDirs.current = dirs;+ }++ function setCurrentDirectoryFiles(files: TS.OrderVisibilitySettings[]) {+ currentDirectoryFiles.current = files;+ }++ function setDirectoryMeta(meta: TS.FileSystemEntryMeta) {+ directoryMeta.current = meta;+ isMetaLoaded.current = true;+ forceUpdate();+ }++ function setSearchQuery(sQuery: TS.SearchQuery) {+ if (Object.keys(searchQuery).length === 0) {+ exitSearchMode();+ } else {+ isSearchMode.current = true;+ searchQuery.current = sQuery;+ forceUpdate();+ }+ }++ const context = useMemo(() => {+ return {+ currentDirectoryEntries: currentDirectoryEntries,+ directoryMeta: directoryMeta.current,+ currentDirectoryPerspective: currentPerspective.current,+ currentDirectoryPath: currentDirectoryPath.current,+ currentDirectoryFiles: currentDirectoryFiles.current,+ currentDirectoryDirs: currentDirectoryDirs.current,+ isMetaFolderExist: isMetaFolderExist.current,+ searchQuery: searchQuery.current,+ isSearchMode: isSearchMode.current,+ setSearchQuery,+ loadDirectoryContent,+ loadParentDirectoryContent,+ enhanceDirectoryContent,+ openDirectory,+ openCurrentDirectory,+ clearDirectoryContent,+ setCurrentDirectoryPerspective,+ setCurrentDirectoryColor,+ setCurrentDirectoryDirs,+ setCurrentDirectoryFiles,+ updateCurrentDirEntry,+ updateCurrentDirEntries,+ updateThumbnailUrl,+ setDirectoryMeta,+ setSearchResults,+ appendSearchResults,+ enterSearchMode,+ exitSearchMode+ };+ }, [+ currentLocation,+ currentDirectoryEntries,+ currentDirectoryPath.current,+ directoryMeta.current,+ currentPerspective.current,+ //isMetaFolderExist.current,+ currentDirectoryFiles.current,+ currentDirectoryDirs.current,+ isSearchMode.current,+ searchQuery.current+ ]);++ return (+ <DirectoryContentContext.Provider value={context}>+ {children}+ </DirectoryContentContext.Provider>+ );+};diff --git a/app/hooks/FsActionsContextProvider.tsx b/app/hooks/FsActionsContextProvider.tsxindex 11ea92c54..67b6b01ec 100644--- a/app/hooks/FsActionsContextProvider.tsx+++ b/app/hooks/FsActionsContextProvider.tsx@@ -18,17 +18,26 @@import React, { createContext, useMemo } from 'react';import { useDispatch, useSelector } from 'react-redux';-import {- actions as AppActions,- AppDispatch,- getDirectoryPath-} from '-/reducers/app';+import { actions as AppActions, AppDispatch } from '-/reducers/app';import { useTranslation } from 'react-i18next';import PlatformIO from '-/services/platform-facade';-import { extractDirectoryName } from '@tagspaces/tagspaces-common/paths';+import {+ extractContainingDirectoryPath,+ extractDirectoryName,+ getBackupFileLocation,+ getMetaFileLocationForFile,+ getThumbFileLocationForFile+} from '@tagspaces/tagspaces-common/paths';import { useOpenedEntryContext } from '-/hooks/useOpenedEntryContext';-import GlobalSearch from '-/services/search-index';import { getUseTrashCan } from '-/reducers/settings';+import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';+import {+ deleteFilesPromise,+ renameFilesPromise,+ toFsEntry+} from '-/services/utils-io';+import { useNotificationContext } from '-/hooks/useNotificationContext';+import { useLocationIndexContext } from '-/hooks/useLocationIndexContext';type FsActionsContextData = {renameDirectory: (@@ -37,12 +46,16 @@ type FsActionsContextData = {) => Promise<string>;createDirectory: (directoryPath: string, reflect?) => Promise<boolean>;deleteDirectory: (directoryPath: string) => Promise<boolean>;+ renameFile: (filePath: string, newFilePath: string) => Promise<boolean>;+ deleteFile: (filePath: string, uuid: string) => Promise<boolean>;};export const FsActionsContext = createContext<FsActionsContextData>({renameDirectory: () => Promise.resolve(''),createDirectory: () => Promise.resolve(false),- deleteDirectory: () => Promise.resolve(false)+ deleteDirectory: () => Promise.resolve(false),+ renameFile: () => Promise.resolve(false),+ deleteFile: () => Promise.resolve(false)});export type FsActionsContextProviderProps = {@@ -58,50 +71,52 @@ export const FsActionsContextProvider = ({reflectRenameDirectory,reflectDeleteDirectory} = useOpenedEntryContext();+ const {+ openDirectory,+ currentDirectoryPath,+ loadParentDirectoryContent+ } = useDirectoryContentContext();+ const {+ reflectDeleteEntry,+ reflectRenameEntry,+ reflectCreateEntry+ } = useLocationIndexContext();+ const { showNotification } = useNotificationContext();const dispatch: AppDispatch = useDispatch();- const currentDirectoryPath = useSelector(getDirectoryPath);const useTrashCan = useSelector(getUseTrashCan);function renameDirectory(directoryPath: string, newDirectoryName: string) {return PlatformIO.renameDirectoryPromise(directoryPath, newDirectoryName).then(newDirPath => {if (currentDirectoryPath === directoryPath) {- dispatch(- AppActions.loadDirectoryContent(newDirPath, false, true)- ).then(() => {+ openDirectory(newDirPath).then(() => {reflectRenameDirectory(directoryPath, newDirPath);- GlobalSearch.getInstance().reflectRenameEntry(- directoryPath,- newDirPath- );+ reflectRenameEntry(directoryPath, newDirPath);});} else {+ reflectRenameEntry(directoryPath, newDirPath);dispatch(AppActions.reflectRenameEntry(directoryPath, newDirPath));}- dispatch(- AppActions.showNotification(- `Renaming directory ${extractDirectoryName(- directoryPath,- PlatformIO.getDirSeparator()- )} successful.`,- 'default',- true- )+ showNotification(+ `Renaming directory ${extractDirectoryName(+ directoryPath,+ PlatformIO.getDirSeparator()+ )} successful.`,+ 'default',+ true);return newDirPath;}).catch(error => {console.warn('Error while renaming directory: ' + error);- dispatch(- AppActions.showNotification(- `Error renaming directory '${extractDirectoryName(- directoryPath,- PlatformIO.getDirSeparator()- )}'`,- 'error',- true- )+ showNotification(+ `Error renaming directory '${extractDirectoryName(+ directoryPath,+ PlatformIO.getDirSeparator()+ )}'`,+ 'error',+ true);throw error;});@@ -116,31 +131,28 @@ export const FsActionsContextProvider = ({}console.log(`Creating directory ${directoryPath} successful.`);if (reflect) {+ reflectCreateEntry(toFsEntry(directoryPath, false));dispatch(AppActions.reflectCreateEntry(directoryPath, false));}- dispatch(- AppActions.showNotification(- `Creating directory ${extractDirectoryName(- directoryPath,- PlatformIO.getDirSeparator()- )} successful.`,- 'default',- true- )+ showNotification(+ `Creating directory ${extractDirectoryName(+ directoryPath,+ PlatformIO.getDirSeparator()+ )} successful.`,+ 'default',+ true);return true;}).catch(error => {console.warn('Error creating directory: ' + error);- dispatch(- AppActions.showNotification(- `Error creating directory '${extractDirectoryName(- directoryPath,- PlatformIO.getDirSeparator()- )}'`,- 'error',- true- )+ showNotification(+ `Error creating directory '${extractDirectoryName(+ directoryPath,+ PlatformIO.getDirSeparator()+ )}'`,+ 'error',+ true);return false;// dispatch stopLoadingAnimation@@ -151,51 +163,183 @@ export const FsActionsContextProvider = ({return PlatformIO.deleteDirectoryPromise(directoryPath, useTrashCan).then(() => {if (directoryPath === currentDirectoryPath) {- dispatch(AppActions.loadParentDirectoryContent());- GlobalSearch.getInstance().reflectDeleteEntry(directoryPath);+ loadParentDirectoryContent();+ reflectDeleteEntry(directoryPath);// close opened entries in deleted dirreflectDeleteDirectory(directoryPath);} else {+ reflectDeleteEntry(directoryPath);dispatch(AppActions.reflectDeleteEntry(directoryPath));}- dispatch(- AppActions.showNotification(- t('deletingDirectorySuccessfull', {+ showNotification(+ t(+ 'deletingDirectorySuccessfull' as any,+ {dirPath: extractDirectoryName(directoryPath,PlatformIO.getDirSeparator())- }),- 'default',- true- )+ } as any+ ) as string,+ 'default',+ true);return true;}).catch(error => {console.warn('Error while deleting directory: ' + error);- dispatch(- AppActions.showNotification(- t('errorDeletingDirectoryAlert', {+ showNotification(+ t(+ 'errorDeletingDirectoryAlert' as any,+ {dirPath: extractDirectoryName(directoryPath,PlatformIO.getDirSeparator())- }),- 'error',- true- )+ } as any+ ) as string,+ 'error',+ true);return false;// dispatch stopLoadingAnimation});}+ function renameFile(filePath: string, newFilePath: string): Promise<boolean> {+ return PlatformIO.renameFilePromise(filePath, newFilePath)+ .then(result => {+ const newFilePathFromPromise = result[1];+ console.info('File renamed ' + filePath + ' to ' + newFilePath);+ showNotification(t('core:renamingSuccessfully'), 'default', true);+ // Update sidecar file and thumb+ return renameFilesPromise([+ [+ getMetaFileLocationForFile(filePath, PlatformIO.getDirSeparator()),+ getMetaFileLocationForFile(+ newFilePath,+ PlatformIO.getDirSeparator()+ )+ ],+ [+ getThumbFileLocationForFile(+ filePath,+ PlatformIO.getDirSeparator(),+ false+ ),+ getThumbFileLocationForFile(+ newFilePath,+ PlatformIO.getDirSeparator(),+ false+ )+ ]+ ])+ .then(() => {+ reflectRenameEntry(filePath, newFilePathFromPromise);+ dispatch(+ AppActions.reflectRenameEntry(filePath, newFilePathFromPromise)+ );+ console.info(+ 'Renaming meta file and thumb successful from ' ++ filePath ++ ' to:' ++ newFilePath+ );+ return true;+ })+ .catch(err => {+ reflectRenameEntry(filePath, newFilePathFromPromise);+ dispatch(+ AppActions.reflectRenameEntry(filePath, newFilePathFromPromise)+ );+ console.warn(+ 'Renaming meta file and thumb failed from ' ++ filePath ++ ' to:' ++ newFilePath,+ err+ );+ return false;+ });+ })+ .catch(error => {+ console.error(`Error while renaming file ${filePath}`, error);+ showNotification(+ `Error while renaming file ${filePath}`,+ 'error',+ true+ );+ return false;+ });+ }++ function deleteFile(filePath: string, uuid: string): Promise<boolean> {+ return PlatformIO.deleteFilePromise(filePath, useTrashCan)+ .then(() => {+ // TODO close file opener if this file is opened+ reflectDeleteEntry(filePath);+ dispatch(AppActions.reflectDeleteEntry(filePath));+ showNotification(+ `Deleting file ${filePath} successful.`,+ 'default',+ true+ );+ // Delete revisions+ const backupFilePath = getBackupFileLocation(+ filePath,+ uuid,+ PlatformIO.getDirSeparator()+ );+ const backupPath = extractContainingDirectoryPath(+ backupFilePath,+ PlatformIO.getDirSeparator()+ );+ PlatformIO.deleteDirectoryPromise(backupPath)+ .then(() => {+ console.log('Cleaning revisions successful for ' + filePath);+ return true;+ })+ .catch(err => {+ console.warn('Cleaning revisions failed ', err);+ });+ // Delete sidecar file and thumb+ deleteFilesPromise([+ getMetaFileLocationForFile(filePath, PlatformIO.getDirSeparator()),+ getThumbFileLocationForFile(+ filePath,+ PlatformIO.getDirSeparator(),+ false+ )+ ])+ .then(() => {+ console.log(+ 'Cleaning meta file and thumb successful for ' + filePath+ );+ return true;+ })+ .catch(err => {+ console.warn('Cleaning meta file and thumb failed with ' + err);+ });+ return true;+ })+ .catch(error => {+ console.warn('Error while deleting file: ' + error);+ showNotification(+ `Error while deleting file ${filePath}`,+ 'error',+ true+ );+ return false;+ });+ }+const context = useMemo(() => {return {renameDirectory,createDirectory,- deleteDirectory+ deleteDirectory,+ renameFile,+ deleteFile};}, [openedEntries]);diff --git a/app/reducers/io-actions.ts b/app/hooks/IOActionsContextProvider.tsxsimilarity index 77%rename from app/reducers/io-actions.tsrename to app/hooks/IOActionsContextProvider.tsxindex 7d951df29..191aa0b32 100644--- a/app/reducers/io-actions.ts+++ b/app/hooks/IOActionsContextProvider.tsx@@ -1,6 +1,6 @@/*** TagSpaces - universal file and folder organizer- * Copyright (C) 2017-present TagSpaces UG (haftungsbeschraenkt)+ * Copyright (C) 2023-present TagSpaces UG (haftungsbeschraenkt)** 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@@ -16,68 +16,153 @@**/-import { Progress } from 'aws-sdk/clients/s3';-import {- enhanceEntry,- loadJSONString-} from '@tagspaces/tagspaces-common/utils-io';+import React, { createContext, useMemo } from 'react';+import { Pro } from '-/pro';+import { useTranslation } from 'react-i18next';+import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';+import { useNotificationContext } from '-/hooks/useNotificationContext';import {+ extractDirectoryName,extractFileName,- getMetaFileLocationForFile,- getThumbFileLocationForFile,getBackupFileDir,- normalizePath,getMetaDirectoryPath,- extractDirectoryName,- joinPaths+ getMetaFileLocationForFile,+ getThumbFileLocationForFile,+ joinPaths,+ normalizePath} from '@tagspaces/tagspaces-common/paths';-import AppConfig from '-/AppConfig';-import { actions as AppActions } from './app';+import PlatformIO from '-/services/platform-facade';+import { actions as AppActions, AppDispatch } from '-/reducers/app';+import { useDispatch } from 'react-redux';import {copyFilesPromise,getThumbPath,loadFileMetaDataPromise,- renameFilesPromise+ renameFilesPromise,+ toFsEntry} from '-/services/utils-io';-import i18n from '../services/i18n';-import { Pro } from '../pro';-import PlatformIO from '-/services/platform-facade';import { TS } from '-/tagspaces.namespace';+import { Progress } from 'aws-sdk/clients/s3';+import AppConfig from '-/AppConfig';import { generateThumbnailPromise } from '-/services/thumbsgenerator';import { base64ToArrayBuffer } from '-/utils/dom';+import {+ enhanceEntry,+ loadJSONString+} from '@tagspaces/tagspaces-common/utils-io';+import { useLocationIndexContext } from '-/hooks/useLocationIndexContext';+import { loadCurrentDirMeta } from '-/services/meta-loader';++type extractOptions = {+ EXIFGeo?: boolean;+ EXIFDateTime?: boolean;+ IPTCDescription?: boolean;+ IPTCTags?: boolean;+};+type IOActionsContextData = {+ extractContent: (options?: extractOptions, addTags?) => Promise<boolean>;+ moveDirs: (+ dirPaths: Array<string>,+ targetPath: string,+ onProgress?+ ) => Promise<boolean>;+ moveFiles: (+ paths: Array<string>,+ targetPath: string,+ onProgress?+ ) => Promise<boolean>;+ copyDirs: (+ dirPaths: Array<any>,+ targetPath: string,+ onProgress?+ ) => Promise<boolean>;+ copyFiles: (+ paths: Array<string>,+ targetPath: string,+ onProgress?+ ) => Promise<boolean>;+ downloadFile: (+ url: string,+ targetPath: string,+ onDownloadProgress?: (progress: Progress, abort, fileName?) => void+ ) => Promise<TS.FileSystemEntry>;+ uploadFilesAPI: (+ files: Array<File>,+ targetPath: string,+ onUploadProgress?: (progress: Progress, abort, fileName?) => void,+ uploadMeta?: boolean+ ) => Promise<TS.FileSystemEntry[]>;+ uploadFiles: (+ paths: Array<string>,+ targetPath: string,+ onUploadProgress?: (progress: Progress, abort, fileName?) => void,+ uploadMeta?: boolean+ ) => Promise<TS.FileSystemEntry[]>;+ reloadDirectory: (dirPath?: string) => Promise<boolean>;+};++export const IOActionsContext = createContext<IOActionsContextData>({+ extractContent: () => Promise.resolve(false),+ moveDirs: () => Promise.resolve(false),+ moveFiles: () => Promise.resolve(false),+ copyDirs: () => Promise.resolve(false),+ copyFiles: () => Promise.resolve(false),+ downloadFile: () => Promise.resolve(undefined),+ uploadFilesAPI: () => Promise.resolve([]),+ uploadFiles: () => Promise.resolve([]),+ reloadDirectory: () => Promise.resolve(false)+});++export type IOActionsContextProviderProps = {+ children: React.ReactNode;+};++export const IOActionsContextProvider = ({+ children+}: IOActionsContextProviderProps) => {+ const { t } = useTranslation();+ const dispatch: AppDispatch = useDispatch();+ const { showNotification, hideNotifications } = useNotificationContext();+ const {+ currentDirectoryEntries,+ currentDirectoryPath,+ openDirectory+ } = useDirectoryContentContext();+ const {+ reflectDeleteEntry,+ reflectCreateEntry,+ reflectDeleteEntries+ } = useLocationIndexContext();-const actions = {- extractContent: (- options: Object = {+ function extractContent(+ options: extractOptions = {EXIFGeo: true,EXIFDateTime: true,IPTCDescription: true,IPTCTags: true},addTags?- ) => (dispatch: (actions: any) => void, getState: () => any) => {- const { currentDirectoryEntries } = getState().app;+ ): Promise<boolean> {if (!Pro || !Pro.ContentExtractor) {- dispatch(- AppActions.showNotification(- i18n.t('core:thisFunctionalityIsAvailableInPro')- )- );- return false;+ showNotification(t('core:thisFunctionalityIsAvailableInPro'));+ return Promise.resolve(false);}+ showNotification('Extracting content...', 'info', false);Pro.ContentExtractor.extractContent(currentDirectoryEntries,- dispatch,- AppActions,addTags,options- );- },- moveDirs: (+ ).then(success => {+ hideNotifications();+ return success;+ });+ }++ function moveDirs(dirPaths: Array<any>,targetPath: string,onProgress = undefined- ) => (dispatch: (actions: Object) => void) => {+ ): Promise<boolean> {const promises = dirPaths.map(({ path, count }) => {const dirName = extractDirectoryName(path, PlatformIO.getDirSeparator());return PlatformIO.moveDirectoryPromise(@@ -87,23 +172,23 @@ const actions = {).then(() => {console.log('Moving dir from ' + path + ' to ' + targetPath);+ reflectDeleteEntry(path);dispatch(AppActions.reflectDeleteEntry(path));return true;}).catch(err => {console.warn('Moving dirs failed ', err);- dispatch(- AppActions.showNotification(i18n.t('core:copyingFoldersFailed'))- );+ showNotification(t('core:copyingFoldersFailed'));});});return Promise.all(promises).then(() => true);- },- moveFiles: (+ }++ function moveFiles(paths: Array<string>,targetPath: string,onProgress = undefined- ) => (dispatch: (actions: Object) => Promise<boolean>) => {+ ): Promise<boolean> {const moveJobs = paths.map(path => [path,normalizePath(targetPath) +@@ -112,10 +197,9 @@ const actions = {]);return renameFilesPromise(moveJobs, onProgress).then(() => {- dispatch(- AppActions.showNotification(i18n.t('core:filesMovedSuccessful'))- );+ showNotification(t('core:filesMovedSuccessful'));// moved files should be added to the index, if the target dir in index+ reflectDeleteEntries(paths);dispatch(AppActions.reflectDeleteEntries(paths));const moveMetaJobs = [];@@ -187,17 +271,16 @@ const actions = {}).catch(err => {console.warn('Moving files failed with ' + err);- dispatch(- AppActions.showNotification(i18n.t('core:copyingFilesFailed'))- );+ showNotification(t('core:copyingFilesFailed'));return false;});- },- copyDirs: (+ }++ function copyDirs(dirPaths: Array<any>,targetPath: string,onProgress = undefined- ) => (dispatch: (actions: Object) => void) => {+ ): Promise<boolean> {const promises = dirPaths.map(({ path, count }) => {const dirName = extractDirectoryName(path, PlatformIO.getDirSeparator());return PlatformIO.copyDirectoryPromise(@@ -211,76 +294,58 @@ const actions = {}).catch(err => {console.warn('Copy dirs failed ', err);- dispatch(- AppActions.showNotification(i18n.t('core:copyingFoldersFailed'))- );+ showNotification(t('core:copyingFoldersFailed'));});});return Promise.all(promises).then(() => true);- },- copyFiles: (paths: Array<string>, targetPath: string, onProgress) => (- dispatch: (actions: Object) => void- ) => {- copyFilesPromise(paths, targetPath, onProgress)+ }++ function copyFiles(+ paths: Array<string>,+ targetPath: string,+ onProgress+ ): Promise<boolean> {+ return copyFilesPromise(paths, targetPath, onProgress).then(() => {// todo return only copied paths- dispatch(- AppActions.showNotification(i18n.t('core:filesCopiedSuccessful'))- );+ showNotification(t('core:filesCopiedSuccessful'));const metaPaths = paths.flatMap(path => [getMetaFileLocationForFile(path, PlatformIO.getDirSeparator()),getThumbFileLocationForFile(path, PlatformIO.getDirSeparator(), false)]);- /*const targetFiles: string[] = paths.map(- path =>- normalizePath(targetPath) +- PlatformIO.getDirSeparator() +- extractFileName(path, PlatformIO.getDirSeparator())- );*/-- copyFilesPromise(+ return copyFilesPromise(metaPaths,getMetaDirectoryPath(targetPath),onProgress).then(() => {console.log('Copy meta and thumbs successful');- /*dispatch(- AppActions.reflectCreateEntries(- targetFiles.map(filePath => toFsEntry(filePath, true))- )- );*/return true;}).catch(err => {- /*dispatch(- AppActions.reflectCreateEntries(- targetFiles.map(filePath => toFsEntry(filePath, true))- )- );*/console.warn('At least one meta or thumb was not copied ' + err);+ return true;});- return true;}).catch(err => {console.warn('Moving files failed with ' + err);- dispatch(- AppActions.showNotification(i18n.t('core:copyingFilesFailed'))- );+ showNotification(t('core:copyingFilesFailed'));+ return false;});- },+ }+/*** S3 TODO work for test files only* @param url* @param targetPath* @param onDownloadProgress*/- downloadFile: (+ function downloadFile(url: string,targetPath: string,onDownloadProgress?: (progress: Progress, abort, fileName?) => void- ) => (dispatch: (actions: Object) => TS.FileSystemEntry) => {+ ): Promise<TS.FileSystemEntry> {function saveFile(response: Response): Promise<TS.FileSystemEntry> {if (AppConfig.isElectron && !PlatformIO.haveObjectStoreSupport()) {return PlatformIO.saveBinaryFilePromise(@@ -327,11 +392,13 @@ const actions = {});}).then((fsEntry: TS.FileSystemEntry) => {+ reflectCreateEntry(fsEntry);dispatch(AppActions.reflectCreateEntryObj(fsEntry));return fsEntry;});//.catch(e => console.log(e));- },+ }+/*** with HTML5 Files API* @param files@@ -340,20 +407,18 @@ const actions = {* @param uploadMeta - try to upload meta and thumbs if available* reader.onload not work for multiple files https://stackoverflow.com/questions/56178918/react-upload-multiple-files-using-window-filereader*/- uploadFilesAPI: (+ function uploadFilesAPI(files: Array<File>,targetPath: string,onUploadProgress?: (progress: Progress, abort, fileName?) => void,uploadMeta = true- ) => (dispatch: (actions: Object) => Promise<Array<TS.FileSystemEntry>>) => {+ ): Promise<TS.FileSystemEntry[]> {if (AppConfig.isElectron || AppConfig.isCordovaiOS) {const arrFiles = [];for (let i = 0; i < files.length; i += 1) {arrFiles.push(files[i].path);}- return dispatch(- actions.uploadFiles(arrFiles, targetPath, onUploadProgress, uploadMeta)- );+ return uploadFiles(arrFiles, targetPath, onUploadProgress, uploadMeta);}return new Promise(async resolve => {@@ -394,12 +459,10 @@ const actions = {fileTargetPath);if (entryProps) {- dispatch(- AppActions.showNotification(- 'File with the same name already exist, importing skipped!',- 'warning',- true- )+ showNotification(+ 'File with the same name already exist, importing skipped!',+ 'warning',+ true);} else {const result = event.currentTarget@@ -442,13 +505,10 @@ const actions = {fsEntry.thumbPath = PlatformIO.getURLforPath(thumbPath);}fsEntries.push(fsEntry);-- dispatch(- AppActions.showNotification(- 'File ' + fileTargetPath + ' successfully imported.',- 'default',- true- )+ showNotification(+ 'File ' + fileTargetPath + ' successfully imported.',+ 'default',+ true);// dispatch(AppActions.reflectCreateEntry(fileTargetPath, true));}@@ -456,12 +516,10 @@ const actions = {console.error('Uploading ' + fileTargetPath + ' failed with ' + error);- dispatch(- AppActions.showNotification(- 'Importing file ' + fileTargetPath + ' failed.',- 'error',- true- )+ showNotification(+ 'Importing file ' + fileTargetPath + ' failed.',+ 'error',+ true);}}@@ -475,7 +533,7 @@ const actions = {}}});- },+ }/*** use with Electron only!@@ -484,13 +542,13 @@ const actions = {* @param onUploadProgress* @param uploadMeta*/- uploadFiles: (+ function uploadFiles(paths: Array<string>,targetPath: string,onUploadProgress?: (progress: Progress, response: any) => void,uploadMeta = true- ) => (dispatch: (actions: Object) => void) =>- new Promise((resolve, reject) => {+ ): Promise<TS.FileSystemEntry[]> {+ return new Promise((resolve, reject) => {function uploadFile(filePath: string,fileType: string,@@ -499,12 +557,10 @@ const actions = {return PlatformIO.getPropertiesPromise(filePath).then(entryProps => {if (entryProps) {- dispatch(- AppActions.showNotification(- 'File with the same name already exist, importing skipped!',- 'warning',- true- )+ showNotification(+ 'File with the same name already exist, importing skipped!',+ 'warning',+ true);dispatch(AppActions.setProgress(filePath, -1, undefined));} else {@@ -533,12 +589,10 @@ const actions = {}).catch(err => {console.error('Importing file ' + filePath + ' failed ', err);- dispatch(- AppActions.showNotification(- 'Importing file ' + filePath + ' failed.',- 'error',- true- )+ showNotification(+ 'Importing file ' + filePath + ' failed.',+ 'error',+ true);return undefined;});@@ -631,15 +685,13 @@ const actions = {});if (arrFiles.length > 0) {const numberOfFile = arrFiles.length;- dispatch(- AppActions.showNotification(- numberOfFile + ' ' + 'file(s) successfully imported.',- // 'Files: ' +- // arrFiles.map(file => file.name).toString() +- // ' successfully imported.',- 'default',- true- )+ showNotification(+ numberOfFile + ' ' + 'file(s) successfully imported.',+ // 'Files: ' ++ // arrFiles.map(file => file.name).toString() ++ // ' successfully imported.',+ 'default',+ true);// Enhance entries@@ -699,7 +751,30 @@ const actions = {console.log('Error import fs: ' + err);reject(err);});- })-};+ });+ }-export default actions;+ function reloadDirectory(directoryPath?: string) {+ return openDirectory(directoryPath ? directoryPath : currentDirectoryPath);+ }++ const context = useMemo(() => {+ return {+ extractContent,+ moveDirs,+ moveFiles,+ copyDirs,+ copyFiles,+ downloadFile,+ uploadFilesAPI,+ uploadFiles,+ reloadDirectory+ };+ }, [currentDirectoryEntries]);++ return (+ <IOActionsContext.Provider value={context}>+ {children}+ </IOActionsContext.Provider>+ );+};diff --git a/app/hooks/LocationIndexContextProvider.tsx b/app/hooks/LocationIndexContextProvider.tsxnew file mode 100644index 000000000..5ad2ff52b--- /dev/null+++ b/app/hooks/LocationIndexContextProvider.tsx@@ -0,0 +1,666 @@+/**+ * TagSpaces - universal file and folder organizer+ * Copyright (C) 2023-present TagSpaces UG (haftungsbeschraenkt)+ *+ * 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/>.+ *+ */++import React, { createContext, useEffect, useMemo, useRef } from 'react';+import { useDispatch, useSelector } from 'react-redux';+import { actions as AppActions, AppDispatch } from '-/reducers/app';+import { useTranslation } from 'react-i18next';+import { TS } from '-/tagspaces.namespace';+import { createDirectoryIndex, toFsEntry } from '-/services/utils-io';+import { getEnableWS } from '-/reducers/settings';+import { locationType } from '@tagspaces/tagspaces-common/misc';+import PlatformIO from '-/services/platform-facade';+import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';+import { getLocations } from '-/reducers/locations';+import AppConfig from '-/AppConfig';+import { hasIndex, loadIndex } from '@tagspaces/tagspaces-platforms/indexer';+import Search from '-/services/search';+import {+ extractFileExtension,+ extractFileName,+ extractTagsAsObjects,+ getThumbFileLocationForFile+} from '@tagspaces/tagspaces-common/paths';+import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';+import { useNotificationContext } from '-/hooks/useNotificationContext';+import { Pro } from '-/pro';+import { PerspectiveIDs } from '-/perspectives';++type LocationIndexContextData = {+ index: TS.FileSystemEntry[];+ indexLoadedOn: number;+ isIndexing: boolean;+ getIndex: () => TS.FileSystemEntry[];+ cancelDirectoryIndexing: () => void;+ createLocationIndex: (location: TS.Location) => Promise<boolean>;+ createLocationsIndexes: (extractText?: boolean) => Promise<boolean>;+ clearDirectoryIndex: () => void;+ searchLocationIndex: (searchQuery: TS.SearchQuery) => void;+ searchAllLocations: (searchQuery: TS.SearchQuery) => void;+ setIndex: (i: TS.FileSystemEntry[]) => void;+ reflectDeleteEntry: (path: string) => void;+ reflectDeleteEntries: (paths: string[]) => void;+ reflectCreateEntry: (newEntry: TS.FileSystemEntry) => void;+ reflectRenameEntry: (path: string, newPath: string) => void;+ indexUpdateSidecarTags: (path: string, tags: Array<TS.Tag>) => void;+ reflectUpdateSidecarMeta: (path: string, entryMeta: Object) => void;+ watchForChanges: () => void;+};++export const LocationIndexContext = createContext<LocationIndexContextData>({+ index: [],+ indexLoadedOn: undefined,+ isIndexing: false,+ getIndex: undefined,+ cancelDirectoryIndexing: () => {},+ createLocationIndex: () => Promise.resolve(false),+ createLocationsIndexes: () => Promise.resolve(false),+ clearDirectoryIndex: () => {},+ searchLocationIndex: () => {},+ searchAllLocations: () => {},+ setIndex: () => {},+ reflectDeleteEntry: () => {},+ reflectDeleteEntries: () => {},+ reflectCreateEntry: () => {},+ reflectRenameEntry: () => {},+ indexUpdateSidecarTags: () => {},+ reflectUpdateSidecarMeta: () => {},+ watchForChanges: () => {}+});++export type LocationIndexContextProviderProps = {+ children: React.ReactNode;+};++export const LocationIndexContextProvider = ({+ children+}: LocationIndexContextProviderProps) => {+ const { t } = useTranslation();+ const dispatch: AppDispatch = useDispatch();++ const { currentLocation } = useCurrentLocationContext();+ const {+ setSearchResults,+ appendSearchResults,+ loadDirectoryContent,+ currentDirectoryPerspective+ } = useDirectoryContentContext();+ const { showNotification, hideNotifications } = useNotificationContext();++ const enableWS = useSelector(getEnableWS);+ const allLocations = useSelector(getLocations);++ const isIndexing = useRef<boolean>(false);+ const lastError = useRef(undefined);+ const index = useRef<TS.FileSystemEntry[]>(undefined);+ const indexLoadedOn = useRef<number>(undefined);++ useEffect(() => {+ clearDirectoryIndex();+ if (currentLocation) {+ watchForChanges();+ } else {+ if (Pro && Pro.Watcher) {+ Pro.Watcher.stopWatching();+ }+ }+ }, [currentLocation]);++ function setIndex(i) {+ index.current = i;+ if (index.current && index.current.length > 0) {+ indexLoadedOn.current = new Date().getTime();+ } else {+ indexLoadedOn.current = undefined;+ }+ }++ function getIndex() {+ return index.current;+ }++ function watchForChanges() {+ if (+ Pro &&+ Pro.Watcher &&+ currentLocation &&+ currentLocation.watchForChanges &&+ currentLocation.type !== locationType.TYPE_CLOUD+ ) {+ function deleteEntry(path: string) {+ reflectDeleteEntry(path);+ dispatch(AppActions.reflectDeleteEntry(path));+ }+ function createEntry(path: string, isFile: boolean) {+ reflectCreateEntry(toFsEntry(path, isFile));+ dispatch(AppActions.reflectCreateEntry(path, isFile));+ }+ const depth =+ currentDirectoryPerspective === PerspectiveIDs.KANBAN ? 3 : 1;+ Pro.Watcher.watchFolder(+ PlatformIO.getLocationPath(currentLocation),+ deleteEntry,+ createEntry,+ loadDirectoryContent,+ depth+ );+ }+ }++ function reflectDeleteEntry(path: string) {+ if (!index.current || index.current.length < 1) {+ return;+ }+ for (let i = 0; i < index.current.length; i += 1) {+ if (index.current[i].path === path) {+ index.current = index.current.splice(i, 1);+ i -= 1;+ }+ }+ }++ function reflectDeleteEntries(paths: string[]) {+ if (!index.current || index.current.length < 1) {+ return;+ }+ for (let i = 0; i < index.current.length; i += 1) {+ if (paths.some(path => index.current[i].path === path)) {+ index.current = index.current.splice(i, 1);+ i -= 1;+ }+ }+ }++ function reflectCreateEntry(newEntry: TS.FileSystemEntry) {+ if (!index.current || index.current.length < 1) {+ return;+ }+ let entryFound = index.current.some(entry => entry.path === newEntry.path);+ if (!entryFound) {+ index.current = [...index.current, newEntry];+ }+ // else todo update index entry ?+ }++ function reflectRenameEntry(path: string, newPath: string) {+ if (!index.current || index.current.length < 1) {+ return;+ }+ for (let i = 0; i < index.current.length; i += 1) {+ if (index.current[i].path === path) {+ index.current[i].path = newPath;+ index.current[i].name = extractFileName(+ newPath,+ PlatformIO.getDirSeparator()+ );+ index.current[i].extension = extractFileExtension(+ newPath,+ PlatformIO.getDirSeparator()+ );+ index.current[i].tags = [+ ...index.current[i].tags.filter(tag => tag.type === 'sidecar'), // add only sidecar tags+ ...extractTagsAsObjects(+ newPath,+ AppConfig.tagDelimiter,+ PlatformIO.getDirSeparator()+ )+ ];+ }+ }+ }++ function indexUpdateSidecarTags(path: string, tags: Array<TS.Tag>) {+ if (!index.current || index.current.length < 1) {+ return;+ }+ for (let i = 0; i < index.current.length; i += 1) {+ if (index.current[i].path === path) {+ index.current[i].tags = [+ ...index.current[i].tags.filter(tag => tag.type === 'plain'),+ ...tags+ ];+ }+ }+ }++ function reflectUpdateSidecarMeta(path: string, entryMeta: Object) {+ if (!index.current || index.current.length < 1) {+ return;+ }+ for (let i = 0; i < index.current.length; i += 1) {+ if (index.current[i].path === path) {+ index.current[i] = {+ ...index.current[i],+ ...entryMeta+ };+ }+ }+ }++ function cancelDirectoryIndexing() {+ window.walkCanceled = true;+ isIndexing.current = false;+ }++ function createDirIndex(+ directoryPath: string,+ extractText: boolean,+ isCurrentLocation = true,+ locationID: string = undefined,+ ignorePatterns: Array<string> = []+ ): Promise<boolean> {+ isIndexing.current = true;+ return createDirectoryIndex(+ { path: directoryPath, locationID },+ extractText,+ ignorePatterns,+ enableWS+ )+ .then(directoryIndex => {+ if (isCurrentLocation) {+ // Load index only if current location+ setIndex(directoryIndex);+ }+ isIndexing.current = false;+ /* if (Pro && Pro.Indexer) {+ Pro.Indexer.persistIndex(+ directoryPath,+ directoryIndex,+ PlatformIO.getDirSeparator()+ );+ } */+ return true;+ })+ .catch(err => {+ isIndexing.current = false;+ lastError.current = err;+ return false;+ });+ }++ function createLocationIndex(location: TS.Location): Promise<boolean> {+ if (location) {+ const isCurrentLocation =+ currentLocation && currentLocation.uuid === location.uuid;+ if (location.type === locationType.TYPE_CLOUD) {+ return PlatformIO.enableObjectStoreSupport(location)+ .then(() =>+ createDirIndex(+ PlatformIO.getLocationPath(location),+ location.fullTextIndex,+ isCurrentLocation,+ location.uuid+ )+ )+ .catch(() => {+ PlatformIO.disableObjectStoreSupport();+ return false;+ });+ } else if (location.type === locationType.TYPE_WEBDAV) {+ PlatformIO.enableWebdavSupport(location);+ return createDirIndex(+ PlatformIO.getLocationPath(location),+ location.fullTextIndex,+ isCurrentLocation,+ location.uuid+ );+ } else if (location.type === locationType.TYPE_LOCAL) {+ PlatformIO.disableObjectStoreSupport();+ return createDirIndex(+ PlatformIO.getLocationPath(location),+ location.fullTextIndex,+ isCurrentLocation,+ location.uuid+ );+ }+ }+ return Promise.resolve(false);+ }++ function createLocationsIndexes(extractText = true): Promise<boolean> {+ isIndexing.current = true;+ const promises = allLocations.map((location: TS.Location) => {+ const nextPath = PlatformIO.getLocationPath(location);+ return (+ createDirectoryIndex(+ { path: nextPath, location: location.uuid },+ extractText,+ location.ignorePatternPaths,+ enableWS+ )+ /* .then(directoryIndex => {+ if (Pro && Pro.Indexer) {+ Pro.Indexer.persistIndex(+ nextPath,+ directoryIndex,+ PlatformIO.getDirSeparator()+ );+ }+ return true;+ }) */+ .catch(err => {+ isIndexing.current = false;+ lastError.current = err;+ })+ );+ });++ return Promise.all(promises)+ .then(e => {+ isIndexing.current = false;+ console.log('Resolution is complete!', e);+ return true;+ })+ .catch(e => {+ console.warn('Resolution is failed!', e);+ return false;+ });+ }++ function clearDirectoryIndex() {+ isIndexing.current = false;+ setIndex([]);+ }++ function searchLocationIndex(searchQuery: TS.SearchQuery) {+ window.walkCanceled = false;+ /*if (!currentLocation) {+ if (searchQuery.currentDirectory) {+ currentLocation = getLocationByPath(+ state,+ searchQuery.currentDirectory+ );+ }+ }*/+ if (!currentLocation) {+ showNotification(t('core:pleaseOpenLocation'), 'warning', true);+ return;+ }++ const isCloudLocation = currentLocation.type === locationType.TYPE_CLOUD;+ showNotification(t('core:searching'), 'default', false, 'TIDSearching');+ setTimeout(async () => {+ const index = getIndex();+ // Workaround used to show the start search notification+ const currentTime = new Date().getTime();+ const indexAge = indexLoadedOn.current+ ? currentTime - indexLoadedOn.current+ : 0;+ const maxIndexAge = currentLocation.maxIndexAge+ ? currentLocation.maxIndexAge+ : AppConfig.maxIndexAge;+ if (+ searchQuery.forceIndexing ||+ (!currentLocation.disableIndexing &&+ (!index || index.length < 1 || indexAge > maxIndexAge))+ ) {+ const currentPath = PlatformIO.getLocationPath(currentLocation);+ console.log('Start creating index for : ' + currentPath);+ const newIndex = await createDirectoryIndex(+ {+ path: currentPath,+ locationID: currentLocation.uuid,+ ...(isCloudLocation && { bucketName: currentLocation.bucketName })+ },+ currentLocation.fullTextIndex,+ currentLocation.ignorePatternPaths,+ enableWS+ );+ setIndex(newIndex);+ } else if (isCloudLocation || !index || index.length === 0) {+ const newIndex = await loadIndex(+ {+ path: PlatformIO.getLocationPath(currentLocation),+ locationID: currentLocation.uuid,+ ...(isCloudLocation && { bucketName: currentLocation.bucketName })+ },+ PlatformIO.getDirSeparator(),+ PlatformIO.loadTextFilePromise+ );+ setIndex(newIndex);+ }+ Search.searchLocationIndex(getIndex(), searchQuery)+ .then(searchResults => {+ if (isCloudLocation) {+ searchResults.forEach((entry: TS.FileSystemEntry) => {+ if (+ entry.thumbPath &&+ entry.thumbPath.length > 1+ // !entry.thumbPath.startsWith('http')+ ) {+ const thumbPath = entry.path.startsWith('/')+ ? entry.path.substring(1)+ : entry.path;+ // eslint-disable-next-line no-param-reassign+ entry.thumbPath = PlatformIO.getURLforPath(+ getThumbFileLocationForFile(+ thumbPath,+ PlatformIO.getDirSeparator()+ )+ );+ }+ });+ }+ setSearchResults(searchResults);+ hideNotifications();+ return true;+ })+ .catch(err => {+ setSearchResults([]);+ // dispatch(AppActions.hideNotifications());+ console.error('Searching Index failed: ', err);+ showNotification(+ t('core:searchingFailed') + ' ' + err.message,+ 'warning',+ true+ );+ });+ }, 50);+ }++ function searchAllLocations(searchQuery: TS.SearchQuery) {+ console.time('globalSearch');+ showNotification(t('core:searching'), 'default', false, 'TIDSearching');++ // Preparing for global search+ // setSearchResults([]);+ if (currentLocation && currentLocation.type === locationType.TYPE_CLOUD) {+ PlatformIO.disableObjectStoreSupport();+ }+ window.walkCanceled = false;+ let searchResultCount = 0;+ let maxSearchResultReached = false;++ const result = allLocations.reduce(+ (accumulatorPromise, location) =>+ accumulatorPromise.then(async () => {+ // cancel search if max search result count reached+ if (searchResultCount >= searchQuery.maxSearchResults) {+ maxSearchResultReached = true;+ return Promise.resolve();+ }+ const nextPath = PlatformIO.getLocationPath(location);+ let directoryIndex = [];+ let indexExist = false;+ const isCloudLocation = location.type === locationType.TYPE_CLOUD;+ console.log('Searching in: ' + nextPath);+ showNotification(+ t('core:searching') + ' ' + location.name,+ 'default',+ true,+ 'TIDSearching'+ );+ if (isCloudLocation) {+ await PlatformIO.enableObjectStoreSupport(location);+ }+ // if (Pro && Pro.Indexer && Pro.Indexer.hasIndex) {+ indexExist = await hasIndex(+ nextPath,+ PlatformIO.getPropertiesPromise+ ); // , PlatformIO.getDirSeparator());++ if (+ searchQuery.forceIndexing ||+ (!location.disableIndexing && !indexExist)+ ) {+ console.log('Creating index for : ' + nextPath);+ directoryIndex = await createDirectoryIndex(+ {+ path: nextPath,+ locationID: location.uuid,+ ...(isCloudLocation && { bucketName: location.bucketName })+ },+ location.fullTextIndex,+ location.ignorePatternPaths,+ enableWS+ );+ /* if (Pro && Pro.Indexer && Pro.Indexer.persistIndex) {+ Pro.Indexer.persistIndex(+ nextPath,+ directoryIndex,+ PlatformIO.getDirSeparator()+ );+ } */+ } else {+ // if (Pro && Pro.Indexer && Pro.Indexer.loadIndex) {+ console.log('Loading index for : ' + nextPath);+ directoryIndex = await loadIndex(+ {+ path: nextPath,+ locationID: location.uuid,+ ...(isCloudLocation && {+ bucketName: currentLocation.bucketName+ })+ },+ PlatformIO.getDirSeparator(),+ PlatformIO.loadTextFilePromise+ );+ }+ return Search.searchLocationIndex(directoryIndex, searchQuery)+ .then((searchResults: Array<TS.FileSystemEntry>) => {+ let enhancedSearchResult = searchResults;+ if (isCloudLocation) {+ enhancedSearchResult = searchResults+ // Excluding s3 folders from global search+ .filter(entry => entry && entry.isFile)+ .map((entry: TS.FileSystemEntry) => {+ const cleanedPath = entry.path.startsWith('/')+ ? entry.path.substr(1)+ : entry.path;+ const url = PlatformIO.getURLforPath(cleanedPath);+ let thumbPath;+ if (+ entry.thumbPath &&+ entry.thumbPath.length > 1 &&+ !entry.thumbPath.startsWith('http')+ ) {+ thumbPath = PlatformIO.getURLforPath(entry.thumbPath);+ }+ return { ...entry, url, thumbPath };+ });+ }++ searchResultCount += enhancedSearchResult.length;+ appendSearchResults(enhancedSearchResult);+ hideNotifications();+ if (isCloudLocation) {+ PlatformIO.disableObjectStoreSupport();+ }+ return true;+ })+ .catch(e => {+ if (isCloudLocation) {+ PlatformIO.disableObjectStoreSupport();+ }+ console.error('Searching Index failed: ', e);+ setSearchResults([]);+ // dispatch(AppActions.hideNotifications());+ showNotification(+ t('core:searchingFailed') + ' ' + e.message,+ 'warning',+ true+ );+ });+ }),+ Promise.resolve()+ );++ result+ .then(() => {+ console.timeEnd('globalSearch');+ if (maxSearchResultReached) {+ showNotification(+ 'Global search finished, reaching the max. search results. The first ' ++ searchResultCount ++ ' entries are listed.',+ 'default',+ true+ );+ } else {+ showNotification(t('Global search completed'), 'default', true);+ }+ console.log('Global search completed!');+ if (+ currentLocation &&+ currentLocation.type === locationType.TYPE_CLOUD+ ) {+ PlatformIO.enableObjectStoreSupport(currentLocation);+ }+ return true;+ })+ .catch(e => {+ if (+ currentLocation &&+ currentLocation.type === locationType.TYPE_CLOUD+ ) {+ PlatformIO.enableObjectStoreSupport(currentLocation);+ }+ console.timeEnd('globalSearch');+ console.warn('Global search failed!', e);+ });+ }++ const context = useMemo(() => {+ return {+ index: index.current,+ indexLoadedOn: indexLoadedOn.current,+ isIndexing: isIndexing.current,+ watchForChanges,+ cancelDirectoryIndexing,+ createLocationIndex,+ createLocationsIndexes,+ clearDirectoryIndex,+ searchLocationIndex,+ searchAllLocations,+ setIndex,+ getIndex,+ reflectDeleteEntry,+ reflectDeleteEntries,+ reflectCreateEntry,+ reflectRenameEntry,+ indexUpdateSidecarTags,+ reflectUpdateSidecarMeta+ };+ }, [currentLocation, index, isIndexing.current]);++ return (+ <LocationIndexContext.Provider value={context}>+ {children}+ </LocationIndexContext.Provider>+ );+};diff --git a/app/hooks/NotificationContextProvider.tsx b/app/hooks/NotificationContextProvider.tsxnew file mode 100644index 000000000..94a3614ff--- /dev/null+++ b/app/hooks/NotificationContextProvider.tsx@@ -0,0 +1,114 @@+/**+ * TagSpaces - universal file and folder organizer+ * Copyright (C) 2023-present TagSpaces UG (haftungsbeschraenkt)+ *+ * 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/>.+ *+ */++import React, { createContext, useMemo, useState } from 'react';++type NotificationStatus = {+ visible: boolean;+ text: string;+ tid: string;+ notificationType: 'default' | 'info' | 'warning' | 'error';+ autohide: boolean;+};++type NotificationContextData = {+ notificationStatus: NotificationStatus;+ showNotification: (+ text: string,+ notificationType?: 'default' | 'info' | 'warning' | 'error',+ autohide?: boolean,+ tid?: string+ ) => void;+ hideNotifications: (excludeTypes?: string[]) => void;+ isGeneratingThumbs: boolean;+ setGeneratingThumbs: (isGen: boolean) => void;+ //NotificationTypes: 'default' | 'error';+};++export const NotificationContext = createContext<NotificationContextData>({+ notificationStatus: undefined,+ showNotification: () => {},+ hideNotifications: () => {},+ isGeneratingThumbs: false,+ setGeneratingThumbs: () => {}+ //NotificationTypes: 'default'+});++export type NotificationContextProviderProps = {+ children: React.ReactNode;+};++export const NotificationContextProvider = ({+ children+}: NotificationContextProviderProps) => {+ const [notificationStatus, setNotificationStatus] = useState<any>({+ visible: false,+ text: null,+ notificationType: 'default',+ autohide: true+ });+ const [isGeneratingThumbs, setGeneratingThumbs] = useState<boolean>(false);++ function showNotification(+ text: string,+ notificationType = 'default',+ autohide = true,+ tid = 'notificationTID'+ ) {+ setNotificationStatus({+ visible: true,+ text,+ tid,+ notificationType,+ autohide+ });+ }++ function hideNotifications(excludeTypes = []) {+ if (+ !excludeTypes.some(type => type === notificationStatus.notificationType)+ ) {+ setNotificationStatus({+ visible: false,+ text: null,+ notificationType: 'default',+ autohide: true+ });+ }+ }++ const context = useMemo(() => {+ return {+ notificationStatus,+ /*NotificationTypes: {+ default: 'default',+ error: 'error'+ },*/+ isGeneratingThumbs,+ setGeneratingThumbs,+ showNotification,+ hideNotifications+ };+ }, [notificationStatus, isGeneratingThumbs]);++ return (+ <NotificationContext.Provider value={context}>+ {children}+ </NotificationContext.Provider>+ );+};diff --git a/app/hooks/OpenedEntryContextProvider.tsx b/app/hooks/OpenedEntryContextProvider.tsxindex 5258c6639..31ee51fe1 100644--- a/app/hooks/OpenedEntryContextProvider.tsx+++ b/app/hooks/OpenedEntryContextProvider.tsx@@ -27,18 +27,15 @@ import { useDispatch, useSelector } from 'react-redux';import {actions as AppActions,AppDispatch,- getDirectoryContent,- getDirectoryPath,getEditedEntryPaths,getLastSelectedEntry,- getOpenLink,- isSearchMode,OpenedEntry} from '-/reducers/app';import { Pro } from '-/pro';import { TS } from '-/tagspaces.namespace';import PlatformIO from '-/services/platform-facade';import {+ enhanceOpenedEntry,findExtensionsForEntry,getAllPropertiesPromise,getCleanLocationPath,@@ -46,14 +43,16 @@ import {getPrevFile,getRelativeEntryPath,loadJSONFile,- openURLExternally+ openedToFsEntry,+ openURLExternally,+ toFsEntry} from '-/services/utils-io';import {actions as SettingsActions,getNewHTMLFileContent,getSupportedFileTypes} from '-/reducers/settings';-import { getCurrentLocation, getLocations } from '-/reducers/locations';+import { getLocations } from '-/reducers/locations';import { clearURLParam, getURLParameter, updateHistory } from '-/utils/dom';import {cleanRootPath,@@ -64,7 +63,6 @@ import {getMetaFileLocationForFile,normalizePath} from '@tagspaces/tagspaces-common/paths';-import GlobalSearch from '-/services/search-index';import {formatDateTime4Tag,locationType@@ -73,6 +71,10 @@ import { useTranslation } from 'react-i18next';import versionMeta from '-/version.json';import AppConfig from '-/AppConfig';import useFirstRender from '-/utils/useFirstRender';+import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';+import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';+import { useNotificationContext } from '-/hooks/useNotificationContext';+import { useLocationIndexContext } from '-/hooks/useLocationIndexContext';type OpenedEntryContextData = {openedEntries: OpenedEntry[];@@ -137,15 +139,23 @@ export const OpenedEntryContextProvider = ({}: OpenedEntryContextProviderProps) => {const dispatch: AppDispatch = useDispatch();const { t } = useTranslation();++ const {+ currentDirectoryEntries,+ currentDirectoryPath,+ openDirectory,+ setCurrentDirectoryColor,+ setCurrentDirectoryPerspective,+ updateCurrentDirEntry+ } = useDirectoryContentContext();+ const { showNotification } = useNotificationContext();+ const { openLocation, currentLocation } = useCurrentLocationContext();+ const { reflectCreateEntry } = useLocationIndexContext();const supportedFileTypes = useSelector(getSupportedFileTypes);- const searchMode = useSelector(isSearchMode);- const currentDirectoryEntries = useSelector(getDirectoryContent);const lastSelectedEntry: TS.FileSystemEntry = useSelector(getLastSelectedEntry);const locations: TS.Location[] = useSelector(getLocations);- const currentLocation: TS.Location = useSelector(getCurrentLocation);- const currentDirectoryPath = useSelector(getDirectoryPath);const historyKeys = Pro && Pro.history ? Pro.history.historyKeys : {};const fileOpenHistory = useSelector((state: any) => state.settings[historyKeys.fileOpenKey]@@ -154,7 +164,7 @@ export const OpenedEntryContextProvider = ({(state: any) => state.settings[historyKeys.folderOpenKey]);const newHTMLFileContent = useSelector(getNewHTMLFileContent);- const initOpenLink = useSelector(getOpenLink);+ //const initOpenLink = useSelector(getOpenLink);const editedEntryPaths = useSelector(getEditedEntryPaths);/* const checkForUpdates = useSelector(getCheckForUpdateOnStartup);const firstRun = useSelector(isFirstRun);@@ -163,16 +173,68 @@ export const OpenedEntryContextProvider = ({const [isEntryInFullWidth, setEntryInFullWidth] = useState(false);const sharingLink = useRef<string>(undefined);const sharingParentFolderLink = useRef<string>(undefined);+ const havePrevOpenedFile = React.useRef<boolean>(false);const firstRender = useFirstRender();/*** Handle openLink from initApp*/useEffect(() => {- if (initOpenLink && initOpenLink.url) {+ if (firstRender && openedEntries.length === 0) {+ const lid = getURLParameter('tslid');+ const dPath = getURLParameter('tsdpath');+ const ePath = getURLParameter('tsepath');+ const cmdOpen = getURLParameter('cmdopen');+ if (lid || dPath || ePath) {+ // openDefaultLocation = false;+ setTimeout(() => {+ openLink(window.location.href);+ }, 1000);+ } else if (cmdOpen) {+ // openDefaultLocation = false;+ setTimeout(() => {+ openLink(+ // window.location.href.split('?')[0] ++ 'ts://?cmdopen=' + cmdOpen,+ { fullWidth: true }+ );+ }, 1000);+ }+ }+ /*if (initOpenLink && initOpenLink.url) {openLink(initOpenLink.url, initOpenLink.options);+ }*/+ }, []);++ useEffect(() => {+ if (+ !firstRender &&+ havePrevOpenedFile.current+ // && selectedEntries.length < 2+ ) {+ if (openedEntries.length > 0) {+ const openedFile = openedEntries[0];+ if (openedFile.path === currentDirectoryPath) {+ if (openedFile.color) {+ setCurrentDirectoryColor(openedFile.color);+ } else if (openedFile.color === undefined) {+ setCurrentDirectoryColor(undefined);+ }+ if (openedFile.perspective) {+ setCurrentDirectoryPerspective(openedFile.perspective);+ }+ } else {+ // update openedFile meta in grid perspective list (like description)+ const currentEntry: OpenedEntry = enhanceOpenedEntry(+ openedFile,+ AppConfig.tagDelimiter+ );+ updateCurrentDirEntry(openedFile.path, openedToFsEntry(currentEntry));+ }+ }}- }, [initOpenLink]);+ havePrevOpenedFile.current = openedEntries.length > 0;+ }, [openedEntries]);/*** HANDLE REFLECT_RENAME_ENTRY@@ -259,7 +321,14 @@ export const OpenedEntryContextProvider = ({if (params.has('tsepath')) {const entryPath = params.get('tsepath');if (openedFile.isFile) {- sharingLink.current = generateSharingLink(locationId, entryPath);+ const dirPath = params.has('tsdpath')+ ? params.get('tsdpath')+ : undefined;+ sharingLink.current = generateSharingLink(+ locationId,+ entryPath,+ dirPath+ );} else {sharingLink.current = generateSharingLink(locationId,@@ -267,6 +336,12 @@ export const OpenedEntryContextProvider = ({entryPath);}+ } else if (params.has('tsdpath')) {+ sharingLink.current = generateSharingLink(+ locationId,+ undefined,+ params.get('tsdpath')+ );} else {sharingLink.current = generateSharingLink(locationId);}@@ -495,9 +570,7 @@ export const OpenedEntryContextProvider = ({return;}if (!lastSelectedEntry.isFile) {- dispatch(- AppActions.loadDirectoryContent(lastSelectedEntry.path, false)- );+ openDirectory(lastSelectedEntry.path); //, false);return;}}@@ -517,12 +590,10 @@ export const OpenedEntryContextProvider = ({: undefined}; // false };addToEntryContainer(entryForOpening);- dispatch(- AppActions.showNotification(- `You can't open another file, because '${openFile.path}' is opened for editing`,- 'default',- true- )+ showNotification(+ `You can't open another file, because '${openFile.path}' is opened for editing`,+ 'default',+ true);return false;}@@ -619,9 +690,7 @@ export const OpenedEntryContextProvider = ({const nextFile = getNextFile(path,lastSelectedEntry ? lastSelectedEntry.path : undefined,- searchMode- ? GlobalSearch.getInstance().getResults()- : currentDirectoryEntries+ currentDirectoryEntries);if (nextFile !== undefined) {openFsEntry(nextFile);@@ -635,9 +704,7 @@ export const OpenedEntryContextProvider = ({const prevFile = getPrevFile(path,lastSelectedEntry ? lastSelectedEntry.path : undefined,- searchMode- ? GlobalSearch.getInstance().getResults()- : currentDirectoryEntries+ currentDirectoryEntries);if (prevFile !== undefined) {openFsEntry(prevFile);@@ -665,26 +732,22 @@ export const OpenedEntryContextProvider = ({openFsEntry(fsEntry);setEntryInFullWidth(options.fullWidth);} else {- dispatch(- AppActions.loadDirectoryContent(fsEntry.path, false, true)- );+ openDirectory(fsEntry.path);}return true;}).catch(err => {// console.log('Error opening from cmd ' + JSON.stringify(err));- dispatch(- AppActions.showNotification(- t('Missing file or folder'),- 'warning',- true- )- );+ showNotification(t('Missing file or folder'), 'warning', true);});} else if (lid && lid.length > 0) {const locationId = decodeURIComponent(lid);- const directoryPath = dPath && decodeURIComponent(dPath);+ let directoryPath = dPath && decodeURIComponent(dPath);const entryPath = ePath && decodeURIComponent(ePath);+ // fix for created bookmarks files without to have tsdpath in url+ if (!directoryPath) {+ directoryPath = extractContainingDirectoryPath(entryPath);+ }// Check for relative pathsconst targetLocation: TS.Location = locations.find(location => location.uuid === locationId@@ -693,14 +756,11 @@ export const OpenedEntryContextProvider = ({let openLocationTimer = 1000;const isCloudLocation =targetLocation.type === locationType.TYPE_CLOUD;- let skipListingLocation = directoryPath && directoryPath.length > 0;if (!currentLocation ||targetLocation.uuid !== currentLocation.uuid) {- dispatch(- AppActions.openLocation(targetLocation, skipListingLocation)- );+ openLocation(targetLocation, true);} else {openLocationTimer = 0;}@@ -719,13 +779,9 @@ export const OpenedEntryContextProvider = ({locationPath.length > 0? locationPath + '/' + newRelDir: directoryPath;- dispatch(- AppActions.loadDirectoryContent(dirFullPath, false, true)- );+ openDirectory(dirFullPath);} else {- dispatch(- AppActions.loadDirectoryContent(locationPath, false, true)- );+ openDirectory(locationPath);}if (entryPath) {@@ -740,13 +796,7 @@ export const OpenedEntryContextProvider = ({return true;}).catch(() =>- dispatch(- AppActions.showNotification(- t('core:invalidLink'),- 'warning',- true- )- )+ showNotification(t('core:invalidLink'), 'warning', true));}// });@@ -757,35 +807,19 @@ export const OpenedEntryContextProvider = ({directoryPath.includes('../') ||directoryPath.includes('..\\')) {- dispatch(- AppActions.showNotification(- t('core:invalidLink'),- 'warning',- true- )- );+ showNotification(t('core:invalidLink'), 'warning', true);return true;}const dirFullPath =locationPath + PlatformIO.getDirSeparator() + directoryPath;- dispatch(- AppActions.loadDirectoryContent(dirFullPath, false, true)- );+ openDirectory(dirFullPath);} else {- dispatch(- AppActions.loadDirectoryContent(locationPath, false, true)- );+ openDirectory(locationPath);}if (entryPath && entryPath.length > 0) {if (entryPath.includes('../') || entryPath.includes('..\\')) {- dispatch(- AppActions.showNotification(- t('core:invalidLink'),- 'warning',- true- )- );+ showNotification(t('core:invalidLink'), 'warning', true);return true;}const entryFullPath =@@ -801,21 +835,13 @@ export const OpenedEntryContextProvider = ({return true;}).catch(() =>- dispatch(- AppActions.showNotification(- t('core:invalidLink'),- 'warning',- true- )- )+ showNotification(t('core:invalidLink'), 'warning', true));}}}, openLocationTimer);} else {- dispatch(- AppActions.showNotification(t('core:invalidLink'), 'warning', true)- );+ showNotification(t('core:invalidLink'), 'warning', true);}} else if (decodedURI.endsWith(location.pathname)) {return true;@@ -846,31 +872,18 @@ export const OpenedEntryContextProvider = ({'.txt';PlatformIO.saveFilePromise({ path: filePath }, '', true).then(() => {+ reflectCreateEntry(toFsEntry(filePath, true));dispatch(AppActions.reflectCreateEntry(filePath, true));- dispatch(- AppActions.showNotification(- t('core:fileCreateSuccessfully'),- 'info',- true- )- );+ showNotification(t('core:fileCreateSuccessfully'), 'info', true);openEntry(filePath);return true;}).catch(err => {console.warn('File creation failed with ' + err);- dispatch(- AppActions.showNotification(- t('core:errorCreatingFile'),- 'warning',- true- )- );+ showNotification(t('core:errorCreatingFile'), 'warning', true);});} else {- dispatch(- AppActions.showNotification(t('core:firstOpenaFolder'), 'warning', true)- );+ showNotification(t('core:firstOpenaFolder'), 'warning', true);}}@@ -909,27 +922,20 @@ export const OpenedEntryContextProvider = ({}PlatformIO.saveFilePromise({ path: filePath }, fileContent, false).then((fsEntry: TS.FileSystemEntry) => {+ reflectCreateEntry(toFsEntry(filePath, true));dispatch(AppActions.reflectCreateEntry(filePath, true));openFsEntry(fsEntry);// dispatch(actions.setSelectedEntries([fsEntry]));- dispatch(- AppActions.showNotification(- `File '${fileNameAndExt}' created.`,- 'default',- true- )- );+ showNotification(`File '${fileNameAndExt}' created.`, 'default', true);return true;}).catch(error => {console.warn('Error creating file: ' + error);- dispatch(- AppActions.showNotification(- `Error creating file '${fileNameAndExt}'`,- 'error',- true- )+ showNotification(+ `Error creating file '${fileNameAndExt}'`,+ 'error',+ true);});}diff --git a/app/hooks/PaginationContextProvider.tsx b/app/hooks/PaginationContextProvider.tsxnew file mode 100644index 000000000..1e0e5b1eb--- /dev/null+++ b/app/hooks/PaginationContextProvider.tsx@@ -0,0 +1,112 @@+/**+ * TagSpaces - universal file and folder organizer+ * Copyright (C) 2023-present TagSpaces UG (haftungsbeschraenkt)+ *+ * 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/>.+ *+ */++import React, { createContext, useEffect, useMemo, useState } from 'react';+import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';+import { defaultSettings } from '-/perspectives/grid-perspective';+import { useSortedDirContext } from '-/perspectives/grid-perspective/hooks/useSortedDirContext';+import { TS } from '-/tagspaces.namespace';+import { loadCurrentDirMeta } from '-/services/meta-loader';++type PaginationContextData = {+ page: number;+ pageFiles: TS.FileSystemEntry[];+ setCurrentPage: (page: number) => Promise<boolean>;+};++export const PaginationContext = createContext<PaginationContextData>({+ page: 1,+ pageFiles: [],+ setCurrentPage: () => Promise.resolve(false)+});++export type PaginationContextProviderProps = {+ children: React.ReactNode;+};++export const PaginationContextProvider = ({+ children+}: PaginationContextProviderProps) => {+ const initPage = 1;+ const {+ currentDirectoryPath,+ currentDirectoryEntries,+ updateCurrentDirEntries+ } = useDirectoryContentContext();+ const { settings, sortedDirContent } = useSortedDirContext();++ const [page, setPage] = useState<number>(initPage);+ // const firstRender = useFirstRender();+ //const pageFiles = useRef<TS.FileSystemEntry[]>(getPageFiles(page));++ useEffect(() => {+ //pageFiles.current = getPageFiles(initPage);+ if (page !== initPage) {+ setPage(initPage);+ }+ /*if (isMetaFolderExist) {+ loadCurrentDirMeta(currentDirectoryPath, pageFiles).then(() =>+ console.debug('meta loaded')+ );+ }*/+ }, [currentDirectoryPath]); //, isMetaFolderExist]);++ const pageFiles: TS.FileSystemEntry[] = useMemo(() => {+ return getPageFiles(page, sortedDirContent);+ }, [page, sortedDirContent, settings]);++ function getPageFiles(currentPage: number, dirContent: TS.FileSystemEntry[]) {+ const gridPageLimit =+ settings && settings.gridPageLimit+ ? settings.gridPageLimit+ : defaultSettings.gridPageLimit;+ const files = dirContent.filter(entry => entry && entry.isFile);+ const showPagination = gridPageLimit && files.length > gridPageLimit;+ if (showPagination) {+ const start = (currentPage - 1) * gridPageLimit;+ return files.slice(start, start + gridPageLimit);+ }+ return files;+ }++ function setCurrentPage(currentPage: number) {+ setPage(currentPage);+ return loadCurrentDirMeta(+ currentDirectoryPath,+ currentDirectoryEntries,+ getPageFiles(currentPage, sortedDirContent)+ ).then(entries => {+ updateCurrentDirEntries(entries);+ return true;+ });+ }++ const context = useMemo(() => {+ return {+ page,+ pageFiles,+ setCurrentPage+ };+ }, [page, pageFiles, currentDirectoryPath]);++ return (+ <PaginationContext.Provider value={context}>+ {children}+ </PaginationContext.Provider>+ );+};diff --git a/app/hooks/TaggingActionsContextProvider.tsx b/app/hooks/TaggingActionsContextProvider.tsxindex 802618921..48f2a4114 100644--- a/app/hooks/TaggingActionsContextProvider.tsx+++ b/app/hooks/TaggingActionsContextProvider.tsx@@ -18,11 +18,7 @@import React, { createContext, useMemo } from 'react';import { useDispatch, useSelector } from 'react-redux';-import {- actions as AppActions,- AppDispatch,- isPersistTagsInSidecarFile-} from '-/reducers/app';+import { actions as AppActions, AppDispatch } from '-/reducers/app';import mgrs from 'mgrs';import { Pro } from '-/pro';import { useTranslation } from 'react-i18next';@@ -34,6 +30,7 @@ import { isGeoTag } from '-/utils/geo';import {getAddTagsToLibrary,getGeoTaggingFormat,+ getPersistTagsInSidecarFile,getPrefixTagContainer,getTagColor,getTagDelimiter,@@ -53,8 +50,12 @@ import {extractTags} from '@tagspaces/tagspaces-common/paths';import { useOpenedEntryContext } from '-/hooks/useOpenedEntryContext';-import GlobalSearch from '-/services/search-index';import { getLocations } from '-/reducers/locations';+import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';+import { useNotificationContext } from '-/hooks/useNotificationContext';+import { useFsActionsContext } from '-/hooks/useFsActionsContext';+import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';+import { useLocationIndexContext } from '-/hooks/useLocationIndexContext';type TaggingActionsContextData = {addTags: (@@ -93,14 +94,16 @@ export const TaggingActionsContextProvider = ({}: TaggingActionsContextProviderProps) => {const { t } = useTranslation();const { openedEntries, updateOpenedFile } = useOpenedEntryContext();+ const { updateCurrentDirEntry } = useDirectoryContentContext();+ const { persistTagsInSidecarFile } = useCurrentLocationContext();+ const { getIndex, indexUpdateSidecarTags } = useLocationIndexContext();+ const { renameFile } = useFsActionsContext();+ const { showNotification } = useNotificationContext();const dispatch: AppDispatch = useDispatch();const geoTaggingFormat = useSelector(getGeoTaggingFormat);const addTagsToLibrary = useSelector(getAddTagsToLibrary);const tagBackgroundColor: string = useSelector(getTagColor);const tagTextColor: string = useSelector(getTagTextColor);- const persistTagsInSidecarFile: boolean = useSelector(- isPersistTagsInSidecarFile- );const tagDelimiter: string = useSelector(getTagDelimiter);const prefixTagContainer: boolean = useSelector(getPrefixTagContainer);const locations: TS.Location[] = useSelector(getLocations);@@ -136,10 +139,8 @@ export const TaggingActionsContextProvider = ({tag.title = defaultTagLocation;dispatch(AppActions.toggleEditTagDialog(tag));} else {- dispatch(- AppActions.showNotification(- t('core:thisFunctionalityIsAvailableInPro' as any) as string- )+ showNotification(+ t('core:thisFunctionalityIsAvailableInPro' as any) as string);}} else if (tag.functionality === 'dateTagging') {@@ -149,10 +150,8 @@ export const TaggingActionsContextProvider = ({tag.title = formatDateTime4Tag(new Date(), true); // defaultTagDate;dispatch(AppActions.toggleEditTagDialog(tag));} else {- dispatch(- AppActions.showNotification(- t('core:thisFunctionalityIsAvailableInPro' as any) as string- )+ showNotification(+ t('core:thisFunctionalityIsAvailableInPro' as any) as string);}} else {@@ -286,9 +285,7 @@ export const TaggingActionsContextProvider = ({return saveMetaDataPromise(path, updatedFsEntryMeta).then(() => {// TODO rethink this updateCurrentDirEntry and not need for KanBan- dispatch(- AppActions.reflectUpdateSidecarTags(path, newTags, updateIndex)- );+ reflectUpdateSidecarTags(path, newTags, updateIndex);updateOpenedFile(path, {id: 'opened_entry_id',tags: newTags@@ -297,12 +294,10 @@ export const TaggingActionsContextProvider = ({}).catch(err => {console.warn('Error adding tags for ' + path + ' with ' + err);- dispatch(- AppActions.showNotification(- t('core:addingTagsFailed' as any) as string,- 'error',- true- )+ showNotification(+ t('core:addingTagsFailed' as any) as string,+ 'error',+ true);return false;});@@ -312,19 +307,15 @@ export const TaggingActionsContextProvider = ({return saveMetaDataPromise(path, newFsEntryMeta).then(() => {// TODO rethink this updateCurrentDirEntry and not need for KanBan- dispatch(- AppActions.reflectUpdateSidecarTags(path, tags, updateIndex)- );+ reflectUpdateSidecarTags(path, tags, updateIndex);return updateOpenedFile(path, { id: '', tags }); //, changed: true });}).catch(error => {console.warn('Error adding tags for ' + path + ' with ' + error);- dispatch(- AppActions.showNotification(- t('core:addingTagsFailed' as any) as string,- 'error',- true- )+ showNotification(+ t('core:addingTagsFailed' as any) as string,+ 'error',+ true);return true;});@@ -361,7 +352,7 @@ export const TaggingActionsContextProvider = ({tagDelimiter,prefixTagContainer);- return dispatch(AppActions.renameFile(path, newFilePath));+ return renameFile(path, newFilePath);}} else {// Handling tags in filename by no sidecar@@ -393,14 +384,14 @@ export const TaggingActionsContextProvider = ({prefixTagContainer);if (path !== newFilePath) {- return dispatch(AppActions.renameFile(path, newFilePath));+ return renameFile(path, newFilePath);}}return Promise.resolve(false);function getNonExistingTags(newTagsArray: Array<TS.Tag>,- fileTagsArray: Array<string>,+ fileTagsArray: string[],sideCarTagsArray: Array<TS.Tag>) {const newTags = [];@@ -491,11 +482,9 @@ export const TaggingActionsContextProvider = ({prefixTagContainer);if (newFileName !== fileName) {- await dispatch(- AppActions.renameFile(- path,- containingDirectoryPath + PlatformIO.getDirSeparator() + newFileName- )+ await renameFile(+ path,+ containingDirectoryPath + PlatformIO.getDirSeparator() + newFileName);}} else {@@ -538,19 +527,15 @@ export const TaggingActionsContextProvider = ({tags: newTagsArray});// TODO rethink this updateCurrentDirEntry and not need for KanBan- dispatch(- AppActions.reflectUpdateSidecarTags(path, newTagsArray, true)- );+ reflectUpdateSidecarTags(path, newTagsArray, true);return true;}).catch(err => {console.warn('Error adding tags for ' + path + ' with ' + err);- dispatch(- AppActions.showNotification(- t('core:addingTagsFailed' as any) as string,- 'error',- true- )+ showNotification(+ t('core:addingTagsFailed' as any) as string,+ 'error',+ true);});return true;@@ -571,19 +556,15 @@ export const TaggingActionsContextProvider = ({tags: fsEntryMeta.tags});// TODO rethink this updateCurrentDirEntry and not need for KanBan- dispatch(- AppActions.reflectUpdateSidecarTags(path, fsEntryMeta.tags)- );+ reflectUpdateSidecarTags(path, fsEntryMeta.tags);return true;}).catch(err => {console.warn('Error adding tags for ' + path + ' with ' + err);- dispatch(- AppActions.showNotification(- t('core:addingTagsFailed' as any) as string,- 'error',- true- )+ showNotification(+ t('core:addingTagsFailed' as any) as string,+ 'error',+ true);});});@@ -680,19 +661,17 @@ export const TaggingActionsContextProvider = ({};return saveMetaDataPromise(path, updatedFsEntryMeta).then(() => {- dispatch(AppActions.reflectUpdateSidecarTags(newFilePath, newTags));+ reflectUpdateSidecarTags(newFilePath, newTags);return true;}).catch(err => {console.warn('Removing sidecar tags failed ' + path + ' with ' + err);- dispatch(- AppActions.showNotification(- t('core:removingSidecarTagsFailed' as any) as string,- 'error',- true- )+ showNotification(+ t('core:removingSidecarTagsFailed' as any) as string,+ 'error',+ true);return false;});@@ -744,9 +723,7 @@ export const TaggingActionsContextProvider = ({prefixTagContainer);if (path !== newFilePath) {- const success = await dispatch(- AppActions.renameFile(path, newFilePath)- );+ const success = await renameFile(path, newFilePath);if (!success) {reject(new Error('Error renaming file'));return;@@ -765,21 +742,12 @@ export const TaggingActionsContextProvider = ({}function collectTagsFromLocation(tagGroup: TS.TagGroup) {- if (GlobalSearch.getInstance().getIndex().length < 1) {- dispatch(- AppActions.showNotification(- 'Please index location first',- 'error',- true- )- );+ if (getIndex().length < 1) {+ showNotification('Please index location first', 'error', true);return true;}- const uniqueTags = collectTagsFromIndex(- GlobalSearch.getInstance().getIndex(),- tagGroup- );+ const uniqueTags = collectTagsFromIndex(getIndex(), tagGroup);if (uniqueTags.length > 0) {const changedTagGroup = {...tagGroup,@@ -818,6 +786,23 @@ export const TaggingActionsContextProvider = ({return uniqueTags;}+ const reflectUpdateSidecarTags = useMemo(() => {+ return (path: string, tags: Array<TS.Tag>, updateIndex = true) => {+ // to reload cell in KanBan if add/remove sidecar tags+ // @ts-ignore+ const action: TS.EditedEntryAction = `edit${tags+ .map(tag => tag.title)+ .join()}`;+ dispatch(AppActions.reflectEditedEntryPaths([{ action, path }])); //[{ [path]: tags }]));+ // @ts-ignore+ updateCurrentDirEntry(path, { tags });++ if (updateIndex) {+ indexUpdateSidecarTags(path, tags);+ }+ };+ }, [updateCurrentDirEntry]);+const context = useMemo(() => {return {addTags,@@ -828,7 +813,12 @@ export const TaggingActionsContextProvider = ({removeAllTags,collectTagsFromLocation};- }, [openedEntries, persistTagsInSidecarFile, addTagsToLibrary]);+ }, [+ openedEntries,+ persistTagsInSidecarFile,+ addTagsToLibrary,+ reflectUpdateSidecarTags+ ]);return (<TaggingActionsContext.Provider value={context}>diff --git a/app/hooks/ThumbGenerationContextProvider.tsx b/app/hooks/ThumbGenerationContextProvider.tsxnew file mode 100644index 000000000..744297923--- /dev/null+++ b/app/hooks/ThumbGenerationContextProvider.tsx@@ -0,0 +1,241 @@+/**+ * TagSpaces - universal file and folder organizer+ * Copyright (C) 2023-present TagSpaces UG (haftungsbeschraenkt)+ *+ * 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/>.+ *+ */++import React, { createContext, useEffect, useMemo, useRef } from 'react';+import { useSelector } from 'react-redux';+import {+ getEnableWS,+ getShowUnixHiddenEntries,+ getUseGenerateThumbnails+} from '-/reducers/settings';+import PlatformIO from '-/services/platform-facade';+import { TS } from '-/tagspaces.namespace';+import AppConfig from '-/AppConfig';+import {+ getThumbnailURLPromise,+ supportedContainers,+ supportedImgs,+ supportedMisc,+ supportedText,+ supportedVideos+} from '-/services/thumbsgenerator';+import { usePaginationContext } from '-/hooks/usePaginationContext';+import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';+import { useNotificationContext } from '-/hooks/useNotificationContext';+import { locationType } from '@tagspaces/tagspaces-common/misc';+import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';+import { loadCurrentDirMeta } from '-/services/meta-loader';++type ThumbGenerationContextData = {+ generateThumbnails: (dirEntries: TS.FileSystemEntry[]) => void;+};++export const ThumbGenerationContext = createContext<ThumbGenerationContextData>(+ {+ generateThumbnails: () => {}+ }+);++export type ThumbGenerationContextProviderProps = {+ children: React.ReactNode;+};++export const ThumbGenerationContextProvider = ({+ children+}: ThumbGenerationContextProviderProps) => {+ const {+ currentDirectoryPath,+ currentDirectoryEntries,+ isMetaFolderExist,+ updateCurrentDirEntries+ } = useDirectoryContentContext();+ const { currentLocation } = useCurrentLocationContext();+ const { pageFiles } = usePaginationContext();+ const { setGeneratingThumbs } = useNotificationContext();+ const useGenerateThumbnails = useSelector(getUseGenerateThumbnails);+ const enableWS = useSelector(getEnableWS);+ const showUnixHiddenEntries = useSelector(getShowUnixHiddenEntries);+ const isGeneratingThumbs = useRef(false);++ function setGenThumbs(isGen: boolean) {+ isGeneratingThumbs.current = isGen;+ setGeneratingThumbs(isGen);+ }++ const supportedImgsWS = [+ 'jpg',+ 'jpeg',+ 'jif',+ 'jfif',+ 'png',+ 'gif',+ 'svg',+ 'tif',+ 'tiff',+ 'ico',+ 'webp',+ 'avif'+ // 'bmp' currently electron main processed: https://github.com/lovell/sharp/issues/806+ ];++ useEffect(() => {+ const entries =+ pageFiles && pageFiles.length > 0 ? pageFiles : currentDirectoryEntries;+ if (+ entries &&+ entries.length > 0 &&+ genThumbnailsEnabled() &&+ isGeneratingThumbs.current === false+ ) {+ generateThumbnails(entries).then(() => {+ if (!isMetaFolderExist) {+ // initial thumbnail generation without .ts folder+ loadCurrentDirMeta(+ currentDirectoryPath,+ currentDirectoryEntries,+ pageFiles+ ).then(entries => updateCurrentDirEntries(entries));+ /*PlatformIO.listMetaDirectoryPromise(currentDirectoryPath)+ .then(meta => {+ const thumbs = getThumbs(meta);+ return updateEntries(thumbs);+ })+ .catch(ex => {+ console.error(ex);+ return false;+ });*/+ }+ return true;+ });+ }+ }, [currentDirectoryEntries, isMetaFolderExist]);++ function genThumbnailsEnabled(): boolean {+ if (+ !currentDirectoryPath ||+ currentDirectoryPath.endsWith(+ AppConfig.dirSeparator + AppConfig.metaFolder+ ) ||+ currentDirectoryPath.endsWith(+ AppConfig.dirSeparator + AppConfig.metaFolder + AppConfig.dirSeparator+ )+ ) {+ return false; // dont generate thumbnails in meta folder+ }+ if (currentLocation.type === locationType.TYPE_CLOUD) {+ return false; // dont generate thumbnails for cloud location+ }+ if (AppConfig.useGenerateThumbnails !== undefined) {+ return AppConfig.useGenerateThumbnails;+ }+ return useGenerateThumbnails;+ }++ function generateThumbnails(+ dirEntries: TS.FileSystemEntry[]+ ): Promise<boolean> {+ if (+ AppConfig.isWeb || // not in web mode+ PlatformIO.haveObjectStoreSupport() || // not in object store mode+ PlatformIO.haveWebDavSupport() // not in webdav mode+ // genThumbnails() // enabled in the settings+ ) {+ return Promise.resolve(false);+ }++ const isWorkerAvailable = enableWS && PlatformIO.isWorkerAvailable();+ const workerEntries: string[] = [];+ const mainEntries: string[] = [];+ dirEntries.map(entry => {+ if (!entry.isFile) {+ return true;+ }+ if (!showUnixHiddenEntries && entry.name.startsWith('.')) {+ return true;+ }+ if (isWorkerAvailable && supportedImgsWS.includes(entry.extension)) {+ workerEntries.push(entry.path);+ } else if (+ supportedImgs.includes(entry.extension) ||+ supportedContainers.includes(entry.extension) ||+ supportedText.includes(entry.extension) ||+ supportedMisc.includes(entry.extension) ||+ supportedVideos.includes(entry.extension)+ ) {+ mainEntries.push(entry.path);+ } else {+ console.log('Unsupported thumb generation ext:' + entry.extension);+ }+ return true;+ });++ if (workerEntries.length > 0) {+ setGenThumbs(true);+ return PlatformIO.createThumbnailsInWorker(workerEntries)+ .then(() =>+ thumbnailMainGeneration(mainEntries).then(() => {+ setGenThumbs(false);+ return true;+ })+ )+ .catch(e => {+ // WS error handle let process thumbgeneration in Main process Generator+ console.error('createThumbnailsInWorker', e);+ return thumbnailMainGeneration([+ ...workerEntries,+ ...mainEntries+ ]).then(() => {+ setGenThumbs(false);+ return true;+ });+ });+ } else if (mainEntries.length > 0) {+ setGenThumbs(true);+ return thumbnailMainGeneration(mainEntries).then(() => {+ setGenThumbs(false);+ return true;+ });+ }+ return Promise.resolve(false);+ }++ function thumbnailMainGeneration(mainEntries: string[]): Promise<boolean> {+ return Promise.all(+ mainEntries.map(tmbPath => getThumbnailURLPromise(tmbPath))+ )+ .then(() => {+ return true;+ })+ .catch(e => {+ console.error('thumbnailMainGeneration', e);+ return false;+ });+ }++ const context = useMemo(() => {+ return {+ generateThumbnails+ };+ }, []);++ return (+ <ThumbGenerationContext.Provider value={context}>+ {children}+ </ThumbGenerationContext.Provider>+ );+};diff --git a/app/hooks/useCurrentLocationContext.tsx b/app/hooks/useCurrentLocationContext.tsxnew file mode 100644index 000000000..d554f6bb8--- /dev/null+++ b/app/hooks/useCurrentLocationContext.tsx@@ -0,0 +1,24 @@+/**+ * TagSpaces - universal file and folder organizer+ * Copyright (C) 2023-present TagSpaces UG (haftungsbeschraenkt)+ *+ * 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/>.+ *+ */++import { useContext } from 'react';++import { CurrentLocationContext } from '-/hooks/CurrentLocationContextProvider';++export const useCurrentLocationContext = () =>+ useContext(CurrentLocationContext);diff --git a/app/hooks/useDirectoryContentContext.tsx b/app/hooks/useDirectoryContentContext.tsxnew file mode 100644index 000000000..8beb4eaf7--- /dev/null+++ b/app/hooks/useDirectoryContentContext.tsx@@ -0,0 +1,24 @@+/**+ * TagSpaces - universal file and folder organizer+ * Copyright (C) 2023-present TagSpaces UG (haftungsbeschraenkt)+ *+ * 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/>.+ *+ */++import { useContext } from 'react';++import { DirectoryContentContext } from '-/hooks/DirectoryContentContextProvider';++export const useDirectoryContentContext = () =>+ useContext(DirectoryContentContext);diff --git a/app/hooks/useIOActionsContext.tsx b/app/hooks/useIOActionsContext.tsxnew file mode 100644index 000000000..f6d3825b2--- /dev/null+++ b/app/hooks/useIOActionsContext.tsx@@ -0,0 +1,23 @@+/**+ * TagSpaces - universal file and folder organizer+ * Copyright (C) 2023-present TagSpaces UG (haftungsbeschraenkt)+ *+ * 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/>.+ *+ */++import { useContext } from 'react';++import { IOActionsContext } from '-/hooks/IOActionsContextProvider';++export const useIOActionsContext = () => useContext(IOActionsContext);diff --git a/app/hooks/useLocationIndexContext.tsx b/app/hooks/useLocationIndexContext.tsxnew file mode 100644index 000000000..1636502c1--- /dev/null+++ b/app/hooks/useLocationIndexContext.tsx@@ -0,0 +1,23 @@+/**+ * TagSpaces - universal file and folder organizer+ * Copyright (C) 2023-present TagSpaces UG (haftungsbeschraenkt)+ *+ * 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/>.+ *+ */++import { useContext } from 'react';++import { LocationIndexContext } from '-/hooks/LocationIndexContextProvider';++export const useLocationIndexContext = () => useContext(LocationIndexContext);diff --git a/app/hooks/useNotificationContext.tsx b/app/hooks/useNotificationContext.tsxnew file mode 100644index 000000000..6e8e7020f--- /dev/null+++ b/app/hooks/useNotificationContext.tsx@@ -0,0 +1,23 @@+/**+ * TagSpaces - universal file and folder organizer+ * Copyright (C) 2023-present TagSpaces UG (haftungsbeschraenkt)+ *+ * 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/>.+ *+ */++import { useContext } from 'react';++import { NotificationContext } from '-/hooks/NotificationContextProvider';++export const useNotificationContext = () => useContext(NotificationContext);diff --git a/app/hooks/usePaginationContext.tsx b/app/hooks/usePaginationContext.tsxnew file mode 100644index 000000000..66d9d50ae--- /dev/null+++ b/app/hooks/usePaginationContext.tsx@@ -0,0 +1,23 @@+/**+ * TagSpaces - universal file and folder organizer+ * Copyright (C) 2023-present TagSpaces UG (haftungsbeschraenkt)+ *+ * 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/>.+ *+ */++import { useContext } from 'react';++import { PaginationContext } from './PaginationContextProvider';++export const usePaginationContext = () => useContext(PaginationContext);diff --git a/app/hooks/useThumbGenerationContext.tsx b/app/hooks/useThumbGenerationContext.tsxnew file mode 100644index 000000000..5b2aba6c2--- /dev/null+++ b/app/hooks/useThumbGenerationContext.tsx@@ -0,0 +1,24 @@+/**+ * TagSpaces - universal file and folder organizer+ * Copyright (C) 2023-present TagSpaces UG (haftungsbeschraenkt)+ *+ * 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/>.+ *+ */++import { useContext } from 'react';++import { ThumbGenerationContext } from './ThumbGenerationContextProvider';++export const useThumbGenerationContext = () =>+ useContext(ThumbGenerationContext);diff --git a/app/perspectives/common/main-container.tsx b/app/perspectives/common/main-container.tsxindex 3ff3c189e..ae215fc77 100644--- a/app/perspectives/common/main-container.tsx+++ b/app/perspectives/common/main-container.tsx@@ -55,7 +55,7 @@ export const renderCell = (directoryContent,openEntry,openFileNatively,- loadDirectoryContent,+ openDirectory,setFileContextMenuAnchorEl,setDirContextMenuAnchorEl,showNotification: (@@ -134,7 +134,7 @@ export const renderCell = (openEntry(fsEntry.path);} else {console.log('Handle Grid cell db click, selected path : ', fsEntry.path);- loadDirectoryContent(fsEntry.path, true, true);+ openDirectory(fsEntry.path, true);}};diff --git a/app/perspectives/grid-perspective/components/CellContent.tsx b/app/perspectives/grid-perspective/components/CellContent.tsxindex d6dd7cb1b..e4a962581 100644--- a/app/perspectives/grid-perspective/components/CellContent.tsx+++ b/app/perspectives/grid-perspective/components/CellContent.tsx@@ -50,8 +50,7 @@ import { TS } from '-/tagspaces.namespace';import {actions as AppActions,AppDispatch,- getLastThumbnailImageChange,- isReadOnlyMode+ getLastThumbnailImageChange} from '-/reducers/app';import { FolderIcon } from '-/components/CommonIcons';import { dataTidFormat } from '-/services/test';@@ -66,6 +65,7 @@ import {} from '-/perspectives/grid-perspective/components/styles.css';import { useTranslation } from 'react-i18next';import { useTaggingActionsContext } from '-/hooks/useTaggingActionsContext';+import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';const maxDescriptionPreviewLength = 100;@@ -108,10 +108,9 @@ function CellContent(props: Props) {} = props;const { t } = useTranslation();- const { addTags, editTagForEntry } = useTaggingActionsContext();-const theme = useTheme();- const readOnlyMode = useSelector(isReadOnlyMode);+ const { addTags, editTagForEntry } = useTaggingActionsContext();+ const { readOnlyMode } = useCurrentLocationContext();const supportedFileTypes = useSelector(getSupportedFileTypes);const reorderTags: boolean = useSelector(isReorderTags);const lastThumbnailImageChange = useSelector(getLastThumbnailImageChange);diff --git a/app/perspectives/grid-perspective/components/GridPagination.tsx b/app/perspectives/grid-perspective/components/GridPagination.tsxindex cafc47259..ec25c87e0 100644--- a/app/perspectives/grid-perspective/components/GridPagination.tsx+++ b/app/perspectives/grid-perspective/components/GridPagination.tsx@@ -17,7 +17,7 @@*/import React, { useEffect, useReducer, useRef } from 'react';-import { connect, useSelector } from 'react-redux';+import { connect } from 'react-redux';import { useTheme } from '@mui/material/styles';import Typography from '@mui/material/Typography';import Tooltip from '-/components/Tooltip';@@ -25,33 +25,18 @@ import Grid from '@mui/material/Grid';import Box from '@mui/material/Box';import ButtonBase from '@mui/material/ButtonBase';import Pagination from '@mui/material/Pagination';-import { bindActionCreators } from 'redux';import AppConfig from '-/AppConfig';+import { extractDirectoryName } from '@tagspaces/tagspaces-common/paths';import {- getMetaFileLocationForDir,- getMetaFileLocationForFile,- getThumbFileLocationForDirectory,- getThumbFileLocationForFile,- extractDirectoryName-} from '@tagspaces/tagspaces-common/paths';-import {- actions as AppActions,- getCurrentDirectoryColor,- getIsMetaLoaded,- getCurrentDirectoryTags,- getCurrentDirectoryDescription,getLastBackgroundImageChange,getLastThumbnailImageChange,- getLastSelectedEntryPath,- getLastSearchTimestamp,- getDirectoryContent+ getLastSelectedEntryPath} from '-/reducers/app';import EntryIcon from '-/components/EntryIcon';import TagsPreview from '-/components/TagsPreview';import TagContainer from '-/components/TagContainer';import { TS } from '-/tagspaces.namespace';import {- getMetaForEntry,getDescriptionPreview,getFolderThumbPath,getFolderBgndPath@@ -60,24 +45,23 @@ import PlatformIO from '-/services/platform-facade';import { MilkdownEditor } from '@tagspaces/tagspaces-md';import { renderCell } from '-/perspectives/common/main-container';import { useTranslation } from 'react-i18next';-import { getCurrentLocation } from '-/reducers/locations';-import GlobalSearch from '-/services/search-index';import { useOpenedEntryContext } from '-/hooks/useOpenedEntryContext';+import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';+import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';+import { usePaginationContext } from '-/hooks/usePaginationContext';+import { useIOActionsContext } from '-/hooks/useIOActionsContext';+import { useNotificationContext } from '-/hooks/useNotificationContext';interface Props {- isMetaLoaded: boolean;- setIsMetaLoaded: (isLoaded: boolean) => void;style?: any;// gridRef: Object;directories: Array<TS.FileSystemEntry>;showDirectories: boolean;showDetails: boolean;showDescription: boolean;- isReadOnlyMode: boolean;layoutType: string;showTags: boolean;desktopMode: boolean;- currentDirectoryDescription: string;thumbnailMode: string;entrySize: string;files: Array<TS.FileSystemEntry>;@@ -91,15 +75,11 @@ interface Props {handleGridCellDblClick,isLast?: boolean) => void;- currentDirectoryColor: string;- currentDirectoryTags: Array<TS.Tag>;- currentPage: number;gridPageLimit: number;currentDirectoryPath: string;onContextMenu: (event: React.MouseEvent<HTMLDivElement>) => void;openRenameEntryDialog: () => void;onClick: (event: React.MouseEvent<HTMLDivElement>) => void;- updateCurrentDirEntries: (dirEntries: TS.FileSystemEntry[]) => void;// eslint-disable-next-line react/no-unused-prop-typessettings; // cache only// eslint-disable-next-line react/no-unused-prop-types@@ -111,21 +91,9 @@ interface Props {singleClickAction: string;lastSelectedEntryPath: string;openFileNatively: (path?: string) => void;- loadDirectoryContent: (- path: string,- generateThumbnails: boolean,- loadDirMeta?: boolean- ) => void;setFileContextMenuAnchorEl: (HTMLElement) => void;setDirContextMenuAnchorEl: (HTMLElement) => void;- showNotification: (- text: string,- notificationType: string,- autohide: boolean- ) => void;- moveFiles: (files: Array<string>, destination: string) => Promise<boolean>;clearSelection: () => void;- lastSearchTimestamp: number;}function GridPagination(props: Props) {@@ -139,36 +107,31 @@ function GridPagination(props: Props) {showTags,singleClickAction,getCellContent,- isReadOnlyMode,desktopMode,- currentDirectoryColor,- currentDirectoryTags,- currentDirectoryDescription,currentDirectoryPath,lastThumbnailImageChange,openRenameEntryDialog,lastSelectedEntryPath,lastBackgroundImageChange,openFileNatively,- loadDirectoryContent,setFileContextMenuAnchorEl,setDirContextMenuAnchorEl,- showNotification,- moveFiles,gridPageLimit,- currentPage,selectedEntries,setSelectedEntries,clearSelection,- files,- lastSearchTimestamp+ files} = props;const { openEntry } = useOpenedEntryContext();-- const directoryContent: Array<TS.FileSystemEntry> = useSelector(- getDirectoryContent- );- const currentLocation: TS.Location = useSelector(getCurrentLocation);+ const { moveFiles } = useIOActionsContext();+ const { showNotification } = useNotificationContext();+ const { readOnlyMode, currentLocation } = useCurrentLocationContext();+ const {+ currentDirectoryEntries,+ openDirectory,+ directoryMeta+ } = useDirectoryContentContext();+ const { page, pageFiles, setCurrentPage } = usePaginationContext();if (!showDirectories) {directories = [];}@@ -180,48 +143,16 @@ function GridPagination(props: Props) {: 10;const containerEl = useRef(null);- // const entriesUpdated = useRef([]);- const page = useRef<number>(currentPage);- const metaLoadedLock = useRef<boolean>(false); // TODO move this for all perspectives - not lock if you open folder with diff perspective nowconst folderTmbPath = useRef<string>(getFolderThumbPath(currentDirectoryPath, lastThumbnailImageChange));const folderBgndPath = useRef<string>(getFolderBgndPath(currentDirectoryPath, lastBackgroundImageChange));- // const [page, setPage] = useState(currentPage);- let pageFiles;- if (showPagination) {- const start = (page.current - 1) * gridPageLimit;- pageFiles = files.slice(start, start + gridPageLimit);- } else {- pageFiles = files;- }const [, forceUpdate] = useReducer(x => x + 1, 0);- useEffect(() => {- if (!props.isMetaLoaded && !metaLoadedLock.current) {- metaLoadedLock.current = true;- PlatformIO.listMetaDirectoryPromise(props.currentDirectoryPath)- .then(meta => {- metaLoadedLock.current = false;- props.setIsMetaLoaded(true);- // props.setMetaForCurrentDir(meta);- const dirEntriesPromises = getDirEntriesPromises();- const fileEntriesPromises = getFileEntriesPromises(meta);- const thumbs = getThumbs(meta);- updateEntries([- ...dirEntriesPromises,- ...fileEntriesPromises,- ...thumbs- ]);- return true;- })- .catch(ex => console.error(ex));- }- }, [page.current, props.isMetaLoaded, files]);-+ // TODO move in DirectoryContentContextProvideruseEffect(() => {folderTmbPath.current = getFolderThumbPath(props.currentDirectoryPath,@@ -239,151 +170,17 @@ function GridPagination(props: Props) {}, [props.currentDirectoryPath, props.lastBackgroundImageChange]);useEffect(() => {- page.current = currentPage;- /* if (page !== currentPage) {- setPage(props.currentPage);- } */if (containerEl && containerEl.current) {containerEl.current.scrollTop = 0;}- }, [- //props.currentLocationPath,- props.currentDirectoryPath,- lastSearchTimestamp- ]);-- const setThumbs = (- entry: TS.FileSystemEntry,- meta: Array<any>- ): TS.FileSystemEntry => {- const thumbEntry = { ...entry };- let thumbPath = getThumbFileLocationForFile(- entry.path,- PlatformIO.getDirSeparator(),- false- );- if (thumbPath && meta.some(metaFile => thumbPath.endsWith(metaFile.path))) {- thumbEntry.thumbPath = thumbPath;- if (- PlatformIO.haveObjectStoreSupport() ||- PlatformIO.haveWebDavSupport()- ) {- if (thumbPath && thumbPath.startsWith('/')) {- thumbPath = thumbPath.substring(1);- }-- thumbPath = PlatformIO.getURLforPath(thumbPath, 604800);- if (thumbPath) {- thumbEntry.thumbPath = thumbPath;- }- }- }- return thumbEntry;- };-- const getThumbs = (meta: Array<any>): Promise<any>[] =>- pageFiles.map(entry =>- Promise.resolve({ [entry.path]: setThumbs(entry, meta) })- );+ }, [currentDirectoryEntries]);- const getDirEntriesPromises = (): Promise<any>[] =>- directories.map(async entry => {- if (entry.name === AppConfig.metaFolder) {- return Promise.resolve({ [entry.path]: undefined });- }- const meta = await PlatformIO.listMetaDirectoryPromise(entry.path);- const metaFilePath = getMetaFileLocationForDir(- entry.path,- PlatformIO.getDirSeparator()- );- const thumbDirPath = getThumbFileLocationForDirectory(- entry.path,- PlatformIO.getDirSeparator()- );- let enhancedEntry;- if (meta.some(metaFile => thumbDirPath.endsWith(metaFile.path))) {- const thumbPath =- PlatformIO.haveObjectStoreSupport() || PlatformIO.haveWebDavSupport()- ? PlatformIO.getURLforPath(thumbDirPath)- : thumbDirPath;- enhancedEntry = { ...entry, thumbPath };- }- if (- meta.some(metaFile => metaFilePath.endsWith(metaFile.path)) &&- // !checkEntryExist(entry.path) &&- entry.path.indexOf(- AppConfig.metaFolder + PlatformIO.getDirSeparator()- ) === -1- ) {- return getMetaForEntry(enhancedEntry || entry, metaFilePath);- }- return Promise.resolve({ [entry.path]: enhancedEntry });- });-- const getFileEntriesPromises = (meta: Array<any>): Promise<any>[] =>- pageFiles.map(entry => {- const metaFilePath = getMetaFileLocationForFile(- entry.path,- PlatformIO.getDirSeparator()- );- if (- // check if metaFilePath exist in listMetaDirectory content- meta.some(metaFile => metaFilePath.endsWith(metaFile.path)) &&- // !checkEntryExist(entry.path) &&- entry.path.indexOf(- AppConfig.metaFolder + PlatformIO.getDirSeparator()- ) === -1- ) {- return getMetaForEntry(entry, metaFilePath);- }- return Promise.resolve({ [entry.path]: undefined });- });-- const updateEntries = metaPromises => {- const catchHandler = error => undefined;- Promise.all(metaPromises.map(promise => promise.catch(catchHandler)))- .then(entries => {- updateCurrentDirEntries(entries); // .filter(entry => entry !== undefined));- // entriesUpdated.current = entries;- return true;- })- .catch(err => {- console.error('err updateEntries:', err);- });- };-- const updateCurrentDirEntries = entries => {- const entriesEnhanced = [];- entries.forEach(entry => {- if (entry) {- for (const [key, value] of Object.entries(entry)) {- if (value) {- // !checkEntryExist(key)) {- entriesEnhanced.push(value);- }- }+ const handleChange = (event, value) => {+ setCurrentPage(value).then(() => {+ if (containerEl && containerEl.current) {+ containerEl.current.scrollTop = 0;}});- if (entriesEnhanced.length > 0) {- props.updateCurrentDirEntries(entriesEnhanced);- }- };-- /* const checkEntryExist = path => {- const index = pageEntries.findIndex(- objUpdated => Object.keys(objUpdated).indexOf(path) > -1- );- return index > -1;- }; */-- const handleChange = (event, value) => {- // setPage(value);- page.current = value;- props.setIsMetaLoaded(false);- // forceUpdate();- if (containerEl && containerEl.current) {- containerEl.current.scrollTop = 0;- }};const folderName = extractDirectoryName(@@ -391,7 +188,7 @@ function GridPagination(props: Props) {PlatformIO.getDirSeparator());- const dirColor = currentDirectoryColor || 'transparent';+ const dirColor = directoryMeta.color || 'transparent';let folderSummary =(directories.length > 0 ? directories.length + ' folder(s) and ' : '') +@@ -401,15 +198,6 @@ function GridPagination(props: Props) {folderSummary = selectedEntries.length + ' entries selected';}- /* let descriptionHTML = '';- if (showDescription && currentDirectoryDescription) {- descriptionHTML = convertMarkDown(- currentDirectoryDescription,- props.currentDirectoryPath- );- }- */-return (// eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-noninteractive-element-interactions,jsx-a11y/no-static-element-interactions<div@@ -445,13 +233,14 @@ function GridPagination(props: Props) {marginTop: 0,marginBottom: 0,height:- !showDescription && currentDirectoryDescription ? 150 : 110,+ !showDescription && directoryMeta.description ? 150 : 110,position: 'relative'}}>{((folderName && folderName.length > 0) ||- (currentDirectoryTags &&- currentDirectoryTags.length > 0)) && (+ (directoryMeta &&+ directoryMeta.tags &&+ directoryMeta.tags.length > 0)) && (<Boxstyle={{display: 'flex',@@ -481,19 +270,14 @@ function GridPagination(props: Props) {</Tooltip>{showTags ? (<span style={{ paddingLeft: 5 }}>- {currentDirectoryTags &&- currentDirectoryTags.map((tag: TS.Tag) => {- return (- <TagContainer- isReadOnlyMode- tag={tag}- tagMode="display"- />- );+ {directoryMeta &&+ directoryMeta.tags &&+ directoryMeta.tags.map((tag: TS.Tag) => {+ return <TagContainer tag={tag} tagMode="display" />;})}</span>) : (- <TagsPreview tags={currentDirectoryTags} />+ <TagsPreview tags={directoryMeta.tags} />)}</Box>)}@@ -516,7 +300,7 @@ function GridPagination(props: Props) {>{folderSummary}</Typography>- {!showDescription && currentDirectoryDescription && (+ {!showDescription && directoryMeta.description && (<Typographystyle={{fontSize: '0.8rem',@@ -525,7 +309,7 @@ function GridPagination(props: Props) {overflowY: 'auto'}}>- {getDescriptionPreview(currentDirectoryDescription, 200)}+ {getDescriptionPreview(directoryMeta.description, 200)}</Typography>)}</Box>@@ -548,7 +332,7 @@ function GridPagination(props: Props) {</div></Grid>)}- {showDescription && currentDirectoryDescription && (+ {showDescription && directoryMeta.description && (<Griditemxs={12}@@ -562,7 +346,7 @@ function GridPagination(props: Props) {}}><MilkdownEditor- content={currentDirectoryDescription}+ content={directoryMeta.description}readOnly={true}dark={theme.palette.mode === 'dark'}currentFolder={currentDirectoryPath}@@ -572,26 +356,24 @@ function GridPagination(props: Props) {)}</Grid><div style={style} data-tid="perspectiveGridFileTable">- {page.current === 1 &&+ {page === 1 &&directories.map((entry, index) =>renderCell(entry,index,getCellContent,showDirectories,- isReadOnlyMode,+ readOnlyMode,desktopMode,singleClickAction,currentLocation,selectedEntries,setSelectedEntries,lastSelectedEntryPath,- lastSearchTimestamp- ? GlobalSearch.getInstance().getResults()- : directoryContent,+ currentDirectoryEntries,openEntry,openFileNatively,- loadDirectoryContent,+ openDirectory,setFileContextMenuAnchorEl,setDirContextMenuAnchorEl,showNotification,@@ -605,19 +387,17 @@ function GridPagination(props: Props) {index,getCellContent,showDirectories,- isReadOnlyMode,+ readOnlyMode,desktopMode,singleClickAction,currentLocation,selectedEntries,setSelectedEntries,lastSelectedEntryPath,- lastSearchTimestamp- ? GlobalSearch.getInstance().getResults()- : directoryContent,+ currentDirectoryEntries,openEntry,openFileNatively,- loadDirectoryContent,+ openDirectory,setFileContextMenuAnchorEl,setDirContextMenuAnchorEl,showNotification,@@ -628,7 +408,7 @@ function GridPagination(props: Props) {)}{pageFiles.length < 1 && directories.length < 1 && (<div style={{ textAlign: 'center' }}>- {!showDescription && currentDirectoryDescription && (+ {!showDescription && directoryMeta.description && (<div style={{ position: 'relative', marginBottom: 150 }}><EntryIcon isFile={false} /></div>@@ -647,7 +427,7 @@ function GridPagination(props: Props) {)}{pageFiles.length < 1 && directories.length >= 1 && !showDirectories && (<div style={{ textAlign: 'center' }}>- {!showDescription && currentDirectoryDescription && (+ {!showDescription && directoryMeta.description && (<div style={{ position: 'relative', marginBottom: 150 }}><EntryIcon isFile={false} /></div>@@ -680,7 +460,7 @@ function GridPagination(props: Props) {padding: 3}}count={paginationCount}- page={page.current}+ page={page}onChange={handleChange}/></Tooltip>@@ -706,30 +486,12 @@ function GridPagination(props: Props) {function mapStateToProps(state) {return {- currentDirectoryColor: getCurrentDirectoryColor(state),- lastSearchTimestamp: getLastSearchTimestamp(state),- // searchResultCount: getSearchResultCount(state),- // pageEntries: getPageEntries(state),- currentDirectoryTags: getCurrentDirectoryTags(state),- isMetaLoaded: getIsMetaLoaded(state),- currentDirectoryDescription: getCurrentDirectoryDescription(state),lastBackgroundImageChange: getLastBackgroundImageChange(state),lastThumbnailImageChange: getLastThumbnailImageChange(state),lastSelectedEntryPath: getLastSelectedEntryPath(state)};}-function mapActionCreatorsToProps(dispatch) {- return bindActionCreators(- {- updateCurrentDirEntries: AppActions.updateCurrentDirEntries,- setIsMetaLoaded: AppActions.setIsMetaLoaded,- loadDirectoryContent: AppActions.loadDirectoryContent- },- dispatch- );-}-const areEqual = (prevProp: Props, nextProp: Props) =>// nextProp.theme === prevProp.theme &&JSON.stringify(nextProp.lastBackgroundImageChange) ===@@ -737,7 +499,6 @@ const areEqual = (prevProp: Props, nextProp: Props) =>JSON.stringify(nextProp.lastThumbnailImageChange) ===JSON.stringify(prevProp.lastThumbnailImageChange) &&nextProp.currentDirectoryPath === prevProp.currentDirectoryPath &&- nextProp.isMetaLoaded === prevProp.isMetaLoaded &&nextProp.showDirectories === prevProp.showDirectories &&nextProp.showDetails === prevProp.showDetails &&nextProp.showDescription === prevProp.showDescription &&@@ -745,19 +506,11 @@ const areEqual = (prevProp: Props, nextProp: Props) =>nextProp.thumbnailMode === prevProp.thumbnailMode &&nextProp.entrySize === prevProp.entrySize &&nextProp.gridPageLimit === prevProp.gridPageLimit &&- nextProp.lastSearchTimestamp === prevProp.lastSearchTimestamp &&- nextProp.currentDirectoryDescription ===- prevProp.currentDirectoryDescription &&JSON.stringify(nextProp.files) === JSON.stringify(prevProp.files) &&JSON.stringify(nextProp.directories) ===JSON.stringify(prevProp.directories) &&JSON.stringify(nextProp.settings) === JSON.stringify(prevProp.settings) &&JSON.stringify(nextProp.selectedEntries) ===- JSON.stringify(prevProp.selectedEntries) &&- JSON.stringify(nextProp.currentDirectoryColor) ===- JSON.stringify(prevProp.currentDirectoryColor);+ JSON.stringify(prevProp.selectedEntries);-export default connect(- mapStateToProps,- mapActionCreatorsToProps-)(React.memo(GridPagination, areEqual));+export default connect(mapStateToProps)(React.memo(GridPagination, areEqual));diff --git a/app/perspectives/grid-perspective/components/MainContainer.tsx b/app/perspectives/grid-perspective/components/MainContainer.tsxindex 8fbe24be9..cd9013d71 100644--- a/app/perspectives/grid-perspective/components/MainContainer.tsx+++ b/app/perspectives/grid-perspective/components/MainContainer.tsx@@ -28,15 +28,11 @@ import EntryTagMenu from '-/components/menus/EntryTagMenu';import AddRemoveTagsDialog from '-/components/dialogs/AddRemoveTagsDialog';import MoveCopyFilesDialog from '-/components/dialogs/MoveCopyFilesDialog';import TagDropContainer from '-/components/TagDropContainer';-import IOActions from '-/reducers/io-actions';import {actions as AppActions,AppDispatch,- getDirectoryMeta,- getLastSearchTimestamp,getLastSelectedEntryPath,- getSelectedEntries,- isReadOnlyMode+ getSelectedEntries} from '-/reducers/app';import CellContent from './CellContent';import MainToolbar from './MainToolbar';@@ -52,14 +48,13 @@ import Links from '-/content/links';import { defaultSettings } from '../index';import { PerspectiveIDs } from '-/perspectives';import { fileOperationsEnabled } from '-/perspectives/common/main-container';-import GlobalSearch from '-/services/search-index';import useFirstRender from '-/utils/useFirstRender';import { openURLExternally } from '-/services/utils-io';import { useSortedDirContext } from '-/perspectives/grid-perspective/hooks/useSortedDirContext';import { useOpenedEntryContext } from '-/hooks/useOpenedEntryContext';+import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';interface Props {- currentDirectoryPath: string;openRenameEntryDialog: () => void;}@@ -78,9 +73,14 @@ function getSettings(directoryMeta: TS.FileSystemEntryMeta): TS.FolderSettings {}function GridPerspective(props: Props) {- const { currentDirectoryPath, openRenameEntryDialog } = props;+ const { openRenameEntryDialog } = props;const { openEntry, openPrevFile, openNextFile } = useOpenedEntryContext();+ const {+ directoryMeta,+ currentDirectoryPath,+ setDirectoryMeta+ } = useDirectoryContentContext();const dispatch: AppDispatch = useDispatch();const {@@ -90,9 +90,6 @@ function GridPerspective(props: Props) {setSortBy,setOrderBy} = useSortedDirContext();- const directoryMeta: TS.FileSystemEntryMeta = useSelector(getDirectoryMeta);- const readOnlyMode = useSelector(isReadOnlyMode);- const lastSearchTimestamp = useSelector(getLastSearchTimestamp);const desktopMode = useSelector(getDesktopMode);const selectedEntries: Array<TS.FileSystemEntry> = useSelector(getSelectedEntries@@ -105,9 +102,6 @@ function GridPerspective(props: Props) {);*/// Create functions that dispatch actions- const handleMoveFiles = (files: Array<string>, destination: string) =>- dispatch(IOActions.moveFiles(files, destination));-const handleSetSelectedEntries = (entries: Array<TS.FileSystemEntry>) => {const selected = showDirectories.current? entries@@ -115,14 +109,6 @@ function GridPerspective(props: Props) {dispatch(AppActions.setSelectedEntries(selected));};- const handleShowNotification = (- text: string,- notificationType: string,- autohide: boolean- ) => {- dispatch(AppActions.showNotification(text, notificationType, autohide));- };-const handleOpenFileNatively = (path?: string) => {dispatch(AppActions.openFileNatively(path));};@@ -325,7 +311,7 @@ function GridPerspective(props: Props) {PerspectiveIDs.GRID,perspectiveSettings).then((fsEntryMeta: TS.FileSystemEntryMeta) => {- dispatch(AppActions.setDirectoryMeta(fsEntryMeta));+ setDirectoryMeta(fsEntryMeta);});} else {localStorage.setItem(@@ -421,11 +407,7 @@ function GridPerspective(props: Props) {if (selectedEntries.length > 1) {clearSelection();} else {- if (!lastSearchTimestamp) {- handleSetSelectedEntries(sortedDirContent);- } else {- handleSetSelectedEntries(GlobalSearch.getInstance().getResults());- }+ handleSetSelectedEntries(sortedDirContent);}};@@ -690,7 +672,6 @@ function GridPerspective(props: Props) {showDetails={showDetails.current}showDescription={showDescription.current}showDirectories={showDirectories.current}- isReadOnlyMode={readOnlyMode}layoutType={layoutType.current}desktopMode={desktopMode}openRenameEntryDialog={openRenameEntryDialog}@@ -699,7 +680,6 @@ function GridPerspective(props: Props) {entrySize={entrySize.current}files={sortedFiles}getCellContent={getCellContent}- currentPage={1}currentDirectoryPath={currentDirectoryPath}onClick={onClick}onContextMenu={onContextMenu}@@ -710,8 +690,6 @@ function GridPerspective(props: Props) {openFileNatively={handleOpenFileNatively}setFileContextMenuAnchorEl={setFileContextMenuAnchorEl}setDirContextMenuAnchorEl={setDirContextMenuAnchorEl}- showNotification={handleShowNotification}- moveFiles={handleMoveFiles}clearSelection={clearSelection}/></GlobalHotKeys>@@ -762,7 +740,7 @@ function GridPerspective(props: Props) {currentDirectoryPath,PerspectiveIDs.GRID).then((fsEntryMeta: TS.FileSystemEntryMeta) => {- dispatch(AppActions.setDirectoryMeta(fsEntryMeta));+ setDirectoryMeta(fsEntryMeta);setIsGridSettingsDialogOpened(false);});}}@@ -797,7 +775,9 @@ function GridPerspective(props: Props) {}openAddRemoveTagsDialog={openAddRemoveTagsDialog}openFileNatively={handleOpenFileNatively}- selectedFilePath={lastSelectedEntryPath}+ selectedFilePath={+ lastSelectedEntryPath ? lastSelectedEntryPath : currentDirectoryPath+ }selectedEntries={selectedEntries}/>)}@@ -811,7 +791,7 @@ function GridPerspective(props: Props) {directoryPath={lastSelectedEntryPath}openRenameDirectoryDialog={openRenameEntryDialog}openMoveCopyFilesDialog={openMoveCopyFilesDialog}- perspectiveMode={lastSelectedEntryPath !== currentDirectoryPath}+ perspectiveMode={true}openAddRemoveTagsDialog={openAddRemoveTagsDialog}/>{/* {Boolean(tagContextMenuAnchorEl) && ( // TODO EntryTagMenu is used in TagSelect we cannot move confirm dialog from menu */}@@ -829,7 +809,6 @@ function GridPerspective(props: Props) {onClose={() => setSortingContextMenuAnchorEl(null)}anchorEl={sortingContextMenuAnchorEl}handleSortBy={handleSortBy}- searchModeEnabled={lastSearchTimestamp !== undefined}/>)}{Boolean(optionsContextMenuAnchorEl) && (diff --git a/app/perspectives/grid-perspective/components/MainToolbar.tsx b/app/perspectives/grid-perspective/components/MainToolbar.tsxindex aa1f11b7a..a92af1ed6 100644--- a/app/perspectives/grid-perspective/components/MainToolbar.tsx+++ b/app/perspectives/grid-perspective/components/MainToolbar.tsx@@ -36,18 +36,12 @@ import {import AppConfig from '-/AppConfig';import { Pro } from '-/pro';import { ProTooltip } from '-/components/HelperComponents';-import {- actions as LocationIndexActions,- getSearchQuery-} from '-/reducers/location-index';import { getKeyBindingObject } from '-/reducers/settings';import { TS } from '-/tagspaces.namespace';import {actions as AppActions,AppDispatch,- getDirectoryPath,- getSelectedEntries,- isReadOnlyMode+ getSelectedEntries} from '-/reducers/app';import {classes,@@ -55,6 +49,9 @@ import {} from '-/perspectives/grid-perspective/components/styles.css';import { useTranslation } from 'react-i18next';import { useOpenedEntryContext } from '-/hooks/useOpenedEntryContext';+import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';+import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';+import { useLocationIndexContext } from '-/hooks/useLocationIndexContext';interface Props {prefixDataTID?: string;@@ -81,17 +78,19 @@ function MainToolbar(props: Props) {const { t } = useTranslation();const { openEntry } = useOpenedEntryContext();+ const {+ loadParentDirectoryContent,+ currentDirectoryPath+ } = useDirectoryContentContext();const selectedEntries: Array<TS.FileSystemEntry> = useSelector(getSelectedEntries);- const searchQuery: TS.SearchQuery = useSelector(getSearchQuery);const keyBindings = useSelector(getKeyBindingObject);const dispatch: AppDispatch = useDispatch();- const readOnlyMode = useSelector(isReadOnlyMode);- const directoryPath = useSelector(getDirectoryPath);+ const { readOnlyMode } = useCurrentLocationContext();function showProperties() {- return openEntry(directoryPath, true);+ return openEntry(currentDirectoryPath, true);}return (@@ -112,12 +111,11 @@ function MainToolbar(props: Props) {aria-label={t('core:navigateToParentDirectory')}data-tid={prefixDataTID + 'PerspectiveOnBackButton'}onClick={() => {- if (searchQuery && Object.keys(searchQuery).length > 0) {+ /*if (searchQuery && Object.keys(searchQuery).length > 0) {dispatch(LocationIndexActions.setSearchQuery({}));- dispatch(AppActions.openCurrentDirectory());- } else {- dispatch(AppActions.loadParentDirectoryContent());- }+ openCurrentDirectory();+ } else {*/+ loadParentDirectoryContent();}}size="large">diff --git a/app/perspectives/grid-perspective/components/SortingMenu.tsx b/app/perspectives/grid-perspective/components/SortingMenu.tsxindex c270e22df..804e5cb47 100644--- a/app/perspectives/grid-perspective/components/SortingMenu.tsx+++ b/app/perspectives/grid-perspective/components/SortingMenu.tsx@@ -25,24 +25,26 @@ import ArrowUpIcon from '@mui/icons-material/KeyboardArrowUp';import ArrowDownIcon from '@mui/icons-material/KeyboardArrowDown';import { useTranslation } from 'react-i18next';import { useSortedDirContext } from '-/perspectives/grid-perspective/hooks/useSortedDirContext';+import { useLocationIndexContext } from '-/hooks/useLocationIndexContext';+import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';interface Props {open: boolean;onClose: () => void;anchorEl: Element;handleSortBy: (sortType: string) => void;- searchModeEnabled: boolean;}function SortingMenu(props: Props) {- const { open, onClose, handleSortBy, anchorEl, searchModeEnabled } = props;+ const { open, onClose, handleSortBy, anchorEl } = props;const { t } = useTranslation();const { sortBy, orderBy } = useSortedDirContext();+ const { isSearchMode } = useDirectoryContentContext();return (<Menu anchorEl={anchorEl} open={open} onClose={onClose}>{/* <ListSubHeader>Sort by</ListSubHeader> */}- {searchModeEnabled && (+ {isSearchMode && (<MenuItemdata-tid="gridPerspectiveSortByRelevance"onClick={() => {diff --git a/app/perspectives/grid-perspective/hooks/SortedDirContextProvider.tsx b/app/perspectives/grid-perspective/hooks/SortedDirContextProvider.tsxindex e1e8ce0e6..297476ee5 100644--- a/app/perspectives/grid-perspective/hooks/SortedDirContextProvider.tsx+++ b/app/perspectives/grid-perspective/hooks/SortedDirContextProvider.tsx@@ -18,22 +18,17 @@import React, { createContext, useMemo, useState } from 'react';import { useSelector } from 'react-redux';-import {- getDirectoryContent,- getDirectoryMeta,- getEditedEntryPaths,- getLastSearchTimestamp,- getSearchFilter-} from '-/reducers/app';+import { getSearchFilter } from '-/reducers/app';import { TS } from '-/tagspaces.namespace';-import GlobalSearch from '-/services/search-index';import { sortByCriteria } from '@tagspaces/tagspaces-common/misc';import { Pro } from '-/pro';import { PerspectiveIDs } from '-/perspectives';import { defaultSettings } from '-/perspectives/grid-perspective';+import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';type SortedDirContextData = {- sortedDirContent: Array<TS.FileSystemEntry>;+ sortedDirContent: TS.FileSystemEntry[];+ settings: TS.FolderSettings;sortBy: string;orderBy: null | boolean;setSortBy: (sort: string) => void;@@ -42,8 +37,9 @@ type SortedDirContextData = {export const SortedDirContext = createContext<SortedDirContextData>({sortedDirContent: undefined,- sortBy: defaultSettings.sortBy,- orderBy: defaultSettings.orderBy,+ settings: undefined,+ sortBy: undefined,+ orderBy: undefined,setSortBy: () => {},setOrderBy: () => {}});@@ -55,16 +51,17 @@ export type SortedDirContextProviderProps = {export const SortedDirContextProvider = ({children}: SortedDirContextProviderProps) => {- const directoryContent: Array<TS.FileSystemEntry> = useSelector(- getDirectoryContent- );- const lastSearchTimestamp = useSelector(getLastSearchTimestamp);+ const {+ currentDirectoryEntries,+ directoryMeta,+ currentDirectoryPerspective+ } = useDirectoryContentContext();const searchFilter: string = useSelector(getSearchFilter);- const directoryMeta: TS.FileSystemEntryMeta = useSelector(getDirectoryMeta);- const editedEntryPaths: Array<TS.EditedEntryPath> = useSelector(- getEditedEntryPaths- );- const settings = getSettings();++ const settings: TS.FolderSettings = useMemo(() => {+ return getSettings(directoryMeta, currentDirectoryPerspective);+ }, [directoryMeta, currentDirectoryPerspective]);+const [sortBy, setSortBy] = useState<string>(settings && settings.sortBy ? settings.sortBy : defaultSettings.sortBy);@@ -74,71 +71,65 @@ export const SortedDirContextProvider = ({: defaultSettings.orderBy);- function getSettings(): TS.FolderSettings {+ function getSettings(+ meta,+ perspective = PerspectiveIDs.GRID+ ): TS.FolderSettings {+ if (perspective === PerspectiveIDs.UNSPECIFIED) {+ perspective = PerspectiveIDs.GRID;+ }if (Pro &&- directoryMeta &&- directoryMeta.perspectiveSettings &&- directoryMeta.perspectiveSettings[PerspectiveIDs.GRID]+ meta &&+ meta.perspectiveSettings &&+ meta.perspectiveSettings[perspective]) {- return directoryMeta.perspectiveSettings[PerspectiveIDs.GRID];+ return meta.perspectiveSettings[perspective];} else {// loading settings for not Proreturn JSON.parse(localStorage.getItem(defaultSettings.settingsKey));}}- function getSortedDirContent() {+ const sortedDirContent = useMemo(() => {if (searchFilter) {- if (lastSearchTimestamp) {+ /*if (lastSearchTimestamp) {return GlobalSearch.getInstance().getResults().filter(entry =>entry.name.toLowerCase().includes(searchFilter.toLowerCase()));- } else {- return sortByCriteria(directoryContent, sortBy, orderBy).filter(entry =>- entry.name.toLowerCase().includes(searchFilter.toLowerCase())- );- }+ } else {*/+ return sortByCriteria(+ currentDirectoryEntries,+ sortBy,+ orderBy+ ).filter(entry =>+ entry.name.toLowerCase().includes(searchFilter.toLowerCase())+ );}- if (lastSearchTimestamp) {- if (sortBy === 'byRelevance') {- // initial search results is sorted by relevance- if (orderBy) {- return GlobalSearch.getInstance().getResults();- } else {- return [...GlobalSearch.getInstance().getResults()].reverse();- }+ if (sortBy === 'byRelevance') {+ // initial search results is sorted by relevance+ if (orderBy) {+ return currentDirectoryEntries;} else {- return sortByCriteria(- GlobalSearch.getInstance().getResults(),- sortBy,- orderBy- );+ return [...currentDirectoryEntries].reverse();}}// not in search mode- return sortByCriteria(directoryContent, sortBy, orderBy);- }+ return sortByCriteria(currentDirectoryEntries, sortBy, orderBy).map(o => o);+ }, [currentDirectoryEntries, searchFilter, sortBy, orderBy]);const context = useMemo(() => {return {- sortedDirContent: getSortedDirContent(),+ sortedDirContent,+ settings,sortBy,orderBy,setSortBy,setOrderBy};- }, [- directoryContent,- lastSearchTimestamp,- directoryMeta,- searchFilter,- editedEntryPaths,- sortBy,- orderBy- ]);+ }, [sortedDirContent, settings, sortBy, orderBy]);return (<SortedDirContext.Provider value={context}>diff --git a/app/perspectives/list/components/MainContainer.tsx b/app/perspectives/list/components/MainContainer.tsxindex 18ca93755..288ad3c61 100644--- a/app/perspectives/list/components/MainContainer.tsx+++ b/app/perspectives/list/components/MainContainer.tsx@@ -28,15 +28,11 @@ import EntryTagMenu from '-/components/menus/EntryTagMenu';import AddRemoveTagsDialog from '-/components/dialogs/AddRemoveTagsDialog';import MoveCopyFilesDialog from '-/components/dialogs/MoveCopyFilesDialog';import TagDropContainer from '-/components/TagDropContainer';-import IOActions from '-/reducers/io-actions';import {actions as AppActions,AppDispatch,- getDirectoryMeta,- getLastSearchTimestamp,getLastSelectedEntryPath,- getSelectedEntries,- isReadOnlyMode+ getSelectedEntries} from '-/reducers/app';import CellContent from '-/perspectives/grid-perspective/components/CellContent';import MainToolbar from '-/perspectives/grid-perspective/components/MainToolbar';@@ -52,14 +48,13 @@ import Links from '-/content/links';import { defaultSettings } from '../index';import { PerspectiveIDs } from '-/perspectives';import { fileOperationsEnabled } from '-/perspectives/common/main-container';-import GlobalSearch from '-/services/search-index';import useFirstRender from '-/utils/useFirstRender';import { openURLExternally } from '-/services/utils-io';import { useSortedDirContext } from '-/perspectives/grid-perspective/hooks/useSortedDirContext';import { useOpenedEntryContext } from '-/hooks/useOpenedEntryContext';+import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';interface Props {- currentDirectoryPath: string;openRenameEntryDialog: () => void;}@@ -78,8 +73,14 @@ function getSettings(directoryMeta: TS.FileSystemEntryMeta): TS.FolderSettings {}function ListPerspective(props: Props) {- const { currentDirectoryPath, openRenameEntryDialog } = props;+ const { openRenameEntryDialog } = props;+ const { openEntry, openPrevFile, openNextFile } = useOpenedEntryContext();+ const {+ directoryMeta,+ currentDirectoryPath,+ setDirectoryMeta+ } = useDirectoryContentContext();const dispatch: AppDispatch = useDispatch();const {@@ -89,10 +90,6 @@ function ListPerspective(props: Props) {setSortBy,setOrderBy} = useSortedDirContext();- const { openEntry, openPrevFile, openNextFile } = useOpenedEntryContext();- const directoryMeta: TS.FileSystemEntryMeta = useSelector(getDirectoryMeta);- const readOnlyMode = useSelector(isReadOnlyMode);- const lastSearchTimestamp = useSelector(getLastSearchTimestamp);const desktopMode = useSelector(getDesktopMode);const selectedEntries: Array<TS.FileSystemEntry> = useSelector(getSelectedEntries@@ -105,9 +102,6 @@ function ListPerspective(props: Props) {);*/// Create functions that dispatch actions- const handleMoveFiles = (files: Array<string>, destination: string) =>- dispatch(IOActions.moveFiles(files, destination));-const handleSetSelectedEntries = (entries: Array<TS.FileSystemEntry>) => {const selected = showDirectories.current? entries@@ -115,14 +109,6 @@ function ListPerspective(props: Props) {dispatch(AppActions.setSelectedEntries(selected));};- const handleShowNotification = (- text: string,- notificationType: string,- autohide: boolean- ) => {- dispatch(AppActions.showNotification(text, notificationType, autohide));- };-const handleOpenFileNatively = (path?: string) => {dispatch(AppActions.openFileNatively(path));};@@ -325,7 +311,7 @@ function ListPerspective(props: Props) {PerspectiveIDs.LIST,perspectiveSettings).then((fsEntryMeta: TS.FileSystemEntryMeta) => {- dispatch(AppActions.setDirectoryMeta(fsEntryMeta));+ setDirectoryMeta(fsEntryMeta);});} else {localStorage.setItem(@@ -414,11 +400,7 @@ function ListPerspective(props: Props) {if (selectedEntries.length > 1) {clearSelection();} else {- if (!lastSearchTimestamp) {- handleSetSelectedEntries(sortedDirContent);- } else {- handleSetSelectedEntries(GlobalSearch.getInstance().getResults());- }+ handleSetSelectedEntries(sortedDirContent);}};@@ -681,7 +663,6 @@ function ListPerspective(props: Props) {showDetails={showDetails.current}showDescription={showDescription.current}showDirectories={showDirectories.current}- isReadOnlyMode={readOnlyMode}layoutType={layoutType.current}desktopMode={desktopMode}openRenameEntryDialog={openRenameEntryDialog}@@ -690,7 +671,6 @@ function ListPerspective(props: Props) {entrySize={entrySize.current}files={sortedFiles}getCellContent={getCellContent}- currentPage={1}currentDirectoryPath={currentDirectoryPath}onClick={onClick}onContextMenu={onContextMenu}@@ -701,8 +681,6 @@ function ListPerspective(props: Props) {openFileNatively={handleOpenFileNatively}setFileContextMenuAnchorEl={setFileContextMenuAnchorEl}setDirContextMenuAnchorEl={setDirContextMenuAnchorEl}- showNotification={handleShowNotification}- moveFiles={handleMoveFiles}clearSelection={clearSelection}/></GlobalHotKeys>@@ -753,7 +731,7 @@ function ListPerspective(props: Props) {currentDirectoryPath,PerspectiveIDs.LIST).then((fsEntryMeta: TS.FileSystemEntryMeta) => {- dispatch(AppActions.setDirectoryMeta(fsEntryMeta));+ setDirectoryMeta(fsEntryMeta);setIsGridSettingsDialogOpened(false);});}}@@ -788,7 +766,9 @@ function ListPerspective(props: Props) {}openAddRemoveTagsDialog={openAddRemoveTagsDialog}openFileNatively={handleOpenFileNatively}- selectedFilePath={lastSelectedEntryPath}+ selectedFilePath={+ lastSelectedEntryPath ? lastSelectedEntryPath : currentDirectoryPath+ }selectedEntries={selectedEntries}/>)}@@ -802,7 +782,7 @@ function ListPerspective(props: Props) {directoryPath={lastSelectedEntryPath}openRenameDirectoryDialog={openRenameEntryDialog}openMoveCopyFilesDialog={openMoveCopyFilesDialog}- perspectiveMode={lastSelectedEntryPath !== currentDirectoryPath}+ perspectiveMode={true}openAddRemoveTagsDialog={openAddRemoveTagsDialog}/>{/* {Boolean(tagContextMenuAnchorEl) && ( // TODO EntryTagMenu is used in TagSelect we cannot move confirm dialog from menu */}@@ -820,7 +800,6 @@ function ListPerspective(props: Props) {onClose={() => setSortingContextMenuAnchorEl(null)}anchorEl={sortingContextMenuAnchorEl}handleSortBy={handleSortBy}- searchModeEnabled={lastSearchTimestamp !== undefined}/>)}{Boolean(optionsContextMenuAnchorEl) && (diff --git a/app/reducers/app.ts b/app/reducers/app.tsindex 2c44703fc..5febc1286 100644--- a/app/reducers/app.ts+++ b/app/reducers/app.ts@@ -16,72 +16,40 @@**/-import {- formatDateTime4Tag,- locationType-} from '@tagspaces/tagspaces-common/misc';import AppConfig from '-/AppConfig';import {extractFileExtension,- extractDirectoryName,extractFileName,getMetaFileLocationForFile,getThumbFileLocationForFile,extractParentDirectoryPath,extractTagsAsObjects,- normalizePath,extractContainingDirectoryPath,- getMetaFileLocationForDir,- generateSharingLink,getBackupFileLocation} from '@tagspaces/tagspaces-common/paths';-import {- getURLParameter,- clearURLParam,- updateHistory,- clearAllURLParams-} from '-/utils/dom';-import { getLocation, getDefaultLocationId } from './locations';+import { getURLParameter, clearAllURLParams } from '-/utils/dom';import PlatformIO from '../services/platform-facade';import {deleteFilesPromise,renameFilesPromise,- getAllPropertiesPromise,- prepareDirectoryContent,- findExtensionsForEntry,- getNextFile,- getPrevFile,- loadJSONFile,- merge,- setLocationType,- getRelativeEntryPath,- getCleanLocationPath,- updateFsEntries,mergeByProp,- toFsEntry,- openURLExternally+ toFsEntry} from '-/services/utils-io';import i18n from '../services/i18n';-import { Pro } from '../pro';-import { actions as LocationIndexActions } from './location-index';import { actions as tagLibraryActions } from './taglibrary';import {actions as SettingsActions,getCheckForUpdateOnStartup,- getPersistTagsInSidecarFile,isFirstRun,isGlobalKeyBindingEnabled} from '-/reducers/settings';import { TS } from '-/tagspaces.namespace';-import { PerspectiveIDs } from '-/perspectives';-import versionMeta from '-/version.json';import {addTag,getTagLibrary,setTagLibrary} from '-/services/taglibrary-utils';import { getProTeaserSlideIndex } from '-/content/ProTeaserSlides';-import GlobalSearch from '-/services/search-index';import { extensionsFound } from '-/extension-config';import { ThunkDispatch } from 'redux-thunk';@@ -98,40 +66,26 @@ export const types = {LAST_BACKGROUND_IMAGE_CHANGE: 'APP/LAST_BACKGROUND_IMAGE_CHANGE',LAST_BACKGROUND_COLOR_CHANGE: 'APP/LAST_BACKGROUND_COLOR_CHANGE',LAST_THUMBNAIL_IMAGE_CHANGE: 'APP/LAST_THUMBNAIL_IMAGE_CHANGE',- OPEN_LINK: 'APP/OPEN_LINK',+ //OPEN_LINK: 'APP/OPEN_LINK',LOGIN_SUCCESS: 'APP/LOGIN_SUCCESS',LOGIN_FAILURE: 'APP/LOGIN_FAILURE',LOGOUT: 'APP/LOGOUT',- LOAD_DIRECTORY_SUCCESS: 'APP/LOAD_DIRECTORY_SUCCESS',+ // LOAD_DIRECTORY_SUCCESS: 'APP/LOAD_DIRECTORY_SUCCESS',SET_DIRECTORY_META: 'APP/SET_DIRECTORY_META',- LOAD_DIRECTORY_FAILURE: 'APP/LOAD_DIRECTORY_FAILURE',- CLEAR_DIRECTORY_CONTENT: 'APP/CLEAR_DIRECTORY_CONTENT',+ //LOAD_DIRECTORY_FAILURE: 'APP/LOAD_DIRECTORY_FAILURE',+ //CLEAR_DIRECTORY_CONTENT: 'APP/CLEAR_DIRECTORY_CONTENT',// LOAD_PAGE_CONTENT: 'APP/LOAD_PAGE_CONTENT',- SET_SEARCH_RESULTS: 'APP/SET_SEARCH_RESULTS',- EXIT_SEARCH_MODE: 'APP/EXIT_SEARCH_MODE',- ENTER_SEARCH_MODE: 'APP/ENTER_SEARCH_MODE',- APPEND_SEARCH_RESULTS: 'APP/APPEND_SEARCH_RESULTS',+ //SET_SEARCH_RESULTS: 'APP/SET_SEARCH_RESULTS',+ //EXIT_SEARCH_MODE: 'APP/EXIT_SEARCH_MODE',+ //ENTER_SEARCH_MODE: 'APP/ENTER_SEARCH_MODE',+ //APPEND_SEARCH_RESULTS: 'APP/APPEND_SEARCH_RESULTS',SET_SEARCH_FILTER: 'APP/SET_SEARCH_FILTER',- //OPEN_FILE: 'APP/OPEN_FILE',- //TOGGLE_ENTRY_FULLWIDTH: 'APP/TOGGLE_ENTRY_FULLWIDTH',- //SET_ENTRY_FULLWIDTH: 'APP/SET_ENTRY_FULLWIDTH',- //CLOSE_ALL_FILES: 'APP/CLOSE_ALL_FILES',- UPDATE_THUMB_URL: 'APP/UPDATE_THUMB_URL',- UPDATE_THUMB_URLS: 'APP/UPDATE_THUMB_URLS',- SET_NOTIFICATION: 'APP/SET_NOTIFICATION',- SET_GENERATING_THUMBNAILS: 'APP/SET_GENERATING_THUMBNAILS',SET_NEW_VERSION_AVAILABLE: 'APP/SET_NEW_VERSION_AVAILABLE',SET_CURRENLOCATIONID: 'APP/SET_CURRENLOCATIONID',- SET_CURRENT_LOCATION: 'APP/SET_CURRENT_LOCATION',- SET_CURRENDIRECTORYCOLOR: 'APP/SET_CURRENDIRECTORYCOLOR',- SET_CURRENDIRECTORYPERSPECTIVE: 'APP/SET_CURRENDIRECTORYPERSPECTIVE',- SET_IS_META_LOADED: 'APP/SET_IS_META_LOADED',SET_LAST_SELECTED_ENTRY: 'APP/SET_LAST_SELECTED_ENTRY',SET_SELECTED_ENTRIES: 'APP/SET_SELECTED_ENTRIES',SET_TAG_LIBRARY_CHANGED: 'APP/SET_TAG_LIBRARY_CHANGED',SET_FILEDRAGGED: 'APP/SET_FILEDRAGGED',- SET_READONLYMODE: 'APP/SET_READONLYMODE',- RENAME_FILE: 'APP/RENAME_FILE',TOGGLE_EDIT_TAG_DIALOG: 'APP/TOGGLE_EDIT_TAG_DIALOG',TOGGLE_ABOUT_DIALOG: 'APP/TOGGLE_ABOUT_DIALOG',TOGGLE_LOCATION_DIALOG: 'APP/TOGGLE_LOCATION_DIALOG',@@ -150,7 +104,7 @@ export const types = {TOGGLE_IMPORT_KANBAN_DIALOG: 'APP/TOGGLE_IMPORT_KANBAN_DIALOG',TOGGLE_UPLOAD_DIALOG: 'APP/TOGGLE_UPLOAD_DIALOG',TOGGLE_TRUNCATED_DIALOG: 'APP/TOGGLE_TRUNCATED_DIALOG',- SET_CURRENT_DIRECTORY_DIRS: 'APP/SET_CURRENT_DIRECTORY_DIRS',+ //SET_CURRENT_DIRECTORY_DIRS: 'APP/SET_CURRENT_DIRECTORY_DIRS',CLEAR_UPLOAD_DIALOG: 'APP/CLEAR_UPLOAD_DIALOG',TOGGLE_PROGRESS_DIALOG: 'APP/TOGGLE_PROGRESS_DIALOG',OPEN_LOCATIONMANAGER_PANEL: 'APP/OPEN_LOCATIONMANAGER_PANEL',@@ -165,8 +119,8 @@ export const types = {REFLECT_CREATE_ENTRIES: 'APP/REFLECT_CREATE_ENTRIES',// REFLECT_UPDATE_SIDECARTAGS: 'APP/REFLECT_UPDATE_SIDECARTAGS',// REFLECT_UPDATE_SIDECARMETA: 'APP/REFLECT_UPDATE_SIDECARMETA',- UPDATE_CURRENTDIR_ENTRY: 'APP/UPDATE_CURRENTDIR_ENTRY',- UPDATE_CURRENTDIR_ENTRIES: 'APP/UPDATE_CURRENTDIR_ENTRIES',+ //UPDATE_CURRENTDIR_ENTRY: 'APP/UPDATE_CURRENTDIR_ENTRY',+ //UPDATE_CURRENTDIR_ENTRIES: 'APP/UPDATE_CURRENTDIR_ENTRIES',REFLECT_EDITED_ENTRY_PATHS: 'APP/REFLECT_EDITED_ENTRY_PATHS',// SET_ISLOADING: 'APP/SET_ISLOADING',ADD_EXTENSIONS: 'APP/ADD_EXTENSIONS',@@ -174,11 +128,6 @@ export const types = {UPDATE_EXTENSION: 'APP/UPDATE_EXTENSION'};-export const NotificationTypes = {- default: 'default',- error: 'error'-};-export type OpenedEntry = {uuid: string;path: string;@@ -238,13 +187,13 @@ export const initialState = {progress: [],isUpdateInProgress: false,isUpdateAvailable: false,- currentLocationId: null,- currentDirectoryPath: '',- currentDirectoryColor: '',- currentDirectoryDescription: '',- currentDirectoryTags: [],- currentDirectoryEntries: [],- isReadOnlyMode: false,+ //currentLocationId: null,+ //currentDirectoryPath: '',+ //currentDirectoryColor: '',+ //currentDirectoryDescription: '',+ //currentDirectoryTags: [],+ //currentDirectoryEntries: [],+ //isReadOnlyMode: false,searchResults: [],notificationStatus: {visible: false,@@ -270,7 +219,7 @@ export const initialState = {selectedEntries: [],tagLibraryChanged: false,isEntryInFullWidth: false,- isGeneratingThumbs: false,+ //isGeneratingThumbs: false,locationManagerPanelOpened: showLocations,tagLibraryPanelOpened: showTagLibrary,searchPanelOpened: showSearch,@@ -316,15 +265,6 @@ export default (state: any = initialState, action: any) => {}};}- case types.OPEN_LINK: {- return {- ...state,- openLink: {- url: action.url,- options: action.options- }- };- }case types.LOGIN_SUCCESS: {return { ...state, user: action.user };}@@ -354,12 +294,6 @@ export default (state: any = initialState, action: any) => {case types.RESET_PROGRESS: {return { ...state, progress: [] };}- case types.SET_READONLYMODE: {- if (action.isReadOnlyMode !== state.isReadOnlyMode) {- return { ...state, isReadOnlyMode: action.isReadOnlyMode };- }- return state;- }case types.SET_NEW_VERSION_AVAILABLE: {if (action.isUpdateAvailable !== state.isUpdateAvailable) {return {@@ -369,89 +303,6 @@ export default (state: any = initialState, action: any) => {}return state;}- case types.SET_DIRECTORY_META: {- return {- ...state,- directoryMeta: action.directoryMeta- };- }- case types.LOAD_DIRECTORY_SUCCESS: {- let { directoryPath } = action;- if (directoryPath && directoryPath.startsWith('./')) {- // relative paths- directoryPath = PlatformIO.resolveFilePath(directoryPath);- }- let currentDirectoryFiles: Array<TS.OrderVisibilitySettings> = [];- if (- action.directoryMeta &&- action.directoryMeta.customOrder &&- action.directoryMeta.customOrder.files- ) {- currentDirectoryFiles = action.directoryMeta.customOrder.files;- }- let currentDirectoryDirs: Array<TS.OrderVisibilitySettings> = [];- if (- action.directoryMeta &&- action.directoryMeta.customOrder &&- action.directoryMeta.customOrder.folders- ) {- currentDirectoryDirs = action.directoryMeta.customOrder.folders;- }- return {- ...state,- currentDirectoryEntries: action.directoryContent,- directoryMeta: action.directoryMeta,- currentDirectoryColor: action.directoryMeta- ? action.directoryMeta.color || ''- : '',- currentDirectoryTags: action.directoryMeta- ? action.directoryMeta.tags || []- : '',- currentDirectoryDescription: action.directoryMeta- ? action.directoryMeta.description || ''- : '',- currentDirectoryPerspective:- action.directoryMeta && action.directoryMeta.perspective- ? action.directoryMeta.perspective- : action.defaultPerspective, // state.currentDirectoryPerspective,- currentDirectoryPath: directoryPath,- /**- * used for reorder files in KanBan- */- currentDirectoryFiles: currentDirectoryFiles,- /**- * used for reorder dirs in KanBan- */- currentDirectoryDirs: currentDirectoryDirs- // isLoading: action.showIsLoading || false- };- }- case types.CLEAR_DIRECTORY_CONTENT: {- return {- ...state,- currentDirectoryEntries: [],- currentDirectoryPath: ''- };- }- case types.SET_CURRENLOCATIONID: {- if (action.currentLocationId !== state.currentLocationId) {- return {- ...state,- currentLocationId: action.locationId- };- }- return state;- }- case types.SET_CURRENT_LOCATION: {- if (action.location.uuid !== state.currentLocationId) {- return {- ...state,- currentDirectoryPath: action.location.path,- currentLocationId: action.location.uuid- };- }- return state;- }case types.SET_SELECTED_ENTRIES: {if (JSON.stringify(action.selectedEntries) !==@@ -464,24 +315,6 @@ export default (state: any = initialState, action: any) => {case types.SET_TAG_LIBRARY_CHANGED: {return { ...state, tagLibraryChanged: !state.tagLibraryChanged };}- case types.SET_CURRENDIRECTORYCOLOR: {- if (state.currentDirectoryColor !== action.color) {- return { ...state, currentDirectoryColor: action.color };- }- return state;- }- case types.SET_CURRENDIRECTORYPERSPECTIVE: {- if (state.currentDirectoryPerspective !== action.perspective) {- return { ...state, currentDirectoryPerspective: action.perspective };- }- return state;- }- case types.SET_IS_META_LOADED: {- if (state.isMetaLoaded !== action.isMetaLoaded) {- return { ...state, isMetaLoaded: action.isMetaLoaded };- }- return state;- }case types.TOGGLE_EDIT_TAG_DIALOG: {return {...state,@@ -585,7 +418,7 @@ export default (state: any = initialState, action: any) => {isTruncatedConfirmDialogOpened: !state.isTruncatedConfirmDialogOpened};}- case types.SET_CURRENT_DIRECTORY_DIRS: {+ /* case types.SET_CURRENT_DIRECTORY_DIRS: {if (JSON.stringify(state.currentDirectoryDirs) !==JSON.stringify(action.dirs)@@ -596,7 +429,7 @@ export default (state: any = initialState, action: any) => {};}return state;- }+ }*/case types.CLEAR_UPLOAD_DIALOG: {// if (PlatformIO.haveObjectStoreSupport()) {// upload dialog have objectStore support only@@ -614,146 +447,48 @@ export default (state: any = initialState, action: any) => {progressDialogOpened: !state.progressDialogOpened};}- case types.SET_SEARCH_RESULTS: {- GlobalSearch.getInstance().setResults(action.searchResults);- return {- ...state,- lastSearchTimestamp: new Date().getTime(),- //isLoading: false,- selectedEntries: []- };- }- case types.EXIT_SEARCH_MODE: {- GlobalSearch.getInstance().setResults([]);- return {- ...state,- searchMode: false,- lastSearchTimestamp: undefined,- searchFilter: undefined,- //isLoading: false,- selectedEntries: []- };- }- case types.ENTER_SEARCH_MODE: {- GlobalSearch.getInstance().setResults([]);- return {- ...state,- searchMode: true,- searchFilter: undefined- //isLoading: false- };- }- case types.APPEND_SEARCH_RESULTS: {- // const newDirEntries = [...state.currentDirectoryEntries];- for (let i = 0; i < action.searchResults.length; i += 1) {- const index = GlobalSearch.getInstance()- .getResults()- .findIndex(entry => entry.path === action.searchResults[i].path);- if (index === -1) {- GlobalSearch.getInstance().setResults([- ...GlobalSearch.getInstance().getResults(),- action.searchResults[i]- ]);- }- }- return {- ...state,- lastSearchTimestamp: new Date().getTime()- // currentDirectoryEntries: newDirEntries,- //isLoading: false- };- }case types.SET_SEARCH_FILTER: {return {...state,searchFilter: action.searchFilter};}- case types.SET_NOTIFICATION: {- return {- ...state,- notificationStatus: {- visible: action.visible,- text: action.text,- tid: action.tid,- notificationType: action.notificationType,- autohide: action.autohide- }- };- }- case types.SET_GENERATING_THUMBNAILS: {- if (action.isGeneratingThumbs !== state.isGeneratingThumbs) {- return {- ...state,- isGeneratingThumbs: action.isGeneratingThumbs- };- }- return state;- }- case types.UPDATE_THUMB_URL: {- const dirEntries = state.currentDirectoryEntries.map(entry => {- if (entry.path === action.filePath) {- return { ...entry, thumbPath: action.thumbUrl };- }- return entry;- });- return {- ...state,- currentDirectoryEntries: dirEntries- };- }- case types.UPDATE_THUMB_URLS: {- const dirEntries = [...state.currentDirectoryEntries];- for (let i = 0; i < dirEntries.length; i++) {- const entry = dirEntries[i];- const tmbURLs: any[] = action.tmbURLs;- const tmbUrl = tmbURLs.find(tmbUrl => tmbUrl.filePath == entry.path);- if (!tmbUrl) continue;- dirEntries[i] = { ...entry };- dirEntries[i].thumbPath = tmbUrl.tmbPath;- }- return {- ...state,- currentDirectoryEntries: dirEntries- };- }case types.REFLECT_DELETE_ENTRY: {- const newDirectoryEntries = state.currentDirectoryEntries.filter(+ /*const newDirectoryEntries = state.currentDirectoryEntries.filter(entry => entry.path !== action.path- );+ );*/const editedEntryPaths = [{ action: 'delete', path: action.path }];// check if currentDirectoryEntries or openedFiles changed- if (+ /*if (state.currentDirectoryEntries.length > newDirectoryEntries.length- // || state.openedFiles.length > newOpenedFiles.length) {return {...state,editedEntryPaths,currentDirectoryEntries: newDirectoryEntries};- }+ }*/return {...state,editedEntryPaths};}case types.REFLECT_DELETE_ENTRIES: {- const newDirectoryEntries = state.currentDirectoryEntries.filter(+ /*const newDirectoryEntries = state.currentDirectoryEntries.filter(entry => !action.paths.some(path => path === entry.path)- );+ );*/const editedEntryPaths = action.paths.map(path => ({action: 'delete',path: path}));// check if currentDirectoryEntries or openedFiles changed- if (state.currentDirectoryEntries.length > newDirectoryEntries.length) {+ /*if (state.currentDirectoryEntries.length > newDirectoryEntries.length) {return {...state,editedEntryPaths,currentDirectoryEntries: newDirectoryEntries};- }+ }*/return {...state,editedEntryPaths@@ -762,13 +497,13 @@ export default (state: any = initialState, action: any) => {case types.REFLECT_CREATE_ENTRY: {const newEntry: TS.FileSystemEntry = action.newEntry;// Prevent adding entry twice e.g. by entry rename in the watcher- if (+ /*if (state.currentDirectoryEntries.some(entry => entry.path === newEntry.path)) {return state;- }+ }*/const editedEntryPaths: Array<TS.EditedEntryPath> = [{action: newEntry.isFile ? 'createFile' : 'createDir',@@ -777,7 +512,7 @@ export default (state: any = initialState, action: any) => {}];// clean all dir separators to have platform independent path match- if (+ /*if (// entryIndex < 0 &&extractParentDirectoryPath(action.newEntry.path,@@ -793,14 +528,14 @@ export default (state: any = initialState, action: any) => {action.newEntry]};- }+ }*/return {...state,editedEntryPaths};}case types.REFLECT_CREATE_ENTRIES: {- if (+ /*if (action.fsEntries.length > 0 &&extractParentDirectoryPath(action.fsEntries[0].path,@@ -823,15 +558,15 @@ export default (state: any = initialState, action: any) => {...action.fsEntries]};- }+ }*/return state;}case types.REFLECT_RENAME_ENTRY: {- const extractedTags = extractTagsAsObjects(+ /*const extractedTags = extractTagsAsObjects(action.newPath,AppConfig.tagDelimiter,PlatformIO.getDirSeparator()- );+ );*/const editedEntryPaths = [{ action: 'rename', path: action.path },@@ -840,8 +575,8 @@ export default (state: any = initialState, action: any) => {return {...state,- editedEntryPaths,- currentDirectoryEntries: state.currentDirectoryEntries.map(entry => {+ editedEntryPaths+ /*currentDirectoryEntries: state.currentDirectoryEntries.map(entry => {if (entry.path !== action.path) {return entry;}@@ -860,10 +595,10 @@ export default (state: any = initialState, action: any) => {...fileNameTags]};- })+ })*/};}- case types.UPDATE_CURRENTDIR_ENTRIES: {+ /*case types.UPDATE_CURRENTDIR_ENTRIES: {if (state.currentDirectoryEntries &&state.currentDirectoryEntries.length > 0@@ -894,14 +629,14 @@ export default (state: any = initialState, action: any) => {...state,currentDirectoryEntries: action.dirEntries};- }+ }*/case types.REFLECT_EDITED_ENTRY_PATHS: {return {...state,editedEntryPaths: action.editedEntryPaths // .map(path => ({ action: 'edit', path }))};}- case types.UPDATE_CURRENTDIR_ENTRY: {+ /*case types.UPDATE_CURRENTDIR_ENTRY: {return {...state,// warning: edit action is handled in FolderContainer; to reload column in KanBan if properties is changed (dir color)@@ -911,7 +646,7 @@ export default (state: any = initialState, action: any) => {[action.entry])};- }+ }*/case types.OPEN_LOCATIONMANAGER_PANEL: {return {...state,@@ -1045,11 +780,11 @@ export const actions = {lastThumbnailImageChange: lastThumbnailImageChange || new Date().getTime()}),loggedIn: user => ({ type: types.LOGIN_SUCCESS, user }),- openLink: (url: string, options = { fullWidth: true }) => ({+ /*openLink: (url: string, options = { fullWidth: true }) => ({type: types.OPEN_LINK,url,options- }),+ }),*/initApp: () => (dispatch: (action) => void, getState: () => any) => {disableBackGestureMac();// migrate TagLibrary from redux state@@ -1090,18 +825,19 @@ export const actions = {});}- let openDefaultLocation = true;- const lid = getURLParameter('tslid');+ // let openDefaultLocation = true;+ /*const lid = getURLParameter('tslid');const dPath = getURLParameter('tsdpath');const ePath = getURLParameter('tsepath');const cmdOpen = getURLParameter('cmdopen');if (lid || dPath || ePath) {- openDefaultLocation = false;+ // openDefaultLocation = false;setTimeout(() => {+ // todo move this in OpenEntryContextProvider -> useEffectdispatch(actions.openLink(window.location.href));}, 1000);} else if (cmdOpen) {- openDefaultLocation = false;+ // openDefaultLocation = false;setTimeout(() => {dispatch(actions.openLink(@@ -1111,15 +847,15 @@ export const actions = {));}, 1000);- }- const defaultLocationId = getDefaultLocationId(state);+ }*/+ /*const defaultLocationId = getDefaultLocationId(state);if (openDefaultLocation &&defaultLocationId &&defaultLocationId.length > 0) {dispatch(actions.openLocationById(defaultLocationId));- }+ }*/},goOnline: () => ({ type: types.DEVICE_ONLINE }),goOffline: () => ({ type: types.DEVICE_OFFLINE }),@@ -1151,7 +887,7 @@ export const actions = {dispatch: (action) => void,getState: () => any) => {- const { app } = getState();+ /* const { app } = getState();if (!app.currentDirectoryPath) {dispatch(actions.showNotification(@@ -1160,15 +896,15 @@ export const actions = {true));- } else {- dispatch(actions.toggleCreateDirectoryDialog());- }+ } else {*/+ dispatch(actions.toggleCreateDirectoryDialog());+ //}},showCreateFileDialog: () => (dispatch: (action) => void,getState: () => any) => {- const { app } = getState();+ /*const { app } = getState();if (!app.currentDirectoryPath) {dispatch(actions.showNotification(@@ -1177,9 +913,9 @@ export const actions = {true));- } else {- dispatch(actions.toggleNewEntryDialog());- }+ } else {*/+ dispatch(actions.toggleNewEntryDialog());+ // }},toggleEditTagDialog: (tag: TS.Tag) => ({type: types.TOGGLE_EDIT_TAG_DIALOG,@@ -1218,10 +954,10 @@ export const actions = {toggleTruncatedConfirmDialog: () => ({type: types.TOGGLE_TRUNCATED_DIALOG}),- setCurrentDirectoryDirs: dirs => ({+ /*setCurrentDirectoryDirs: dirs => ({type: types.SET_CURRENT_DIRECTORY_DIRS,dirs- }),+ }),*/clearUploadDialog: () => ({type: types.CLEAR_UPLOAD_DIALOG}),@@ -1232,251 +968,6 @@ export const actions = {openTagLibraryPanel: () => ({ type: types.OPEN_TAGLIBRARY_PANEL }),openSearchPanel: () => ({ type: types.OPEN_SEARCH_PANEL }),openHelpFeedbackPanel: () => ({ type: types.OPEN_HELPFEEDBACK_PANEL }),- //closeAllVerticalPanels: () => ({ type: types.CLOSE_ALLVERTICAL_PANELS }),- /*setIsLoading: (isLoading: boolean) => ({- type: types.SET_ISLOADING,- isLoading- }),*/- loadParentDirectoryContent: () => (- dispatch: (action) => void,- getState: () => any- ) => {- const state = getState();- const { currentDirectoryPath } = state.app;- const currentLocationPath = normalizePath(getCurrentLocationPath(state));-- // dispatch(actions.setIsLoading(true));-- if (currentDirectoryPath) {- const parentDirectory = extractParentDirectoryPath(- currentDirectoryPath,- PlatformIO.getDirSeparator()- );- // console.log('parentDirectory: ' + parentDirectory + ' - currentLocationPath: ' + currentLocationPath);- if (parentDirectory.includes(currentLocationPath)) {- dispatch(actions.loadDirectoryContent(parentDirectory, false, true));- } else {- dispatch(- actions.showNotification(- i18n.t('core:parentDirNotInLocation'),- 'warning',- true- )- );- // dispatch(actions.setIsLoading(false));- }- } else {- dispatch(- actions.showNotification(- i18n.t('core:firstOpenaFolder'),- 'warning',- true- )- );- // dispatch(actions.setIsLoading(false));- }- },- updateCurrentDirectoryPerspective: (perspective: string) => (- dispatch: (action) => void,- getState: () => any- ) => {- const { currentDirectoryPerspective } = getState();- if (perspective) {- if (currentDirectoryPerspective !== perspective) {- dispatch(actions.setCurrentDirectoryPerspective(perspective));- }- } else if (currentDirectoryPerspective !== PerspectiveIDs.UNSPECIFIED) {- dispatch(- actions.setCurrentDirectoryPerspective(PerspectiveIDs.UNSPECIFIED)- );- }- },- loadDirectoryContentInt: (- directoryPath: string,- generateThumbnails: boolean,- fsEntryMeta?: TS.FileSystemEntryMeta- ) => (dispatch: (action) => void, getState: () => any) => {- const { settings } = getState();-- dispatch(actions.showNotification(i18n.t('core:loading'), 'info', false));- const currentLocation: TS.Location = getLocation(- getState(),- getState().app.currentLocationId- );- const resultsLimit = {- maxLoops:- currentLocation && currentLocation.maxLoops- ? currentLocation.maxLoops- : AppConfig.maxLoops,- IsTruncated: false- };- PlatformIO.listDirectoryPromise(- directoryPath,- fsEntryMeta &&- fsEntryMeta.perspective &&- (fsEntryMeta.perspective === PerspectiveIDs.KANBAN ||- fsEntryMeta.perspective === PerspectiveIDs.GALLERY)- ? ['extractThumbPath']- : [], // mode,- currentLocation ? currentLocation.ignorePatternPaths : [],- resultsLimit- )- .then(results => {- if (resultsLimit.IsTruncated) {- //OPEN ISTRUNCATED dialog- dispatch(actions.toggleTruncatedConfirmDialog());- }- updateHistory(currentLocation, directoryPath);- if (results !== undefined) {- // console.debug('app listDirectoryPromise resolved:' + results.length);- prepareDirectoryContent(- results,- directoryPath,- settings,- dispatch,- getState,- fsEntryMeta,- generateThumbnails- );- }- dispatch(- actions.updateCurrentDirectoryPerspective(- fsEntryMeta ? fsEntryMeta.perspective : undefined- )- );- return true;- })- .catch(error => {- // console.timeEnd('listDirectoryPromise');- dispatch(actions.loadDirectoryFailure(directoryPath, error));- dispatch(- actions.updateCurrentDirectoryPerspective(- fsEntryMeta ? fsEntryMeta.perspective : undefined- )- );- });- },- loadDirectoryContent: (- directoryPath: string,- generateThumbnails: boolean,- loadDirMeta = false- ) => async (dispatch: (action) => void, getState: () => any) => {- // console.debug('loadDirectoryContent:' + directoryPath);- window.walkCanceled = false;-- // dispatch(actions.setIsLoading(true));-- const state = getState();- const { selectedEntries } = state.app;- if (selectedEntries.length > 0) {- dispatch(actions.setSelectedEntries([]));- }- if (loadDirMeta) {- try {- const metaFilePath = getMetaFileLocationForDir(- directoryPath,- PlatformIO.getDirSeparator()- );- const fsEntryMeta = await loadJSONFile(metaFilePath);- // console.debug('Loading meta succeeded for:' + directoryPath);- dispatch(- actions.loadDirectoryContentInt(- directoryPath,- generateThumbnails,- fsEntryMeta- // description: getDescriptionPreview(fsEntryMeta.description, 200)- )- );- } catch (err) {- console.debug('Error loading meta of:' + directoryPath + ' ' + err);- dispatch(- actions.loadDirectoryContentInt(directoryPath, generateThumbnails)- );- }- } else {- dispatch(- actions.loadDirectoryContentInt(directoryPath, generateThumbnails)- );- }- },- loadDirectorySuccess: (- directoryPath: string,- directoryContent: Array<any>,- directoryMeta?: TS.FileSystemEntryMeta- ) => (dispatch: (action) => void, getState: () => any) => {- const { settings } = getState();- dispatch(actions.hideNotifications(['error']));- dispatch(actions.exitSearchMode());- dispatch(- actions.loadDirectorySuccessInt(- directoryPath,- directoryContent,- false,- directoryMeta,- settings.defaultPerspective- )- );- dispatch(actions.setIsMetaLoaded(false));- },- loadDirectorySuccessInt: (- directoryPath: string,- directoryContent: Array<any>,- showIsLoading?: boolean,- directoryMeta?: TS.FileSystemEntryMeta,- defaultPerspective?: string- ) => ({- type: types.LOAD_DIRECTORY_SUCCESS,- directoryPath: directoryPath || PlatformIO.getDirSeparator(),- directoryContent,- directoryMeta,- showIsLoading,- defaultPerspective- }),- setDirectoryMeta: (directoryMeta: TS.FileSystemEntryMeta) => ({- type: types.SET_DIRECTORY_META,- directoryMeta- }),- loadDirectoryFailure: (directoryPath: string, error?: any) => (- dispatch: (action) => void- ) => {- console.error('Error loading directory: ', error);- dispatch(actions.hideNotifications());-- dispatch(- actions.showNotification(- i18n.t('core:errorLoadingFolder') + ': ' + error.message,- 'warning',- false- )- );- dispatch(actions.closeAllLocations());- // dispatch(actions.loadDirectorySuccess(directoryPath, []));- },- updateThumbnailUrl: (filePath: string, thumbUrl: string) => ({- type: types.UPDATE_THUMB_URL,- filePath,- thumbUrl // + '?' + new Date().getTime()- }),- updateThumbnailUrls: (tmbURLs: Array<any>) => ({- type: types.UPDATE_THUMB_URLS,- tmbURLs- }),- setGeneratingThumbnails: (isGeneratingThumbs: boolean) => ({- type: types.SET_GENERATING_THUMBNAILS,- isGeneratingThumbs- }),- setCurrentDirectoryColor: (color: string) => ({- type: types.SET_CURRENDIRECTORYCOLOR,- color- }),- setCurrentDirectoryPerspective: (perspective: string) => ({- type: types.SET_CURRENDIRECTORYPERSPECTIVE,- perspective- }),- setIsMetaLoaded: (isMetaLoaded: boolean) => ({- type: types.SET_IS_META_LOADED,- isMetaLoaded- }),setSelectedEntries: (selectedEntries: Array<TS.FileSystemEntry>) => (dispatch: (action) => void) => {@@ -1501,301 +992,24 @@ export const actions = {tagLibraryChanged: () => ({type: types.SET_TAG_LIBRARY_CHANGED}),- openDirectory: (directoryPath: string) => () => {+ /*openDirectory: (directoryPath: string) => () => {PlatformIO.openDirectory(directoryPath);- },- showInFileManager: (filePath: string) => () => {+ },*/+ /*showInFileManager: (filePath: string) => () => {PlatformIO.showInFileManager(filePath);- },- setSearchResults: (searchResults: Array<any> | []) => ({- type: types.SET_SEARCH_RESULTS,- searchResults- }),- exitSearchMode: () => (dispatch: (action) => void, getState: () => any) => {- const { searchMode } = getState().app;- if (searchMode) {- dispatch(actions.exitSearchModeInt());- }- },- exitSearchModeInt: () => ({- type: types.EXIT_SEARCH_MODE- }),- enterSearchMode: () => (dispatch: (action) => void, getState: () => any) => {- const { searchMode } = getState().app;- if (!searchMode) {- dispatch(actions.enterSearchModeInt());- }- },- enterSearchModeInt: () => ({- type: types.ENTER_SEARCH_MODE- }),- appendSearchResults: (searchResults: Array<any> | []) => ({- type: types.APPEND_SEARCH_RESULTS,- searchResults- }),+ },*/setSearchFilter: (searchFilter: string) => ({type: types.SET_SEARCH_FILTER,searchFilter}),- setCurrentLocationId: (locationId: string | null) => ({- type: types.SET_CURRENLOCATIONID,- locationId- }),- setCurrentLocation: (location: TS.Location) => ({- type: types.SET_CURRENT_LOCATION,- location- }),- changeLocation: (location: TS.Location) => (- dispatch: (action) => void,- getState: () => any- ) => {- //dispatch(actions.changeLocationByID(location.uuid));- const { currentLocationId } = getState().app;- if (location.uuid !== currentLocationId) {- // dispatch(actions.exitSearchMode());- dispatch(LocationIndexActions.clearDirectoryIndex());- dispatch(actions.setCurrentLocation(location));- }- },- changeLocationByID: (locationId: string) => (- dispatch: (action) => void,- getState: () => any- ) => {- const { currentLocationId } = getState().app;- if (locationId !== currentLocationId) {- // dispatch(actions.exitSearchMode());- dispatch(LocationIndexActions.clearDirectoryIndex());- dispatch(actions.setCurrentLocationId(locationId));- }- },- switchLocationTypeByID: (locationID: string) => (- dispatch: (action) => Promise<string | null>,- getState: () => any- ): Promise<string | null> => {- const location: TS.Location = getLocation(getState(), locationID);- return dispatch(actions.switchLocationType(location));- },- /**- * @param location- * return Promise<currentLocationId> if location is changed or null if location and type is changed- */- switchLocationType: (location: TS.Location) => (- dispatch: (action) => string | null,- getState: () => any- ): Promise<string | null> => {- const { currentLocationId } = getState().app;- if (location && location.uuid !== currentLocationId) {- const currentLocation: TS.Location = getLocation(- getState(),- currentLocationId- );- if (- currentLocation === undefined ||- location.type !== currentLocation.type- ) {- return setLocationType(location).then(() => null);- } else {- // handle the same location type but different location- // dispatch(actions.setCurrentLocationId(location.uuid));- return setLocationType(location).then(() => currentLocationId);- }- }- return Promise.resolve(null);- },- switchCurrentLocationType: (currentLocationId?: string) => (- dispatch: (action) => boolean,- getState: () => any- ): Promise<boolean> => {- // dispatch(actions.setCurrentLocationId(location.uuid));- const location: TS.Location = getLocation(- getState(),- currentLocationId || getState().app.currentLocationId- );-- return setLocationType(location);- },- openLocationById: (locationId: string, skipInitialDirList?: boolean) => (- dispatch: (action) => void,- getState: () => any- ) => {- const { locations } = getState();- locations.map(location => {- if (location.uuid === locationId) {- dispatch(actions.openLocation(location, skipInitialDirList));- }- return true;- });- },- openLocation: (location: TS.Location, skipInitialDirList?: boolean) => (- dispatch: (action) => void,- getState: () => any- ) => {- if (Pro && Pro.Watcher) {- Pro.Watcher.stopWatching();- }- if (location.type === locationType.TYPE_CLOUD) {- PlatformIO.enableObjectStoreSupport(location)- .then(() => {- dispatch(- actions.showNotification(- i18n.t('core:connectedtoObjectStore'),- 'default',- true- )- );- dispatch(actions.setReadOnlyMode(location.isReadOnly || false));- dispatch(actions.changeLocation(location));- if (!skipInitialDirList) {- dispatch(- actions.loadDirectoryContent(- PlatformIO.getLocationPath(location),- false,- true- )- );- }- return true;- })- .catch(e => {- console.log('connectedtoObjectStoreFailed', e);- dispatch(- actions.showNotification(- i18n.t('core:connectedtoObjectStoreFailed'),- 'warning',- true- )- );- PlatformIO.disableObjectStoreSupport();- });- } else {- if (location.type === locationType.TYPE_WEBDAV) {- PlatformIO.enableWebdavSupport(location);- } else {- PlatformIO.disableObjectStoreSupport();- PlatformIO.disableWebdavSupport();- }- dispatch(actions.setReadOnlyMode(location.isReadOnly || false));- dispatch(actions.changeLocation(location));- if (!skipInitialDirList) {- dispatch(- actions.loadDirectoryContent(- PlatformIO.getLocationPath(location),- true,- true- )- );- }- dispatch(actions.watchForChanges(location));- }- },- watchForChanges: (location?: TS.Location) => (- dispatch: (action) => void,- getState: () => any- ) => {- if (location === undefined) {- location = getLocation(getState(), getState().app.currentLocationId);- }- if (Pro && Pro.Watcher && location && location.watchForChanges) {- const perspective = getCurrentDirectoryPerspective(getState());- const depth = perspective === PerspectiveIDs.KANBAN ? 3 : 1;- Pro.Watcher.watchFolder(- PlatformIO.getLocationPath(location),- dispatch,- actions,- depth- );- }- },- closeLocation: (locationId: string) => (- dispatch: (action) => void,- getState: () => any- ) => {- const { locations } = getState();- const { currentLocationId } = getState().app;- if (currentLocationId === locationId) {- locations.map(location => {- if (location.uuid === locationId) {- // location needed evtl. to unwatch many loc. root folders if available- dispatch(actions.setCurrentLocationId(null));- dispatch(actions.clearDirectoryContent());- dispatch(LocationIndexActions.clearDirectoryIndex());- dispatch(actions.setSelectedEntries([]));- dispatch(actions.exitSearchMode());- if (Pro && Pro.Watcher) {- Pro.Watcher.stopWatching();- }- }- clearAllURLParams();- return true;- });- }- },- closeAllLocations: () => (dispatch: (action) => void) => {- // location needed evtl. to unwatch many loc. root folders if available- dispatch(actions.setCurrentLocationId(null));- dispatch(actions.clearDirectoryContent());- dispatch(LocationIndexActions.clearDirectoryIndex());- dispatch(actions.setSelectedEntries([]));- if (Pro && Pro.Watcher) {- Pro.Watcher.stopWatching();- }- clearAllURLParams();- return true;- },- clearDirectoryContent: () => ({- type: types.CLEAR_DIRECTORY_CONTENT- }),- showNotification: (- text: string,- notificationType = 'default',- autohide = true,- tid = 'notificationTID'- ) => ({- type: types.SET_NOTIFICATION,- visible: true,- text,- notificationType,- autohide,- tid- }),- hideNotifications: (excludeTypes = []) => (- dispatch: (action) => void,- getState: () => any- ) => {- const { notificationStatus } = getState().app;- if (- !excludeTypes.some(type => type === notificationStatus.notificationType)- ) {- dispatch(actions.hideNotificationsInt());- }- },- hideNotificationsInt: () => ({- type: types.SET_NOTIFICATION,- visible: false,- text: null,- notificationType: 'default',- autohide: true- }),- setReadOnlyMode: (isReadOnlyMode: boolean) => ({- type: types.SET_READONLYMODE,- isReadOnlyMode- }),- reflectDeleteEntryInt: (path: string) => ({+ reflectDeleteEntry: (path: string) => ({type: types.REFLECT_DELETE_ENTRY,path}),- reflectDeleteEntriesInt: (paths: string[]) => ({+ reflectDeleteEntries: (paths: string[]) => ({type: types.REFLECT_DELETE_ENTRIES,paths}),- reflectDeleteEntry: (path: string) => (dispatch: (action) => void) => {- dispatch(actions.reflectDeleteEntryInt(path));- GlobalSearch.getInstance().reflectDeleteEntry(path);- },- reflectDeleteEntries: (paths: string[]) => (dispatch: (action) => void) => {- dispatch(actions.reflectDeleteEntriesInt(paths));- GlobalSearch.getInstance().reflectDeleteEntries(paths);- },reflectCreateEntryInt: (newEntry: TS.FileSystemEntry) => ({type: types.REFLECT_CREATE_ENTRY,newEntry@@ -1820,7 +1034,7 @@ export const actions = {) => {dispatch(actions.setSelectedEntries([newEntry]));dispatch(actions.reflectCreateEntryInt(newEntry));- GlobalSearch.getInstance().reflectCreateEntry(newEntry);+ //GlobalSearch.getInstance().reflectCreateEntry(newEntry);},reflectRenameEntryInt: (path: string, newPath: string) => ({type: types.REFLECT_RENAME_ENTRY,@@ -1828,220 +1042,16 @@ export const actions = {newPath}),reflectRenameEntry: (path: string, newPath: string) => (- dispatch: (action) => void,- getState: () => any+ dispatch: (action) => void) => {- const { searchMode } = getState().app;- if (searchMode) {- const results = GlobalSearch.getInstance()- .getResults()- .map((fsEntry: TS.FileSystemEntry) => {- if (fsEntry.path === path) {- return {- ...fsEntry,- path: newPath,- name: extractFileName(newPath, PlatformIO.getDirSeparator())- };- }- return fsEntry;- });- GlobalSearch.getInstance().setResults(results);- }dispatch(actions.reflectRenameEntryInt(path, newPath));- GlobalSearch.getInstance().reflectRenameEntry(path, newPath);+ // GlobalSearch.getInstance().reflectRenameEntry(path, newPath);dispatch(actions.setSelectedEntries([]));},- /**- * TODO include path in entry => only one entry parameter- * @param path- * @param entry- */- updateCurrentDirEntry: (path: string, entry: any) => (- dispatch: (action) => void,- getState: () => any- ) => {- const { searchMode } = getState().app;- if (searchMode) {- const results = updateFsEntries(GlobalSearch.getInstance().getResults(), [- { ...entry, path }- ]);- GlobalSearch.getInstance().setResults(results);- } else {- dispatch(actions.updateCurrentDirEntryInt(path, entry));- }- },- updateCurrentDirEntryInt: (path: string, entry: any) => ({- type: types.UPDATE_CURRENTDIR_ENTRY,- entry: { ...entry, path }- }),- updateCurrentDirEntries: (dirEntries: TS.FileSystemEntry[]) => ({- type: types.UPDATE_CURRENTDIR_ENTRIES,- dirEntries- }),reflectEditedEntryPaths: (editedEntryPaths: Array<TS.EditedEntryPath>) => ({type: types.REFLECT_EDITED_ENTRY_PATHS,editedEntryPaths}),- /**- * @param path- * @param tags- * @param updateIndex- */- reflectUpdateSidecarTags: (- path: string,- tags: Array<TS.Tag>,- updateIndex = true- ) => (dispatch: (action) => void, getState: () => any) => {- // const { openedFiles, selectedEntries } = getState().app;- // to reload cell in KanBan if add/remove sidecar tags- const action: TS.EditedEntryAction = `edit${tags- .map(tag => tag.title)- .join()}`;- dispatch(actions.reflectEditedEntryPaths([{ action, path }])); //[{ [path]: tags }]));- dispatch(actions.updateCurrentDirEntry(path, { tags }));-- if (updateIndex) {- GlobalSearch.getInstance().reflectUpdateSidecarTags(path, tags);- }- },- deleteFile: (filePath: string, uuid: string) => (- dispatch: (action) => void,- getState: () => any- ) => {- const { settings } = getState();- return PlatformIO.deleteFilePromise(filePath, settings.useTrashCan)- .then(() => {- // TODO close file opener if this file is opened- dispatch(actions.reflectDeleteEntry(filePath));- dispatch(- actions.showNotification(- `Deleting file ${filePath} successful.`,- 'default',- true- )- );- // Delete revisions- const backupFilePath = getBackupFileLocation(- filePath,- uuid,- PlatformIO.getDirSeparator()- );- const backupPath = extractContainingDirectoryPath(- backupFilePath,- PlatformIO.getDirSeparator()- );- PlatformIO.deleteDirectoryPromise(backupPath)- .then(() => {- console.log('Cleaning revisions successful for ' + filePath);- return true;- })- .catch(err => {- console.warn('Cleaning revisions failed ', err);- });- // Delete sidecar file and thumb- deleteFilesPromise([- getMetaFileLocationForFile(filePath, PlatformIO.getDirSeparator()),- getThumbFileLocationForFile(- filePath,- PlatformIO.getDirSeparator(),- false- )- ])- .then(() => {- console.log(- 'Cleaning meta file and thumb successful for ' + filePath- );- return true;- })- .catch(err => {- console.warn('Cleaning meta file and thumb failed with ' + err);- });- return true;- })- .catch(error => {- console.warn('Error while deleting file: ' + error);- dispatch(- actions.showNotification(- `Error while deleting file ${filePath}`,- 'error',- true- )- );- });- },- renameFile: (filePath: string, newFilePath: string) => (- dispatch: (action) => void- ): Promise<boolean> =>- PlatformIO.renameFilePromise(filePath, newFilePath)- .then(result => {- const newFilePathFromPromise = result[1];- console.info('File renamed ' + filePath + ' to ' + newFilePath);- dispatch(- actions.showNotification(- i18n.t('core:renamingSuccessfully'),- 'default',- true- )- );- // Update sidecar file and thumb- return renameFilesPromise([- [- getMetaFileLocationForFile(filePath, PlatformIO.getDirSeparator()),- getMetaFileLocationForFile(- newFilePath,- PlatformIO.getDirSeparator()- )- ],- [- getThumbFileLocationForFile(- filePath,- PlatformIO.getDirSeparator(),- false- ),- getThumbFileLocationForFile(- newFilePath,- PlatformIO.getDirSeparator(),- false- )- ]- ])- .then(() => {- dispatch(- actions.reflectRenameEntry(filePath, newFilePathFromPromise)- );- console.info(- 'Renaming meta file and thumb successful from ' +- filePath +- ' to:' +- newFilePath- );- return true;- })- .catch(err => {- dispatch(- actions.reflectRenameEntry(filePath, newFilePathFromPromise)- );- console.warn(- 'Renaming meta file and thumb failed from ' +- filePath +- ' to:' +- newFilePath,- err- );- return false;- });- })- .catch(error => {- console.error(`Error while renaming file ${filePath}`, error);- dispatch(- actions.showNotification(- `Error while renaming file ${filePath}`,- 'error',- true- )- );- return false;- }),openFileNatively: (selectedFile?: string) => (dispatch: (action) => void,getState: () => any@@ -2062,33 +1072,6 @@ export const actions = {const { warningOpeningFilesExternally } = getState().settings;PlatformIO.openFile(selectedFile, warningOpeningFilesExternally);}- },- saveFile: () => (dispatch: (action) => void) => {- dispatch(- actions.showNotification(- i18n.t('core:notImplementedYet'),- 'warning',- true- )- );- },- isCurrentLocation: (uuid: string) => (- dispatch: (action) => void,- getState: () => any- ) => {- const { currentLocationId } = getState().app;- return currentLocationId === uuid;- },- openCurrentDirectory: () => (- dispatch: (action) => void,- getState: () => any- ) => {- const { currentDirectoryPath } = getState().app;- if (currentDirectoryPath) {- dispatch(actions.loadDirectoryContent(currentDirectoryPath, false, true));- } else {- dispatch(actions.setSearchResults([]));- }}};@@ -2100,65 +1083,14 @@ export const getLastBackgroundColorChange = (state: any) =>export const getLastThumbnailImageChange = (state: any) =>state.app.lastThumbnailImageChange;export const currentUser = (state: any) => state.app.user;-export const getIsMetaLoaded = (state: any) => state.app.isMetaLoaded;-export const getDirectoryContent = (state: any) =>- state.app.currentDirectoryEntries;-// export const getPageEntries = (state: any) => state.app.pageEntries;export const getEditedEntryPaths = (state: any) => state.app.editedEntryPaths;-export const getCurrentDirectoryFiles = (state: any) =>- state.app.currentDirectoryFiles;-export const getCurrentDirectoryDirs = (state: any) =>- state.app.currentDirectoryDirs;-export const getCurrentDirectoryColor = (state: any) =>+/*export const getCurrentDirectoryColor = (state: any) =>state.app.currentDirectoryColor;export const getCurrentDirectoryDescription = (state: any) =>state.app.currentDirectoryDescription;export const getCurrentDirectoryTags = (state: any) =>- state.app.currentDirectoryTags;-export const getCurrentDirectoryPerspective = (state: any) =>- state.app.currentDirectoryPerspective;-export const getDirectoryPath = (state: any) => state.app.currentDirectoryPath;+ state.app.currentDirectoryTags;*/export const getProgress = (state: any) => state.app.progress;-export const getCurrentLocationPath = (state: any) => {- if (state.locations) {- for (let i = 0; i < state.locations.length; i += 1) {- const location = state.locations[i];- if (- state.app.currentLocationId &&- location.uuid === state.app.currentLocationId- ) {- return PlatformIO.getLocationPath(location);- }- }- }- return undefined;-};-export const isPersistTagsInSidecarFile = (state: any): boolean => {- const locationPersistTagsInSidecarFile = getLocationPersistTagsInSidecarFile(- state- );- if (locationPersistTagsInSidecarFile !== undefined) {- return locationPersistTagsInSidecarFile;- }- if (AppConfig.useSidecarsForFileTaggingDisableSetting) {- return AppConfig.useSidecarsForFileTagging;- }- return state.settings.persistTagsInSidecarFile;-};-export const getLocationPersistTagsInSidecarFile = (state: any) => {- if (state.locations) {- for (let i = 0; i < state.locations.length; i += 1) {- const location = state.locations[i];- if (- state.app.currentLocationId &&- location.uuid === state.app.currentLocationId- ) {- return location.persistTagsInSidecarFile;- }- }- }- return undefined;-};export const isUpdateAvailable = (state: any) => state.app.isUpdateAvailable;export const isUpdateInProgress = (state: any) => state.app.isUpdateInProgress;export const isOnline = (state: any) => state.app.isOnline;@@ -2170,11 +1102,11 @@ export const getLastSelectedEntry = (state: any) => {return undefined;};export const getLastSelectedEntryPath = (state: any) => {- const { selectedEntries, currentDirectoryPath } = state.app;+ const { selectedEntries } = state.app;if (selectedEntries && selectedEntries.length > 0) {return selectedEntries[selectedEntries.length - 1].path;}- return currentDirectoryPath;+ return undefined;};export const getSelectedTag = (state: any) => state.app.tag;export const isTagLibraryChanged = (state: any) => state.app.tagLibraryChanged;@@ -2183,9 +1115,9 @@ export const getSelectedEntries = (state: any) =>export const getSelectedEntriesLength = (state: any) =>state.app.selectedEntries ? state.app.selectedEntries.length : 0;export const getExtensions = (state: any) => state.app.extensions;-export const getDirectoryMeta = (state: any) => state.app.directoryMeta;-export const isGeneratingThumbs = (state: any) => state.app.isGeneratingThumbs;-export const isReadOnlyMode = (state: any) => state.app.isReadOnlyMode;+// export const getDirectoryMeta = (state: any) => state.app.directoryMeta;+// export const isGeneratingThumbs = (state: any) => state.app.isGeneratingThumbs;+// export const isReadOnlyMode = (state: any) => state.app.isReadOnlyMode;export const isOnboardingDialogOpened = (state: any) =>state.app.onboardingDialogOpened;export const isEditTagDialogOpened = (state: any) =>@@ -2219,10 +1151,10 @@ export const isOpenLinkDialogOpened = (state: any) =>export const isProTeaserVisible = (state: any) => state.app.proTeaserIndex > -1;export const getProTeaserIndex = (state: any) => state.app.proTeaserIndex;export const isProgressOpened = (state: any) => state.app.progressDialogOpened;-export const getOpenLink = (state: any) => state.app.openLink;+//export const getOpenLink = (state: any) => state.app.openLink;export const getNotificationStatus = (state: any) =>state.app.notificationStatus;-export const getCurrentLocationId = (state: any) => state.app.currentLocationId;+//export const getCurrentLocationId = (state: any) => state.app.currentLocationId;export const isEntryInFullWidth = (state: any) => state.app.isEntryInFullWidth;//export const isLoading = (state: any) => state.app.isLoading;export const isLocationManagerPanelOpened = (state: any) =>@@ -2232,9 +1164,9 @@ export const isTagLibraryPanelOpened = (state: any) =>export const isSearchPanelOpened = (state: any) => state.app.searchPanelOpened;export const isHelpFeedbackPanelOpened = (state: any) =>state.app.helpFeedbackPanelOpened;-export const getLastSearchTimestamp = (state: any) =>- state.app.lastSearchTimestamp;-export const isSearchMode = (state: any) => state.app.searchMode;+/*export const getLastSearchTimestamp = (state: any) =>+ state.app.lastSearchTimestamp;*/+//export const isSearchMode = (state: any) => state.app.searchMode;export const getSearchFilter = (state: any) => state.app.searchFilter;// export type CreateDirectoryAction = ReturnType<typeof actions.createDirectory>;diff --git a/app/reducers/index.ts b/app/reducers/index.tsindex 8fd4d4d19..63c09e5bf 100644--- a/app/reducers/index.ts+++ b/app/reducers/index.ts@@ -24,14 +24,13 @@ import settings from './settings';import app from './app';import locations from './locations';import taglibrary from './taglibrary';-import locationIndex from './location-index';import searches from './searches';const externalLocations = window.ExtLocations || false;// const externalTagLibrary = window.ExtTagLibrary || false;const externalSearches = window.ExtSearches || false;-const blacklist = ['app', 'locationIndex'];+const blacklist = ['app'];if (!AppConfig.saveLocationsInBrowser &&(externalLocations || AppConfig.isWeb)@@ -112,8 +111,7 @@ const rootReducer = persistCombineReducers(rootPersistConfig, {app,locations: externalLocations ? () => externalLocations : locations,taglibrary, // externalTagLibrary ? () => externalTagLibrary : taglibrary,- searches: externalSearches ? () => externalSearches : searches,- locationIndex+ searches: externalSearches ? () => externalSearches : searches});export default rootReducer;diff --git a/app/reducers/location-index.ts b/app/reducers/location-index.tsdeleted file mode 100644index 2a79c8f55..000000000--- a/app/reducers/location-index.ts+++ /dev/null@@ -1,702 +0,0 @@-/**- * TagSpaces - universal file and folder organizer- * Copyright (C) 2017-present TagSpaces UG (haftungsbeschraenkt)- *- * 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/>.- *- */--import { loadIndex, hasIndex } from '@tagspaces/tagspaces-platforms/indexer';-import { locationType } from '@tagspaces/tagspaces-common/misc';-import { getThumbFileLocationForFile } from '@tagspaces/tagspaces-common/paths';-import AppConfig from '-/AppConfig';-import {- getCurrentLocation,- getLocation,- getLocationByPath,- getLocations-} from './locations';-import { createDirectoryIndex } from '-/services/utils-io';-import Search, { defaultTitle } from '../services/search';-import { actions as AppActions } from './app';-import i18n from '../services/i18n';-import PlatformIO from '../services/platform-facade';-import GlobalSearch from '../services/search-index';-import { TS } from '-/tagspaces.namespace';-import { Pro } from '-/pro';--export const types = {- SET_SEARCH_QUERY: 'SET_SEARCH_QUERY',- INDEX_DIRECTORY: 'INDEX_DIRECTORY',- INDEX_DIRECTORY_CLEAR: 'INDEX_DIRECTORY_CLEAR',- INDEX_DIRECTORY_START: 'INDEX_DIRECTORY_START',- INDEX_DIRECTORY_CANCEL: 'INDEX_DIRECTORY_CANCEL',- INDEX_DIRECTORY_SUCCESS: 'INDEX_DIRECTORY_SUCCESS',- INDEX_DIRECTORY_FAILURE: 'INDEX_DIRECTORY_FAILURE',- INDEX_DIRECTORY_SEARCH: 'INDEX_DIRECTORY_SEARCH'- /*REFLECT_DELETE_ENTRY: 'INDEX/REFLECT_DELETE_ENTRY',- REFLECT_CREATE_ENTRY: 'INDEX/REFLECT_CREATE_ENTRY',- REFLECT_RENAME_ENTRY: 'INDEX/REFLECT_RENAME_ENTRY',- REFLECT_UPDATE_SIDECARTAGS: 'INDEX/REFLECT_UPDATE_SIDECARTAGS',- REFLECT_UPDATE_SIDECARMETA: 'INDEX/REFLECT_UPDATE_SIDECARMETA'*/-};--export const initialState = {- isIndexing: false,- searchQuery: {}-};--export default (state: any = initialState, action: any) => {- switch (action.type) {- case types.SET_SEARCH_QUERY: {- return { ...state, searchQuery: action.searchQuery };- }- case types.INDEX_DIRECTORY_START: {- return {- ...state,- isIndexing: true- };- }- case types.INDEX_DIRECTORY_CLEAR: {- /*if (GlobalSearch.index) {- GlobalSearch.index.splice(0, GlobalSearch.index.length);- }*/- GlobalSearch.getInstance().setIndex([]);- GlobalSearch.getInstance().setIndexLoadedOn(undefined);- return {- ...state,- isIndexing: false- };- }- case types.INDEX_DIRECTORY_CANCEL: {- window.walkCanceled = true;- return { ...state, isIndexing: false };- }- case types.INDEX_DIRECTORY_SUCCESS: {- return {- ...state,- isIndexing: false- };- }- case types.INDEX_DIRECTORY_FAILURE: {- return {- ...state,- lastError: action.error,- isIndexing: false- };- }- /*case types.REFLECT_DELETE_ENTRY: {- const index = GlobalSearch.getInstance().getIndex();- if (!index || index.length < 1) {- return state;- }- for (let i = 0; i < index.length; i += 1) {- if (index[i].path === action.path) {- GlobalSearch.getInstance().setIndex(index.splice(i, 1));- i -= 1;- }- }- return state;- }*/- /*case types.REFLECT_CREATE_ENTRY: {- const index = GlobalSearch.getInstance().getIndex();- if (!index || index.length < 1) {- return state;- }- let entryFound = false;- for (let i = 0; i < index.length; i += 1) {- if (index[i].path === action.path) {- entryFound = true;- }- }- if (entryFound) {- return state;- }- GlobalSearch.getInstance().setIndex([...index, action.newEntry]);- return state;- }*/- // TODO move it from reducer to GlobalSearch singleton- /* case types.REFLECT_RENAME_ENTRY: {- const index = GlobalSearch.getInstance().getIndex();- if (!index || index.length < 1) {- return state;- }- for (let i = 0; i < index.length; i += 1) {- if (index[i].path === action.path) {- index[i].path = action.newPath;- index[i].name = extractFileName(- action.newPath,- PlatformIO.getDirSeparator()- );- index[i].extension = extractFileExtension(- action.newPath,- PlatformIO.getDirSeparator()- );- index[i].tags = [- ...index[i].tags.filter(tag => tag.type === 'sidecar'), // add only sidecar tags- ...extractTagsAsObjects(- action.newPath,- AppConfig.tagDelimiter,- PlatformIO.getDirSeparator()- )- ];- }- }- return state;- }*/- /*case types.REFLECT_UPDATE_SIDECARTAGS: {- const index = GlobalSearch.getInstance().getIndex();- for (let i = 0; i < index.length; i += 1) {- if (index[i].path === action.path) {- index[i].tags = [- ...index[i].tags.filter(tag => tag.type === 'plain'),- ...action.tags- ];- }- }- return state;- }*/- /*case types.REFLECT_UPDATE_SIDECARMETA: {- const index = GlobalSearch.getInstance().getIndex();- for (let i = 0; i < index.length; i += 1) {- if (index[i].path === action.path) {- index[i] = {- ...index[i],- ...action.entryMeta- };- }- }- return state;- }*/- default: {- return state;- }- }-};--export const actions = {- setSearchQuery: (searchQuery: TS.SearchQuery) => (- dispatch: (action) => void,- getState: () => any- ) => {- dispatch(actions.setSearchQueryInt(searchQuery));- // TODO rethink right place for this -to switch search mode based on searchQuery- if (Object.keys(searchQuery).length === 0) {- dispatch(AppActions.exitSearchMode());- } else {- const searchTitle = defaultTitle(searchQuery);- if (searchTitle.length > 0 && Pro && Pro.history) {- const historyKeys = Pro.history.historyKeys;- const currentLocation = getCurrentLocation(getState());- if (currentLocation) {- Pro.history.saveHistory(- historyKeys.searchHistoryKey,- {- path:- searchTitle +- ' ' +- (currentLocation.path- ? currentLocation.path- : currentLocation.name),- url: '/',- lid: currentLocation.uuid,- searchQuery: searchQuery- },- getState().settings[historyKeys.searchHistoryKey]- );- }- }- dispatch(AppActions.enterSearchMode());- }- },- setSearchQueryInt: (searchQuery: TS.SearchQuery) => ({- type: types.SET_SEARCH_QUERY,- searchQuery- }),- startDirectoryIndexing: () => ({ type: types.INDEX_DIRECTORY_START }),- cancelDirectoryIndexing: () => ({ type: types.INDEX_DIRECTORY_CANCEL }),- createDirectoryIndex: (- directoryPath: string,- extractText: boolean,- isCurrentLocation = true,- locationID: string = undefined,- ignorePatterns: Array<string> = []- ) => (dispatch: (actions: Object) => void, getState: () => any) => {- const { settings } = getState();- dispatch(actions.startDirectoryIndexing());- createDirectoryIndex(- { path: directoryPath, locationID },- extractText,- ignorePatterns,- settings.enableWS- )- .then(directoryIndex => {- if (isCurrentLocation) {- // Load index only if current location- GlobalSearch.getInstance().setIndex(directoryIndex);- }- dispatch(actions.indexDirectorySuccess());- /* if (Pro && Pro.Indexer) {- Pro.Indexer.persistIndex(- directoryPath,- directoryIndex,- PlatformIO.getDirSeparator()- );- } */- return true;- })- .catch(err => {- dispatch(actions.indexDirectoryFailure(err));- });- },- createLocationIndex: (location: TS.Location) => (- dispatch: (actions: Object) => void,- getState: () => any- ) => {- if (location) {- const { currentLocationId } = getState().app;- const isCurrentLocation = currentLocationId === location.uuid;- if (location.type === locationType.TYPE_CLOUD) {- PlatformIO.enableObjectStoreSupport(location)- .then(() => {- dispatch(- actions.createDirectoryIndex(- PlatformIO.getLocationPath(location),- location.fullTextIndex,- isCurrentLocation,- location.uuid- )- );- return true;- })- .catch(() => {- PlatformIO.disableObjectStoreSupport();- });- } else if (location.type === locationType.TYPE_WEBDAV) {- PlatformIO.enableWebdavSupport(location);- dispatch(- actions.createDirectoryIndex(- PlatformIO.getLocationPath(location),- location.fullTextIndex,- isCurrentLocation,- location.uuid- )- );- } else if (location.type === locationType.TYPE_LOCAL) {- PlatformIO.disableObjectStoreSupport();- dispatch(- actions.createDirectoryIndex(- PlatformIO.getLocationPath(location),- location.fullTextIndex,- isCurrentLocation,- location.uuid- )- );- }- }- },- createLocationsIndexes: (extractText = true) => (- dispatch: (actions: Object) => void,- getState: () => any- ) => {- const state = getState();- dispatch(actions.startDirectoryIndexing());- const allLocations = getLocations(state);-- const promises = allLocations.map((location: TS.Location) => {- const nextPath = PlatformIO.getLocationPath(location);- return (- createDirectoryIndex(- { path: nextPath, location: location.uuid },- extractText,- location.ignorePatternPaths,- state.settings.enableWS- )- /* .then(directoryIndex => {- if (Pro && Pro.Indexer) {- Pro.Indexer.persistIndex(- nextPath,- directoryIndex,- PlatformIO.getDirSeparator()- );- }- return true;- }) */- .catch(err => {- dispatch(actions.indexDirectoryFailure(err));- })- );- });-- Promise.all(promises)- .then(e => {- dispatch(actions.indexDirectorySuccess());- console.log('Resolution is complete!', e);- return true;- })- .catch(e => {- console.warn('Resolution is faled!', e);- });- },- clearDirectoryIndex: () => ({- type: types.INDEX_DIRECTORY_CLEAR- }),- searchLocationIndex: (searchQuery: TS.SearchQuery) => (- dispatch: (actions: Object) => void,- getState: () => any- ) => {- const state = getState();- let currentLocation: TS.Location = getLocation(- state,- state.app.currentLocationId- );- window.walkCanceled = false;- if (!currentLocation) {- if (searchQuery.currentDirectory) {- currentLocation = getLocationByPath(- state,- searchQuery.currentDirectory- );- }- }- if (!currentLocation) {- dispatch(- AppActions.showNotification(- i18n.t('core:pleaseOpenLocation'),- 'warning',- true- )- );- return;- }-- const isCloudLocation = currentLocation.type === locationType.TYPE_CLOUD;- dispatch(- AppActions.showNotification(- i18n.t('core:searching'),- 'default',- false,- 'TIDSearching'- )- );- setTimeout(async () => {- const index = GlobalSearch.getInstance().getIndex();- // Workaround used to show the start search notification- const currentTime = new Date().getTime();- const indexAge = GlobalSearch.getInstance().getIndexLoadedOn()- ? currentTime - GlobalSearch.getInstance().getIndexLoadedOn()- : 0;- const maxIndexAge = currentLocation.maxIndexAge- ? currentLocation.maxIndexAge- : AppConfig.maxIndexAge;- if (- searchQuery.forceIndexing ||- (!currentLocation.disableIndexing &&- (!index || index.length < 1 || indexAge > maxIndexAge))- ) {- const currentPath = PlatformIO.getLocationPath(currentLocation);- console.log('Start creating index for : ' + currentPath);- const newIndex = await createDirectoryIndex(- {- path: currentPath,- locationID: currentLocation.uuid,- ...(isCloudLocation && { bucketName: currentLocation.bucketName })- },- currentLocation.fullTextIndex,- currentLocation.ignorePatternPaths,- state.settings.enableWS- );- GlobalSearch.getInstance().setIndex(newIndex);-- if (newIndex && newIndex.length > 0) {- GlobalSearch.getInstance().setIndexLoadedOn(new Date().getTime());- }- } else if (isCloudLocation || !index || index.length === 0) {- const newIndex = await loadIndex(- {- path: PlatformIO.getLocationPath(currentLocation),- locationID: currentLocation.uuid,- ...(isCloudLocation && { bucketName: currentLocation.bucketName })- },- PlatformIO.getDirSeparator(),- PlatformIO.loadTextFilePromise- );- GlobalSearch.getInstance().setIndex(newIndex);- }- Search.searchLocationIndex(- GlobalSearch.getInstance().getIndex(),- searchQuery- )- .then(searchResults => {- if (isCloudLocation) {- searchResults.forEach((entry: TS.FileSystemEntry) => {- if (- entry.thumbPath &&- entry.thumbPath.length > 1- // !entry.thumbPath.startsWith('http')- ) {- const thumbPath = entry.path.startsWith('/')- ? entry.path.substring(1)- : entry.path;- // eslint-disable-next-line no-param-reassign- entry.thumbPath = PlatformIO.getURLforPath(- getThumbFileLocationForFile(- thumbPath,- PlatformIO.getDirSeparator()- )- );- }- });- }- dispatch(AppActions.setSearchResults(searchResults));- dispatch(AppActions.hideNotifications());- return true;- })- .catch(err => {- dispatch(AppActions.setSearchResults([]));- // dispatch(AppActions.hideNotifications());- console.error('Searching Index failed: ', err);- dispatch(- AppActions.showNotification(- i18n.t('core:searchingFailed') + ' ' + err.message,- 'warning',- true- )- );- });- }, 50);- },- searchAllLocations: (searchQuery: TS.SearchQuery) => (- dispatch: (actions: Object) => void,- getState: () => any- ) => {- const state = getState();- const currentLocation: TS.Location = getLocation(- state,- state.app.currentLocationId- );- console.time('globalSearch');- dispatch(- AppActions.showNotification(- i18n.t('core:searching'),- 'default',- false,- 'TIDSearching'- )- );-- // Preparing for global search- dispatch(AppActions.setSearchResults([]));- if (currentLocation && currentLocation.type === locationType.TYPE_CLOUD) {- PlatformIO.disableObjectStoreSupport();- }- window.walkCanceled = false;- const allLocations = getLocations(state);- let searchResultCount = 0;- let maxSearchResultReached = false;-- const result = allLocations.reduce(- (accumulatorPromise, location) =>- accumulatorPromise.then(async () => {- // cancel search if max search result count reached- if (searchResultCount >= searchQuery.maxSearchResults) {- maxSearchResultReached = true;- return Promise.resolve();- }- const nextPath = PlatformIO.getLocationPath(location);- let directoryIndex = [];- let indexExist = false;- const isCloudLocation = location.type === locationType.TYPE_CLOUD;- console.log('Searching in: ' + nextPath);- dispatch(- AppActions.showNotification(- i18n.t('core:searching') + ' ' + location.name,- 'default',- true,- 'TIDSearching'- )- );- if (isCloudLocation) {- await PlatformIO.enableObjectStoreSupport(location);- }- // if (Pro && Pro.Indexer && Pro.Indexer.hasIndex) {- indexExist = await hasIndex(- nextPath,- PlatformIO.getPropertiesPromise- ); // , PlatformIO.getDirSeparator());-- if (- searchQuery.forceIndexing ||- (!location.disableIndexing && !indexExist)- ) {- console.log('Creating index for : ' + nextPath);- directoryIndex = await createDirectoryIndex(- {- path: nextPath,- locationID: location.uuid,- ...(isCloudLocation && { bucketName: location.bucketName })- },- location.fullTextIndex,- location.ignorePatternPaths,- state.settings.enableWS- );- /* if (Pro && Pro.Indexer && Pro.Indexer.persistIndex) {- Pro.Indexer.persistIndex(- nextPath,- directoryIndex,- PlatformIO.getDirSeparator()- );- } */- } else {- // if (Pro && Pro.Indexer && Pro.Indexer.loadIndex) {- console.log('Loading index for : ' + nextPath);- directoryIndex = await loadIndex(- {- path: nextPath,- locationID: location.uuid,- ...(isCloudLocation && {- bucketName: currentLocation.bucketName- })- },- PlatformIO.getDirSeparator(),- PlatformIO.loadTextFilePromise- );- }- return Search.searchLocationIndex(directoryIndex, searchQuery)- .then((searchResults: Array<TS.FileSystemEntry>) => {- let enhancedSearchResult = searchResults;- if (isCloudLocation) {- enhancedSearchResult = searchResults- // Excluding s3 folders from global search- .filter(entry => entry && entry.isFile)- .map((entry: TS.FileSystemEntry) => {- const cleanedPath = entry.path.startsWith('/')- ? entry.path.substr(1)- : entry.path;- const url = PlatformIO.getURLforPath(cleanedPath);- let thumbPath;- if (- entry.thumbPath &&- entry.thumbPath.length > 1 &&- !entry.thumbPath.startsWith('http')- ) {- thumbPath = PlatformIO.getURLforPath(entry.thumbPath);- }- return { ...entry, url, thumbPath };- });- }-- searchResultCount += enhancedSearchResult.length;- dispatch(AppActions.appendSearchResults(enhancedSearchResult));- dispatch(AppActions.hideNotifications());- if (isCloudLocation) {- PlatformIO.disableObjectStoreSupport();- }- return true;- })- .catch(e => {- if (isCloudLocation) {- PlatformIO.disableObjectStoreSupport();- }- console.error('Searching Index failed: ', e);- dispatch(AppActions.setSearchResults([]));- // dispatch(AppActions.hideNotifications());- dispatch(- AppActions.showNotification(- i18n.t('core:searchingFailed') + ' ' + e.message,- 'warning',- true- )- );- });- }),- Promise.resolve()- );-- result- .then(() => {- console.timeEnd('globalSearch');- if (maxSearchResultReached) {- dispatch(- AppActions.showNotification(- 'Global search finished, reaching the max. search results. The first ' +- searchResultCount +- ' entries are listed.',- 'default',- true- )- );- } else {- dispatch(- AppActions.showNotification(- i18n.t('Global search completed'),- 'default',- true- )- );- }- console.log('Global search completed!');- if (- currentLocation &&- currentLocation.type === locationType.TYPE_CLOUD- ) {- PlatformIO.enableObjectStoreSupport(currentLocation);- }- return true;- })- .catch(e => {- if (- currentLocation &&- currentLocation.type === locationType.TYPE_CLOUD- ) {- PlatformIO.enableObjectStoreSupport(currentLocation);- }- console.timeEnd('globalSearch');- console.warn('Global search failed!', e);- });- },- indexDirectorySuccess: () => ({- type: types.INDEX_DIRECTORY_SUCCESS- }),- indexDirectoryFailure: (error: string) => ({- type: types.INDEX_DIRECTORY_FAILURE,- error- })- /*reflectDeleteEntry: (path: string) => ({- type: types.REFLECT_DELETE_ENTRY,- path- }),*/- /*reflectCreateEntry: (newEntry: Object) => ({- type: types.REFLECT_CREATE_ENTRY,- newEntry- }),*/- /*reflectRenameEntry: (path: string, newPath: string) => ({- type: types.REFLECT_RENAME_ENTRY,- path,- newPath- }),*/- /*reflectUpdateSidecarTags: (path: string, tags: Array<TS.Tag>) => ({- type: types.REFLECT_UPDATE_SIDECARTAGS,- path,- tags- }),*/- /*reflectUpdateSidecarMeta: (path: string, entryMeta: Object) => ({- type: types.REFLECT_UPDATE_SIDECARMETA,- path,- entryMeta- })*/-};--// Selectors-export const isIndexing = (state: any) => state.locationIndex.isIndexing;-export const getSearchQuery = (state: any) => state.locationIndex.searchQuery;diff --git a/app/reducers/locations.ts b/app/reducers/locations.tsindex 6ee5581f5..262669460 100644--- a/app/reducers/locations.ts+++ b/app/reducers/locations.ts@@ -154,62 +154,6 @@ export default (state: Array<TS.Location> = initialState, action: any) => {};export const actions = {- setDefaultLocations: t => (dispatch: (actions: Object) => void) => {- PlatformIO.getDevicePaths()- .then(devicePaths => {- if (devicePaths) {- Object.keys(devicePaths).forEach(key => {- dispatch(- actions.addLocation(- {- uuid: getUuid(),- type: locationType.TYPE_LOCAL,- name: t('core:' + key) as string,- path: devicePaths[key] as string,- isDefault: false, // AppConfig.isWeb && devicePaths[key] === '/files/', // Used for the web ts demo- isReadOnly: false,- disableIndexing: false- },- false- )- );- });- }- return true;- })- .catch(ex => console.error(ex));- },- addLocation: (- location: TS.Location,- openAfterCreate = true,- locationPosition: number = undefined- ) => (dispatch: (actions: Object) => void) => {- dispatch(actions.createLocation(location, locationPosition));- if (openAfterCreate) {- dispatch(AppActions.openLocation(location));- }- },- /**- * @param arrLocations- * @param override = true - if location exist override else skip- */- addLocations: (arrLocations: Array<TS.Location>, override = true) => (- dispatch: (actions: Object) => void,- getState: () => any- ) => {- arrLocations.forEach((newLocation: TS.Location, idx, array) => {- const { locations } = getState();- const locationExist: boolean = locations.some(- location => location.uuid === newLocation.uuid- );- const isLast = idx === array.length - 1;- if (!locationExist) {- dispatch(actions.addLocation(newLocation, isLast));- } else if (override) {- dispatch(actions.editLocation(newLocation, isLast));- }- });- },createLocation: (location: TS.Location,locationPosition: number = undefined@@ -228,7 +172,7 @@ export const actions = {type: types.MOVE_DOWN_LOCATION,uuid}),- editLocation: (location: TS.Location, openAfterEdit = true) => (+ /*editLocation: (location: TS.Location, openAfterEdit = true) => (dispatch: (actions: Object) => void) => {dispatch(actions.changeLocation(location));@@ -241,9 +185,9 @@ export const actions = {PlatformIO.disableWebdavSupport();}if (openAfterEdit) {- /**+ /!*** check if location uuid is changed- */+ *!/if (location.newuuid !== undefined &&location.newuuid !== location.uuid@@ -256,8 +200,8 @@ export const actions = {}dispatch(AppActions.setReadOnlyMode(location.isReadOnly || false));}- },- switchLocationType: (locationId: string) => (+ },*/+ /*switchLocationType: (locationId: string) => (dispatch: (actions) => Promise<string | null>,getState: () => any): Promise<string | null> => {@@ -269,17 +213,17 @@ export const actions = {return dispatch(AppActions.switchLocationType(location));}return Promise.resolve(null);- },+ },*/changeLocation: (location: TS.Location) => ({type: types.EDIT_LOCATION,location}),- removeLocation: (location: TS.Location) => (+ /*removeLocation: (location: TS.Location) => (dispatch: (actions: Object) => void) => {- dispatch(AppActions.closeLocation(location.uuid));+ //dispatch(AppActions.closeLocation(location.uuid));dispatch(actions.deleteLocation(location));- },+ },*/deleteLocation: (location: TS.Location) => ({type: types.REMOVE_LOCATION,location@@ -293,8 +237,8 @@ export const getLocation = (locationId: string): TS.Location | null =>state.locations.find(location => location.uuid === locationId);-export const getLocationPosition = (state: any, locationId: string): number =>- state.locations.findIndex(location => location.uuid === locationId);+/*export const getLocationPosition = (state: any, locationId: string): number =>+ state.locations.findIndex(location => location.uuid === locationId);*/export const getLocationByPath = (state: any,path: string@@ -304,12 +248,12 @@ export const getDefaultLocationId = (state: any): string | undefined => {let foundLocation = state.locations.find(location => location.isDefault);return foundLocation ? foundLocation.uuid : undefined;};-export const getCurrentLocation = (state: any): TS.Location | undefined => {+/*export const getCurrentLocation = (state: any): TS.Location | undefined => {let foundLocation = state.locations.find(location => location.uuid === state.app.currentLocationId);return foundLocation ? foundLocation : undefined;-};+};*/export const getFirstRWLocation = (state: any): TS.Location | undefined => {let foundLocation = state.locations.find(location => location.isDefault && !location.isReadOnlydiff --git a/app/reducers/tagging-actions.ts b/app/reducers/tagging-actions.tsdeleted file mode 100644index 9377717cd..000000000--- a/app/reducers/tagging-actions.ts+++ /dev/null@@ -1,920 +0,0 @@-/*-/!**- * TagSpaces - universal file and folder organizer- * Copyright (C) 2017-present TagSpaces UG (haftungsbeschraenkt)- *- * 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/>.- *- *!/-import OpenLocationCode from 'open-location-code-typescript';-import mgrs from 'mgrs';-import { formatDateTime4Tag } from '@tagspaces/tagspaces-common/misc';-import i18n from '../services/i18n';-import {- actions as AppActions,- getLocationPersistTagsInSidecarFile-} from './app';-import {- extractFileExtension,- extractFileName,- extractTags,- extractTitle,- extractContainingDirectoryPath-} from '@tagspaces/tagspaces-common/paths';-import {- loadMetaDataPromise,- saveMetaDataPromise,- generateFileName,- loadFileMetaDataPromise,- loadDirMetaDataPromise-} from '-/services/utils-io';-import { isGeoTag } from '-/utils/geo';-import PlatformIO from '../services/platform-facade';-import { Pro } from '../pro';-import GlobalSearch from '../services/search-index';-import { getPersistTagsInSidecarFile } from './settings';-import { TS } from '-/tagspaces.namespace';-import { getTagLibrary, mergeTagGroup } from '-/services/taglibrary-utils';--// export const defaultTagLocation = OpenLocationCode.encode(51.48, 0, undefined); // default tag coordinate Greenwich--const persistTagsInSidecarFile = state => {- const locationPersistTagsInSidecarFile = getLocationPersistTagsInSidecarFile(- state- );- if (locationPersistTagsInSidecarFile !== undefined) {- return locationPersistTagsInSidecarFile;- }- return getPersistTagsInSidecarFile(state);-};--const actions = {- addTags: (paths: Array<string>, tags: Array<TS.Tag>, updateIndex = true) => (- dispatch: (action) => void,- getState: () => any- ): Promise<boolean> => {- const { settings } = getState();- let defaultTagLocation;- if (settings.geoTaggingFormat.toLowerCase() === 'mgrs') {- defaultTagLocation = mgrs.forward([0, 51.48]);- } else {- defaultTagLocation = OpenLocationCode.encode(51.48, 0, undefined);- }-- const processedTags = [];- tags.map(pTag => {- const tag = { ...pTag };- tag.type = 'sidecar';- if (tag.id) {- delete tag.id;- }- if (tag.functionality && tag.functionality.length > 0) {- delete tag.color;- delete tag.textcolor;- delete tag.icon;- delete tag.description;- if (tag.functionality === 'geoTagging') {- if (Pro) {- tag.path = paths[0]; // todo rethink and remove this!- // delete tag.functionality;- tag.title = defaultTagLocation;- dispatch(AppActions.toggleEditTagDialog(tag));- } else {- dispatch(- AppActions.showNotification(- i18n.t('core:thisFunctionalityIsAvailableInPro')- )- );- }- } else if (tag.functionality === 'dateTagging') {- if (Pro) {- tag.path = paths[0]; // todo rethink and remove this!- // delete tag.functionality;- tag.title = formatDateTime4Tag(new Date(), true); // defaultTagDate;- dispatch(AppActions.toggleEditTagDialog(tag));- } else {- dispatch(- AppActions.showNotification(- i18n.t('core:thisFunctionalityIsAvailableInPro')- )- );- }- } else {- tag.title = generateTagValue(tag);- delete tag.functionality;- processedTags.push(tag);- }- } else {- processedTags.push(tag);- }- return true;- });-- if (processedTags.length > 0) {- const promises = paths.map(path =>- dispatch(actions.addTagsToEntry(path, processedTags, updateIndex))- );-- if (settings.addTagsToLibrary) {- // collecting tags- // filter existed in tagLibrary- const uniqueTags = [];- processedTags.map(tag => {- if (- getTagLibrary().findIndex(- tagGroup =>- tagGroup.children.findIndex(obj => obj.title === tag.title) !==- -1- ) === -1 &&- !/^(?:\d+~\d+|\d+)$/.test(tag.title) && // skip adding of tag containing only digits- !isGeoTag(tag.title) // skip adding of tag containing geo information- ) {- uniqueTags.push({- ...tag,- color: tag.color || settings.tagBackgroundColor,- textcolor: tag.textcolor || settings.tagTextColor- });- }- return true;- });- if (uniqueTags.length > 0) {- const tagGroup = {- uuid: 'collected_tag_group_id', // uuid needs to be constant here (see mergeTagGroup)- title: i18n.t('core:collectedTags'),- color: settings.tagBackgroundColor,- textcolor: settings.tagTextColor,- children: uniqueTags,- created_date: new Date().getTime(),- modified_date: new Date().getTime()- };- mergeTagGroup(tagGroup, getTagLibrary());- dispatch(AppActions.tagLibraryChanged());- }- }- return Promise.all(promises).then(() => true);- }- return Promise.resolve(false);- },- addTagsToEntry: (- path: string,- tags: Array<TS.Tag>,- updateIndex = true- ) => async (- dispatch: (actions: Object) => Promise<boolean>,- getState: () => any- ): Promise<boolean> => {- const { settings } = getState();- const entryProperties = await PlatformIO.getPropertiesPromise(path);- let fsEntryMeta;- try {- fsEntryMeta = entryProperties.isFile- ? await loadFileMetaDataPromise(path)- : await loadDirMetaDataPromise(path);- } catch (error) {- console.log('No sidecar found ' + error);- }-- if (!entryProperties.isFile || persistTagsInSidecarFile(getState())) {- // Handling adding tags in sidecar- if (fsEntryMeta) {- const uniqueTags = getNonExistingTags(- tags,- extractTags(- path,- settings.tagDelimiter,- PlatformIO.getDirSeparator()- ),- fsEntryMeta.tags- );- if (uniqueTags.length > 0) {- const newTags = [...fsEntryMeta.tags, ...uniqueTags];- const updatedFsEntryMeta = {- ...fsEntryMeta,- tags: newTags- };- return saveMetaDataPromise(path, updatedFsEntryMeta)- .then(() => {- dispatch(- // TODO rethink this updateCurrentDirEntry and not need for KanBan- AppActions.reflectUpdateSidecarTags(path, newTags, updateIndex)- );- const { openedFiles } = getState().app;- if (openedFiles.find(obj => obj.path === path)) {- return dispatch(- AppActions.updateOpenedFile(path, {- tags: newTags- })- );- }- return true;- })- .catch(err => {- console.warn('Error adding tags for ' + path + ' with ' + err);- dispatch(- AppActions.showNotification(- i18n.t('core:addingTagsFailed'),- 'error',- true- )- );- return false;- });- }- } else {- const newFsEntryMeta = { tags };- return saveMetaDataPromise(path, newFsEntryMeta)- .then(() => {- dispatch(- // TODO rethink this updateCurrentDirEntry and not need for KanBan- AppActions.reflectUpdateSidecarTags(path, tags, updateIndex)- );- const { openedFiles } = getState().app;- if (openedFiles.find(obj => obj.path === path)) {- return dispatch(- AppActions.updateOpenedFile(path, { tags, changed: true })- );- }- return true;- })- .catch(error => {- console.warn('Error adding tags for ' + path + ' with ' + error);- dispatch(- AppActions.showNotification(- i18n.t('core:addingTagsFailed'),- 'error',- true- )- );- return true;- });- }- } else if (fsEntryMeta) {- // Handling tags in filename by existing sidecar- const extractedTags = extractTags(- path,- settings.tagDelimiter,- PlatformIO.getDirSeparator()- );- const uniqueTags = getNonExistingTags(- tags,- extractedTags,- fsEntryMeta.tags- );- if (uniqueTags.length > 0) {- const fileName = extractFileName(path, PlatformIO.getDirSeparator());- const containingDirectoryPath = extractContainingDirectoryPath(- path,- PlatformIO.getDirSeparator()- );-- for (let i = 0; i < uniqueTags.length; i += 1) {- extractedTags.push(uniqueTags[i].title);- }- const newFilePath =- (containingDirectoryPath- ? containingDirectoryPath + PlatformIO.getDirSeparator()- : '') +- generateFileName(- fileName,- extractedTags,- settings.tagDelimiter,- settings.prefixTagContainer- );- return dispatch(AppActions.renameFile(path, newFilePath));- }- } else {- // Handling tags in filename by no sidecar- const fileName = extractFileName(path, PlatformIO.getDirSeparator());- const containingDirectoryPath = extractContainingDirectoryPath(- path,- PlatformIO.getDirSeparator()- );- const extractedTags = extractTags(- path,- settings.tagDelimiter,- PlatformIO.getDirSeparator()- );- for (let i = 0; i < tags.length; i += 1) {- // check if tag is already in the tag array- if (extractedTags.indexOf(tags[i].title) < 0) {- // Adding the new tag- extractedTags.push(tags[i].title);- }- }- const newFilePath =- (containingDirectoryPath- ? containingDirectoryPath + PlatformIO.getDirSeparator()- : '') +- generateFileName(- fileName,- extractedTags,- settings.tagDelimiter,- settings.prefixTagContainer- );- if (path !== newFilePath) {- return dispatch(AppActions.renameFile(path, newFilePath));- }- }- return Promise.resolve(false);-- function getNonExistingTags(- newTagsArray: Array<TS.Tag>,- fileTagsArray: Array<string>,- sideCarTagsArray: Array<TS.Tag>- ) {- const newTags = [];- for (let i = 0; i < newTagsArray.length; i += 1) {- // check if tag is already in the fileTagsArray- if (fileTagsArray.indexOf(newTagsArray[i].title) === -1) {- // check if tag is already in the sideCarTagsArray- if (- sideCarTagsArray.findIndex(- sideCarTag => sideCarTag.title === newTagsArray[i].title- ) === -1- ) {- newTags.push(newTagsArray[i]);- }- }- }- return newTags;- }- },- /!**- * if Tag not exist in meta it will be added see: addMode- * @param path- * @param tag- * @param newTagTitle- * @returns {Function}- *!/- editTagForEntry: (path: string, tag: TS.Tag, newTagTitle?: string) => async (- dispatch: (actions: Object) => void,- getState: () => any- ) => {- const { settings } = getState();- if (newTagTitle === undefined) {- // eslint-disable-next-line no-param-reassign- newTagTitle = tag.title;- }- if (- tag.functionality === 'geoTagging' ||- tag.functionality === 'dateTagging'- ) {- // Work around solution- delete tag.functionality;- const entryProperties = await PlatformIO.getPropertiesPromise(path);- if (entryProperties.isFile && !persistTagsInSidecarFile(getState())) {- tag.type = 'plain';- }- }- delete tag.description;- delete tag.functionality;- delete tag.path;- delete tag.id;-- const extractedTags: string[] = extractTags(- path,- settings.tagDelimiter,- PlatformIO.getDirSeparator()- );- // TODO: Handle adding already added tags- if (extractedTags.includes(tag.title)) {- // tag.type === 'plain') {- const fileName = extractFileName(path, PlatformIO.getDirSeparator());- const containingDirectoryPath = extractContainingDirectoryPath(- path,- PlatformIO.getDirSeparator()- );-- let tagFoundPosition = -1;- for (let i = 0; i < extractedTags.length; i += 1) {- // check if tag is already in the tag array- if (extractedTags[i] === tag.title) {- extractedTags[i] = newTagTitle.trim();- tagFoundPosition = i;- }- }- if (tagFoundPosition === -1) {- // needed for the current implementation of geo tagging- extractedTags.push(newTagTitle); // tag.title);- } else if (tag.position !== undefined) {- // move tag- const element = extractedTags[tagFoundPosition];- extractedTags.splice(tagFoundPosition, 1);- extractedTags.splice(tag.position, 0, element);- }- const newFileName = generateFileName(- fileName,- extractedTags,- settings.tagDelimiter,- settings.prefixTagContainer- );- if (newFileName !== fileName) {- dispatch(- AppActions.renameFile(- path,- containingDirectoryPath + PlatformIO.getDirSeparator() + newFileName- )- );- }- } else {- //if (tag.type === 'sidecar') {- loadMetaDataPromise(path)- .then(fsEntryMeta => {- let tagFoundPosition = -1;- let newTagsArray = fsEntryMeta.tags.map((sidecarTag, index) => {- if (sidecarTag.title === tag.title) {- tagFoundPosition = index;- return {- ...sidecarTag,- title: newTagTitle- };- }- return sidecarTag;- });- if (tag.position !== undefined && tagFoundPosition > -1) {- // move tag (reorder)- const element = newTagsArray[tagFoundPosition];- newTagsArray.splice(tagFoundPosition, 1);- newTagsArray.splice(tag.position, 0, element);- }- if (tagFoundPosition === -1) {- // Add mode- newTagsArray.push({ ...tag, title: newTagTitle });- }- // clear duplicates- newTagsArray = newTagsArray.filter(- (item, pos, array) =>- array.findIndex(el => el.title === item.title) === pos- );- saveMetaDataPromise(path, {- ...fsEntryMeta,- tags: newTagsArray- })- .then(() => {- const { openedFiles } = getState().app;- if (openedFiles.find(obj => obj.path === path)) {- dispatch(- AppActions.updateOpenedFile(path, {- tags: newTagsArray- })- );- }- // TODO rethink this updateCurrentDirEntry and not need for KanBan- dispatch(- AppActions.reflectUpdateSidecarTags(path, newTagsArray, true)- );- return true;- })- .catch(err => {- console.warn('Error adding tags for ' + path + ' with ' + err);- dispatch(- AppActions.showNotification(- i18n.t('core:addingTagsFailed'),- 'error',- true- )- );- });- return true;- })- .catch(error => {- // json metadata not exist -create the new one- console.warn(- 'json metadata not exist create new ' + path + ' with ' + error- );- // dispatch(AppActions.showNotification(i18n.t('core:addingTagsFailed'), 'error', true));- // eslint-disable-next-line no-param-reassign- tag.title = newTagTitle;- const fsEntryMeta = { tags: [tag] };- saveMetaDataPromise(path, fsEntryMeta)- .then(() => {- const { openedFiles } = getState().app;- if (openedFiles.find(obj => obj.path === path)) {- dispatch(- AppActions.updateOpenedFile(path, {- tags: fsEntryMeta.tags- })- );- }- // TODO rethink this updateCurrentDirEntry and not need for KanBan- dispatch(- AppActions.reflectUpdateSidecarTags(path, fsEntryMeta.tags)- );- return true;- })- .catch(err => {- console.warn('Error adding tags for ' + path + ' with ' + err);- dispatch(- AppActions.showNotification(- i18n.t('core:addingTagsFailed'),- 'error',- true- )- );- });- });- }-- if (settings.addTagsToLibrary) {- // collecting tags- // filter existed in tagLibrary- const uniqueTags = [];- if (- getTagLibrary().findIndex(- tagGroup =>- tagGroup.children.findIndex(obj => obj.title === newTagTitle) !== -1- ) === -1 &&- !/^(?:\d+~\d+|\d+)$/.test(newTagTitle) &&- !isGeoTag(newTagTitle) // skip adding of tag containing only digits or geo tags- ) {- uniqueTags.push({- ...tag,- title: newTagTitle,- color: tag.color || settings.tagBackgroundColor,- textcolor: tag.textcolor || settings.tagTextColor- });- }- if (uniqueTags.length > 0) {- const tagGroup = {- uuid: 'collected_tag_group_id', // uuid needs to be constant here (see mergeTagGroup)- title: i18n.t('core:collectedTags'),- color: settings.tagBackgroundColor,- textcolor: settings.tagTextColor,- children: uniqueTags,- created_date: new Date().getTime(),- modified_date: new Date().getTime()- };- mergeTagGroup(tagGroup, getTagLibrary());- dispatch(AppActions.tagLibraryChanged());- }- }- },- removeTags: (paths: Array<string>, tags?: Array<TS.Tag>) => async (- dispatch: (actions: Object) => Promise<boolean>- ): Promise<boolean> => {- for (const path of paths) {- const success = await dispatch(actions.removeTagsFromEntry(path, tags));- if (!success) {- return Promise.resolve(false);- }- }- return Promise.resolve(true);- },- /!**- * @param path- * @param tags? if undefined will remove all tags- *!/- removeTagsFromEntry: (path: string, tags?: Array<TS.Tag>) => (- dispatch: (actions: Object) => Promise<boolean>,- getState: () => any- ): Promise<boolean> => {- const { settings } = getState();- const tagTitlesForRemoving = tags ? tags.map(tag => tag.title) : undefined;- return loadMetaDataPromise(path)- .then((fsEntryMeta: TS.FileSystemEntryMeta) => {- const newTags = tagTitlesForRemoving- ? fsEntryMeta.tags.filter(- sidecarTag => !tagTitlesForRemoving.includes(sidecarTag.title)- )- : [];-- return removeTagsFromFilename(fsEntryMeta.isFile).then(newFilePath => {- return removeTagsFromSideCar(fsEntryMeta, newTags, newFilePath).then(- () => {- // dispatch(AppActions.reflectEditedEntryPaths([newFilePath]));- const { openedFiles } = getState().app;- if (openedFiles.find(obj => obj.path === path)) {- return dispatch(- AppActions.updateOpenedFile(path, {- tags: newTags- })- );- }- return true;- }- );- });- })- .catch(error => {- console.warn('Error removing tags for ' + path + ' with ' + error);- // dispatch(AppActions.showNotification(i18n.t('core:removingSidecarTagsFailed'), 'error', true));- return removeTagsFromFilename().then(() => true);- });-- function removeTagsFromSideCar(- fsEntryMeta: TS.FileSystemEntryMeta,- newTags,- newFilePath- ): Promise<boolean> {- if (newFilePath === path) {- // no file rename - only sidecar tags removed- const updatedFsEntryMeta = {- ...fsEntryMeta,- tags: newTags- };- return saveMetaDataPromise(path, updatedFsEntryMeta)- .then(() => {- dispatch(AppActions.reflectUpdateSidecarTags(newFilePath, newTags));- return true;- })- .catch(err => {- console.warn(- 'Removing sidecar tags failed ' + path + ' with ' + err- );- dispatch(- AppActions.showNotification(- i18n.t('core:removingSidecarTagsFailed'),- 'error',- true- )- );- return false;- });- }- return Promise.resolve(true);- }- /!**- * return new file path- * @param isFile- *!/- function removeTagsFromFilename(isFile: boolean = true): Promise<string> {- if (!isFile) {- return Promise.resolve(path);- }- return new Promise(async (resolve, reject) => {- let extractedTags = extractTags(- path,- settings.tagDelimiter,- PlatformIO.getDirSeparator()- );- if (extractedTags.length > 0) {- const fileName = extractFileName(path, PlatformIO.getDirSeparator());- const containingDirectoryPath = extractContainingDirectoryPath(- path,- PlatformIO.getDirSeparator()- );- if (tagTitlesForRemoving) {- for (let i = 0; i < tagTitlesForRemoving.length; i += 1) {- const tagLoc = extractedTags.indexOf(tagTitlesForRemoving[i]);- if (tagLoc < 0) {- console.log(- 'The tag cannot be removed because it is not part of the file name.'- );- } else {- extractedTags.splice(tagLoc, 1);- }- }- } else {- extractedTags = [];- }- const newFilePath =- (containingDirectoryPath- ? containingDirectoryPath + PlatformIO.getDirSeparator()- : '') +- generateFileName(- fileName,- extractedTags,- settings.tagDelimiter,- settings.prefixTagContainer- );- if (path !== newFilePath) {- const success = await dispatch(- AppActions.renameFile(path, newFilePath)- );- if (!success) {- reject(new Error('Error renaming file'));- return;- }- }- resolve(newFilePath);- } else {- resolve(path);- }- });- }- },- removeAllTags: (paths: Array<string>) => async (- dispatch: (action) => Promise<boolean>- ): Promise<boolean> => {- return dispatch(actions.removeTags(paths));- /!*for (const path of paths) {- const success = await dispatch(actions.removeAllTagsFromFilename(path));- if (success) {- await dispatch(actions.removeAllTagsFromMetaData(path));- } else {- return Promise.resolve(false);- }- }- return Promise.resolve(true);*!/- },- /!*removeAllTagsFromFilename: (path: string) => (- dispatch: (action) => Promise<boolean>,- getState: () => any- ): Promise<boolean> => {- const { settings } = getState();- // Tags in file name case, check is file- const extractedTags = extractTags(- path,- settings.tagDelimiter,- PlatformIO.getDirSeparator()- );- if (extractedTags.length > 0) {- const fileTitle = extractTitle(path, false, PlatformIO.getDirSeparator());- let fileExt = extractFileExtension(path, PlatformIO.getDirSeparator());- const containingDirectoryPath = extractContainingDirectoryPath(- path,- PlatformIO.getDirSeparator()- );- if (fileExt.length > 0) {- fileExt = '.' + fileExt;- }- const newFilePath =- (containingDirectoryPath- ? containingDirectoryPath + PlatformIO.getDirSeparator()- : '') +- fileTitle +- fileExt;- return dispatch(AppActions.renameFile(path, newFilePath));- }- return Promise.resolve(true);- },- removeAllTagsFromMetaData: (path: string) => (- dispatch: (action) => void,- getState: () => any- ): Promise<boolean> =>- loadMetaDataPromise(path)- .then(fsEntryMeta => {- const updatedFsEntryMeta = {- ...fsEntryMeta,- tags: []- };- return saveMetaDataPromise(path, updatedFsEntryMeta)- .then(() => {- // TODO rethink this updateCurrentDirEntry and not need for KanBan- dispatch(AppActions.reflectUpdateSidecarTags(path, []));- const { openedFiles } = getState().app;- if (openedFiles.find(obj => obj.path === path)) {- dispatch(AppActions.updateOpenedFile(path, { tags: [] }));- }- return true;- })- .catch(err => {- console.warn(- 'Removing sidecar tags failed for ' + path + ' with ' + err- );- dispatch(- AppActions.showNotification(- i18n.t('core:removingTagsInSidecarFileFailed'),- 'error',- true- )- );- return false;- });- })- .catch(error => {- console.warn('Could not find meta file for ' + path + ' with ' + error);- // dispatch(AppActions.showNotification('Adding tags failed', 'error', true));- return false;- }),*!/- // smart tagging -> PRO- addDateTag: (paths: Array<string>) => () =>- // dispatch: (actions: Object) => void- {- // dispatch(actions.createLocation(location));- },- editDateTag: (path: string) => () =>- // dispatch: (actions: Object) => void- {- // dispatch(actions.createLocation(location));- },- addGeoTag: (paths: Array<string>) => () =>- // dispatch: (actions: Object) => void- {- // dispatch(actions.createLocation(location));- },- editGeoTag: (path: string) => () =>- // dispatch: (actions: Object) => void- {- // dispatch(actions.createLocation(location));- },- collectTagsFromLocation: (tagGroup: TS.TagGroup) => (- dispatch: (actions: Object) => void,- getState: () => any- ) => {- const { settings } = getState();-- if (GlobalSearch.getInstance().getIndex().length < 1) {- dispatch(- AppActions.showNotification(- 'Please index location first',- 'error',- true- )- );- return true;- }-- const uniqueTags = collectTagsFromIndex(- GlobalSearch.getInstance().getIndex(),- tagGroup,- settings- );- if (uniqueTags.length > 0) {- const changedTagGroup = {- ...tagGroup,- children: uniqueTags,- modified_date: new Date().getTime()- };- const { locations } = getState();- mergeTagGroup(changedTagGroup, getTagLibrary(), locations);- // dispatch(TagLibraryActions.mergeTagGroup(changedTagGroup));- }- }-};--function generateTagValue(tag) {- let tagTitle = tag.functionality;- switch (tag.functionality) {- case 'today': {- tagTitle = formatDateTime4Tag(new Date(), false);- break;- }- case 'tomorrow': {- const d = new Date();- d.setDate(d.getDate() + 1);- tagTitle = formatDateTime4Tag(d, false);- break;- }- case 'yesterday': {- const d = new Date();- d.setDate(d.getDate() - 1);- tagTitle = formatDateTime4Tag(d, false);- break;- }- case 'currentMonth': {- let cMonth = '' + (new Date().getMonth() + 1);- if (cMonth.length === 1) {- cMonth = '0' + cMonth;- }- tagTitle = '' + new Date().getFullYear() + cMonth;- break;- }- case 'currentYear': {- tagTitle = '' + new Date().getFullYear();- break;- }- case 'now': {- tagTitle = formatDateTime4Tag(new Date(), true);- break;- }- default: {- break;- }- }- return tagTitle;-}--function collectTagsFromIndex(- locationIndex: any,- tagGroup: any,- settings: any-) {- const uniqueTags = [];- const defaultTagColor = settings.tagBackgroundColor;- const defaultTagTextColor = settings.tagTextColor;- locationIndex.map(entry => {- if (entry.tags && entry.tags.length > 0) {- entry.tags.map(tag => {- if (- uniqueTags.findIndex(obj => obj.title === tag.title) < 0 && // element not already added- tagGroup.children.findIndex(obj => obj.title === tag.title) < 0 && // element not already added- !/^(?:\d+~\d+|\d+)$/.test(tag.title) && // skip adding of tag containing only digits- !isGeoTag(tag.title) // skip adding of tag containing geo information- ) {- uniqueTags.push({- ...tag,- color: tag.color || defaultTagColor,- textcolor: tag.textcolor || defaultTagTextColor- });- }- return true;- });- }- return true;- });- return uniqueTags;-}--export default actions;-*/diff --git a/app/services/meta-loader.ts b/app/services/meta-loader.tsnew file mode 100644index 000000000..100f886dc--- /dev/null+++ b/app/services/meta-loader.ts@@ -0,0 +1,156 @@+import { TS } from '-/tagspaces.namespace';+import PlatformIO from '-/services/platform-facade';+import { getMetaForEntry } from '-/services/utils-io';+import {+ getMetaFileLocationForDir,+ getMetaFileLocationForFile,+ getThumbFileLocationForDirectory,+ getThumbFileLocationForFile+} from '@tagspaces/tagspaces-common/paths';+import AppConfig from '-/AppConfig';++export function loadCurrentDirMeta(+ directoryPath: string,+ dirEntries: TS.FileSystemEntry[],+ pageFiles?: TS.FileSystemEntry[]+): Promise<TS.FileSystemEntry[]> {+ return PlatformIO.listMetaDirectoryPromise(directoryPath)+ .then(meta => {+ //metaLoadedLock.current = false;+ //props.setIsMetaLoaded(true);+ // props.setMetaForCurrentDir(meta);+ const dirEntriesPromises = dirEntries+ .filter(entry => !entry.isFile)+ .map(entry => getEnhancedDir(entry));+ const files = pageFiles+ ? pageFiles+ : dirEntries.filter(entry => entry.isFile);+ const fileEntriesPromises = getFileEntriesPromises(files, meta);+ const thumbs = getThumbs(files, meta);+ return getEntries([+ ...dirEntriesPromises,+ ...fileEntriesPromises,+ ...thumbs+ ]);+ })+ .catch(ex => {+ console.error(ex);+ return undefined;+ });+}++function getEntries(metaPromises): Promise<TS.FileSystemEntry[]> {+ const catchHandler = error => undefined;+ return Promise.all(metaPromises.map(promise => promise.catch(catchHandler)))+ .then((entries: TS.FileSystemEntry[]) => {+ return entries;+ })+ .catch(err => {+ console.error('err updateEntries:', err);+ return undefined;+ });+}++function getFileEntriesPromises(+ pageFiles: TS.FileSystemEntry[],+ meta: Array<any>+): Promise<TS.FileSystemEntry>[] {+ return pageFiles.map(entry => {+ const metaFilePath = getMetaFileLocationForFile(+ entry.path,+ PlatformIO.getDirSeparator()+ );+ if (+ // check if metaFilePath exist in listMetaDirectory content+ meta.some(metaFile => metaFilePath.endsWith(metaFile.path)) &&+ // !checkEntryExist(entry.path) &&+ entry.path.indexOf(+ AppConfig.metaFolder + PlatformIO.getDirSeparator()+ ) === -1+ ) {+ return getMetaForEntry(+ entry,+ metaFilePath+ ); /*Promise.resolve({+ [entry.path]: getMetaForEntry(entry, metaFilePath)+ });*/+ }+ return Promise.resolve(undefined); //Promise.resolve({ [entry.path]: undefined });+ });+}++function getThumbs(+ pageFiles: TS.FileSystemEntry[],+ meta: Array<any>+): Promise<TS.FileSystemEntry>[] {+ return pageFiles.map(entry => Promise.resolve(setThumbForEntry(entry, meta)));+}++function setThumbForEntry(+ entry: TS.FileSystemEntry,+ meta: Array<any>+): TS.FileSystemEntry {+ const thumbEntry = { ...entry };+ let thumbPath = getThumbFileLocationForFile(+ entry.path,+ PlatformIO.getDirSeparator(),+ false+ );+ if (thumbPath && meta.some(metaFile => thumbPath.endsWith(metaFile.path))) {+ thumbEntry.thumbPath = thumbPath;+ if (PlatformIO.haveObjectStoreSupport() || PlatformIO.haveWebDavSupport()) {+ if (thumbPath && thumbPath.startsWith('/')) {+ thumbPath = thumbPath.substring(1);+ }++ thumbPath = PlatformIO.getURLforPath(thumbPath, 604800);+ if (thumbPath) {+ thumbEntry.thumbPath = thumbPath;+ }+ }+ }+ return thumbEntry;+}++export function getEnhancedDir(+ entry: TS.FileSystemEntry+): Promise<TS.FileSystemEntry> {+ if (!entry) {+ return Promise.resolve(undefined);+ }+ if (entry.isFile) {+ return Promise.reject(+ new Error('getEnhancedDir accept dir only:' + entry.path)+ );+ }+ if (entry.name === AppConfig.metaFolder) {+ return Promise.resolve(undefined);+ }+ return PlatformIO.listMetaDirectoryPromise(entry.path).then(meta => {+ const metaFilePath = getMetaFileLocationForDir(+ entry.path,+ PlatformIO.getDirSeparator()+ );+ const thumbDirPath = getThumbFileLocationForDirectory(+ entry.path,+ PlatformIO.getDirSeparator()+ );+ let enhancedEntry;+ if (meta.some(metaFile => thumbDirPath.endsWith(metaFile.path))) {+ const thumbPath =+ PlatformIO.haveObjectStoreSupport() || PlatformIO.haveWebDavSupport()+ ? PlatformIO.getURLforPath(thumbDirPath)+ : thumbDirPath;+ enhancedEntry = { ...entry, thumbPath };+ }+ if (+ meta.some(metaFile => metaFilePath.endsWith(metaFile.path)) &&+ entry.path.indexOf(+ AppConfig.metaFolder + PlatformIO.getDirSeparator()+ ) === -1+ ) {+ return getMetaForEntry(enhancedEntry || entry, metaFilePath);+ }+ return enhancedEntry;+ });+}diff --git a/app/services/search-index.ts b/app/services/search-index.tsindex bb4e18a51..07b810ac1 100644--- a/app/services/search-index.ts+++ b/app/services/search-index.ts@@ -1,4 +1,5 @@-/**+/*+/!*** TagSpaces - universal file and folder organizer* Copyright (C) 2020-present TagSpaces UG (haftungsbeschraenkt)*@@ -14,13 +15,8 @@* 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/>.*- */+ *!/-/*const GlobalSearch = {- indexLoadedOn: undefined,- index: [],- results: []-};*/import {extractFileName,extractFileExtension,@@ -34,9 +30,10 @@ const GlobalSearch = (function() {let instance;function init() {- let indexLoadedOn = undefined;+ // DateCreated for index+ let indexLoadedOn: number = undefined;let index = [];- let results = [];+ //let results = [];return {setIndexLoadedOn: function(loaded) {@@ -47,10 +44,10 @@ const GlobalSearch = (function() {index = i;},getIndex: () => index,- setResults: function(r) {+ /!*setResults: function(r) {results = r;},- getResults: () => results,+ getResults: () => results,*!/reflectDeleteEntry: (path: string) => {if (!index || index.length < 1) {return;@@ -149,3 +146,4 @@ const GlobalSearch = (function() {};})();export default GlobalSearch;+*/diff --git a/app/services/utils-io.ts b/app/services/utils-io.tsindex 0e398cf15..9cd1c9c58 100644--- a/app/services/utils-io.ts+++ b/app/services/utils-io.ts@@ -69,102 +69,14 @@ import { base64ToArrayBuffer } from '-/utils/dom';import { Pro } from '-/pro';import { supportedFileTypes } from '-/extension-config';-const supportedImgsWS = [- 'jpg',- 'jpeg',- 'jif',- 'jfif',- 'png',- 'gif',- 'svg',- 'tif',- 'tiff',- 'ico',- 'webp',- 'avif'- // 'bmp' currently electron main processed: https://github.com/lovell/sharp/issues/806-];--export function enhanceDirectoryContent(- dirEntries,- isCloudLocation,- showUnixHiddenEntries,- useGenerateThumbnails,- showDirs = true,- limit = undefined,- enableWS = true-) {- const directoryContent = [];- const tmbGenerationPromises = [];- const tmbGenerationList = [];- const isWorkerAvailable = enableWS && PlatformIO.isWorkerAvailable();-- dirEntries.map(entry => {- if (!showUnixHiddenEntries && entry.name.startsWith('.')) {- return true;- }-- if (!showDirs && !entry.isFile) {- return true;- }-- if (limit !== undefined && directoryContent.length >= limit) {- return true;- }-- const enhancedEntry: TS.FileSystemEntry = enhanceEntry(- entry,- AppConfig.tagDelimiter,- PlatformIO.getDirSeparator()- );- directoryContent.push(enhancedEntry);- if (- // Enable thumb generation by- !AppConfig.isWeb && // not in webdav mode- !PlatformIO.haveObjectStoreSupport() && // not in object store mode- !PlatformIO.haveWebDavSupport() && // not in webdav mode- enhancedEntry.isFile && // only for files- useGenerateThumbnails // enabled in the settings- ) {- // const isPDF = enhancedEntry.path.endsWith('.pdf');- if (- isWorkerAvailable &&- supportedImgsWS.includes(enhancedEntry.extension)- ) {- // !isPDF) {- tmbGenerationList.push(enhancedEntry.path);- } else if (- supportedImgs.includes(enhancedEntry.extension) ||- supportedContainers.includes(enhancedEntry.extension) ||- supportedText.includes(enhancedEntry.extension) ||- supportedMisc.includes(enhancedEntry.extension) ||- supportedVideos.includes(enhancedEntry.extension)- ) {- tmbGenerationPromises.push(getThumbnailURLPromise(enhancedEntry.path));- } else {- console.log(- 'Unsupported thumbgeneration ext:' + enhancedEntry.extension- );- }- }- return true;- });-- return {- directoryContent,- tmbGenerationPromises,- tmbGenerationList- };-}--export async function getMetaForEntry(+export function getMetaForEntry(entry: TS.FileSystemEntry,metaFilePath?: string-): Promise<any> {+): Promise<TS.FileSystemEntry> {if (entry.meta) {// && Object.keys(entry.meta).length > 0) {// entry is Enhanced- return { [entry.path]: { ...entry } };+ return Promise.resolve(entry);}if (!metaFilePath) {if (entry.isFile) {@@ -179,22 +91,22 @@ export async function getMetaForEntry();}}- const meta: TS.FileSystemEntryMeta = await loadJSONFile(metaFilePath);- if (meta) {- const entryEnhanced = enhanceEntry(- {- ...entry,- meta: {- ...meta,- description: getDescriptionPreview(meta.description, 200)- }- },- AppConfig.tagDelimiter,- PlatformIO.getDirSeparator()- );- return { [entry.path]: entryEnhanced };- }- return Promise.resolve({ [entry.path]: undefined });+ return loadJSONFile(metaFilePath).then((meta: TS.FileSystemEntryMeta) => {+ if (meta) {+ return enhanceEntry(+ {+ ...entry,+ meta: {+ ...meta,+ description: getDescriptionPreview(meta.description, 200)+ }+ },+ AppConfig.tagDelimiter,+ PlatformIO.getDirSeparator()+ );+ }+ return entry;+ });}export function enhanceOpenedEntry(@@ -232,7 +144,7 @@ export function enhanceOpenedEntry(return entry;}-export function prepareDirectoryContent(+/*export function prepareDirectoryContent(dirEntries,directoryPath,settings,@@ -339,7 +251,7 @@ export function prepareDirectoryContent(dirEntryMeta));-}+}*/export function orderDirectories(directories,@@ -1597,10 +1509,13 @@ export function getFolderThumbPath(path: string,lastThumbnailImageChange: any) {- return getThumbPath(- getThumbFileLocationForDirectory(path, PlatformIO.getDirSeparator()),- lastThumbnailImageChange- );+ if (path) {+ return getThumbPath(+ getThumbFileLocationForDirectory(path, PlatformIO.getDirSeparator()),+ lastThumbnailImageChange+ );+ }+ return undefined;}export function getThumbPath(@@ -1637,10 +1552,13 @@ export function getFolderBgndPath(path: string,lastBackgroundImageChange: any) {- return getBgndPath(- getBgndFileLocationForDirectory(path, PlatformIO.getDirSeparator()),- lastBackgroundImageChange- );+ if (path) {+ return getBgndPath(+ getBgndFileLocationForDirectory(path, PlatformIO.getDirSeparator()),+ lastBackgroundImageChange+ );+ }+ return undefined;}export function getBgndPath(bgndPath: string, lastBackgroundImageChange: any) {@@ -1697,7 +1615,7 @@ export function getRelativeEntryPath(/*** @param entries- * @param entriesChanges Array<TS.FileSystemEntry> but partly changes from FileSystemEntry model like { tags:[] } are acceptable+ * @param entriesChanges Array<TS.FileSystemEntry> but partly changes from FileSystemEntry model like { path, tags:[] } are acceptable* return entries: Array<TS.FileSystemEntry> updated from*/export function updateFsEntries(@@ -1745,6 +1663,25 @@ export function toFsEntry(path: string, isFile: boolean): TS.FileSystemEntry {};}+export function openedToFsEntry(openedEntry: OpenedEntry): TS.FileSystemEntry {+ return {+ uuid: getUuid(),+ name: openedEntry.isFile+ ? extractFileName(openedEntry.path, PlatformIO.getDirSeparator())+ : extractDirectoryName(openedEntry.path, PlatformIO.getDirSeparator()),+ isFile: openedEntry.isFile,+ extension: extractFileExtension(+ openedEntry.path,+ PlatformIO.getDirSeparator()+ ),+ description: openedEntry.description,+ tags: openedEntry.tags,+ size: openedEntry.size,+ lmdt: openedEntry.lmdt,+ path: openedEntry.path+ };+}+export function createFsEntryMeta(path: string,props: any = {}@@ -1786,48 +1723,3 @@ export function openURLExternally(url: string, skipConfirmation = false) {PlatformIO.openUrl(url);}}--/*export function getSharingLink(- openedFile: OpenedEntry,- locations: Array<TS.Location>-) {- let sharingLink = '';- let sharingParentFolderLink = '';- if (window.location.href.indexOf('?') > 0) {- const sharingURL = new URL(window.location.href);- const params = new URLSearchParams(sharingURL.search);- if (params.has('tslid')) {- const locationId = params.get('tslid');- //if (params.has('tsdpath')) {- // const folderPath2 = params.get('tsdpath');- const folderLocation = locations.find(- location => location.uuid === locationId- );- const folderPath = extractContainingDirectoryPath(openedFile.path);- if (folderPath.indexOf(folderLocation.path) === 0) {- sharingParentFolderLink = generateSharingLink(- locationId,- undefined,- cleanRootPath(- folderPath,- folderLocation.path,- PlatformIO.getDirSeparator()- )- );- }-- //}- if (params.has('tsepath')) {- const entryPath = params.get('tsepath');- if (openedFile.isFile) {- sharingLink = generateSharingLink(locationId, entryPath);- } else {- sharingLink = generateSharingLink(locationId, undefined, entryPath);- }- } else {- sharingLink = generateSharingLink(locationId);- }- }- }- return { sharingLink, sharingParentFolderLink };-}*/diff --git a/app/utils/HandleAuth.tsx b/app/utils/HandleAuth.tsxindex 6a735d73d..30d9e2f3a 100644--- a/app/utils/HandleAuth.tsx+++ b/app/utils/HandleAuth.tsx@@ -12,15 +12,15 @@ import { actions as LocationActions } from '-/reducers/locations';import { actions as AppActions } from '-/reducers/app';import { TS } from '-/tagspaces.namespace';import { importTagGroups } from '-/services/taglibrary-utils';+import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';interface Props {loggedIn: (user: CognitoUserInterface) => void;initApp: () => void;- addLocations: (locations: Array<TS.Location>, override: boolean) => void;- // importTagGroups: (tagGroups: Array<TS.TagGroup>, replace: boolean) => void;}function HandleAuth(props: Props) {const username = useRef(undefined);+ const { addLocations } = useCurrentLocationContext();React.useEffect(() => {onAuthUIStateChange((nextAuthState, authData) => {@@ -46,7 +46,7 @@ function HandleAuth(props: Props) {fetchTenant().then(async tenant => {if (tenant) {- await addLocations(tenant, queries.getExtconfig);+ await saveLocations(tenant, queries.getExtconfig);await addTagGroups(tenant, queries.tagGroupsByTenant);}return true;@@ -67,7 +67,7 @@ function HandleAuth(props: Props) {});}, []);- const addLocations = async (tenant: string, query: any) => {+ const saveLocations = async (tenant: string, query: any) => {// @ts-ignoreconst { data } = await API.graphql({query,@@ -75,7 +75,7 @@ function HandleAuth(props: Props) {});if (data) {// console.log(data.getExtconfig.Locations.items);- props.addLocations(JSON.parse(data.getExtconfig.Locations), false);+ addLocations(JSON.parse(data.getExtconfig.Locations), false);}};@@ -123,8 +123,7 @@ function mapDispatchToProps(dispatch) {return bindActionCreators({loggedIn: AppActions.loggedIn,- initApp: AppActions.initApp,- addLocations: LocationActions.addLocations+ initApp: AppActions.initApp// importTagGroups: TagGroupActions.importTagGroups},dispatchdiff --git a/package-lock.json b/package-lock.jsonindex 8fdff049e..87484cb8b 100644--- a/package-lock.json+++ b/package-lock.json@@ -10,14 +10,14 @@"license": "AGPL-3.0","dependencies": {"@aws-amplify/ui-react": "^1.2.26",- "@date-io/date-fns": "^2.16.0",+ "@date-io/date-fns": "^2.17.0","@elife/pm2": "^3.6.1",- "@emotion/react": "11.10.0",- "@emotion/styled": "11.10.0",+ "@emotion/react": "11.11.1",+ "@emotion/styled": "11.11.0","@gorillastack/jmespath": "^1.3.0",- "@mui/icons-material": "^5.13.7",- "@mui/lab": "^5.0.0-alpha.135",- "@mui/material": "^5.13.7",+ "@mui/icons-material": "^5.14.13",+ "@mui/lab": "^5.0.0-alpha.148",+ "@mui/material": "^5.14.13","@mui/x-date-pickers": "^5.0.20","@tagspaces/tagspaces-common": "3.0.17","@tagspaces/tagspaces-md": "3.0.19",@@ -133,7 +133,7 @@"current-git-branch": "^1.1.0","detect-port": "^1.3.0","dotenv-webpack": "^8.0.1",- "electron": "25.8.3",+ "electron": "26.4.0","electron-builder": "^24.4.0","electron-devtools-installer": "^3.2.0","electron-notarize": "^1.2.2",@@ -8548,9 +8548,9 @@"integrity": "sha512-x/rqGMdzj+fWZvCOYForTghzbtqPDZ5gPwaoNGHdgDfF2QA/XZbCBp4Moo5scrkAMPhB7z26XM/AaHuIJdgauA=="},"node_modules/@babel/runtime": {- "version": "7.22.11",- "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.22.11.tgz",- "integrity": "sha512-ee7jVNlWN09+KftVOu9n7S8gQzD/Z6hN/I8VBRXW4P1+Xe7kJGXMwu8vds4aGIMHZnNbdpSWCfZZtinytpcAvA==",+ "version": "7.23.2",+ "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.23.2.tgz",+ "integrity": "sha512-mM8eg4yl5D6i3lu2QKPuPH4FArvJ8KhTofbE7jwMUv9KX5mBvwPAqnV3MlyBNqdp9RyRKP6Yck8TrfYrPvX3bg==","dependencies": {"regenerator-runtime": "^0.14.0"},@@ -9007,26 +9007,23 @@"integrity": "sha512-W2P2c/VRW1/1tLox0mVUalvnWXxavmv/Oum2aPsRcoDJuob75FC3Y8FbpfLwUegRcxINtGUMPq0tFCvYNTBXNA=="},"node_modules/@emotion/react": {- "version": "11.10.0",- "resolved": "https://registry.npmjs.org/@emotion/react/-/react-11.10.0.tgz",- "integrity": "sha512-K6z9zlHxxBXwN8TcpwBKcEsBsOw4JWCCmR+BeeOWgqp8GIU1yA2Odd41bwdAAr0ssbQrbJbVnndvv7oiv1bZeQ==",+ "version": "11.11.1",+ "resolved": "https://registry.npmjs.org/@emotion/react/-/react-11.11.1.tgz",+ "integrity": "sha512-5mlW1DquU5HaxjLkfkGN1GA/fvVGdyHURRiX/0FHl2cfIfRxSOfmxEH5YS43edp0OldZrZ+dkBKbngxcNCdZvA==","dependencies": {"@babel/runtime": "^7.18.3",- "@emotion/babel-plugin": "^11.10.0",- "@emotion/cache": "^11.10.0",- "@emotion/serialize": "^1.1.0",- "@emotion/utils": "^1.2.0",- "@emotion/weak-memoize": "^0.3.0",+ "@emotion/babel-plugin": "^11.11.0",+ "@emotion/cache": "^11.11.0",+ "@emotion/serialize": "^1.1.2",+ "@emotion/use-insertion-effect-with-fallbacks": "^1.0.1",+ "@emotion/utils": "^1.2.1",+ "@emotion/weak-memoize": "^0.3.1","hoist-non-react-statics": "^3.3.1"},"peerDependencies": {- "@babel/core": "^7.0.0","react": ">=16.8.0"},"peerDependenciesMeta": {- "@babel/core": {- "optional": true- },"@types/react": {"optional": true}@@ -9050,25 +9047,22 @@"integrity": "sha512-0QBtGvaqtWi+nx6doRwDdBIzhNdZrXUppvTM4dtZZWEGTXL/XE/yJxLMGlDT1Gt+UHH5IX1n+jkXyytE/av7OA=="},"node_modules/@emotion/styled": {- "version": "11.10.0",- "resolved": "https://registry.npmjs.org/@emotion/styled/-/styled-11.10.0.tgz",- "integrity": "sha512-V9oaEH6V4KePeQpgUE83i8ht+4Ri3E8Djp/ZPJ4DQlqWhSKITvgzlR3/YQE2hdfP4Jw3qVRkANJz01LLqK9/TA==",+ "version": "11.11.0",+ "resolved": "https://registry.npmjs.org/@emotion/styled/-/styled-11.11.0.tgz",+ "integrity": "sha512-hM5Nnvu9P3midq5aaXj4I+lnSfNi7Pmd4EWk1fOZ3pxookaQTNew6bp4JaCBYM4HVFZF9g7UjJmsUmC2JlxOng==","dependencies": {"@babel/runtime": "^7.18.3",- "@emotion/babel-plugin": "^11.10.0",- "@emotion/is-prop-valid": "^1.2.0",- "@emotion/serialize": "^1.1.0",- "@emotion/utils": "^1.2.0"+ "@emotion/babel-plugin": "^11.11.0",+ "@emotion/is-prop-valid": "^1.2.1",+ "@emotion/serialize": "^1.1.2",+ "@emotion/use-insertion-effect-with-fallbacks": "^1.0.1",+ "@emotion/utils": "^1.2.1"},"peerDependencies": {- "@babel/core": "^7.0.0","@emotion/react": "^11.0.0-rc.0","react": ">=16.8.0"},"peerDependenciesMeta": {- "@babel/core": {- "optional": true- },"@types/react": {"optional": true}@@ -9079,6 +9073,14 @@"resolved": "https://registry.npmjs.org/@emotion/unitless/-/unitless-0.8.1.tgz","integrity": "sha512-KOEGMu6dmJZtpadb476IsZBclKvILjopjUii3V+7MnXIQCYh8W3NgNcgwo21n9LXZX6EDIKvqfjYxXebDwxKmQ=="},+ "node_modules/@emotion/use-insertion-effect-with-fallbacks": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/@emotion/use-insertion-effect-with-fallbacks/-/use-insertion-effect-with-fallbacks-1.0.1.tgz",+ "integrity": "sha512-jT/qyKZ9rzLErtrjGgdkMBn2OP8wl0G3sQlBb3YPryvKHsjvINUhVaPFfP+fpBcOkmrVOVEEHQFJ7nbj2TH2gw==",+ "peerDependencies": {+ "react": ">=16.8.0"+ }+ },"node_modules/@emotion/utils": {"version": "1.2.1","resolved": "https://registry.npmjs.org/@emotion/utils/-/utils-1.2.1.tgz",@@ -9195,20 +9197,20 @@}},"node_modules/@floating-ui/core": {- "version": "1.4.1",- "resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.4.1.tgz",- "integrity": "sha512-jk3WqquEJRlcyu7997NtR5PibI+y5bi+LS3hPmguVClypenMsCY3CBa3LAQnozRCtCrYWSEtAdiskpamuJRFOQ==",+ "version": "1.5.0",+ "resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.5.0.tgz",+ "integrity": "sha512-kK1h4m36DQ0UHGj5Ah4db7R0rHemTqqO0QLvUqi1/mUUp3LuAWbWxdxSIf/XsnH9VS6rRVPLJCncjRzUvyCLXg==","dependencies": {- "@floating-ui/utils": "^0.1.1"+ "@floating-ui/utils": "^0.1.3"}},"node_modules/@floating-ui/dom": {- "version": "1.5.1",- "resolved": "https://registry.npmjs.org/@floating-ui/dom/-/dom-1.5.1.tgz",- "integrity": "sha512-KwvVcPSXg6mQygvA1TjbN/gh///36kKtllIF8SUm0qpFj8+rvYrpvlYdL1JoA71SHpDqgSSdGOSoQ0Mp3uY5aw==",+ "version": "1.5.3",+ "resolved": "https://registry.npmjs.org/@floating-ui/dom/-/dom-1.5.3.tgz",+ "integrity": "sha512-ClAbQnEqJAKCJOEbbLo5IUlZHkNszqhuxS4fHAVxRPXPya6Ysf2G8KypnYcOTpx6I8xcgF9bbHb6g/2KpbV8qA==","dependencies": {- "@floating-ui/core": "^1.4.1",- "@floating-ui/utils": "^0.1.1"+ "@floating-ui/core": "^1.4.2",+ "@floating-ui/utils": "^0.1.3"}},"node_modules/@floating-ui/react-dom": {@@ -9224,9 +9226,9 @@}},"node_modules/@floating-ui/utils": {- "version": "0.1.1",- "resolved": "https://registry.npmjs.org/@floating-ui/utils/-/utils-0.1.1.tgz",- "integrity": "sha512-m0G6wlnhm/AX0H12IOWtK8gASEMffnX08RtKkCgTdHb9JpHKGloI7icFfLg9ZmQeavcvR0PKmzxClyuFPSjKWw=="+ "version": "0.1.6",+ "resolved": "https://registry.npmjs.org/@floating-ui/utils/-/utils-0.1.6.tgz",+ "integrity": "sha512-OfX7E2oUDYxtBvsuS4e/jSn4Q9Qb6DzgeYtsAdkPZ47znpoNsMgZw0+tVijiv3uGNR6dgNlty6r9rzIzHjtd/A=="},"node_modules/@gorillastack/jmespath": {"version": "1.3.0",@@ -9976,19 +9978,17 @@"dev": true},"node_modules/@mui/base": {- "version": "5.0.0-beta.13",- "resolved": "https://registry.npmjs.org/@mui/base/-/base-5.0.0-beta.13.tgz",- "integrity": "sha512-uC0l97pBspfDAp+iz2cJq8YZ8Sd9i73V77+WzUiOAckIVEyCm5dyVDZCCO2/phmzckVEeZCGcytybkjMQuhPQw==",- "dependencies": {- "@babel/runtime": "^7.22.10",- "@emotion/is-prop-valid": "^1.2.1",- "@floating-ui/react-dom": "^2.0.1",- "@mui/types": "^7.2.4",- "@mui/utils": "^5.14.7",+ "version": "5.0.0-beta.19",+ "resolved": "https://registry.npmjs.org/@mui/base/-/base-5.0.0-beta.19.tgz",+ "integrity": "sha512-maNBgAscddyPNzFZQUJDF/puxM27Li+NqSBsr/lAP8TLns2VvWS2SoL3OKFOIoRnAMKGY/Ic6Aot6gCYeQnssA==",+ "dependencies": {+ "@babel/runtime": "^7.23.1",+ "@floating-ui/react-dom": "^2.0.2",+ "@mui/types": "^7.2.6",+ "@mui/utils": "^5.14.13","@popperjs/core": "^2.11.8","clsx": "^2.0.0",- "prop-types": "^15.8.1",- "react-is": "^18.2.0"+ "prop-types": "^15.8.1"},"engines": {"node": ">=12.0.0"@@ -10009,20 +10009,20 @@}},"node_modules/@mui/core-downloads-tracker": {- "version": "5.14.7",- "resolved": "https://registry.npmjs.org/@mui/core-downloads-tracker/-/core-downloads-tracker-5.14.7.tgz",- "integrity": "sha512-sCWTUNElBPgB30iLvWe3PU7SIlTKZNf6/E/sko85iHVeHCM6WPkDw+y89CrZYjhFNmPqt2fIQM/pZu+rP2lFLA==",+ "version": "5.14.13",+ "resolved": "https://registry.npmjs.org/@mui/core-downloads-tracker/-/core-downloads-tracker-5.14.13.tgz",+ "integrity": "sha512-3ZUbzcH4yloLKlV6Y+S0Edn2wef9t+EGHSfEkwVCn8E0ULdshifEFgfEroKRegQifDIwcKS/ofccxuZ8njTAYg==","funding": {"type": "opencollective","url": "https://opencollective.com/mui"}},"node_modules/@mui/icons-material": {- "version": "5.14.7",- "resolved": "https://registry.npmjs.org/@mui/icons-material/-/icons-material-5.14.7.tgz",- "integrity": "sha512-mWp4DwMa8c1Gx9yOEtPgxM4b+e6hAbtZyzfSubdBwrnEE6G5D2rbAJ5MB+If6kfI48JaYaJ5j8+zAdmZLuZc0A==",+ "version": "5.14.13",+ "resolved": "https://registry.npmjs.org/@mui/icons-material/-/icons-material-5.14.13.tgz",+ "integrity": "sha512-fxKE1UrjI4xVxHe9IAGuVQZrc18dSBJg0P+Sqi2SZmcDUCShmgRq6Jq7l7GduvuMIkOSqAJdNgLtXmtmZkjtLg==","dependencies": {- "@babel/runtime": "^7.22.10"+ "@babel/runtime": "^7.23.1"},"engines": {"node": ">=12.0.0"@@ -10043,18 +10043,18 @@}},"node_modules/@mui/lab": {- "version": "5.0.0-alpha.142",- "resolved": "https://registry.npmjs.org/@mui/lab/-/lab-5.0.0-alpha.142.tgz",- "integrity": "sha512-JDrT5G3QBZ0nzkKMFWzJY5KN8WcyDx4p7qOjg6hs7yKLq90VSdsqIOmyhvWDxJR7zPNQjo0WRYBAaRaQ5FlGxg==",- "dependencies": {- "@babel/runtime": "^7.22.10",- "@mui/base": "5.0.0-beta.13",- "@mui/system": "^5.14.7",- "@mui/types": "^7.2.4",- "@mui/utils": "^5.14.7",+ "version": "5.0.0-alpha.148",+ "resolved": "https://registry.npmjs.org/@mui/lab/-/lab-5.0.0-alpha.148.tgz",+ "integrity": "sha512-FfgHSYO59tznwMkn6FAjuowU1KteTV2AQRD7NsZq82TpiRBpBFkDtcsap02uf+rRVdwgF/yokdYLtVJ96snDGA==",+ "dependencies": {+ "@babel/runtime": "^7.23.1",+ "@mui/base": "5.0.0-beta.19",+ "@mui/system": "^5.14.13",+ "@mui/types": "^7.2.6",+ "@mui/utils": "^5.14.13",+ "@mui/x-tree-view": "6.0.0-alpha.1","clsx": "^2.0.0",- "prop-types": "^15.8.1",- "react-is": "^18.2.0"+ "prop-types": "^15.8.1"},"engines": {"node": ">=12.0.0"@@ -10084,17 +10084,17 @@}},"node_modules/@mui/material": {- "version": "5.14.7",- "resolved": "https://registry.npmjs.org/@mui/material/-/material-5.14.7.tgz",- "integrity": "sha512-jIZj9F7zMv6IlyaYDVv5M2Kp20jIX8c0kzuwteySHS/A0IvPVyomQEPtWc51MCbpDNCqzwoZUp3rQtA2lI8k7A==",- "dependencies": {- "@babel/runtime": "^7.22.10",- "@mui/base": "5.0.0-beta.13",- "@mui/core-downloads-tracker": "^5.14.7",- "@mui/system": "^5.14.7",- "@mui/types": "^7.2.4",- "@mui/utils": "^5.14.7",- "@types/react-transition-group": "^4.4.6",+ "version": "5.14.13",+ "resolved": "https://registry.npmjs.org/@mui/material/-/material-5.14.13.tgz",+ "integrity": "sha512-iPEFwhoVG789UVsXX4gqd1eJUlcLW1oceqwJYQN8Z4MpcAKfL9Lv3fda65AwG7pQ5lf+d7IbHzm4m48SWZxI2g==",+ "dependencies": {+ "@babel/runtime": "^7.23.1",+ "@mui/base": "5.0.0-beta.19",+ "@mui/core-downloads-tracker": "^5.14.13",+ "@mui/system": "^5.14.13",+ "@mui/types": "^7.2.6",+ "@mui/utils": "^5.14.13",+ "@types/react-transition-group": "^4.4.7","clsx": "^2.0.0","csstype": "^3.1.2","prop-types": "^15.8.1",@@ -10128,12 +10128,12 @@}},"node_modules/@mui/private-theming": {- "version": "5.14.7",- "resolved": "https://registry.npmjs.org/@mui/private-theming/-/private-theming-5.14.7.tgz",- "integrity": "sha512-Y86+hmDnJab2Ka42PgxKpK3oL7EiacbeeX3X/lG9LGO0wSc45wZjHeTfIlVSkkUCkexiMKEJp5NlSjZhr27NRQ==",+ "version": "5.14.13",+ "resolved": "https://registry.npmjs.org/@mui/private-theming/-/private-theming-5.14.13.tgz",+ "integrity": "sha512-5EFqk4tqiSwPguj4NW/6bUf4u1qoUWXy9lrKfNh9H6oAohM+Ijv/7qSxFjnxPGBctj469/Sc5aKAR35ILBKZLQ==","dependencies": {- "@babel/runtime": "^7.22.10",- "@mui/utils": "^5.14.7",+ "@babel/runtime": "^7.23.1",+ "@mui/utils": "^5.14.13","prop-types": "^15.8.1"},"engines": {@@ -10154,11 +10154,11 @@}},"node_modules/@mui/styled-engine": {- "version": "5.14.7",- "resolved": "https://registry.npmjs.org/@mui/styled-engine/-/styled-engine-5.14.7.tgz",- "integrity": "sha512-hKBETEDsIAkL8/mBwPiQj/vw28OeIhMXC3Tvj4J2bb9snxAKpiZioR1PwqP+6P41twsC/GKBd0Vr9oaWYaHuMg==",+ "version": "5.14.13",+ "resolved": "https://registry.npmjs.org/@mui/styled-engine/-/styled-engine-5.14.13.tgz",+ "integrity": "sha512-1ff/egFQl26hiwcUtCMKAkp4Sgqpm3qIewmXq+GN27fb44lDIACquehMFBuadOjceOFmbIXbayzbA46ZyqFYzA==","dependencies": {- "@babel/runtime": "^7.22.10",+ "@babel/runtime": "^7.23.1","@emotion/cache": "^11.11.0","csstype": "^3.1.2","prop-types": "^15.8.1"@@ -10185,15 +10185,15 @@}},"node_modules/@mui/system": {- "version": "5.14.7",- "resolved": "https://registry.npmjs.org/@mui/system/-/system-5.14.7.tgz",- "integrity": "sha512-jeZtHglc+Pi6qjGoopT6O4RqYXVBMqHVOsjMGP0hxGSSPm1T4gsAu7jU8eqGx9YwwjvvJ0eotTjFqw7iJ6qE2Q==",- "dependencies": {- "@babel/runtime": "^7.22.10",- "@mui/private-theming": "^5.14.7",- "@mui/styled-engine": "^5.14.7",- "@mui/types": "^7.2.4",- "@mui/utils": "^5.14.7",+ "version": "5.14.13",+ "resolved": "https://registry.npmjs.org/@mui/system/-/system-5.14.13.tgz",+ "integrity": "sha512-+5+Dx50lG4csbx2sGjrKLozXQJeCpJ4dIBZolyFLkZ+XphD1keQWouLUvJkPQ3MSglLLKuD37pp52YjMncZMEQ==",+ "dependencies": {+ "@babel/runtime": "^7.23.1",+ "@mui/private-theming": "^5.14.13",+ "@mui/styled-engine": "^5.14.13",+ "@mui/types": "^7.2.6",+ "@mui/utils": "^5.14.13","clsx": "^2.0.0","csstype": "^3.1.2","prop-types": "^15.8.1"@@ -10224,11 +10224,11 @@}},"node_modules/@mui/types": {- "version": "7.2.4",- "resolved": "https://registry.npmjs.org/@mui/types/-/types-7.2.4.tgz",- "integrity": "sha512-LBcwa8rN84bKF+f5sDyku42w1NTxaPgPyYKODsh01U1fVstTClbUoSA96oyRBnSNyEiAVjKm6Gwx9vjR+xyqHA==",+ "version": "7.2.6",+ "resolved": "https://registry.npmjs.org/@mui/types/-/types-7.2.6.tgz",+ "integrity": "sha512-7sjLQrUmBwufm/M7jw/quNiPK/oor2+pGUQP2CULRcFCArYTq78oJ3D5esTaL0UMkXKJvDqXn6Ike69yAOBQng==","peerDependencies": {- "@types/react": "*"+ "@types/react": "^17.0.0 || ^18.0.0"},"peerDependenciesMeta": {"@types/react": {@@ -10237,13 +10237,12 @@}},"node_modules/@mui/utils": {- "version": "5.14.7",- "resolved": "https://registry.npmjs.org/@mui/utils/-/utils-5.14.7.tgz",- "integrity": "sha512-RtheP/aBoPogVdi8vj8Vo2IFnRa4mZVmnD0RGlVZ49yF60rZs+xP4/KbpIrTr83xVs34QmHQ2aQ+IX7I0a0dDw==",+ "version": "5.14.13",+ "resolved": "https://registry.npmjs.org/@mui/utils/-/utils-5.14.13.tgz",+ "integrity": "sha512-2AFpyXWw7uDCIqRu7eU2i/EplZtks5LAMzQvIhC79sPV9IhOZU2qwOWVnPtdctRXiQJOAaXulg+A37pfhEueQw==","dependencies": {- "@babel/runtime": "^7.22.10",- "@types/prop-types": "^15.7.5",- "@types/react-is": "^18.2.1",+ "@babel/runtime": "^7.23.1",+ "@types/prop-types": "^15.7.7","prop-types": "^15.8.1","react-is": "^18.2.0"},@@ -10255,7 +10254,13 @@"url": "https://opencollective.com/mui"},"peerDependencies": {+ "@types/react": "^17.0.0 || ^18.0.0","react": "^17.0.0 || ^18.0.0"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }}},"node_modules/@mui/x-date-pickers": {@@ -10324,6 +10329,35 @@"node": ">=6"}},+ "node_modules/@mui/x-tree-view": {+ "version": "6.0.0-alpha.1",+ "resolved": "https://registry.npmjs.org/@mui/x-tree-view/-/x-tree-view-6.0.0-alpha.1.tgz",+ "integrity": "sha512-JUG3HmBrmGEALbCFg1b+i7h726e1dWYZs4db3syO1j+Q++E3nbvE4Lehp5yGTFm+8esH0Tny50tuJaa4WX6VSA==",+ "dependencies": {+ "@babel/runtime": "^7.22.6",+ "@mui/utils": "^5.14.3",+ "@types/react-transition-group": "^4.4.6",+ "clsx": "^2.0.0",+ "prop-types": "^15.8.1",+ "react-transition-group": "^4.4.5"+ },+ "engines": {+ "node": ">=14.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/mui"+ },+ "peerDependencies": {+ "@emotion/react": "^11.9.0",+ "@emotion/styled": "^11.8.1",+ "@mui/base": "^5.0.0-alpha.87",+ "@mui/material": "^5.8.6",+ "@mui/system": "^5.8.0",+ "react": "^17.0.0 || ^18.0.0",+ "react-dom": "^17.0.0 || ^18.0.0"+ }+ },"node_modules/@nicolo-ribaudo/eslint-scope-5-internals": {"version": "5.1.1-v1","resolved": "https://registry.npmjs.org/@nicolo-ribaudo/eslint-scope-5-internals/-/eslint-scope-5-internals-5.1.1-v1.tgz",@@ -12661,9 +12695,9 @@"integrity": "sha512-ZTaqn/qSqUuAq1YwvOFQfVW1AR/oQJlLSZVustdjwI+GZ8kr0MSHBj0tsXPW1EqHubx50gtBEjbPGsdZwQwCjQ=="},"node_modules/@types/prop-types": {- "version": "15.7.5",- "resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.5.tgz",- "integrity": "sha512-JCB8C6SnDoQf0cNycqd/35A7MjcnK+ZTqE7judS6o7utxUCg6imJg3QK2qzHKszlTjcj2cn+NwMB2i96ubpj7w=="+ "version": "15.7.8",+ "resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.8.tgz",+ "integrity": "sha512-kMpQpfZKSCBqltAJwskgePRaYRFukDkm1oItcAbC3gNELR20XIBcN9VRgg4+m8DKsTfkWeA4m4Imp4DDuWy7FQ=="},"node_modules/@types/qs": {"version": "6.9.7",@@ -12696,14 +12730,6 @@"@types/react": "*"}},- "node_modules/@types/react-is": {- "version": "18.2.1",- "resolved": "https://registry.npmjs.org/@types/react-is/-/react-is-18.2.1.tgz",- "integrity": "sha512-wyUkmaaSZEzFZivD8F2ftSyAfk6L+DfFliVj/mYdOXbVjRcS87fQJLTnhk6dRZPuJjI+9g6RZJO4PNCngUrmyw==",- "dependencies": {- "@types/react": "*"- }- },"node_modules/@types/react-redux": {"version": "7.1.26","resolved": "https://registry.npmjs.org/@types/react-redux/-/react-redux-7.1.26.tgz",@@ -12737,9 +12763,9 @@}},"node_modules/@types/react-transition-group": {- "version": "4.4.6",- "resolved": "https://registry.npmjs.org/@types/react-transition-group/-/react-transition-group-4.4.6.tgz",- "integrity": "sha512-VnCdSxfcm08KjsJVQcfBmhEQAPnLB8G08hAxn39azX1qYBQ/5RVQuoHuKIcfKOdncuaUvEpFKFzEvbtIMsfVew==",+ "version": "4.4.7",+ "resolved": "https://registry.npmjs.org/@types/react-transition-group/-/react-transition-group-4.4.7.tgz",+ "integrity": "sha512-ICCyBl5mvyqYp8Qeq9B5G/fyBSRC0zx3XM3sCC6KkcMsNeAHqXBKkmat4GqdJET5jtYUpZXrxI5flve5qhi2Eg==","dependencies": {"@types/react": "*"}@@ -18819,9 +18845,9 @@}},"node_modules/electron": {- "version": "25.8.3",- "resolved": "https://registry.npmjs.org/electron/-/electron-25.8.3.tgz",- "integrity": "sha512-BdcTIrhQIf6YgsihCXYh3DgKobtLaNcFb1B5C/5euepxxXQ7qmTWC6WgNUm+IntLOFEDQO926rvm2nhRdSN+Nw==",+ "version": "26.4.0",+ "resolved": "https://registry.npmjs.org/electron/-/electron-26.4.0.tgz",+ "integrity": "sha512-FUEFwmIlflLxImRtTmDp8CWpH4KqlyAwga6vauaz6+882SmyC3bJRhgqOIT5s6rMbW25WezNiaqfKqHDJjz3pw==","dev": true,"hasInstallScript": true,"dependencies": {@@ -49605,9 +49631,9 @@"integrity": "sha512-x/rqGMdzj+fWZvCOYForTghzbtqPDZ5gPwaoNGHdgDfF2QA/XZbCBp4Moo5scrkAMPhB7z26XM/AaHuIJdgauA=="},"@babel/runtime": {- "version": "7.22.11",- "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.22.11.tgz",- "integrity": "sha512-ee7jVNlWN09+KftVOu9n7S8gQzD/Z6hN/I8VBRXW4P1+Xe7kJGXMwu8vds4aGIMHZnNbdpSWCfZZtinytpcAvA==",+ "version": "7.23.2",+ "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.23.2.tgz",+ "integrity": "sha512-mM8eg4yl5D6i3lu2QKPuPH4FArvJ8KhTofbE7jwMUv9KX5mBvwPAqnV3MlyBNqdp9RyRKP6Yck8TrfYrPvX3bg==","requires": {"regenerator-runtime": "^0.14.0"}@@ -49962,16 +49988,17 @@"integrity": "sha512-W2P2c/VRW1/1tLox0mVUalvnWXxavmv/Oum2aPsRcoDJuob75FC3Y8FbpfLwUegRcxINtGUMPq0tFCvYNTBXNA=="},"@emotion/react": {- "version": "11.10.0",- "resolved": "https://registry.npmjs.org/@emotion/react/-/react-11.10.0.tgz",- "integrity": "sha512-K6z9zlHxxBXwN8TcpwBKcEsBsOw4JWCCmR+BeeOWgqp8GIU1yA2Odd41bwdAAr0ssbQrbJbVnndvv7oiv1bZeQ==",+ "version": "11.11.1",+ "resolved": "https://registry.npmjs.org/@emotion/react/-/react-11.11.1.tgz",+ "integrity": "sha512-5mlW1DquU5HaxjLkfkGN1GA/fvVGdyHURRiX/0FHl2cfIfRxSOfmxEH5YS43edp0OldZrZ+dkBKbngxcNCdZvA==","requires": {"@babel/runtime": "^7.18.3",- "@emotion/babel-plugin": "^11.10.0",- "@emotion/cache": "^11.10.0",- "@emotion/serialize": "^1.1.0",- "@emotion/utils": "^1.2.0",- "@emotion/weak-memoize": "^0.3.0",+ "@emotion/babel-plugin": "^11.11.0",+ "@emotion/cache": "^11.11.0",+ "@emotion/serialize": "^1.1.2",+ "@emotion/use-insertion-effect-with-fallbacks": "^1.0.1",+ "@emotion/utils": "^1.2.1",+ "@emotion/weak-memoize": "^0.3.1","hoist-non-react-statics": "^3.3.1"}},@@ -49993,15 +50020,16 @@"integrity": "sha512-0QBtGvaqtWi+nx6doRwDdBIzhNdZrXUppvTM4dtZZWEGTXL/XE/yJxLMGlDT1Gt+UHH5IX1n+jkXyytE/av7OA=="},"@emotion/styled": {- "version": "11.10.0",- "resolved": "https://registry.npmjs.org/@emotion/styled/-/styled-11.10.0.tgz",- "integrity": "sha512-V9oaEH6V4KePeQpgUE83i8ht+4Ri3E8Djp/ZPJ4DQlqWhSKITvgzlR3/YQE2hdfP4Jw3qVRkANJz01LLqK9/TA==",+ "version": "11.11.0",+ "resolved": "https://registry.npmjs.org/@emotion/styled/-/styled-11.11.0.tgz",+ "integrity": "sha512-hM5Nnvu9P3midq5aaXj4I+lnSfNi7Pmd4EWk1fOZ3pxookaQTNew6bp4JaCBYM4HVFZF9g7UjJmsUmC2JlxOng==","requires": {"@babel/runtime": "^7.18.3",- "@emotion/babel-plugin": "^11.10.0",- "@emotion/is-prop-valid": "^1.2.0",- "@emotion/serialize": "^1.1.0",- "@emotion/utils": "^1.2.0"+ "@emotion/babel-plugin": "^11.11.0",+ "@emotion/is-prop-valid": "^1.2.1",+ "@emotion/serialize": "^1.1.2",+ "@emotion/use-insertion-effect-with-fallbacks": "^1.0.1",+ "@emotion/utils": "^1.2.1"}},"@emotion/unitless": {@@ -50009,6 +50037,12 @@"resolved": "https://registry.npmjs.org/@emotion/unitless/-/unitless-0.8.1.tgz","integrity": "sha512-KOEGMu6dmJZtpadb476IsZBclKvILjopjUii3V+7MnXIQCYh8W3NgNcgwo21n9LXZX6EDIKvqfjYxXebDwxKmQ=="},+ "@emotion/use-insertion-effect-with-fallbacks": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/@emotion/use-insertion-effect-with-fallbacks/-/use-insertion-effect-with-fallbacks-1.0.1.tgz",+ "integrity": "sha512-jT/qyKZ9rzLErtrjGgdkMBn2OP8wl0G3sQlBb3YPryvKHsjvINUhVaPFfP+fpBcOkmrVOVEEHQFJ7nbj2TH2gw==",+ "requires": {}+ },"@emotion/utils": {"version": "1.2.1","resolved": "https://registry.npmjs.org/@emotion/utils/-/utils-1.2.1.tgz",@@ -50094,20 +50128,20 @@"dev": true},"@floating-ui/core": {- "version": "1.4.1",- "resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.4.1.tgz",- "integrity": "sha512-jk3WqquEJRlcyu7997NtR5PibI+y5bi+LS3hPmguVClypenMsCY3CBa3LAQnozRCtCrYWSEtAdiskpamuJRFOQ==",+ "version": "1.5.0",+ "resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.5.0.tgz",+ "integrity": "sha512-kK1h4m36DQ0UHGj5Ah4db7R0rHemTqqO0QLvUqi1/mUUp3LuAWbWxdxSIf/XsnH9VS6rRVPLJCncjRzUvyCLXg==","requires": {- "@floating-ui/utils": "^0.1.1"+ "@floating-ui/utils": "^0.1.3"}},"@floating-ui/dom": {- "version": "1.5.1",- "resolved": "https://registry.npmjs.org/@floating-ui/dom/-/dom-1.5.1.tgz",- "integrity": "sha512-KwvVcPSXg6mQygvA1TjbN/gh///36kKtllIF8SUm0qpFj8+rvYrpvlYdL1JoA71SHpDqgSSdGOSoQ0Mp3uY5aw==",+ "version": "1.5.3",+ "resolved": "https://registry.npmjs.org/@floating-ui/dom/-/dom-1.5.3.tgz",+ "integrity": "sha512-ClAbQnEqJAKCJOEbbLo5IUlZHkNszqhuxS4fHAVxRPXPya6Ysf2G8KypnYcOTpx6I8xcgF9bbHb6g/2KpbV8qA==","requires": {- "@floating-ui/core": "^1.4.1",- "@floating-ui/utils": "^0.1.1"+ "@floating-ui/core": "^1.4.2",+ "@floating-ui/utils": "^0.1.3"}},"@floating-ui/react-dom": {@@ -50119,9 +50153,9 @@}},"@floating-ui/utils": {- "version": "0.1.1",- "resolved": "https://registry.npmjs.org/@floating-ui/utils/-/utils-0.1.1.tgz",- "integrity": "sha512-m0G6wlnhm/AX0H12IOWtK8gASEMffnX08RtKkCgTdHb9JpHKGloI7icFfLg9ZmQeavcvR0PKmzxClyuFPSjKWw=="+ "version": "0.1.6",+ "resolved": "https://registry.npmjs.org/@floating-ui/utils/-/utils-0.1.6.tgz",+ "integrity": "sha512-OfX7E2oUDYxtBvsuS4e/jSn4Q9Qb6DzgeYtsAdkPZ47znpoNsMgZw0+tVijiv3uGNR6dgNlty6r9rzIzHjtd/A=="},"@gorillastack/jmespath": {"version": "1.3.0",@@ -50688,61 +50722,59 @@}},"@mui/base": {- "version": "5.0.0-beta.13",- "resolved": "https://registry.npmjs.org/@mui/base/-/base-5.0.0-beta.13.tgz",- "integrity": "sha512-uC0l97pBspfDAp+iz2cJq8YZ8Sd9i73V77+WzUiOAckIVEyCm5dyVDZCCO2/phmzckVEeZCGcytybkjMQuhPQw==",- "requires": {- "@babel/runtime": "^7.22.10",- "@emotion/is-prop-valid": "^1.2.1",- "@floating-ui/react-dom": "^2.0.1",- "@mui/types": "^7.2.4",- "@mui/utils": "^5.14.7",+ "version": "5.0.0-beta.19",+ "resolved": "https://registry.npmjs.org/@mui/base/-/base-5.0.0-beta.19.tgz",+ "integrity": "sha512-maNBgAscddyPNzFZQUJDF/puxM27Li+NqSBsr/lAP8TLns2VvWS2SoL3OKFOIoRnAMKGY/Ic6Aot6gCYeQnssA==",+ "requires": {+ "@babel/runtime": "^7.23.1",+ "@floating-ui/react-dom": "^2.0.2",+ "@mui/types": "^7.2.6",+ "@mui/utils": "^5.14.13","@popperjs/core": "^2.11.8","clsx": "^2.0.0",- "prop-types": "^15.8.1",- "react-is": "^18.2.0"+ "prop-types": "^15.8.1"}},"@mui/core-downloads-tracker": {- "version": "5.14.7",- "resolved": "https://registry.npmjs.org/@mui/core-downloads-tracker/-/core-downloads-tracker-5.14.7.tgz",- "integrity": "sha512-sCWTUNElBPgB30iLvWe3PU7SIlTKZNf6/E/sko85iHVeHCM6WPkDw+y89CrZYjhFNmPqt2fIQM/pZu+rP2lFLA=="+ "version": "5.14.13",+ "resolved": "https://registry.npmjs.org/@mui/core-downloads-tracker/-/core-downloads-tracker-5.14.13.tgz",+ "integrity": "sha512-3ZUbzcH4yloLKlV6Y+S0Edn2wef9t+EGHSfEkwVCn8E0ULdshifEFgfEroKRegQifDIwcKS/ofccxuZ8njTAYg=="},"@mui/icons-material": {- "version": "5.14.7",- "resolved": "https://registry.npmjs.org/@mui/icons-material/-/icons-material-5.14.7.tgz",- "integrity": "sha512-mWp4DwMa8c1Gx9yOEtPgxM4b+e6hAbtZyzfSubdBwrnEE6G5D2rbAJ5MB+If6kfI48JaYaJ5j8+zAdmZLuZc0A==",+ "version": "5.14.13",+ "resolved": "https://registry.npmjs.org/@mui/icons-material/-/icons-material-5.14.13.tgz",+ "integrity": "sha512-fxKE1UrjI4xVxHe9IAGuVQZrc18dSBJg0P+Sqi2SZmcDUCShmgRq6Jq7l7GduvuMIkOSqAJdNgLtXmtmZkjtLg==","requires": {- "@babel/runtime": "^7.22.10"+ "@babel/runtime": "^7.23.1"}},"@mui/lab": {- "version": "5.0.0-alpha.142",- "resolved": "https://registry.npmjs.org/@mui/lab/-/lab-5.0.0-alpha.142.tgz",- "integrity": "sha512-JDrT5G3QBZ0nzkKMFWzJY5KN8WcyDx4p7qOjg6hs7yKLq90VSdsqIOmyhvWDxJR7zPNQjo0WRYBAaRaQ5FlGxg==",- "requires": {- "@babel/runtime": "^7.22.10",- "@mui/base": "5.0.0-beta.13",- "@mui/system": "^5.14.7",- "@mui/types": "^7.2.4",- "@mui/utils": "^5.14.7",+ "version": "5.0.0-alpha.148",+ "resolved": "https://registry.npmjs.org/@mui/lab/-/lab-5.0.0-alpha.148.tgz",+ "integrity": "sha512-FfgHSYO59tznwMkn6FAjuowU1KteTV2AQRD7NsZq82TpiRBpBFkDtcsap02uf+rRVdwgF/yokdYLtVJ96snDGA==",+ "requires": {+ "@babel/runtime": "^7.23.1",+ "@mui/base": "5.0.0-beta.19",+ "@mui/system": "^5.14.13",+ "@mui/types": "^7.2.6",+ "@mui/utils": "^5.14.13",+ "@mui/x-tree-view": "6.0.0-alpha.1","clsx": "^2.0.0",- "prop-types": "^15.8.1",- "react-is": "^18.2.0"+ "prop-types": "^15.8.1"}},"@mui/material": {- "version": "5.14.7",- "resolved": "https://registry.npmjs.org/@mui/material/-/material-5.14.7.tgz",- "integrity": "sha512-jIZj9F7zMv6IlyaYDVv5M2Kp20jIX8c0kzuwteySHS/A0IvPVyomQEPtWc51MCbpDNCqzwoZUp3rQtA2lI8k7A==",- "requires": {- "@babel/runtime": "^7.22.10",- "@mui/base": "5.0.0-beta.13",- "@mui/core-downloads-tracker": "^5.14.7",- "@mui/system": "^5.14.7",- "@mui/types": "^7.2.4",- "@mui/utils": "^5.14.7",- "@types/react-transition-group": "^4.4.6",+ "version": "5.14.13",+ "resolved": "https://registry.npmjs.org/@mui/material/-/material-5.14.13.tgz",+ "integrity": "sha512-iPEFwhoVG789UVsXX4gqd1eJUlcLW1oceqwJYQN8Z4MpcAKfL9Lv3fda65AwG7pQ5lf+d7IbHzm4m48SWZxI2g==",+ "requires": {+ "@babel/runtime": "^7.23.1",+ "@mui/base": "5.0.0-beta.19",+ "@mui/core-downloads-tracker": "^5.14.13",+ "@mui/system": "^5.14.13",+ "@mui/types": "^7.2.6",+ "@mui/utils": "^5.14.13",+ "@types/react-transition-group": "^4.4.7","clsx": "^2.0.0","csstype": "^3.1.2","prop-types": "^15.8.1",@@ -50751,55 +50783,54 @@}},"@mui/private-theming": {- "version": "5.14.7",- "resolved": "https://registry.npmjs.org/@mui/private-theming/-/private-theming-5.14.7.tgz",- "integrity": "sha512-Y86+hmDnJab2Ka42PgxKpK3oL7EiacbeeX3X/lG9LGO0wSc45wZjHeTfIlVSkkUCkexiMKEJp5NlSjZhr27NRQ==",+ "version": "5.14.13",+ "resolved": "https://registry.npmjs.org/@mui/private-theming/-/private-theming-5.14.13.tgz",+ "integrity": "sha512-5EFqk4tqiSwPguj4NW/6bUf4u1qoUWXy9lrKfNh9H6oAohM+Ijv/7qSxFjnxPGBctj469/Sc5aKAR35ILBKZLQ==","requires": {- "@babel/runtime": "^7.22.10",- "@mui/utils": "^5.14.7",+ "@babel/runtime": "^7.23.1",+ "@mui/utils": "^5.14.13","prop-types": "^15.8.1"}},"@mui/styled-engine": {- "version": "5.14.7",- "resolved": "https://registry.npmjs.org/@mui/styled-engine/-/styled-engine-5.14.7.tgz",- "integrity": "sha512-hKBETEDsIAkL8/mBwPiQj/vw28OeIhMXC3Tvj4J2bb9snxAKpiZioR1PwqP+6P41twsC/GKBd0Vr9oaWYaHuMg==",+ "version": "5.14.13",+ "resolved": "https://registry.npmjs.org/@mui/styled-engine/-/styled-engine-5.14.13.tgz",+ "integrity": "sha512-1ff/egFQl26hiwcUtCMKAkp4Sgqpm3qIewmXq+GN27fb44lDIACquehMFBuadOjceOFmbIXbayzbA46ZyqFYzA==","requires": {- "@babel/runtime": "^7.22.10",+ "@babel/runtime": "^7.23.1","@emotion/cache": "^11.11.0","csstype": "^3.1.2","prop-types": "^15.8.1"}},"@mui/system": {- "version": "5.14.7",- "resolved": "https://registry.npmjs.org/@mui/system/-/system-5.14.7.tgz",- "integrity": "sha512-jeZtHglc+Pi6qjGoopT6O4RqYXVBMqHVOsjMGP0hxGSSPm1T4gsAu7jU8eqGx9YwwjvvJ0eotTjFqw7iJ6qE2Q==",- "requires": {- "@babel/runtime": "^7.22.10",- "@mui/private-theming": "^5.14.7",- "@mui/styled-engine": "^5.14.7",- "@mui/types": "^7.2.4",- "@mui/utils": "^5.14.7",+ "version": "5.14.13",+ "resolved": "https://registry.npmjs.org/@mui/system/-/system-5.14.13.tgz",+ "integrity": "sha512-+5+Dx50lG4csbx2sGjrKLozXQJeCpJ4dIBZolyFLkZ+XphD1keQWouLUvJkPQ3MSglLLKuD37pp52YjMncZMEQ==",+ "requires": {+ "@babel/runtime": "^7.23.1",+ "@mui/private-theming": "^5.14.13",+ "@mui/styled-engine": "^5.14.13",+ "@mui/types": "^7.2.6",+ "@mui/utils": "^5.14.13","clsx": "^2.0.0","csstype": "^3.1.2","prop-types": "^15.8.1"}},"@mui/types": {- "version": "7.2.4",- "resolved": "https://registry.npmjs.org/@mui/types/-/types-7.2.4.tgz",- "integrity": "sha512-LBcwa8rN84bKF+f5sDyku42w1NTxaPgPyYKODsh01U1fVstTClbUoSA96oyRBnSNyEiAVjKm6Gwx9vjR+xyqHA==",+ "version": "7.2.6",+ "resolved": "https://registry.npmjs.org/@mui/types/-/types-7.2.6.tgz",+ "integrity": "sha512-7sjLQrUmBwufm/M7jw/quNiPK/oor2+pGUQP2CULRcFCArYTq78oJ3D5esTaL0UMkXKJvDqXn6Ike69yAOBQng==","requires": {}},"@mui/utils": {- "version": "5.14.7",- "resolved": "https://registry.npmjs.org/@mui/utils/-/utils-5.14.7.tgz",- "integrity": "sha512-RtheP/aBoPogVdi8vj8Vo2IFnRa4mZVmnD0RGlVZ49yF60rZs+xP4/KbpIrTr83xVs34QmHQ2aQ+IX7I0a0dDw==",+ "version": "5.14.13",+ "resolved": "https://registry.npmjs.org/@mui/utils/-/utils-5.14.13.tgz",+ "integrity": "sha512-2AFpyXWw7uDCIqRu7eU2i/EplZtks5LAMzQvIhC79sPV9IhOZU2qwOWVnPtdctRXiQJOAaXulg+A37pfhEueQw==","requires": {- "@babel/runtime": "^7.22.10",- "@types/prop-types": "^15.7.5",- "@types/react-is": "^18.2.1",+ "@babel/runtime": "^7.23.1",+ "@types/prop-types": "^15.7.7","prop-types": "^15.8.1","react-is": "^18.2.0"}@@ -50830,6 +50861,19 @@}}},+ "@mui/x-tree-view": {+ "version": "6.0.0-alpha.1",+ "resolved": "https://registry.npmjs.org/@mui/x-tree-view/-/x-tree-view-6.0.0-alpha.1.tgz",+ "integrity": "sha512-JUG3HmBrmGEALbCFg1b+i7h726e1dWYZs4db3syO1j+Q++E3nbvE4Lehp5yGTFm+8esH0Tny50tuJaa4WX6VSA==",+ "requires": {+ "@babel/runtime": "^7.22.6",+ "@mui/utils": "^5.14.3",+ "@types/react-transition-group": "^4.4.6",+ "clsx": "^2.0.0",+ "prop-types": "^15.8.1",+ "react-transition-group": "^4.4.5"+ }+ },"@nicolo-ribaudo/eslint-scope-5-internals": {"version": "5.1.1-v1","resolved": "https://registry.npmjs.org/@nicolo-ribaudo/eslint-scope-5-internals/-/eslint-scope-5-internals-5.1.1-v1.tgz",@@ -52650,9 +52694,9 @@"integrity": "sha512-ZTaqn/qSqUuAq1YwvOFQfVW1AR/oQJlLSZVustdjwI+GZ8kr0MSHBj0tsXPW1EqHubx50gtBEjbPGsdZwQwCjQ=="},"@types/prop-types": {- "version": "15.7.5",- "resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.5.tgz",- "integrity": "sha512-JCB8C6SnDoQf0cNycqd/35A7MjcnK+ZTqE7judS6o7utxUCg6imJg3QK2qzHKszlTjcj2cn+NwMB2i96ubpj7w=="+ "version": "15.7.8",+ "resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.8.tgz",+ "integrity": "sha512-kMpQpfZKSCBqltAJwskgePRaYRFukDkm1oItcAbC3gNELR20XIBcN9VRgg4+m8DKsTfkWeA4m4Imp4DDuWy7FQ=="},"@types/qs": {"version": "6.9.7",@@ -52685,14 +52729,6 @@"@types/react": "*"}},- "@types/react-is": {- "version": "18.2.1",- "resolved": "https://registry.npmjs.org/@types/react-is/-/react-is-18.2.1.tgz",- "integrity": "sha512-wyUkmaaSZEzFZivD8F2ftSyAfk6L+DfFliVj/mYdOXbVjRcS87fQJLTnhk6dRZPuJjI+9g6RZJO4PNCngUrmyw==",- "requires": {- "@types/react": "*"- }- },"@types/react-redux": {"version": "7.1.26","resolved": "https://registry.npmjs.org/@types/react-redux/-/react-redux-7.1.26.tgz",@@ -52726,9 +52762,9 @@}},"@types/react-transition-group": {- "version": "4.4.6",- "resolved": "https://registry.npmjs.org/@types/react-transition-group/-/react-transition-group-4.4.6.tgz",- "integrity": "sha512-VnCdSxfcm08KjsJVQcfBmhEQAPnLB8G08hAxn39azX1qYBQ/5RVQuoHuKIcfKOdncuaUvEpFKFzEvbtIMsfVew==",+ "version": "4.4.7",+ "resolved": "https://registry.npmjs.org/@types/react-transition-group/-/react-transition-group-4.4.7.tgz",+ "integrity": "sha512-ICCyBl5mvyqYp8Qeq9B5G/fyBSRC0zx3XM3sCC6KkcMsNeAHqXBKkmat4GqdJET5jtYUpZXrxI5flve5qhi2Eg==","requires": {"@types/react": "*"}@@ -57496,9 +57532,9 @@}},"electron": {- "version": "25.8.3",- "resolved": "https://registry.npmjs.org/electron/-/electron-25.8.3.tgz",- "integrity": "sha512-BdcTIrhQIf6YgsihCXYh3DgKobtLaNcFb1B5C/5euepxxXQ7qmTWC6WgNUm+IntLOFEDQO926rvm2nhRdSN+Nw==",+ "version": "26.4.0",+ "resolved": "https://registry.npmjs.org/electron/-/electron-26.4.0.tgz",+ "integrity": "sha512-FUEFwmIlflLxImRtTmDp8CWpH4KqlyAwga6vauaz6+882SmyC3bJRhgqOIT5s6rMbW25WezNiaqfKqHDJjz3pw==","dev": true,"requires": {"@electron/get": "^2.0.0",diff --git a/package.json b/package.jsonindex 7d1091fe6..46fd13b2e 100644--- a/package.json+++ b/package.json@@ -48,6 +48,7 @@"cordova-remove-android": "cd cordova && cordova platform remove android && cd ..","cordova-remove-ios": "cd cordova && cordova platform remove ios && cd ..","dev": "npm run prepare-node && npm run generate-jwt && npm run generate-extensions && node -r @babel/register ./internals/scripts/CheckPortInUse.js && cross-env START_HOT=0 npm run start-renderer-dev",+ "dev-open-file": "git apply run-with-args.patch && npm run dev","generate-jwt": "node scripts/jwt_generate.js","generate-extensions": "node scripts/generateExtensionsConfig.js","install-ext-node-check": "npx cross-env PD_PLATFORM=node node scripts/checkWSinstalled.js",@@ -139,14 +140,14 @@},"dependencies": {"@aws-amplify/ui-react": "^1.2.26",- "@date-io/date-fns": "^2.16.0",+ "@date-io/date-fns": "^2.17.0","@elife/pm2": "^3.6.1",- "@emotion/react": "11.10.0",- "@emotion/styled": "11.10.0",+ "@emotion/react": "11.11.1",+ "@emotion/styled": "11.11.0","@gorillastack/jmespath": "^1.3.0",- "@mui/icons-material": "^5.13.7",- "@mui/lab": "^5.0.0-alpha.135",- "@mui/material": "^5.13.7",+ "@mui/icons-material": "^5.14.13",+ "@mui/lab": "^5.0.0-alpha.148",+ "@mui/material": "^5.14.13","@mui/x-date-pickers": "^5.0.20","@tagspaces/tagspaces-common": "3.0.17","@tagspaces/tagspaces-md": "3.0.19",@@ -262,7 +263,7 @@"current-git-branch": "^1.1.0","detect-port": "^1.3.0","dotenv-webpack": "^8.0.1",- "electron": "25.8.3",+ "electron": "26.4.0","electron-builder": "^24.4.0","electron-devtools-installer": "^3.2.0","electron-notarize": "^1.2.2",diff --git a/run-with-args.patch b/run-with-args.patchnew file mode 100644index 000000000..a00b8d9e8--- /dev/null+++ b/run-with-args.patch@@ -0,0 +1,30 @@+Index: app/main.dev.ts+IDEA additional info:+Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP+<+>UTF-8+===================================================================+diff --git a/app/main.dev.ts b/app/main.dev.ts+--- a/app/main.dev.ts (revision d0f660fb4378c8eb8c59c516ecd10ff161c63d67)++++ b/app/main.dev.ts (date 1697032441057)+@@ -90,6 +90,8 @@+ const devMode =+ process.env.NODE_ENV === 'development' || process.env.DEBUG_PROD === 'true';+++process.argv = [...process.argv, 'C:\\Users\\Stanimir\\search_history.png'];+++ process.argv.forEach((arg, count) => {+ console.log('Opening file: ' + arg);+ if (+@@ -102,10 +104,10 @@+ } else if (arg.toLowerCase() === '-p' || arg.toLowerCase() === '--portable') {+ app.setPath('userData', process.cwd() + '/tsprofile'); // making the app portable+ portableMode = true;+- } else if (testMode || devMode) {++ } /* else if (testMode || devMode) {+ // ignoring the spectron testing+ arg = '';+- } else if (++ } */ else if (+ arg.endsWith('main.prod.js') ||+ arg === './app/main.dev.babel.js' ||+ arg === '.' ||