Skip to content

TagSpaces is an offline, open source, document manager with tagging support

opened-entries-refactoring (#1988)

Stanimir2601d96ca45c
diff --git a/app/components/EditDescription.tsx b/app/components/EditDescription.tsx
index a7e61fc72..d3d318ac9 100644
--- a/app/components/EditDescription.tsx
+++ b/app/components/EditDescription.tsx
@@ -1,32 +1,23 @@
import React, { useRef, useState, useEffect } from 'react';
import { styled, useTheme } from '@mui/material/styles';
-import Button from '@mui/material/Button';
import Typography from '@mui/material/Typography';
import { MilkdownEditor, MilkdownRef } from '@tagspaces/tagspaces-md';
-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, getOpenedFiles, OpenedEntry } from '-/reducers/app';
-import { useDescriptionContext } from '-/components/hooks/useDescriptionContext';
+import { getDirectoryPath, OpenedEntry } from '-/reducers/app';
+import { useDescriptionContext } from '-/hooks/useDescriptionContext';
+import { useOpenedEntryContext } from '-/hooks/useOpenedEntryContext';
+import EditDescriptionButtons from '-/components/EditDescriptionButtons';
const PREFIX = 'EditDescription';
const classes = {
- button: `${PREFIX}-button`,
mdHelpers: `${PREFIX}-mdHelpers`,
formControl: `${PREFIX}-formControl`
};
const Root = styled('div')(({ theme }) => ({
height: '90%',
- [`& .${classes.button}`]: {
- position: 'relative',
- padding: '8px 12px 6px 8px',
- margin: '0'
- },
-
[`& .${classes.mdHelpers}`]: {
borderRadius: '0.25rem',
paddingLeft: '0.25rem',
@@ -42,21 +33,19 @@ const Root = styled('div')(({ theme }) => ({
function EditDescription() {
const { t } = useTranslation();
const theme = useTheme();
- const openedFiles: Array<OpenedEntry> = useSelector(getOpenedFiles);
- const openedFile: OpenedEntry = openedFiles[0];
+ const { openedEntries } = useOpenedEntryContext();
+ const openedFile: OpenedEntry = openedEntries[0];
const currentFolder = useSelector(getDirectoryPath);
const fileDescriptionRef = useRef<MilkdownRef>(null);
- const {
- description,
- setDescription,
- saveDescription
- } = useDescriptionContext();
+ const { description, setDescription } = useDescriptionContext();
+
const [editMode, setEditMode] = useState<boolean>(false);
const descriptionFocus = useRef<boolean>(false);
+ const descriptionButtonsRef = useRef(null);
useEffect(() => {
fileDescriptionRef.current?.setDarkMode(theme.palette.mode === 'dark');
- }, [theme]); // , settings]);
+ }, [theme]);
/*const keyBindingHandlers = {
saveDocument: () => {
@@ -72,6 +61,7 @@ function EditDescription() {
const milkdownListener = React.useCallback((markdown: string) => {
if (descriptionFocus.current && markdown !== description) {
setDescription(markdown);
+ descriptionButtonsRef.current.setDescriptionChanged(true);
}
// update codeMirror
/*const { current } = codeMirrorRef;
@@ -79,59 +69,6 @@ function EditDescription() {
current.update(markdown);*/
}, []);
- const printHTML = () => {
- const sanitizedDescription = description
- ? convertMarkDown(description, currentFolder)
- : t('core:addMarkdownDescription');
-
- const printWin = window.open('', 'PRINT', 'height=400,width=600');
- printWin.document.write(
- '<html><head><title>' + currentFolder + ' description</title>'
- );
- printWin.document.write('</head><body >');
- printWin.document.write(sanitizedDescription);
- printWin.document.write('</body></html>');
- printWin.document.close(); // necessary for IE >= 10
- printWin.focus(); // necessary for IE >= 10*/
- printWin.print();
- // printWin.close();
- return true;
- };
-
- const editSaveActions = (
- <span style={{ float: 'right' }}>
- {editMode && (
- <Button
- className={classes.button}
- onClick={() => {
- setEditMode(false);
- }}
- >
- {t('core:cancel')}
- </Button>
- )}
- {!editMode && (
- <Button className={classes.button} onClick={printHTML}>
- {t('core:print')}
- </Button>
- )}
- <ProTooltip tooltip={t('editDescription')}>
- <Button
- data-tid="editDescriptionTID"
- color="primary"
- className={classes.button}
- disabled={!Pro}
- onClick={() => {
- setEditMode(!editMode);
- saveDescription();
- }}
- >
- {editMode ? t('core:confirmSaveButton') : t('core:edit')}
- </Button>
- </ProTooltip>
- </span>
- );
-
const noDescription = !description || description.length < 1;
return (
<Root>
@@ -154,7 +91,13 @@ function EditDescription() {
{t('core:filePropertiesDescription')}
</Typography>*/}
</span>
- {!openedFile.editMode && editSaveActions}
+ {!openedFile.editMode && (
+ <EditDescriptionButtons
+ buttonsRef={descriptionButtonsRef}
+ editMode={editMode}
+ setEditMode={setEditMode}
+ />
+ )}
<div
data-tid="descriptionTID"
onDoubleClick={() => {
diff --git a/app/components/EditDescriptionButtons.tsx b/app/components/EditDescriptionButtons.tsx
new file mode 100644
index 000000000..c3022dcfa
--- /dev/null
+++ b/app/components/EditDescriptionButtons.tsx
@@ -0,0 +1,139 @@
+import React, { ForwardedRef, useEffect, useState } from 'react';
+import { styled } from '@mui/material/styles';
+import Button from '@mui/material/Button';
+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';
+
+const PREFIX = 'EditDescriptionButtons';
+
+const classes = {
+ button: `${PREFIX}-button`
+};
+
+const Root = styled('span')(({ theme }) => ({
+ float: 'right',
+ [`& .${classes.button}`]: {
+ position: 'relative',
+ padding: '8px 12px 6px 8px',
+ margin: '0'
+ }
+}));
+
+export interface DescriptionChangedRef {
+ setDescriptionChanged: (changed: boolean) => void;
+}
+
+type Props = {
+ buttonsRef: ForwardedRef<DescriptionChangedRef>;
+ editMode: boolean;
+ setEditMode: (edit: boolean) => void;
+};
+
+const EditDescriptionButtons: React.FC<Props> = ({
+ buttonsRef,
+ editMode,
+ setEditMode
+}) => {
+ const { t } = useTranslation();
+ const currentFolder = useSelector(getDirectoryPath);
+ const {
+ description,
+ isSaveDescriptionConfirmOpened,
+ setSaveDescriptionConfirmOpened,
+ saveDescription
+ } = useDescriptionContext();
+ const [isDescriptionChanged, descriptionChanged] = useState<boolean>(false);
+
+ React.useImperativeHandle(buttonsRef, () => ({
+ setDescriptionChanged: changed => {
+ descriptionChanged(changed);
+ }
+ }));
+
+ useEffect(() => {
+ if (!editMode && isDescriptionChanged) {
+ descriptionChanged(false);
+ }
+ }, [editMode]);
+
+ const printHTML = () => {
+ const sanitizedDescription = description
+ ? convertMarkDown(description, currentFolder)
+ : t('core:addMarkdownDescription');
+
+ const printWin = window.open('', 'PRINT', 'height=400,width=600');
+ printWin.document.write(
+ '<html><head><title>' + currentFolder + ' description</title>'
+ );
+ printWin.document.write('</head><body >');
+ printWin.document.write(sanitizedDescription);
+ printWin.document.write('</body></html>');
+ printWin.document.close(); // necessary for IE >= 10
+ printWin.focus(); // necessary for IE >= 10*/
+ printWin.print();
+ // printWin.close();
+ return true;
+ };
+
+ return (
+ <Root>
+ {editMode && (
+ <Button
+ className={classes.button}
+ onClick={() => {
+ setEditMode(false);
+ }}
+ >
+ {t(isDescriptionChanged ? 'core:cancel' : 'core:close')}
+ </Button>
+ )}
+ {!editMode && (
+ <Button className={classes.button} onClick={printHTML}>
+ {t('core:print')}
+ </Button>
+ )}
+ <ProTooltip tooltip={t('editDescription')}>
+ <Button
+ data-tid="editDescriptionTID"
+ color="primary"
+ className={classes.button}
+ disabled={!Pro}
+ onClick={() => {
+ if (editMode) {
+ saveDescription();
+ }
+ setEditMode(!editMode);
+ }}
+ >
+ {editMode ? t('core:confirmSaveButton') : t('core:edit')}
+ </Button>
+ </ProTooltip>
+ <ConfirmDialog
+ open={isSaveDescriptionConfirmOpened}
+ onClose={() => {
+ setSaveDescriptionConfirmOpened(false);
+ }}
+ title={t('core:confirm')}
+ content={t('core:saveFileBeforeClosingFile')}
+ confirmCallback={result => {
+ if (result) {
+ saveDescription();
+ } else {
+ setSaveDescriptionConfirmOpened(false);
+ }
+ }}
+ cancelDialogTID="cancelSaveDescCloseDialog"
+ confirmDialogTID="confirmSaveDescCloseDialog"
+ confirmDialogContentTID="confirmDescDialogContent"
+ />
+ </Root>
+ );
+};
+
+export default EditDescriptionButtons;
diff --git a/app/components/EntryContainer.tsx b/app/components/EntryContainer.tsx
index 898aa70d9..8ec89ec3f 100644
--- a/app/components/EntryContainer.tsx
+++ b/app/components/EntryContainer.tsx
@@ -24,8 +24,7 @@ import React, {
useRef,
useState
} from 'react';
-import { connect, useSelector } from 'react-redux';
-import { bindActionCreators } from 'redux';
+import { useDispatch, useSelector } from 'react-redux';
import { GlobalHotKeys } from 'react-hotkeys';
import fscreen from 'fscreen';
import Button from '@mui/material/Button';
@@ -40,8 +39,6 @@ import { getUuid } from '@tagspaces/tagspaces-common/utils-io';
import { buffer } from '@tagspaces/tagspaces-common/misc';
import AppConfig from '-/AppConfig';
import {
- getMetaFileLocationForDir,
- getMetaFileLocationForFile,
extractContainingDirectoryPath,
getBackupFileLocation,
extractFileExtension
@@ -50,139 +47,68 @@ import ConfirmDialog from '-/components/dialogs/ConfirmDialog';
import PlatformIO from '-/services/platform-facade';
import AddRemoveTagsDialog from '-/components/dialogs/AddRemoveTagsDialog';
import {
- actions as SettingsActions,
isDesktopMode,
getKeyBindingObject,
isRevisionsEnabled,
- getEntryContainerTab
+ getEntryContainerTab,
+ getFileEditHistoryKey
} from '-/reducers/settings';
import {
OpenedEntry,
NotificationTypes,
isReadOnlyMode,
actions as AppActions,
- getDirectoryPath
+ getDirectoryPath,
+ AppDispatch
} from '-/reducers/app';
import useEventListener from '-/utils/useEventListener';
import { TS } from '-/tagspaces.namespace';
import FileView from '-/components/FileView';
import { Pro } from '-/pro';
-import { actions as LocationActions } from '-/reducers/locations';
import { Switch } from '@mui/material';
import useFirstRender from '-/utils/useFirstRender';
import ResolveConflictDialog from '-/components/dialogs/ResolveConflictDialog';
-import { loadJSONFile } from '-/services/utils-io';
import { styled, 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 '-/components/hooks/useDescriptionContext';
+import { useDescriptionContext } from '-/hooks/useDescriptionContext';
+import { useOpenedEntryContext } from '-/hooks/useOpenedEntryContext';
//const defaultSplitSize = '7.86%'; // '7.2%'; // 103;
-
-const bufferedSplitResize = buffer({
- timeout: 300,
- id: 'buffered-split-resize'
-});
-
-const PREFIX = 'EntryContainer';
-const classes = {
- toolbar2: `${PREFIX}-toolbar2`,
- flexLeft: `${PREFIX}-flexLeft`
-};
-
-const Root = styled(Box)(({ theme }) => ({
- width: '100%',
- flexDirection: 'column',
- flex: '1 1 100%',
- display: 'flex',
- backgroundColor: theme.palette.background.default,
- borderBottom: '5px solid ' + theme.palette.background.default,
- overflow: 'hidden',
- // height: '100%', // filePropsHeight ||
- [`& .${classes.toolbar2}`]: {
- width: '100%',
- paddingLeft: 0,
- paddingRight: 5,
- paddingTop: 0,
- display: 'flex',
- flexDirection: 'row',
- justifyContent: 'flex-start',
- zIndex: 2
- // borderBottom: '1px solid ' + theme.palette.divider
- },
- [`& .${classes.flexLeft}`]: {
- flexDirection: 'row',
- flex: '1 1',
- display: 'flex',
- alignItems: 'baseline',
- overflowX: 'auto',
- overflowY: 'hidden',
- paddingRight: 100
- }
-}));
-
-interface Props {
- openedFiles: Array<OpenedEntry>;
- settings: any;
- keyBindings: any;
- closeAllFiles: () => void;
- openPrevFile: (path: string) => void;
- openNextFile: (path: string) => void;
- //openFileNatively: (path: string) => void;
- //openLink: (url: string, options?: any) => void;
- //openDirectory: (path: string) => void;
- showNotification: (
- text: string,
- notificationType?: string, // NotificationTypes
- autohide?: boolean
- ) => void;
- //deleteFile: (path: string, uuid: string) => void;
- //toggleEntryFullWidth: () => void;
- isReadOnlyMode: boolean;
- setEntryPropertiesSplitSize: (size: string) => void;
- updateOpenedFile: (
- entryPath: string,
- fsEntryMeta: any // FileSystemEntryMeta
- ) => Promise<boolean>;
- // reflectUpdateSidecarMeta: (path: string, entryMeta: Object) => void;
- // setLastSelectedEntry: (path: string) => void;
- loadDirectoryContent: (
- path: string,
- generateThumbnails: boolean,
- loadDirMeta?: boolean
- ) => void;
- desktopMode: boolean;
- switchLocationType: (locationId: string) => Promise<string | null>;
- switchCurrentLocationType: (currentLocationId) => Promise<boolean>;
- revisionsEnabled: boolean;
-}
+// const bufferedSplitResize = buffer({
+// timeout: 300,
+// id: 'buffered-split-resize'
+// });
const historyKeys = Pro && Pro.history ? Pro.history.historyKeys : {};
-function EntryContainer(props: Props) {
+function EntryContainer() {
+ const { t } = useTranslation();
+ const dispatch: AppDispatch = useDispatch();
const {
- keyBindings,
- settings,
- openedFiles,
- desktopMode,
- isReadOnlyMode,
- updateOpenedFile,
+ openedEntries,
closeAllFiles,
- setEntryPropertiesSplitSize,
- showNotification
- } = props;
- const { t } = useTranslation();
+ openNextFile,
+ openPrevFile,
+ updateOpenedFile,
+ reloadOpenedFile
+ } = useOpenedEntryContext();
const { saveDescription } = useDescriptionContext();
const tabIndex = useSelector(getEntryContainerTab);
const currentDirectoryPath = useSelector(getDirectoryPath);
+ const fileEditHistoryKey = useSelector(getFileEditHistoryKey);
+ const readOnlyMode = useSelector(isReadOnlyMode);
+ const keyBindings = useSelector(getKeyBindingObject);
+ const desktopMode = useSelector(isDesktopMode);
+ const revisionsEnabled = useSelector(isRevisionsEnabled);
const theme = useTheme();
// const [percent, setPercent] = React.useState<number | undefined>(undefined);
- const percent = useRef<number | undefined>(undefined);
+ // const percent = useRef<number | undefined>(undefined);
const timer = useRef<NodeJS.Timeout>(null);
- const openedFile = openedFiles[0];
- const openedFilePath = useRef(openedFile.path);
+ const openedFile = openedEntries[0];
+ //const openedFilePath = useRef(openedFile.path);
const [propertiesStyles, setPropertiesStyles] = useState<React.CSSProperties>(
{ display: 'flex', flexDirection: 'column' }
@@ -210,6 +136,9 @@ function EntryContainer(props: Props) {
false
);
const [isSavingInProgress, setSavingInProgress] = useState<boolean>(false);
+ const [entryPropertiesHeight, setEntryPropertiesHeight] = useState<number>(
+ 100
+ );
const fileViewer: MutableRefObject<HTMLIFrameElement> = useRef<
HTMLIFrameElement
>(null);
@@ -218,7 +147,7 @@ function EntryContainer(props: Props) {
>(null);
const fileChanged = useRef<boolean>(false);
const eventID = useRef<string>(getUuid());
- const firstRender = useFirstRender();
+ // const firstRender = useFirstRender();
useEventListener('message', e => {
if (typeof e.data === 'string') {
@@ -345,7 +274,7 @@ function EntryContainer(props: Props) {
}
}, [settings.currentTheme]);*/
- useEffect(() => {
+ /* useEffect(() => {
// if (openedFiles.length > 0) {
if (
!firstRender &&
@@ -356,7 +285,7 @@ function EntryContainer(props: Props) {
) {
setSaveBeforeReloadConfirmDialogOpened(true);
}
- }, [openedFilePath.current, isReadOnlyMode]); // , settings]);
+ }, [openedFilePath.current, readOnlyMode]);*/
// always open for dirs
/*const isPropPanelVisible = openedFile.isFile
@@ -364,7 +293,7 @@ function EntryContainer(props: Props) {
: true;*/
const editingSupported: boolean =
- !isReadOnlyMode &&
+ !readOnlyMode &&
openedFile.editingExtensionId !== undefined &&
openedFile.editingExtensionId.length > 3;
@@ -377,7 +306,9 @@ function EntryContainer(props: Props) {
if (data.message) {
message = message + ': ' + data.message;
}
- showNotification(message, NotificationTypes.default);
+ dispatch(
+ AppActions.showNotification(message, NotificationTypes.default)
+ );
break;
case 'saveDocument':
savingFile(data.force !== undefined ? data.force : false);
@@ -388,7 +319,7 @@ function EntryContainer(props: Props) {
}
break;
case 'playbackEnded':
- openNextFile();
+ openNextFileAction();
break;
// case 'openLinkExternally':
// // openLink(data.link);
@@ -414,9 +345,8 @@ function EntryContainer(props: Props) {
// if (!this.state.currentEntry.isFile) {
// textFilePath += '/index.html';
// }
- props
- .switchLocationType(openedFile.locationId)
- .then(currentLocationId => {
+ dispatch(AppActions.switchLocationTypeByID(openedFile.locationId)).then(
+ currentLocationId => {
PlatformIO.loadTextFilePromise(
textFilePath,
data.preview ? data.preview : false
@@ -453,20 +383,25 @@ function EntryContainer(props: Props) {
content,
fileDirectory,
!openedFile.editMode,
- settings.currentTheme
+ theme.palette.mode
);
}
if (currentLocationId) {
- return props.switchCurrentLocationType(currentLocationId);
+ return dispatch(
+ AppActions.switchCurrentLocationType(currentLocationId)
+ );
}
})
.catch(err => {
console.warn('Error loading text content ' + err);
if (currentLocationId) {
- return props.switchCurrentLocationType(currentLocationId);
+ return dispatch(
+ AppActions.switchCurrentLocationType(currentLocationId)
+ );
}
});
- });
+ }
+ );
break;
case 'contentChangedInEditor': {
if (!fileChanged.current) {
@@ -484,7 +419,7 @@ function EntryContainer(props: Props) {
}
};
- const reloadOpenedFile = () => {
+ /*const reloadOpenedFile = () => {
if (openedFile) {
const metaFilePath = openedFile.isFile
? getMetaFileLocationForFile(
@@ -519,7 +454,7 @@ function EntryContainer(props: Props) {
});
}
}
- };
+ };*/
const reloadDocument = () => {
if (openedFile) {
@@ -558,7 +493,7 @@ function EntryContainer(props: Props) {
}
};
- function savingFile(force = false) {
+ const savingFile = (force = false) => {
if (
fileViewer &&
fileViewer.current &&
@@ -587,70 +522,70 @@ function EntryContainer(props: Props) {
console.debug('function getContent not exist for video file:', e);
}
}
- }
+ };
const override = (): Promise<boolean> => {
- return props
- .switchLocationType(openedFile.locationId)
- .then(currentLocationId =>
- PlatformIO.getPropertiesPromise(
- openedFile.path
- ).then((entryProp: TS.FileSystemEntry) =>
- save({ ...openedFile, lmdt: entryProp.lmdt }).then(() =>
- props.switchCurrentLocationType(currentLocationId)
- )
+ return dispatch(
+ AppActions.switchLocationTypeByID(openedFile.locationId)
+ ).then(currentLocationId =>
+ PlatformIO.getPropertiesPromise(
+ openedFile.path
+ ).then((entryProp: TS.FileSystemEntry) =>
+ save({ ...openedFile, lmdt: entryProp.lmdt }).then(() =>
+ dispatch(AppActions.switchCurrentLocationType(currentLocationId))
)
- );
+ )
+ );
};
const saveAs = (newFilePath: string): Promise<boolean> => {
- return props
- .switchLocationType(openedFile.locationId)
- .then(currentLocationId =>
- PlatformIO.copyFilePromise(openedFile.path, newFilePath).then(() =>
- PlatformIO.getPropertiesPromise(newFilePath).then(
- (entryProp: TS.FileSystemEntry) =>
- save({
- ...openedFile,
- path: entryProp.path,
- lmdt: entryProp.lmdt
- }).then(() => {
- const openedFileDir = extractContainingDirectoryPath(
- entryProp.path
- );
- if (currentDirectoryPath === openedFileDir) {
- props.loadDirectoryContent(
- openedFileDir,
- true,
- true
- ); /*
+ return dispatch(
+ AppActions.switchLocationTypeByID(openedFile.locationId)
+ ).then(currentLocationId =>
+ PlatformIO.copyFilePromise(openedFile.path, newFilePath).then(() =>
+ PlatformIO.getPropertiesPromise(newFilePath).then(
+ (entryProp: TS.FileSystemEntry) =>
+ save({
+ ...openedFile,
+ path: entryProp.path,
+ lmdt: entryProp.lmdt
+ }).then(() => {
+ const openedFileDir = extractContainingDirectoryPath(
+ entryProp.path
+ );
+ if (currentDirectoryPath === openedFileDir) {
+ dispatch(
+ AppActions.loadDirectoryContent(openedFileDir, true, true)
+ ); /*
updateOpenedFile(openedFile.path, {
...openedFile,
editMode: false,
shouldReload: !openedFile.shouldReload
});*/
- }
- return props.switchCurrentLocationType(currentLocationId);
- })
- )
+ }
+ return dispatch(
+ AppActions.switchCurrentLocationType(currentLocationId)
+ );
+ })
)
- );
+ )
+ );
};
const saveFile = (): Promise<boolean> => {
- return props
- .switchLocationType(openedFile.locationId)
- .then(currentLocationId =>
- save(openedFile).then(() =>
- props.switchCurrentLocationType(currentLocationId)
- )
- );
+ return dispatch(
+ AppActions.switchLocationTypeByID(openedFile.locationId)
+ ).then(currentLocationId =>
+ save(openedFile).then(() =>
+ dispatch(AppActions.switchCurrentLocationType(currentLocationId))
+ )
+ );
};
async function save(fileOpen: OpenedEntry): Promise<boolean> {
// @ts-ignore
const textContent = fileViewer.current.contentWindow.getContent();
- if (Pro && props.revisionsEnabled) {
+ if (Pro && revisionsEnabled) {
const id = await Pro.MetaOperations.getMetadataID(
fileOpen.path,
fileOpen.uuid
@@ -680,14 +615,15 @@ function EntryContainer(props: Props) {
url: fileOpen.url,
lid: fileOpen.locationId
},
- settings[historyKeys.fileEditKey]
+ fileEditHistoryKey
);
}
return updateOpenedFile(fileOpen.path, {
+ id: '',
...fileOpen,
editMode: true,
- changed: false,
+ //changed: false,
shouldReload: undefined
}).then(() => true);
})
@@ -699,18 +635,21 @@ function EntryContainer(props: Props) {
}
const editOpenedFile = () => {
- props.switchLocationType(openedFile.locationId).then(currentLocationId => {
- updateOpenedFile(openedFile.path, {
- ...openedFile,
- editMode: true,
- shouldReload: undefined
- }).then(() => {
- props.switchCurrentLocationType(currentLocationId);
- });
- });
+ dispatch(AppActions.switchLocationTypeByID(openedFile.locationId)).then(
+ currentLocationId => {
+ updateOpenedFile(openedFile.path, {
+ id: '',
+ ...openedFile,
+ editMode: true,
+ shouldReload: undefined
+ }).then(() => {
+ dispatch(AppActions.switchCurrentLocationType(currentLocationId));
+ });
+ }
+ );
};
- const setPercent = (p: number | undefined) => {
+ /*const setPercent = (p: number | undefined) => {
percent.current = p;
// console.log('Percent ' + percent.current);
if (p !== undefined) {
@@ -720,7 +659,7 @@ function EntryContainer(props: Props) {
// parseInt(defaultSplitSize, 10)) {
closePanel();
} else {
- if (settings.entrySplitSize !== p + '%') {
+ if (entrySplitSize !== p + '%') {
setEntryPropertiesSplitSize(p + '%');
}
openPanel();
@@ -728,7 +667,7 @@ function EntryContainer(props: Props) {
});
}
forceUpdate();
- };
+ };*/
const openPanel = () => {
setPropertiesStyles({ display: 'flex', flexDirection: 'column' });
@@ -738,12 +677,12 @@ function EntryContainer(props: Props) {
}*/
};
- const closePanel = () => {
- /*if (isPropertiesPanelVisible) {
+ /* const closePanel = () => {
+ if (isPropertiesPanelVisible) {
percent.current = undefined;
setPropertiesPanelVisible(false);
- }*/
- };
+ }
+ }; */
const toggleProperties = () => {
if (propertiesStyles !== undefined) {
@@ -751,33 +690,13 @@ function EntryContainer(props: Props) {
} else {
setPropertiesStyles({ display: 'flex', flexDirection: 'column' });
}
- /*if (isPropPanelVisible && !isRevisionPanelVisible) {
- closePanel();
- } else {
- openPanel();
- }
-
- if (isRevisionPanelVisible) {
- setRevisionPanelVisible(false);
- }*/
};
-
- const toggleRevisions = () => {
- if (isRevisionPanelVisible) {
- setRevisionPanelVisible(false);
- closePanel();
- } else {
- setRevisionPanelVisible(true);
- openPanel();
- }
+ const openNextFileAction = () => {
+ openNextFile(openedFile.path);
};
- const openNextFile = () => {
- props.openNextFile(openedFile.path);
- };
-
- const openPrevFile = () => {
- props.openPrevFile(openedFile.path);
+ const openPrevFileAction = () => {
+ openPrevFile(openedFile.path);
};
const fileExtension = extractFileExtension(
@@ -790,246 +709,180 @@ function EntryContainer(props: Props) {
const toggleAutoSave = (event: React.ChangeEvent<HTMLInputElement>) => {
const autoSave = event.target.checked;
if (Pro && Pro.MetaOperations) {
- props
- .switchLocationType(openedFile.locationId)
- .then(currentLocationId => {
+ dispatch(AppActions.switchLocationTypeByID(openedFile.locationId)).then(
+ currentLocationId => {
Pro.MetaOperations.saveFsEntryMeta(openedFile.path, {
autoSave
}).then(entryMeta => {
updateOpenedFile(openedFile.path, entryMeta).then(() => {
- props.switchCurrentLocationType(currentLocationId);
+ dispatch(AppActions.switchCurrentLocationType(currentLocationId));
});
});
- });
+ }
+ );
} else {
- showNotification(
- t('core:thisFunctionalityIsAvailableInPro'),
- NotificationTypes.default
+ dispatch(
+ AppActions.showNotification(
+ t('core:thisFunctionalityIsAvailableInPro'),
+ NotificationTypes.default
+ )
);
}
};
- const renderPanels = () => {
- const toolbarButtons = () => {
- return (
- <Box
- style={{
- paddingLeft: 0,
- paddingRight: 50,
- paddingTop: 0,
- minHeight: 50,
- display: 'flex',
- flexDirection: 'row',
- justifyContent: 'flex-start'
- }}
- >
- <Box
- className={classes.flexLeft}
- style={{
- paddingLeft: 5,
- display: 'flex',
- alignItems: 'center',
- paddingRight: editingSupported ? 85 : 5
- }}
- >
- <EntryContainerTitle
- isFileChanged={fileChanged.current}
- openedFile={openedFile}
- reloadDocument={reloadDocument}
- toggleFullScreen={toggleFullScreen}
- />
- </Box>
- <EntryContainerNav
- isFile={openedFile.isFile}
- startClosingFile={startClosingFile}
- />
- </Box>
- );
- };
+ const toggleEntryPropertiesHeight = () => {
+ if (entryPropertiesHeight === 100) {
+ setEntryPropertiesHeight(150);
+ } else if (entryPropertiesHeight === 150) {
+ setEntryPropertiesHeight(50);
+ } else if (entryPropertiesHeight === 50) {
+ setEntryPropertiesHeight(100);
+ }
+ };
- const tabs = () => {
- const autoSave = isEditable && props.revisionsEnabled && (
- <Tooltip
- title={
- t('core:autosave') +
- (!Pro ? ' - ' + t('core:thisFunctionalityIsAvailableInPro') : '')
+ const tabs = () => {
+ const autoSave = isEditable && revisionsEnabled && (
+ <Tooltip
+ title={
+ t('core:autosave') +
+ (!Pro ? ' - ' + t('core:thisFunctionalityIsAvailableInPro') : '')
+ }
+ >
+ <Switch
+ data-tid="autoSaveTID"
+ checked={
+ openedFile.isAutoSaveEnabled !== undefined &&
+ openedFile.isAutoSaveEnabled
}
- >
- <Switch
- data-tid="autoSaveTID"
- checked={
- openedFile.isAutoSaveEnabled !== undefined &&
- openedFile.isAutoSaveEnabled
- }
- onChange={toggleAutoSave}
- name="autoSave"
- color="primary"
- />
- </Tooltip>
- );
+ onChange={toggleAutoSave}
+ name="autoSave"
+ color="primary"
+ />
+ </Tooltip>
+ );
- let closeCancelIcon;
- if (desktopMode) {
- closeCancelIcon = fileChanged.current ? (
- <CancelIcon />
- ) : (
- <CloseEditIcon />
- );
- }
+ let closeCancelIcon;
+ if (desktopMode) {
+ closeCancelIcon = fileChanged.current ? (
+ <CancelIcon />
+ ) : (
+ <CloseEditIcon />
+ );
+ }
- let editFile = null;
- if (editingSupported) {
- if (openedFile.editMode) {
- editFile = (
- <ButtonGroup>
- <Tooltip title={t('core:cancelEditing')}>
- <Button
- onClick={reloadDocument}
- aria-label={t('core:cancelEditing')}
- size="small"
- variant="outlined"
- color="primary"
- startIcon={closeCancelIcon}
- >
- {fileChanged.current
- ? t('core:cancel')
- : t('core:closeButton')}
- </Button>
- </Tooltip>
- <Tooltip
- title={
- t('core:saveFile') +
- ' (' +
- (AppConfig.isMaclike ? '⌘' : 'CTRL') +
- ' + S)'
- }
- >
- <LoadingButton
- disabled={false}
- onClick={startSavingFile}
- aria-label={t('core:saveFile')}
- data-tid="fileContainerSaveFile"
- size="small"
- variant="outlined"
- color="primary"
- startIcon={desktopMode && <SaveIcon />}
- loading={isSavingInProgress}
- >
- {t('core:save')}
- </LoadingButton>
- </Tooltip>
- </ButtonGroup>
- );
- } else {
- editFile = (
- <Tooltip title={t('core:editFile')}>
+ let editFile = null;
+ if (editingSupported) {
+ if (openedFile.editMode) {
+ editFile = (
+ <ButtonGroup>
+ <Tooltip title={t('core:cancelEditing')}>
<Button
- disabled={false}
+ onClick={reloadDocument}
+ aria-label={t('core:cancelEditing')}
size="small"
variant="outlined"
color="primary"
- onClick={editOpenedFile}
- aria-label={t('core:editFile')}
- data-tid="fileContainerEditFile"
- startIcon={<EditIcon />}
+ startIcon={closeCancelIcon}
>
- {t('core:edit')}
+ {fileChanged.current ? t('core:cancel') : t('core:closeButton')}
</Button>
</Tooltip>
- );
- }
- }
- const tabsComponent = (marginRight = undefined) => (
- <EntryContainerTabs
- isEditable={isEditable}
- openedFile={openedFile}
- openPanel={openPanel}
- toggleProperties={toggleProperties}
- marginRight={marginRight}
- isDesktopMode={desktopMode}
- />
- );
-
- if (!autoSave && !editFile) {
- return tabsComponent();
+ <Tooltip
+ title={
+ t('core:saveFile') +
+ ' (' +
+ (AppConfig.isMaclike ? '⌘' : 'CTRL') +
+ ' + S)'
+ }
+ >
+ <LoadingButton
+ disabled={false}
+ onClick={startSavingFile}
+ aria-label={t('core:saveFile')}
+ data-tid="fileContainerSaveFile"
+ size="small"
+ variant="outlined"
+ color="primary"
+ startIcon={desktopMode && <SaveIcon />}
+ loading={isSavingInProgress}
+ >
+ {t('core:save')}
+ </LoadingButton>
+ </Tooltip>
+ </ButtonGroup>
+ );
+ } else {
+ editFile = (
+ <Tooltip title={t('core:editFile')}>
+ <Button
+ disabled={false}
+ size="small"
+ variant="outlined"
+ color="primary"
+ onClick={editOpenedFile}
+ aria-label={t('core:editFile')}
+ data-tid="fileContainerEditFile"
+ startIcon={<EditIcon />}
+ >
+ {t('core:edit')}
+ </Button>
+ </Tooltip>
+ );
}
+ }
+ const tabsComponent = (marginRight = undefined) => (
+ <EntryContainerTabs
+ isEditable={isEditable}
+ openedFile={openedFile}
+ openPanel={openPanel}
+ toggleProperties={toggleProperties}
+ marginRight={marginRight}
+ />
+ );
- return (
- <div
- style={{
- position: 'relative',
- overflow: 'hidden',
- height: '100%'
- }}
- >
- {tabsComponent('160px')}
- <div
- style={{
- zIndex: 1,
- position: 'absolute',
- right: 10,
- top: 8,
- backgroundColor: theme.palette.background.default,
- display: 'flex',
- alignItems: 'center'
- }}
- >
- {autoSave}
- {editFile}
- </div>
- </div>
- );
- };
- /*let initSize;
- if (isPropPanelVisible) {
- initSize = openedFile.isFile ? settings.entrySplitSize : '100%';
- } else {
- initSize = defaultSplitSize; // '0%';
- }*/
+ if (!autoSave && !editFile) {
+ return tabsComponent();
+ }
return (
<div
style={{
- // height: 'calc(100% - 47px)',
- height: '100%',
- //minHeight: '100%',
- ...(tabIndex !== undefined && propertiesStyles)
+ position: 'relative',
+ overflow: 'hidden',
+ height: '100%'
}}
>
- <Root>
- {openedFile.path !== undefined ? (
- <>
- {toolbarButtons()}
- {tabs()}
- </>
- ) : (
- <div>{t('core:noEntrySelected')}</div>
- )}
- </Root>
- {openedFile.isFile && (
- <FileView
- key="FileViewID"
- openedFile={openedFile}
- isFullscreen={isFullscreen}
- fileViewer={fileViewer}
- fileViewerContainer={fileViewerContainer}
- toggleFullScreen={toggleFullScreen}
- eventID={eventID.current}
- height={tabIndex !== undefined ? '100%' : 'calc(100% - 100px)'}
- />
- )}
+ {tabsComponent('160px')}
+ <div
+ style={{
+ zIndex: 1,
+ position: 'absolute',
+ right: 10,
+ top: 8,
+ backgroundColor: theme.palette.background.default,
+ display: 'flex',
+ alignItems: 'center'
+ }}
+ >
+ {autoSave}
+ {editFile}
+ </div>
</div>
);
};
+ if (openedFile.path === undefined) {
+ return <div>{t('core:noEntrySelected')}</div>;
+ }
+
return (
<GlobalHotKeys
handlers={{
closeViewer: startClosingFile,
saveDocument: startSavingFile,
editDocument: editOpenedFile,
- nextDocument: openNextFile,
- prevDocument: openPrevFile,
+ nextDocument: openNextFileAction,
+ prevDocument: openPrevFileAction,
toggleFullScreen
}}
keyMap={{
@@ -1041,6 +894,77 @@ function EntryContainer(props: Props) {
toggleFullScreen: keyBindings.toggleFullScreen
}}
>
+ <div
+ style={{
+ height: '100%',
+ ...(tabIndex !== undefined && propertiesStyles)
+ }}
+ >
+ <div
+ style={{
+ width: '100%',
+ flexDirection: 'column',
+ flex: '1 1 ' + entryPropertiesHeight + '%',
+ display: 'flex',
+ backgroundColor: theme.palette.background.default,
+ overflow: 'hidden'
+ }}
+ >
+ <Box
+ style={{
+ paddingLeft: 0,
+ paddingRight: 50,
+ paddingTop: 0,
+ minHeight: 50,
+ display: 'flex',
+ flexDirection: 'row',
+ justifyContent: 'flex-start'
+ }}
+ >
+ <EntryContainerTitle
+ isFileChanged={fileChanged.current}
+ openedFile={openedFile}
+ reloadDocument={reloadDocument}
+ toggleFullScreen={toggleFullScreen}
+ />
+ <EntryContainerNav
+ isFile={openedFile.isFile}
+ startClosingFile={startClosingFile}
+ />
+ </Box>
+ {tabs()}
+ {openedFile.isFile && (
+ <Tooltip title="Toggle preview height">
+ <div
+ style={{
+ textAlign: 'center',
+ // paddingRight: 5,
+ maxHeight: 9,
+ minHeight: 9,
+ backgroundColor: theme.palette.background.default,
+ borderBottom: '1px solid ' + theme.palette.divider
+ // color: theme.palette.divider
+ }}
+ onClick={toggleEntryPropertiesHeight}
+ >
+ |||
+ </div>
+ </Tooltip>
+ )}
+ </div>
+ {openedFile.isFile && (
+ <FileView
+ key="FileViewID"
+ openedFile={openedFile}
+ isFullscreen={isFullscreen}
+ fileViewer={fileViewer}
+ fileViewerContainer={fileViewerContainer}
+ toggleFullScreen={toggleFullScreen}
+ eventID={eventID.current}
+ height={tabIndex !== undefined ? '100%' : 'calc(100% - 100px)'}
+ />
+ )}
+ </div>
{isSaveBeforeCloseConfirmDialogOpened && (
<ConfirmDialog
open={isSaveBeforeCloseConfirmDialogOpened}
@@ -1077,6 +1001,7 @@ function EntryContainer(props: Props) {
} else {
setSaveBeforeReloadConfirmDialogOpened(false);
updateOpenedFile(openedFile.path, {
+ id: '',
...openedFile,
editMode: false,
// changed: false,
@@ -1106,50 +1031,8 @@ function EntryContainer(props: Props) {
/>
{/* eslint-disable-next-line jsx-a11y/anchor-has-content,jsx-a11y/anchor-is-valid */}
<a href="#" id="downloadFile" />
- {renderPanels()}
</GlobalHotKeys>
);
}
-function mapStateToProps(state) {
- return {
- settings: state.settings,
- isReadOnlyMode: isReadOnlyMode(state),
- keyBindings: getKeyBindingObject(state),
- desktopMode: isDesktopMode(state),
- revisionsEnabled: isRevisionsEnabled(state)
- };
-}
-
-function mapActionCreatorsToProps(dispatch) {
- return bindActionCreators(
- {
- setEntryPropertiesSplitSize: SettingsActions.setEntryPropertiesSplitSize,
- closeAllFiles: AppActions.closeAllFiles,
- showNotification: AppActions.showNotification,
- openNextFile: AppActions.openNextFile,
- openPrevFile: AppActions.openPrevFile,
- updateOpenedFile: AppActions.updateOpenedFile,
- switchLocationType: LocationActions.switchLocationType,
- switchCurrentLocationType: AppActions.switchCurrentLocationType
- },
- dispatch
- );
-}
-const areEqual = (prevProp, nextProp) =>
- // JSON.stringify(nextProp.theme) === JSON.stringify(prevProp.theme) &&
- nextProp.settings.currentTheme === prevProp.settings.currentTheme &&
- nextProp.settings.entrySplitSize === prevProp.settings.entrySplitSize &&
- JSON.stringify(nextProp.openedFiles) === JSON.stringify(prevProp.openedFiles);
-/* nextProp.openedFiles[0].path === prevProp.openedFiles[0].path &&
- nextProp.openedFiles[0].shouldReload ===
- prevProp.openedFiles[0].shouldReload &&
- nextProp.openedFiles[0].editMode === prevProp.openedFiles[0].editMode; */
-
-export default connect(
- mapStateToProps,
- mapActionCreatorsToProps
-)(
- // @ts-ignore
- React.memo(EntryContainer, areEqual)
-);
+export default EntryContainer;
diff --git a/app/components/EntryContainerMenu.tsx b/app/components/EntryContainerMenu.tsx
index 8978821e3..42b6acf4a 100644
--- a/app/components/EntryContainerMenu.tsx
+++ b/app/components/EntryContainerMenu.tsx
@@ -37,6 +37,7 @@ import FileDownloadIcon from '@mui/icons-material/AssignmentReturned';
import ConfirmDialog from '-/components/dialogs/ConfirmDialog';
import { isDesktopMode } from '-/reducers/settings';
import { useTranslation } from 'react-i18next';
+import { useOpenedEntryContext } from '-/hooks/useOpenedEntryContext';
interface Props {
anchorEl: null | HTMLElement;
@@ -60,6 +61,7 @@ function EntryContainerMenu(props: Props) {
} = props;
const { t } = useTranslation();
// const theme = useTheme();
+ const { toggleEntryFullWidth } = useOpenedEntryContext();
const readOnlyMode = useSelector(isReadOnlyMode);
const desktopMode = useSelector(isDesktopMode);
const dispatch: AppDispatch = useDispatch();
@@ -185,6 +187,7 @@ function EntryContainerMenu(props: Props) {
if (openedEntry.isFile) {
menuItems.push(
<MenuItem
+ key={'downloadFileKey'}
data-tid="downloadFileTID"
aria-label={t('core:downloadFile')}
onClick={() => downloadFile()}
@@ -195,9 +198,10 @@ function EntryContainerMenu(props: Props) {
<ListItemText primary={t('core:downloadFile')} />
</MenuItem>
);
- menuItems.push(<Divider />);
+ menuItems.push(<Divider key={'divider1'} />);
menuItems.push(
<MenuItem
+ key={'fileContainerSwitchToFullScreenKey'}
data-tid="fileContainerSwitchToFullScreen"
aria-label={t('core:switchToFullscreen')}
onClick={() => {
@@ -214,10 +218,11 @@ function EntryContainerMenu(props: Props) {
if (desktopMode) {
menuItems.push(
<MenuItem
+ key={'openInFullWidthKey'}
data-tid="openInFullWidthTID"
aria-label={t('core:openInFullWidth')}
onClick={() => {
- dispatch(AppActions.toggleEntryFullWidth());
+ toggleEntryFullWidth();
handleClose();
}}
>
@@ -228,9 +233,10 @@ function EntryContainerMenu(props: Props) {
</MenuItem>
);
}
- menuItems.push(<Divider />);
+ menuItems.push(<Divider key={'divider2'} />);
menuItems.push(
<MenuItem
+ key={'navigateToParentKey'}
data-tid="navigateToParentTID"
aria-label={t('core:navigateToParentDirectory')}
onClick={navigateToFolder}
@@ -244,6 +250,7 @@ function EntryContainerMenu(props: Props) {
if (!AppConfig.isCordova) {
menuItems.push(
<MenuItem
+ key={'openInWindowKey'}
data-tid="openInWindowTID"
aria-label={t('core:openInWindow')}
onClick={openInNewWindow}
@@ -258,6 +265,7 @@ function EntryContainerMenu(props: Props) {
if (AppConfig.isCordova) {
menuItems.push(
<MenuItem
+ key={'shareFileKey'}
data-tid="shareFileTID"
aria-label={t('core:shareFile')}
onClick={() => shareFile(`file:///${openedEntry.path}`)}
@@ -278,6 +286,7 @@ function EntryContainerMenu(props: Props) {
) {
menuItems.push(
<MenuItem
+ key={'openFileExternallyKey'}
data-tid="openFileExternallyTID"
aria-label={t('core:openFileExternally')}
onClick={openNatively}
@@ -291,6 +300,7 @@ function EntryContainerMenu(props: Props) {
}
menuItems.push(
<MenuItem
+ key={'reloadPropertiesKey'}
data-tid="reloadPropertiesTID"
aria-label={t('core:reloadFile')}
onClick={() => {
@@ -305,9 +315,10 @@ function EntryContainerMenu(props: Props) {
</MenuItem>
);
if (!readOnlyMode) {
- menuItems.push(<Divider />);
+ menuItems.push(<Divider key={'divider3'} />);
menuItems.push(
<MenuItem
+ key={'deleteEntryKey'}
data-tid="deleteEntryTID"
aria-label={t('core:deleteEntry')}
onClick={() => {
@@ -326,6 +337,7 @@ function EntryContainerMenu(props: Props) {
// folder
menuItems.push(
<MenuItem
+ key={'openInMainAreaKey'}
data-tid="openInMainAreaTID"
aria-label={t('core:openInMainArea')}
onClick={navigateToFolder}
@@ -339,6 +351,7 @@ function EntryContainerMenu(props: Props) {
if (!AppConfig.isCordova) {
menuItems.push(
<MenuItem
+ key={'openInWindowKey'}
data-tid="openInWindowTID"
aria-label={t('core:openInWindow')}
onClick={openInNewWindow}
@@ -359,6 +372,7 @@ function EntryContainerMenu(props: Props) {
) {
menuItems.push(
<MenuItem
+ key={'openDirectoryExternallyKey'}
data-tid="openDirectoryExternallyTID"
aria-label={t('core:openDirectoryExternally')}
onClick={openNatively}
@@ -373,10 +387,11 @@ function EntryContainerMenu(props: Props) {
if (desktopMode) {
menuItems.push(
<MenuItem
+ key={'openInFullWidthKey'}
data-tid="openInFullWidthTID"
aria-label={t('core:openInFullWidth')}
onClick={() => {
- dispatch(AppActions.toggleEntryFullWidth());
+ toggleEntryFullWidth();
handleClose();
}}
>
@@ -387,9 +402,10 @@ function EntryContainerMenu(props: Props) {
</MenuItem>
);
}
- menuItems.push(<Divider />);
+ menuItems.push(<Divider key={'divider4'} />);
menuItems.push(
<MenuItem
+ key={'reloadFolderKey'}
data-tid="reloadFolderTID"
aria-label={t('core:reloadDirectory')}
onClick={() => {
@@ -406,6 +422,7 @@ function EntryContainerMenu(props: Props) {
if (!readOnlyMode) {
menuItems.push(
<MenuItem
+ key={'deleteFolderKey'}
data-tid="deleteFolderTID"
aria-label={t('core:deleteDirectory')}
onClick={() => {
diff --git a/app/components/EntryContainerNav.tsx b/app/components/EntryContainerNav.tsx
index 1360958b7..deeb93014 100644
--- a/app/components/EntryContainerNav.tsx
+++ b/app/components/EntryContainerNav.tsx
@@ -4,9 +4,8 @@ import { IconButton, Tooltip } from '@mui/material';
import CloseIcon from '@mui/icons-material/Close';
import PrevDocumentIcon from '@mui/icons-material/KeyboardArrowUp';
import NextDocumentIcon from '@mui/icons-material/KeyboardArrowDown';
-import { actions as AppActions, AppDispatch } from '-/reducers/app';
-import { useDispatch } from 'react-redux';
import { useTranslation } from 'react-i18next';
+import { useOpenedEntryContext } from '-/hooks/useOpenedEntryContext';
interface Props {
isFile: boolean;
@@ -16,8 +15,8 @@ interface Props {
function EntryContainerNav(props: Props) {
const { isFile, startClosingFile } = props;
const { t } = useTranslation();
+ const { openNextFile, openPrevFile } = useOpenedEntryContext();
const theme = useTheme();
- const dispatch: AppDispatch = useDispatch();
return (
<div
@@ -36,7 +35,7 @@ function EntryContainerNav(props: Props) {
<IconButton
aria-label={t('core:openPrevFileTooltip')}
data-tid="fileContainerPrevFile"
- onClick={() => dispatch(AppActions.openPrevFile())}
+ onClick={() => openPrevFile()}
size="large"
>
<PrevDocumentIcon />
@@ -46,7 +45,7 @@ function EntryContainerNav(props: Props) {
<IconButton
aria-label={t('core:openNextFileTooltip')}
data-tid="fileContainerNextFile"
- onClick={() => dispatch(AppActions.openNextFile())}
+ onClick={() => openNextFile()}
size="large"
>
<NextDocumentIcon />
diff --git a/app/components/EntryContainerTabs.tsx b/app/components/EntryContainerTabs.tsx
index d6b72884a..0928e4688 100644
--- a/app/components/EntryContainerTabs.tsx
+++ b/app/components/EntryContainerTabs.tsx
@@ -30,12 +30,12 @@ import {
} from '-/reducers/app';
import Revisions from '-/components/Revisions';
import EntryProperties from '-/components/EntryProperties';
-import TaggingActions from '-/reducers/tagging-actions';
import { TS } from '-/tagspaces.namespace';
import {
actions as SettingsActions,
getEntryContainerTab,
- getMapTileServer
+ getMapTileServer,
+ isDesktopMode
} from '-/reducers/settings';
import {
FolderPropertiesIcon,
@@ -56,6 +56,8 @@ const StyledTabs = styled((props: StyledTabsProps) => (
{...props}
variant="scrollable"
scrollButtons="auto"
+ allowScrollButtonsMobile
+ selectionFollowsFocus
TabIndicatorProps={{ children: <span className="MuiTabs-indicatorSpan" /> }}
/>
))(({ theme }) => ({
@@ -105,7 +107,6 @@ interface EntryContainerTabsProps {
openedFile: OpenedEntry;
openPanel: () => void;
toggleProperties: () => void;
- isDesktopMode: boolean;
isEditable: boolean;
marginRight: string;
}
@@ -126,11 +127,12 @@ function EntryContainerTabs(props: EntryContainerTabsProps) {
} = props;
const { t } = useTranslation();
+
const tabIndex = useSelector(getEntryContainerTab);
const readOnlyMode = useSelector(isReadOnlyMode);
const tileServer = useSelector(getMapTileServer);
+ const desktopMode = useSelector(isDesktopMode);
const dispatch: AppDispatch = useDispatch();
- const { isDesktopMode } = props;
function TsTabPanel(tprops: TabPanelProps) {
const { children, value, index, ...other } = tprops;
@@ -159,17 +161,6 @@ function EntryContainerTabs(props: EntryContainerTabsProps) {
const handleRenameFile = (filePath: string, newFilePath: string) =>
dispatch(AppActions.renameFile(filePath, newFilePath));
- const handleRenameDirectory = (
- directoryPath: string,
- newDirectoryName: string
- ) => dispatch(AppActions.renameDirectory(directoryPath, newDirectoryName));
-
- const handleAddTags = (
- paths: Array<string>,
- tags: Array<TS.Tag>,
- updateIndex = true
- ) => dispatch(TaggingActions.addTags(paths, tags, updateIndex));
-
const handleChange = (event: React.SyntheticEvent, newValue: number) => {
dispatch(SettingsActions.setEntryContainerTab(newValue));
openPanel();
@@ -254,14 +245,14 @@ function EntryContainerTabs(props: EntryContainerTabsProps) {
<StyledTab
data-tid="detailsTabTID"
icon={<FolderPropertiesIcon />}
- label={isDesktopMode && t('core:details')}
+ label={desktopMode && t('core:details')}
{...a11yProps(0)}
onClick={handleTabClick}
/>
<StyledTab
data-tid="descriptionTabTID"
icon={<DescriptionIcon />}
- label={isDesktopMode && t('core:filePropertiesDescription')}
+ label={desktopMode && t('core:filePropertiesDescription')}
{...a11yProps(1)}
onClick={handleTabClick}
/>
@@ -269,7 +260,7 @@ function EntryContainerTabs(props: EntryContainerTabsProps) {
<StyledTab
data-tid="revisionsTabTID"
icon={<RevisionIcon />}
- label={isDesktopMode && t('core:revisions')}
+ label={desktopMode && t('core:revisions')}
{...a11yProps(2)}
onClick={handleTabClick}
/>
@@ -279,10 +270,7 @@ function EntryContainerTabs(props: EntryContainerTabsProps) {
<TsTabPanel value={selectedTabIndex} index={0}>
<EntryProperties
key={openedFile.path}
- openedEntry={openedFile}
renameFile={handleRenameFile}
- renameDirectory={handleRenameDirectory}
- addTags={handleAddTags}
isReadOnlyMode={readOnlyMode}
tileServer={tileServer}
/>
diff --git a/app/components/EntryContainerTitle.tsx b/app/components/EntryContainerTitle.tsx
index 46aa346c7..442cecb80 100644
--- a/app/components/EntryContainerTitle.tsx
+++ b/app/components/EntryContainerTitle.tsx
@@ -130,7 +130,18 @@ function EntryContainerTitle(props: Props) {
}
return (
- <>
+ <Box
+ style={{
+ paddingLeft: 5,
+ display: 'flex',
+ alignItems: 'center',
+ marginRight: openedFile.isFile ? 90 : 0,
+ flexDirection: 'row',
+ flex: '1 1',
+ overflowX: 'auto',
+ overflowY: 'hidden'
+ }}
+ >
{openedFile.isFile ? (
<>
{isFileChanged ? (
@@ -240,7 +251,7 @@ function EntryContainerTitle(props: Props) {
sharingParentFolderLink={sharingParentFolderLink}
toggleFullScreen={toggleFullScreen}
/>
- </>
+ </Box>
);
}
diff --git a/app/components/EntryProperties.tsx b/app/components/EntryProperties.tsx
index d42537ac2..f9114bd47 100644
--- a/app/components/EntryProperties.tsx
+++ b/app/components/EntryProperties.tsx
@@ -98,8 +98,10 @@ import { actions as AppActions } from '-/reducers/app';
import useFirstRender from '-/utils/useFirstRender';
import LinkGeneratorDialog from '-/components/dialogs/LinkGeneratorDialog';
import { LinkIcon } from '-/components/CommonIcons';
-import TaggingActions from '-/reducers/tagging-actions';
import { useTranslation } from 'react-i18next';
+import { useOpenedEntryContext } from '-/hooks/useOpenedEntryContext';
+import { useTaggingActionsContext } from '-/hooks/useTaggingActionsContext';
+import { useFsActionsContext } from '-/hooks/useFsActionsContext';
const PREFIX = 'EntryProperties';
@@ -188,16 +190,10 @@ const BgndImgChooserDialog =
Pro && Pro.UI ? Pro.UI.BgndImgChooserDialog : false;
interface Props {
- openedEntry: OpenedEntry;
locations: Array<TS.Location>;
renameFile: (path: string, nextPath: string) => Promise<boolean>;
- renameDirectory: (path: string, nextPath: string) => Promise<boolean>;
showNotification: (message: string) => void;
- updateOpenedFile: (entryPath: string, fsEntryMeta: any) => Promise<boolean>;
updateThumbnailUrl: (path: string, thumbUrl: string) => void;
- addTags: (paths: Array<string>, tags: Array<TS.Tag>) => Promise<boolean>;
- removeTags: (paths: Array<string>, tags: Array<TS.Tag>) => Promise<boolean>;
- removeAllTags: (paths: Array<string>) => Promise<boolean>;
switchLocationType: (locationId: string) => Promise<string | null>;
switchCurrentLocationType: (currentLocationId: string) => Promise<boolean>;
isReadOnlyMode: boolean;
@@ -223,28 +219,28 @@ const defaultBackgrounds = [
function EntryProperties(props: Props) {
const { t } = useTranslation();
const theme = useTheme();
+ const { openedEntries, updateOpenedFile } = useOpenedEntryContext();
+ const { renameDirectory } = useFsActionsContext();
+ const { addTags, removeTags, removeAllTags } = useTaggingActionsContext();
const fileNameRef = useRef<HTMLInputElement>(null);
const sharingLinkRef = useRef<HTMLInputElement>(null);
// const fileDescriptionRef = useRef<MilkdownRef>(null);
const disableConfirmButton = useRef<boolean>(true);
const fileNameError = useRef<boolean>(false);
-
- const directoryPath = props.openedEntry.isFile
+ const openedEntry = openedEntries[0];
+ /*const directoryPath = openedEntry.isFile
? extractContainingDirectoryPath(
- props.openedEntry.path,
+ openedEntry.path,
PlatformIO.getDirSeparator()
)
- : props.openedEntry.path;
+ : openedEntry.path;*/
- const entryName = props.openedEntry.isFile
- ? extractFileName(props.openedEntry.path, PlatformIO.getDirSeparator())
- : extractDirectoryName(
- props.openedEntry.path,
- PlatformIO.getDirSeparator()
- );
+ const entryName = openedEntry.isFile
+ ? extractFileName(openedEntry.path, PlatformIO.getDirSeparator())
+ : extractDirectoryName(openedEntry.path, PlatformIO.getDirSeparator());
const currentEntry = useRef<OpenedEntry>(
- enhanceOpenedEntry(props.openedEntry, props.tagDelimiter)
+ enhanceOpenedEntry(openedEntry, props.tagDelimiter)
);
const [editName, setEditName] = useState<string>(undefined);
const [isMoveCopyFilesDialogOpened, setMoveCopyFilesDialogOpened] = useState<
@@ -306,12 +302,12 @@ function EntryProperties(props: Props) {
useEffect(() => {
if (
!firstRender &&
- props.openedEntry != undefined
+ openedEntry != undefined
// && currentEntry.current.description !== props.openedEntry.description
) {
// update description
currentEntry.current = enhanceOpenedEntry(
- props.openedEntry,
+ openedEntry,
props.tagDelimiter
);
forceUpdate();
@@ -320,11 +316,11 @@ function EntryProperties(props: Props) {
if (!current) return;
current.update(currentEntry.current.description);*/
}
- }, [props.openedEntry]);
+ }, [openedEntries]);
const renameEntry = () => {
if (editName !== undefined) {
- const { renameFile, renameDirectory } = props;
+ const { renameFile } = props;
const path = extractContainingDirectoryPath(
currentEntry.current.path,
@@ -333,7 +329,7 @@ function EntryProperties(props: Props) {
const nextPath = path + PlatformIO.getDirSeparator() + editName;
props
- .switchLocationType(props.openedEntry.locationId)
+ .switchLocationType(openedEntry.locationId)
.then(currentLocationId => {
if (currentEntry.current.isFile) {
renameFile(currentEntry.current.path, nextPath)
@@ -347,7 +343,7 @@ function EntryProperties(props: Props) {
});
} else {
renameDirectory(currentEntry.current.path, editName)
- .then(() => {
+ .then(newDirPath => {
props.switchCurrentLocationType(currentLocationId);
return true;
})
@@ -408,7 +404,7 @@ function EntryProperties(props: Props) {
const setThumb = (filePath, thumbFilePath) => {
if (filePath !== undefined) {
return props
- .switchLocationType(props.openedEntry.locationId)
+ .switchLocationType(openedEntry.locationId)
.then(currentLocationId => {
if (
PlatformIO.haveObjectStoreSupport() ||
@@ -473,30 +469,30 @@ function EntryProperties(props: Props) {
color = 'transparent';
}
currentEntry.current.color = color;
- props
- .switchLocationType(props.openedEntry.locationId)
- .then(currentLocationId => {
- Pro.MetaOperations.saveFsEntryMeta(currentEntry.current.path, { color })
- .then(entryMeta => {
- // if (props.entryPath === props.currentDirectoryPath) {
- props.setLastBackgroundColorChange(
- currentEntry.current.path,
- new Date().getTime()
- );
- // todo handle LastBackgroundColorChange and skip updateOpenedFile
- props.updateOpenedFile(currentEntry.current.path, entryMeta);
- props.switchCurrentLocationType(currentLocationId);
- /* } else {
+ props.switchLocationType(openedEntry.locationId).then(currentLocationId => {
+ Pro.MetaOperations.saveFsEntryMeta(currentEntry.current.path, { color })
+ .then(entryMeta => {
+ // if (props.entryPath === props.currentDirectoryPath) {
+ props.setLastBackgroundColorChange(
+ currentEntry.current.path,
+ new Date().getTime()
+ );
+ // todo handle LastBackgroundColorChange and skip updateOpenedFile
+ updateOpenedFile(currentEntry.current.path, entryMeta).then(() =>
+ props.switchCurrentLocationType(currentLocationId)
+ );
+
+ /* } else {
setCurrentEntry({ ...currentEntry, color });
} */
- return true;
- })
- .catch(error => {
- props.switchCurrentLocationType(currentLocationId);
- console.warn('Error saving color for folder ' + error);
- props.showNotification(t('Error saving color for folder'));
- });
- });
+ return true;
+ })
+ .catch(error => {
+ props.switchCurrentLocationType(currentLocationId);
+ console.warn('Error saving color for folder ' + error);
+ props.showNotification(t('Error saving color for folder'));
+ });
+ });
};
const handleFileNameChange = (event: ChangeEvent<HTMLInputElement>) => {
@@ -529,44 +525,43 @@ function EntryProperties(props: Props) {
};*/
const handleChange = (name: string, value: Array<TS.Tag>, action: string) => {
- props
- .switchLocationType(props.openedEntry.locationId)
- .then(currentLocationId => {
- if (action === 'remove-value') {
- if (!value) {
- // no tags left in the select element
- props.removeAllTags([currentEntry.current.path]).then(() => {
- props
- .updateOpenedFile(currentEntry.current.path, { tags: [] })
- .then(() => {
- props.switchCurrentLocationType(currentLocationId);
- });
- });
- } else {
- props.removeTags([currentEntry.current.path], value).then(() => {
+ props.switchLocationType(openedEntry.locationId).then(currentLocationId => {
+ if (action === 'remove-value') {
+ if (!value) {
+ // no tags left in the select element
+ removeAllTags([currentEntry.current.path]).then(() => {
+ updateOpenedFile(currentEntry.current.path, {
+ id: '',
+ tags: []
+ }).then(() => {
props.switchCurrentLocationType(currentLocationId);
});
- }
- } else if (action === 'clear') {
- props.removeAllTags([currentEntry.current.path]).then(() => {
- props.switchCurrentLocationType(currentLocationId);
});
} else {
- // create-option or select-option
- const tags =
- currentEntry.current.tags === undefined
- ? value
- : value.filter(
- tag =>
- !currentEntry.current.tags.some(
- obj => obj.title === tag.title
- )
- );
- return props
- .addTags([currentEntry.current.path], tags)
- .then(() => props.switchCurrentLocationType(currentLocationId));
+ removeTags([currentEntry.current.path], value).then(() => {
+ props.switchCurrentLocationType(currentLocationId);
+ });
}
- });
+ } else if (action === 'clear') {
+ removeAllTags([currentEntry.current.path]).then(() => {
+ props.switchCurrentLocationType(currentLocationId);
+ });
+ } else {
+ // create-option or select-option
+ const tags =
+ currentEntry.current.tags === undefined
+ ? value
+ : value.filter(
+ tag =>
+ !currentEntry.current.tags.some(
+ obj => obj.title === tag.title
+ )
+ );
+ return addTags([currentEntry.current.path], tags).then(() =>
+ props.switchCurrentLocationType(currentLocationId)
+ );
+ }
+ });
};
const { isReadOnlyMode } = props;
@@ -653,7 +648,7 @@ function EntryProperties(props: Props) {
const perspective = event.target.value;
savePerspective(currentEntry.current.path, perspective)
.then((entryMeta: TS.FileSystemEntryMeta) => {
- props.updateOpenedFile(currentEntry.current.path, entryMeta);
+ updateOpenedFile(currentEntry.current.path, entryMeta);
return true;
})
.catch(error => {
@@ -1413,9 +1408,6 @@ function mapActionCreatorsToProps(dispatch) {
switchCurrentLocationType: AppActions.switchCurrentLocationType,
setLastBackgroundColorChange: AppActions.setLastBackgroundColorChange,
setSelectedEntries: AppActions.setSelectedEntries,
- removeTags: TaggingActions.removeTags,
- removeAllTags: TaggingActions.removeAllTags,
- updateOpenedFile: AppActions.updateOpenedFile,
updateThumbnailUrl: AppActions.updateThumbnailUrl,
showNotification: AppActions.showNotification
},
@@ -1424,8 +1416,6 @@ function mapActionCreatorsToProps(dispatch) {
}
const areEqual = (prevProp: Props, nextProp: Props) =>
- JSON.stringify(nextProp.openedEntry) ===
- JSON.stringify(prevProp.openedEntry) &&
JSON.stringify(nextProp.lastThumbnailImageChange) ===
JSON.stringify(prevProp.lastThumbnailImageChange) &&
JSON.stringify(nextProp.lastBackgroundImageChange) ===
diff --git a/app/components/FileView.tsx b/app/components/FileView.tsx
index 27df93bed..fd07936fd 100644
--- a/app/components/FileView.tsx
+++ b/app/components/FileView.tsx
@@ -17,11 +17,11 @@
*/
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 { connect } from 'react-redux';
import { getSearchQuery } from '-/reducers/location-index';
import { TS } from '-/tagspaces.namespace';
import { useTranslation } from 'react-i18next';
@@ -31,25 +31,22 @@ interface Props {
isFullscreen?: boolean;
fileViewer: MutableRefObject<HTMLIFrameElement>;
fileViewerContainer: MutableRefObject<HTMLDivElement>;
- searchQuery: TS.SearchQuery;
toggleFullScreen?: () => void;
height?: string;
- //currentTheme: string;
eventID: string;
}
function FileView(props: Props) {
const { i18n } = useTranslation();
const theme = useTheme();
+ const searchQuery = useSelector(getSearchQuery);
const {
openedFile,
fileViewer,
isFullscreen,
fileViewerContainer,
toggleFullScreen,
- searchQuery,
height,
- //currentTheme,
eventID
} = props; // .openedFiles[0];
@@ -132,6 +129,7 @@ function FileView(props: Props) {
} else {
fileOpenerURL = 'about:blank';
}
+
return (
<div
ref={fileViewerContainer}
@@ -187,15 +185,5 @@ const areEqual = (prevProp, nextProp) =>
nextProp.openedFile.shouldReload === prevProp.openedFile.shouldReload &&
nextProp.isFullscreen === prevProp.isFullscreen &&
nextProp.height === prevProp.height;
-// nextProp.currentTheme === prevProp.currentTheme; // Commented due to reloading of the editors with changed content
-/* ((nextProp.openedFile.editMode === undefined &&
- prevProp.openedFile.editMode === true) ||
- nextProp.openedFile.editMode === prevProp.openedFile.editMode); */
-
-function mapStateToProps(state) {
- return {
- searchQuery: getSearchQuery(state)
- };
-}
-export default connect(mapStateToProps)(React.memo(FileView, areEqual));
+export default React.memo(FileView, areEqual);
diff --git a/app/components/FolderContainer.tsx b/app/components/FolderContainer.tsx
index c4c776868..6a1e7e663 100644
--- a/app/components/FolderContainer.tsx
+++ b/app/components/FolderContainer.tsx
@@ -17,7 +17,7 @@
*/
import React, { useCallback, useEffect, useState } from 'react';
-import { styled, useTheme } from '@mui/material/styles';
+import { useTheme } from '@mui/material/styles';
import { connect, useSelector } from 'react-redux';
import { bindActionCreators } from 'redux';
import IconButton from '@mui/material/IconButton';
@@ -26,7 +26,6 @@ import CircularProgress from '@mui/material/CircularProgress';
import Tooltip from '-/components/Tooltip';
import Typography from '@mui/material/Typography';
import InputAdornment from '@mui/material/InputAdornment';
-import Badge from '@mui/material/Badge';
import ToggleButton from '@mui/material/ToggleButton';
import ToggleButtonGroup from '@mui/material/ToggleButtonGroup';
import AppConfig from '-/AppConfig';
@@ -41,14 +40,12 @@ import {
getDirectoryContent,
isReadOnlyMode,
getCurrentDirectoryPerspective,
- OpenedEntry,
getSelectedEntries,
getProgress,
isSearchMode,
getLastSearchTimestamp,
getDirectoryPath
} from '../reducers/app';
-import TaggingActions from '../reducers/tagging-actions';
import LoadingLazy from '../components/LoadingLazy';
import {
GoBackIcon,
@@ -72,37 +69,7 @@ import SearchBox from '-/components/SearchBox';
import useFirstRender from '-/utils/useFirstRender';
import { useTranslation } from 'react-i18next';
import { SortedDirContextProvider } from '-/perspectives/grid-perspective/hooks/SortedDirContextProvider';
-
-const PREFIX = 'FolderContainer';
-
-const classes = {
- button: `${PREFIX}-button`
-};
-
-const Root = styled('div')(({ theme }) => ({
- position: 'relative',
- height: '100%',
- [`& .${classes.button}`]: {
- position: 'relative',
- padding: '8px 12px 6px 8px',
- margin: '0'
- }
-}));
-
-/*const CounterBadge: any = withStyles(theme => ({
- badge: {
- top: '50%',
- right: -15,
- color:
- theme.palette.mode === 'light'
- ? theme.palette.grey[900]
- : theme.palette.grey[200],
- backgroundColor:
- theme.palette.mode === 'light'
- ? theme.palette.grey[200]
- : theme.palette.grey[900]
- }
-}))(Badge);*/
+import { useOpenedEntryContext } from '-/hooks/useOpenedEntryContext';
const GridPerspective = React.lazy(() =>
import(
@@ -185,12 +152,7 @@ function WelcomePanelAsync(props) {
interface Props {
settings: any;
directoryContent: Array<TS.FileSystemEntry>;
- //searchResultCount: number;
- addTags: () => void;
- removeAllTags: () => void;
- editTagForEntry: () => void;
renameFile: () => void;
- openEntry: (path: string) => void;
reflectCreateEntry: (path: string, isFile: boolean) => void;
loadParentDirectoryContent: () => void;
setSelectedEntries: (selectedEntries: Array<Object>) => void;
@@ -204,7 +166,6 @@ interface Props {
maxSearchResults: number;
defaultPerspective: string;
currentDirectoryPerspective: string;
- openedFiles: Array<OpenedEntry>;
updateCurrentDirEntry: (path: string, entry: Object) => void;
setCurrentDirectoryColor: (color: string) => void;
selectedEntries: Array<TS.FileSystemEntry>;
@@ -214,7 +175,6 @@ interface Props {
setSearchQuery: (searchQuery: TS.SearchQuery) => void;
enterSearchMode: () => void;
exitSearchMode: () => void;
- // editedEntryPaths: Array<TS.EditedEntryPath>;
goBack: () => void;
goForward: () => void;
lastSearchTimestamp: number;
@@ -231,7 +191,6 @@ function FolderContainer(props: Props) {
currentDirectoryPerspective,
setSelectedEntries,
reflectCreateEntry,
- openEntry,
defaultPerspective,
goBack,
goForward
@@ -239,18 +198,20 @@ 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 (props.openedFiles.length > 0) {
- const openedFile = props.openedFiles[0];
+ if (openedEntries.length > 0) {
+ const openedFile = openedEntries[0];
if (openedFile.path === currentDirectoryPath) {
if (openedFile.color) {
props.setCurrentDirectoryColor(openedFile.color);
@@ -270,8 +231,8 @@ function FolderContainer(props: Props) {
}
}
}
- havePrevOpenedFile.current = props.openedFiles.length > 0;
- }, [props.openedFiles]);
+ havePrevOpenedFile.current = openedEntries.length > 0;
+ }, [openedEntries]);
/**
* reflect update openedFile from perspective
@@ -331,7 +292,6 @@ function FolderContainer(props: Props) {
<GalleryPerspectiveAsync
directoryContent={props.directoryContent}
lastSearchTimestamp={props.lastSearchTimestamp}
- openEntry={openEntry}
currentDirectoryPath={currentDirectoryPath}
switchPerspective={switchPerspective}
/>
@@ -344,7 +304,6 @@ function FolderContainer(props: Props) {
lastSearchTimestamp={props.lastSearchTimestamp}
currentDirectoryPath={currentDirectoryPath}
switchPerspective={switchPerspective}
- openedFiles={props.openedFiles}
/>
);
}
@@ -353,14 +312,10 @@ function FolderContainer(props: Props) {
<KanBanPerspectiveAsync
directoryContent={props.directoryContent}
lastSearchTimestamp={props.lastSearchTimestamp}
- openEntry={props.openEntry}
openRenameEntryDialog={openRenameEntryDialog}
loadParentDirectoryContent={props.loadParentDirectoryContent}
renameFile={props.renameFile}
currentDirectoryPath={currentDirectoryPath}
- addTags={props.addTags}
- editTagForEntry={props.editTagForEntry}
- removeAllTags={props.removeAllTags}
switchPerspective={switchPerspective}
/>
);
@@ -462,145 +417,145 @@ function FolderContainer(props: Props) {
? ' (' + (AppConfig.isMaclike ? '⌘' : 'Ctrl') + '+Shift+F)'
: '';
// keyBindings['openSearch'].toUpperCase()
+
return (
- <Root data-tid="folderContainerTID">
+ <div
+ style={{
+ width: '100%',
+ height: 'calc(100% - 50px)',
+ backgroundColor: theme.palette.background.default,
+ display: 'flex',
+ flexDirection: 'column',
+ position: 'relative'
+ }}
+ data-tid="folderContainerTID"
+ >
<div
style={{
- flex: '1 1 100%',
- width: '100%',
- height: '100%',
- maxHeight: '100%',
- overflow: 'unset',
- backgroundColor: theme.palette.background.default,
+ paddingLeft: 5,
+ paddingRight: 5,
display: 'flex',
- flexDirection: 'column'
+ alignItems: 'center',
+ minHeight: 50
}}
>
- <div
- style={{
- paddingLeft: 5,
- paddingRight: 5,
- display: 'flex',
- //overflowY: 'hidden',
- alignItems: 'center'
- //overflowX: 'auto'
- }}
+ <IconButton
+ id="mobileMenuButton"
+ // style={{
+ // transform: drawerOpened ? 'rotate(0deg)' : 'rotate(180deg)',
+ // width: 50
+ // }}
+ onClick={toggleDrawer}
+ >
+ <MainMenuIcon />
+ </IconButton>
+ <Tooltip
+ title={
+ t('core:goback') + ' - BETA - ' + t('core:gobackClarification')
+ }
>
<IconButton
- id="mobileMenuButton"
- // style={{
- // transform: drawerOpened ? 'rotate(0deg)' : 'rotate(180deg)',
- // width: 50
- // }}
- onClick={toggleDrawer}
+ id="goBackButton"
+ disabled={window.history.length < 2}
+ onClick={goBack}
>
- <MainMenuIcon />
+ <GoBackIcon />
</IconButton>
- <Tooltip
- title={
- t('core:goback') + ' - BETA - ' + t('core:gobackClarification')
- }
- >
+ </Tooltip>
+ {isDesktopMode && (
+ <Tooltip title={t('core:goforward') + ' - BETA'}>
<IconButton
- id="goBackButton"
+ id="goForwardButton"
disabled={window.history.length < 2}
- onClick={goBack}
+ onClick={goForward}
>
- <GoBackIcon />
+ <GoForwardIcon />
</IconButton>
</Tooltip>
- {isDesktopMode && (
- <Tooltip title={t('core:goforward') + ' - BETA'}>
- <IconButton
- id="goForwardButton"
- disabled={window.history.length < 2}
- onClick={goForward}
- >
- <GoForwardIcon />
- </IconButton>
- </Tooltip>
- )}
- {props.isSearchMode ? (
- /* todo rethink if open props is needed */
- <SearchBox
- open={props.isSearchMode}
- textQuery={props.searchQuery.textQuery}
+ )}
+ {props.isSearchMode ? (
+ /* todo rethink if open props is needed */
+ <SearchBox
+ open={props.isSearchMode}
+ textQuery={props.searchQuery.textQuery}
+ />
+ ) : (
+ <>
+ <div
+ style={{
+ flex: '1 1 1%',
+ display: 'flex',
+ flexDirection: 'column'
+ }}
/>
- ) : (
- <>
- <div
- style={{
- flex: '1 1 1%',
- display: 'flex',
- flexDirection: 'column'
- }}
- />
- <MainSearchField
- fullWidth
- data-tid="toggleSearch"
- defaultValue=""
- variant="outlined"
- size="small"
+ <MainSearchField
+ fullWidth
+ data-tid="toggleSearch"
+ defaultValue=""
+ variant="outlined"
+ size="small"
+ style={{
+ minWidth: 40,
+ width: 220,
+ marginRight: 10
+ }}
+ onKeyDown={toggleSearchMode}
+ onClick={toggleSearchMode}
+ margin="dense"
+ placeholder={t('core:searchTitle') + openSearchKeyBinding}
+ InputProps={{
+ startAdornment: (
+ <InputAdornment position="start" style={{ marginRight: 0 }}>
+ <IconButton size="small" edge="end">
+ <SearchIcon />
+ </IconButton>
+ </InputAdornment>
+ )
+ }}
+ />
+ {props.progress && props.progress.length > 0 && (
+ <IconButton
+ id="progressButton"
+ title={t('core:progress')}
+ data-tid="uploadProgress"
+ onClick={() => props.toggleUploadDialog()}
style={{
- minWidth: 40,
- width: 220,
- marginRight: 10
- }}
- onKeyDown={toggleSearchMode}
- onClick={toggleSearchMode}
- margin="dense"
- placeholder={t('core:searchTitle') + openSearchKeyBinding}
- InputProps={{
- startAdornment: (
- <InputAdornment position="start" style={{ marginRight: 0 }}>
- <IconButton size="small" edge="end">
- <SearchIcon />
- </IconButton>
- </InputAdornment>
- )
+ position: 'relative',
+ padding: '8px 12px 6px 8px',
+ margin: '0'
}}
- />
- {props.progress && props.progress.length > 0 && (
- <IconButton
- id="progressButton"
- title={t('core:progress')}
- data-tid="uploadProgress"
- onClick={() => props.toggleUploadDialog()}
- className={classes.button}
- >
- <CircularProgressWithLabel value={getProgressValue()} />
- </IconButton>
- )}
- {/* {isDesktopMode && <LocationMenu />} */}
- <PathBreadcrumbs
- switchPerspective={switchPerspective}
- setSelectedEntries={setSelectedEntries}
- reflectCreateEntry={reflectCreateEntry}
- isDesktopMode={isDesktopMode}
- openRenameDirectoryDialog={() =>
- setIsRenameEntryDialogOpened(true)
- }
- openMoveCopyFilesDialog={props.openMoveCopyFilesDialog}
- />
- </>
- )}
- </div>
- <div
- style={{
- height: '100%', // props.windowHeight + 1,
- flex: '1 1 auto',
- width: '100%'
- }}
- >
- {/*<LoadingAnimation />*/}
- {renderPerspective()}
- {isRenameEntryDialogOpened && (
- <RenameEntryDialog
- open={isRenameEntryDialogOpened}
- onClose={() => setIsRenameEntryDialogOpened(false)}
+ >
+ <CircularProgressWithLabel value={getProgressValue()} />
+ </IconButton>
+ )}
+ {/* {isDesktopMode && <LocationMenu />} */}
+ <PathBreadcrumbs
+ switchPerspective={switchPerspective}
+ setSelectedEntries={setSelectedEntries}
+ reflectCreateEntry={reflectCreateEntry}
+ isDesktopMode={isDesktopMode}
+ openRenameDirectoryDialog={() =>
+ setIsRenameEntryDialogOpened(true)
+ }
+ openMoveCopyFilesDialog={props.openMoveCopyFilesDialog}
/>
- )}
- </div>
+ </>
+ )}
+ </div>
+ <div
+ style={{
+ minHeight: '100%',
+ width: '100%'
+ }}
+ >
+ {/*<LoadingAnimation />*/}
+ {renderPerspective()}
+ {isRenameEntryDialogOpened && (
+ <RenameEntryDialog
+ open={isRenameEntryDialogOpened}
+ onClose={() => setIsRenameEntryDialogOpened(false)}
+ />
+ )}
</div>
{props.isDesktopMode && (
<ToggleButtonGroup
@@ -611,7 +566,7 @@ function FolderContainer(props: Props) {
aria-label="change perspective"
exclusive
style={{
- bottom: 15,
+ bottom: -40,
right: 15,
zIndex: 1000,
opacity: 0.9,
@@ -622,7 +577,7 @@ function FolderContainer(props: Props) {
{perspectiveToggleButtons}
</ToggleButtonGroup>
)}
- </Root>
+ </div>
);
}
@@ -649,11 +604,7 @@ function mapActionCreatorsToProps(dispatch) {
return bindActionCreators(
{
toggleUploadDialog: AppActions.toggleUploadDialog,
- addTags: TaggingActions.addTags,
- removeAllTags: TaggingActions.removeAllTags,
- editTagForEntry: TaggingActions.editTagForEntry,
renameFile: AppActions.renameFile,
- openEntry: AppActions.openEntry,
reflectCreateEntry: AppActions.reflectCreateEntry,
loadParentDirectoryContent: AppActions.loadParentDirectoryContent,
setSelectedEntries: AppActions.setSelectedEntries,
@@ -679,10 +630,6 @@ const areEqual = (prevProp: Props, nextProp: Props) =>
JSON.stringify(nextProp.progress) === JSON.stringify(prevProp.progress) &&
JSON.stringify(nextProp.directoryContent) ===
JSON.stringify(prevProp.directoryContent) &&
- JSON.stringify(nextProp.openedFiles) ===
- JSON.stringify(prevProp.openedFiles) &&
- //JSON.stringify(nextProp.theme) === JSON.stringify(prevProp.theme) &&
- // JSON.stringify(nextProp.editedEntryPaths) === JSON.stringify(prevProp.editedEntryPaths) &&
JSON.stringify(nextProp.searchQuery) ===
JSON.stringify(prevProp.searchQuery) &&
nextProp.lastSearchTimestamp === prevProp.lastSearchTimestamp &&
diff --git a/app/components/RenderHistory.tsx b/app/components/RenderHistory.tsx
index 3a1356ccd..ab1b28349 100644
--- a/app/components/RenderHistory.tsx
+++ b/app/components/RenderHistory.tsx
@@ -39,6 +39,7 @@ import {
AppDispatch,
getCurrentLocationId
} from '-/reducers/app';
+import { useOpenedEntryContext } from '-/hooks/useOpenedEntryContext';
interface Props {
historyKey: string;
@@ -50,6 +51,7 @@ interface Props {
function RenderHistory(props: Props) {
const { t } = useTranslation();
const dispatch: AppDispatch = useDispatch();
+ const { openEntry } = useOpenedEntryContext();
const currentLocationId = useSelector(getCurrentLocationId);
const { historyKey, items, update, maxItems, showDelete = true } = props;
@@ -59,9 +61,6 @@ function RenderHistory(props: Props) {
const openLocationByIdDispatch = locationId =>
dispatch(AppActions.openLocationById(locationId));
- const openEntryDispatch = entryPath =>
- dispatch(AppActions.openEntry(entryPath));
-
return (
<>
{items &&
@@ -89,7 +88,7 @@ function RenderHistory(props: Props) {
currentLocationId,
openLinkDispatch,
openLocationByIdDispatch,
- openEntryDispatch
+ openEntry
)
}
>
diff --git a/app/components/Revisions.tsx b/app/components/Revisions.tsx
index 5a40995dd..02e355bd9 100644
--- a/app/components/Revisions.tsx
+++ b/app/components/Revisions.tsx
@@ -22,13 +22,7 @@ import {
extractContainingDirectoryPath
} from '@tagspaces/tagspaces-common/paths';
import Tooltip from '-/components/Tooltip';
-import {
- actions as AppActions,
- AppDispatch,
- getOpenedFiles,
- OpenedEntry
-} from '-/reducers/app';
-import { useSelector, useDispatch } from 'react-redux';
+import { OpenedEntry } from '-/reducers/app';
import PlatformIO from '-/services/platform-facade';
import { TS } from '-/tagspaces.namespace';
import { format, formatDistanceToNow } from 'date-fns';
@@ -50,13 +44,14 @@ import {
import { Pro } from '-/pro';
import FilePreviewDialog from '-/components/dialogs/FilePreviewDialog';
import { useTranslation } from 'react-i18next';
+import { useOpenedEntryContext } from '-/hooks/useOpenedEntryContext';
const initialRowsPerPage = 10;
function Revisions() {
const { t } = useTranslation();
- const dispatch: AppDispatch = useDispatch();
- const openedFiles: Array<OpenedEntry> = useSelector(getOpenedFiles);
+ // const dispatch: AppDispatch = useDispatch();
+ const { openedEntries, updateOpenedFile } = useOpenedEntryContext();
const [rows, setRows] = useState<Array<TS.FileSystemEntry>>([]);
const [page, setPage] = useState<number>(0);
const [rowsPerPage, setRowsPerPage] = React.useState<number>(
@@ -69,11 +64,11 @@ function Revisions() {
useEffect(() => {
// if no history item path - not loadHistoryItems for items in metaFolder
- const openedFile = openedFiles[0];
+ const openedFile = openedEntries[0];
if (openedFile && openedFile.path.indexOf(AppConfig.metaFolder) === -1) {
loadHistoryItems(openedFile);
}
- }, [openedFiles]);
+ }, [openedEntries]);
function loadHistoryItems(openedFile: OpenedEntry) {
Pro.MetaOperations.getMetadataID(openedFile.path, openedFile.uuid).then(
@@ -108,7 +103,7 @@ function Revisions() {
function deleteRevision(path) {
PlatformIO.deleteFilePromise(path, true).then(() =>
- loadHistoryItems(openedFiles[0])
+ loadHistoryItems(openedEntries[0])
);
}
@@ -117,12 +112,12 @@ function Revisions() {
const promises = rows.map(row =>
PlatformIO.deleteFilePromise(row.path, true)
);
- Promise.all(promises).then(() => loadHistoryItems(openedFiles[0]));
+ Promise.all(promises).then(() => loadHistoryItems(openedEntries[0]));
}
}
function restoreRevision(revisionPath) {
- const openedFile = openedFiles[0];
+ const openedFile = openedEntries[0];
const targetPath = getBackupFileLocation(
openedFile.path,
openedFile.uuid,
@@ -134,13 +129,12 @@ function Revisions() {
).then(() =>
PlatformIO.copyFilePromiseOverwrite(revisionPath, openedFile.path).then(
() =>
- dispatch(
- AppActions.updateOpenedFile(openedFile.path, {
- ...openedFile,
- editMode: false,
- shouldReload: !openedFile.shouldReload
- })
- )
+ updateOpenedFile(openedFile.path, {
+ id: '',
+ ...openedFile,
+ editMode: false,
+ shouldReload: !openedFile.shouldReload
+ })
)
);
}
@@ -218,7 +212,7 @@ function Revisions() {
<TableBody>
{paginatedRows.map(row => (
<TableRow
- data-tid={openedFiles[0].uuid}
+ data-tid={openedEntries[0].uuid}
key={row.path}
sx={{ '&:last-child td, &:last-child th': { border: 0 } }}
>
diff --git a/app/components/SearchAutocomplete.tsx b/app/components/SearchAutocomplete.tsx
index 8414f72e9..6d60d9806 100644
--- a/app/components/SearchAutocomplete.tsx
+++ b/app/components/SearchAutocomplete.tsx
@@ -71,6 +71,7 @@ import { getSearchOptions } from '-/components/SearchOptionsMenu';
import { dataTidFormat } from '-/services/test';
import { useTheme } from '@mui/material/styles';
import { useTranslation } from 'react-i18next';
+import { useOpenedEntryContext } from '-/hooks/useOpenedEntryContext';
interface Props {
style?: any;
@@ -92,6 +93,7 @@ interface Props {
function SearchAutocomplete(props: Props) {
const { t } = useTranslation();
const theme = useTheme();
+ const { openEntry } = useOpenedEntryContext();
const dispatch: AppDispatch = useDispatch();
const indexing = useSelector(isIndexing);
const searchQuery: TS.SearchQuery = useSelector(getSearchQuery);
@@ -108,8 +110,6 @@ function SearchAutocomplete(props: Props) {
dispatch(AppActions.openLink(link, options));
const openLocationByIdDispatch = locationId =>
dispatch(AppActions.openLocationById(locationId));
- const openEntryDispatch = entryPath =>
- dispatch(AppActions.openEntry(entryPath));
const { setTextQuery, textQuery, open, setAnchorSearch } = props;
// const [, forceUpdate] = useReducer(x => x + 1, 0);
@@ -1005,7 +1005,7 @@ function SearchAutocomplete(props: Props) {
currentLocation.uuid,
openLinkDispatch,
openLocationByIdDispatch,
- openEntryDispatch
+ openEntry
);
}
searchOptions.current = getSearchOptions();
@@ -1025,7 +1025,7 @@ function SearchAutocomplete(props: Props) {
currentLocation.uuid,
openLinkDispatch,
openLocationByIdDispatch,
- openEntryDispatch
+ openEntry
);
}
searchOptions.current = getSearchOptions();
diff --git a/app/components/TagLibrary.tsx b/app/components/TagLibrary.tsx
index c8cde3070..59a9cebf4 100644
--- a/app/components/TagLibrary.tsx
+++ b/app/components/TagLibrary.tsx
@@ -34,7 +34,6 @@ import TagGroupContainer from './TagGroupContainer';
import TagMenu from './menus/TagMenu';
import TagLibraryMenu from './menus/TagLibraryMenu';
import TagGroupMenu from './menus/TagGroupMenu';
-import TaggingActions from '../reducers/tagging-actions';
import {
actions as SettingsActions,
getSaveTagInLocation,
@@ -75,6 +74,8 @@ import {
import useFirstRender from '-/utils/useFirstRender';
import { classes, SidePanel } from '-/components/SidePanels.css';
import { useTranslation } from 'react-i18next';
+import { useOpenedEntryContext } from '-/hooks/useOpenedEntryContext';
+import { useTaggingActionsContext } from '-/hooks/useTaggingActionsContext';
interface Props {
style?: any;
@@ -83,6 +84,7 @@ interface Props {
function TagLibrary(props: Props) {
const { t } = useTranslation();
+ const { addTags } = useTaggingActionsContext();
const dispatch: AppDispatch = useDispatch();
const tagBackgroundColor = useSelector(getTagColor);
const tagTextColor = useSelector(getTagTextColor);
@@ -97,11 +99,6 @@ function TagLibrary(props: Props) {
const toggleTagGroupDispatch = uuid =>
dispatch(SettingsActions.toggleTagGroup(uuid));
- const addTagsDispatch = (
- paths: Array<string>,
- tags: Array<TS.Tag>,
- updateIndex
- ) => dispatch(TaggingActions.addTags(paths, tags, updateIndex));
const [tagGroups, setTagGroups] = useState<Array<TS.TagGroup>>(
getTagLibrary()
@@ -301,7 +298,7 @@ function TagLibrary(props: Props) {
tag={tag}
tagGroup={tagGroup}
handleTagMenu={handleTagMenuCallback}
- addTags={addTagsDispatch}
+ addTags={addTags}
/*moveTag={(
tagTitle: string,
fromTagGroupId: TS.Uuid,
@@ -326,7 +323,7 @@ function TagLibrary(props: Props) {
tag={tag}
tagGroup={tagGroup}
handleTagMenu={handleTagMenuCallback}
- addTags={addTagsDispatch}
+ addTags={addTags}
moveTag={(
tagTitle: string,
fromTagGroupId: TS.Uuid,
diff --git a/app/components/dialogs/AddRemoveTagsDialog.tsx b/app/components/dialogs/AddRemoveTagsDialog.tsx
index 211655e31..3398fceb7 100644
--- a/app/components/dialogs/AddRemoveTagsDialog.tsx
+++ b/app/components/dialogs/AddRemoveTagsDialog.tsx
@@ -41,9 +41,9 @@ import { TS } from '-/tagspaces.namespace';
import DialogCloseButton from '-/components/dialogs/DialogCloseButton';
import { useTheme } from '@mui/material/styles';
import useMediaQuery from '@mui/material/useMediaQuery';
-import TaggingActions from '-/reducers/tagging-actions';
import { AppDispatch } from '-/reducers/app';
import { useTranslation } from 'react-i18next';
+import { useTaggingActionsContext } from '-/hooks/useTaggingActionsContext';
interface Props {
open: boolean;
@@ -53,7 +53,8 @@ interface Props {
function AddRemoveTagsDialog(props: Props) {
const { t } = useTranslation();
- const dispatch: AppDispatch = useDispatch();
+
+ const { addTags, removeTags, removeAllTags } = useTaggingActionsContext();
const [newlyAddedTags, setNewlyAddedTags] = useState<Array<TS.Tag>>([]);
const handleChange = (name: string, value: Array<TS.Tag>, action: string) => {
@@ -76,37 +77,31 @@ function AddRemoveTagsDialog(props: Props) {
props.onClose(clearSelection);
};
- const addTags = () => {
+ const addTagsAction = () => {
if (props.selectedEntries && props.selectedEntries.length > 0) {
- dispatch(
- TaggingActions.addTags(
- selectedEntries.map(entry => entry.path),
- newlyAddedTags
- )
+ addTags(
+ selectedEntries.map(entry => entry.path),
+ newlyAddedTags
);
}
onCloseDialog(true);
};
- const removeTags = () => {
+ const removeTagsAction = () => {
const { selectedEntries } = props;
if (selectedEntries && selectedEntries.length > 0) {
- dispatch(
- TaggingActions.removeTags(
- selectedEntries.map(entry => entry.path),
- newlyAddedTags
- )
+ removeTags(
+ selectedEntries.map(entry => entry.path),
+ newlyAddedTags
);
}
onCloseDialog(true);
};
- const removeAllTags = () => {
+ const removeAllTagsAction = () => {
const { selectedEntries } = props;
if (selectedEntries && selectedEntries.length > 0) {
- dispatch(
- TaggingActions.removeAllTags(selectedEntries.map(entry => entry.path))
- );
+ removeAllTags(selectedEntries.map(entry => entry.path));
}
onCloseDialog(true);
};
@@ -186,7 +181,7 @@ function AddRemoveTagsDialog(props: Props) {
data-tid="cleanTagsMultipleEntries"
disabled={selectedEntries.length < 1}
color="primary"
- onClick={removeAllTags}
+ onClick={removeAllTagsAction}
>
{t('core:tagOperationCleanTags')}
</Button>
@@ -194,7 +189,7 @@ function AddRemoveTagsDialog(props: Props) {
data-tid="removeTagsMultipleEntries"
disabled={disabledButtons}
color="primary"
- onClick={removeTags}
+ onClick={removeTagsAction}
>
{t('core:tagOperationRemoveTag')}
</Button>
@@ -203,7 +198,7 @@ function AddRemoveTagsDialog(props: Props) {
disabled={disabledButtons}
color="primary"
variant="contained"
- onClick={addTags}
+ onClick={addTagsAction}
>
{t('core:tagOperationAddTag')}
</Button>
diff --git a/app/components/dialogs/CreateDirectoryDialog.tsx b/app/components/dialogs/CreateDirectoryDialog.tsx
index e54f9065f..ab3efb02e 100644
--- a/app/components/dialogs/CreateDirectoryDialog.tsx
+++ b/app/components/dialogs/CreateDirectoryDialog.tsx
@@ -35,6 +35,8 @@ 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';
interface Props {
open: boolean;
@@ -46,7 +48,7 @@ interface Props {
function CreateDirectoryDialog(props: Props) {
const { t } = useTranslation();
- const dispatch: AppDispatch = useDispatch();
+ const { createDirectory } = useFsActionsContext();
const [inputError, setInputError] = useState(false);
const isFirstRun = useRef(true);
const [disableConfirmButton, setDisableConfirmButton] = useState(true);
@@ -83,16 +85,13 @@ function CreateDirectoryDialog(props: Props) {
: currentDirectoryPath,
name
);
- dispatch(
- AppActions.createDirectory(
- dirPath,
- reflect !== undefined ? reflect : true
- )
- ).then(() => {
- if (props.callback) {
- props.callback(dirPath);
+ createDirectory(dirPath, reflect !== undefined ? reflect : true).then(
+ () => {
+ if (props.callback) {
+ props.callback(dirPath);
+ }
}
- });
+ );
resetState();
props.onClose();
}
diff --git a/app/components/dialogs/EditEntryTagDialog.tsx b/app/components/dialogs/EditEntryTagDialog.tsx
index 7ae586868..68e97eada 100644
--- a/app/components/dialogs/EditEntryTagDialog.tsx
+++ b/app/components/dialogs/EditEntryTagDialog.tsx
@@ -38,7 +38,6 @@ import EditIcon from '@mui/icons-material/Edit';
import { isGeoTag } from '-/utils/geo';
import { Pro } from '-/pro';
import { getSelectedEntries, getSelectedTag } from '-/reducers/app';
-import TaggingActions from '-/reducers/tagging-actions';
import { isDateTimeTag } from '-/utils/dates';
import { TS } from '-/tagspaces.namespace';
import useValidation from '-/utils/useValidation';
@@ -47,26 +46,11 @@ import DialogCloseButton from '-/components/dialogs/DialogCloseButton';
import { useTheme } from '@mui/material/styles';
import useMediaQuery from '@mui/material/useMediaQuery';
import { useTranslation } from 'react-i18next';
-
-const PREFIX = 'EditEntryTagDialog';
-
-const classes = {
- root: `${PREFIX}-root`
-};
-
-const StyledDialog = styled(Dialog)(() => ({
- [`& .${classes.root}`]: {
- minWidth: 400,
- height: '100%',
- marginBottom: 30
- }
-}));
+import { useTaggingActionsContext } from '-/hooks/useTaggingActionsContext';
interface Props {
- classes: any;
open: boolean;
onClose: () => void;
- editTagForEntry: (path: string, tag: TS.Tag, title: string) => void;
selectedEntries: Array<TS.FileSystemEntry>;
selectedTag: TS.Tag;
tileServer: TS.MapTileServer;
@@ -78,6 +62,8 @@ const DateTagEditor = Pro && Pro.UI ? Pro.UI.DateTagEditor : React.Fragment;
function EditEntryTagDialog(props: Props) {
const { t } = useTranslation();
+
+ const { editTagForEntry } = useTaggingActionsContext();
const [showAdvancedMode, setShowAdvancedMode] = useState<boolean>(false);
const [title, setTitle] = useState(
props.selectedTag && props.selectedTag.title
@@ -131,7 +117,7 @@ function EditEntryTagDialog(props: Props) {
props.editTagForEntry(entry.path, props.selectedTag, title)
);
} else { */
- props.editTagForEntry(props.selectedTag.path, props.selectedTag, title);
+ editTagForEntry(props.selectedTag.path, props.selectedTag, title);
props.onClose();
}
}
@@ -151,7 +137,6 @@ function EditEntryTagDialog(props: Props) {
return (
<DialogContent
data-tid="editEntryTagDialog"
- className={classes.root}
style={{
overflow: 'auto'
}}
@@ -244,10 +229,15 @@ function EditEntryTagDialog(props: Props) {
const theme = useTheme();
const fullScreen = useMediaQuery(theme.breakpoints.down('md'));
return (
- <StyledDialog
+ <Dialog
open={open}
fullScreen={fullScreen}
onClose={onClose}
+ style={{
+ minWidth: 400,
+ height: '100%',
+ marginBottom: 30
+ }}
onKeyDown={event => {
if (event.key === 'Enter' || event.keyCode === 13) {
event.preventDefault();
@@ -261,7 +251,7 @@ function EditEntryTagDialog(props: Props) {
{renderTitle()}
{renderContent()}
{renderActions()}
- </StyledDialog>
+ </Dialog>
);
}
@@ -274,19 +264,9 @@ function mapStateToProps(state) {
};
}
-function mapDispatchToProps(dispatch) {
- return bindActionCreators(
- {
- editTagForEntry: TaggingActions.editTagForEntry
- },
- dispatch
- );
-}
-
const areEqual = (prevProp, nextProp) =>
JSON.stringify(nextProp.selectedTag) === JSON.stringify(prevProp.selectedTag);
-export default connect(
- mapStateToProps,
- mapDispatchToProps
-)(React.memo(EditEntryTagDialog, areEqual));
+export default connect(mapStateToProps)(
+ React.memo(EditEntryTagDialog, areEqual)
+);
diff --git a/app/components/dialogs/RenameEntryDialog.tsx b/app/components/dialogs/RenameEntryDialog.tsx
index ea24d5aed..999cdc534 100644
--- a/app/components/dialogs/RenameEntryDialog.tsx
+++ b/app/components/dialogs/RenameEntryDialog.tsx
@@ -43,6 +43,8 @@ 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';
interface Props {
open: boolean;
@@ -52,6 +54,7 @@ interface Props {
function RenameEntryDialog(props: Props) {
const { open, onClose } = props;
const { t } = useTranslation();
+ const { renameDirectory } = useFsActionsContext();
const currentDirectoryPath = useSelector(getDirectoryPath);
const [inputError, setInputError] = useState<boolean>(false);
const disableConfirmButton = useRef<boolean>(true);
@@ -62,10 +65,6 @@ function RenameEntryDialog(props: Props) {
dispatch(AppActions.renameFile(source, target));
};
- const renameDirectory = (directoryPath, newDirectoryName) => {
- dispatch(AppActions.renameDirectory(directoryPath, newDirectoryName));
- };
-
let defaultName = '';
let originPath;
let isFile;
diff --git a/app/components/dialogs/components/CreateFile.tsx b/app/components/dialogs/components/CreateFile.tsx
index 574b2b712..f49ceebf0 100644
--- a/app/components/dialogs/components/CreateFile.tsx
+++ b/app/components/dialogs/components/CreateFile.tsx
@@ -39,6 +39,8 @@ 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';
const PREFIX = 'CreateFile';
@@ -75,7 +77,9 @@ function CreateFile(props: Props) {
AppConfig.endTagContainer
);
const [inputError, setInputError] = useState<boolean>(false);
- const [ignored, forceUpdate] = useReducer(x => x + 1, 0);
+
+ const { createFileAdvanced } = useOpenedEntryContext();
+ const [ignored, forceUpdate] = useReducer(x => x + 1, 0, undefined);
const fileContent = '';
const noSuitableLocation = !targetDirectoryPath;
@@ -96,13 +100,11 @@ function CreateFile(props: Props) {
function createRichTextFile() {
if (targetDirectoryPath && !fileNameValidation(fileName.current)) {
loadLocation();
- dispatch(
- AppActions.createFileAdvanced(
- targetDirectoryPath,
- fileName.current,
- fileContent,
- 'html'
- )
+ createFileAdvanced(
+ targetDirectoryPath,
+ fileName.current,
+ fileContent,
+ 'html'
);
onClose();
}
@@ -111,13 +113,11 @@ function CreateFile(props: Props) {
function createTextFile() {
if (targetDirectoryPath && !fileNameValidation(fileName.current)) {
loadLocation();
- dispatch(
- AppActions.createFileAdvanced(
- targetDirectoryPath,
- fileName.current,
- fileContent,
- 'txt'
- )
+ createFileAdvanced(
+ targetDirectoryPath,
+ fileName.current,
+ fileContent,
+ 'txt'
);
onClose();
}
@@ -126,13 +126,11 @@ function CreateFile(props: Props) {
function createMarkdownFile() {
if (targetDirectoryPath && !fileNameValidation(fileName.current)) {
loadLocation();
- dispatch(
- AppActions.createFileAdvanced(
- targetDirectoryPath,
- fileName.current,
- fileContent,
- 'md'
- )
+ createFileAdvanced(
+ targetDirectoryPath,
+ fileName.current,
+ fileContent,
+ 'md'
);
onClose();
}
diff --git a/app/components/hooks/DescriptionContextProvider.tsx b/app/components/hooks/DescriptionContextProvider.tsx
deleted file mode 100644
index 854535761..000000000
--- a/app/components/hooks/DescriptionContextProvider.tsx
+++ /dev/null
@@ -1,140 +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 React, { createContext, useEffect, useMemo, useRef } from 'react';
-import { useDispatch, useSelector } from 'react-redux';
-import {
- actions as AppActions,
- AppDispatch,
- getOpenedFiles,
- isReadOnlyMode,
- OpenedEntry
-} from '-/reducers/app';
-import { Pro } from '-/pro';
-import { useTranslation } from 'react-i18next';
-
-type DescriptionContextData = {
- description: string;
- setDescription: (description: string) => void;
- saveDescription: () => void;
-};
-
-export const DescriptionContext = createContext<DescriptionContextData>({
- description: undefined,
- setDescription: () => {},
- saveDescription: () => {}
-});
-
-export type DescriptionContextProviderProps = {
- children: React.ReactNode;
-};
-
-export const DescriptionContextProvider = ({
- children
-}: DescriptionContextProviderProps) => {
- const { t } = useTranslation();
- const dispatch: AppDispatch = useDispatch();
- const readOnlyMode = useSelector(isReadOnlyMode);
- const openedFiles: Array<OpenedEntry> = useSelector(getOpenedFiles);
- const openedFile: OpenedEntry = openedFiles[0];
- // const [ignored, forceUpdate] = useReducer(x => x + 1, 0, undefined);
-
- const description = useRef<string>(openedFile.description);
-
- useEffect(() => {
- if (openedFile.description !== description.current) {
- description.current = openedFile.description;
- } /*else {
- forceUpdate();
- }*/
- }, [openedFile.description]);
-
- const saveDescription = () => {
- if (readOnlyMode) {
- return;
- }
- if (!Pro) {
- dispatch(
- AppActions.showNotification(t('core:thisFunctionalityIsAvailableInPro'))
- );
- return;
- }
- if (!Pro.MetaOperations) {
- dispatch(
- AppActions.showNotification(t('Saving description not supported'))
- );
- return;
- }
- if (description.current !== undefined) {
- if (openedFile.locationId) {
- dispatch(AppActions.switchLocationTypeByID(openedFile.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'))
- );
- });
- }
- );
- } else {
- console.debug(
- 'openedFile:' +
- openedFile.path +
- ' dont have locationId! Current Location can be changed. Trying to save opened file in current location'
- );
- saveMetaData();
- }
- }
- };
-
- function saveMetaData() {
- return Pro.MetaOperations.saveFsEntryMeta(openedFile.path, {
- description: description.current
- }).then(entryMeta =>
- dispatch(AppActions.updateOpenedFile(openedFile.path, entryMeta))
- );
- }
-
- function setDescription(d: string) {
- description.current = d;
- }
-
- const context = useMemo(() => {
- return {
- description: description.current,
- setDescription,
- saveDescription
- };
- }, [description.current, openedFile.description]);
-
- return (
- <DescriptionContext.Provider value={context}>
- {children}
- </DescriptionContext.Provider>
- );
-};
diff --git a/app/components/hooks/useDescriptionContext.tsx b/app/components/hooks/useDescriptionContext.tsx
deleted file mode 100644
index 8eb3417ee..000000000
--- a/app/components/hooks/useDescriptionContext.tsx
+++ /dev/null
@@ -1,5 +0,0 @@
-import { useContext } from 'react';
-
-import { DescriptionContext } from './DescriptionContextProvider';
-
-export const useDescriptionContext = () => useContext(DescriptionContext);
diff --git a/app/components/menus/DirectoryMenu.tsx b/app/components/menus/DirectoryMenu.tsx
index c992b0ed4..4c59f5ab2 100644
--- a/app/components/menus/DirectoryMenu.tsx
+++ b/app/components/menus/DirectoryMenu.tsx
@@ -38,7 +38,6 @@ import {
getSelectedEntries,
isReadOnlyMode
} from '-/reducers/app';
-import TaggingActions from '-/reducers/tagging-actions';
import FileUploadContainer, {
FileUploadContainerRef
} from '-/components/FileUploadContainer';
@@ -49,6 +48,8 @@ import PlatformFacade from '-/services/platform-facade';
import { getDirectoryMenuItems } from '-/perspectives/common/DirectoryMenuItems';
import { getCurrentLocation, getLocations } from '-/reducers/locations';
import { useTranslation } from 'react-i18next';
+import { useOpenedEntryContext } from '-/hooks/useOpenedEntryContext';
+import { useTaggingActionsContext } from '-/hooks/useTaggingActionsContext';
interface Props {
open: boolean;
@@ -68,6 +69,8 @@ interface Props {
function DirectoryMenu(props: Props) {
const { t } = useTranslation();
+ const { openEntry } = useOpenedEntryContext();
+ const { addTags } = useTaggingActionsContext();
const fileUploadContainerRef = useRef<FileUploadContainerRef>(null);
const {
open,
@@ -101,8 +104,6 @@ function DirectoryMenu(props: Props) {
dispatch(AppActions.toggleCreateDirectoryDialog());
};
- const openEntry = path => dispatch(AppActions.openEntry(path, true));
-
const reflectCreateEntry = (path, isFile) => {
dispatch(AppActions.reflectCreateEntry(path, isFile));
};
@@ -115,10 +116,6 @@ function DirectoryMenu(props: Props) {
dispatch(AppActions.toggleProgressDialog());
};
- const addTags = (paths, tags, updateIndex) => {
- dispatch(TaggingActions.addTags(paths, tags, updateIndex));
- };
-
const toggleDeleteMultipleEntriesDialog = () => {
dispatch(AppActions.toggleDeleteMultipleEntriesDialog());
};
diff --git a/app/components/menus/EntryTagMenu.tsx b/app/components/menus/EntryTagMenu.tsx
index c3fe73616..561d32a77 100644
--- a/app/components/menus/EntryTagMenu.tsx
+++ b/app/components/menus/EntryTagMenu.tsx
@@ -36,7 +36,7 @@ import {
} from '-/reducers/app';
import { TS } from '-/tagspaces.namespace';
import { useTranslation } from 'react-i18next';
-import TaggingActions from '-/reducers/tagging-actions';
+import { useTaggingActionsContext } from '-/hooks/useTaggingActionsContext';
interface Props {
open: boolean;
@@ -55,10 +55,12 @@ function EntryTagMenu(props: Props) {
anchorEl,
selectedTag,
currentEntryPath,
- removeTags,
setIsAddTagDialogOpened
} = props;
+ const removeTagsProps = props.removeTags;
const { t } = useTranslation();
+
+ const { removeTags } = useTaggingActionsContext();
const [isDeleteTagDialogOpened, setIsDeleteTagDialogOpened] = useState(false);
const dispatch: AppDispatch = useDispatch();
const maxSearchResults: number = useSelector(getMaxSearchResults);
@@ -105,12 +107,12 @@ function EntryTagMenu(props: Props) {
}
function confirmRemoveTag() {
- if (removeTags) {
- removeTags([currentEntryPath], [selectedTag]);
+ if (removeTagsProps) {
+ removeTagsProps([currentEntryPath], [selectedTag]);
} else {
- dispatch(
- TaggingActions.removeTags([currentEntryPath], [selectedTag])
- ).then(() => handleCloseDialogs());
+ removeTags([currentEntryPath], [selectedTag]).then(() =>
+ handleCloseDialogs()
+ );
}
}
diff --git a/app/components/menus/FileMenu.tsx b/app/components/menus/FileMenu.tsx
index 936c5f241..735b0c0e7 100644
--- a/app/components/menus/FileMenu.tsx
+++ b/app/components/menus/FileMenu.tsx
@@ -68,6 +68,7 @@ import {
import { getCurrentLocation, getLocations } from '-/reducers/locations';
import PropertiesIcon from '@mui/icons-material/Info';
import { useTranslation } from 'react-i18next';
+import { useOpenedEntryContext } from '-/hooks/useOpenedEntryContext';
interface Props {
anchorEl: Element;
@@ -110,6 +111,7 @@ function FileMenu(props: Props) {
const { t } = useTranslation();
const dispatch: AppDispatch = useDispatch();
+ const { openEntry } = useOpenedEntryContext();
const currentLocation: TS.Location = useSelector(getCurrentLocation);
const locations: Array<TS.Location> = useSelector(getLocations);
const readOnlyMode = useSelector(isReadOnlyMode);
@@ -129,7 +131,7 @@ function FileMenu(props: Props) {
function showProperties() {
onClose();
if (selectedEntries && selectedEntries.length === 1) {
- dispatch(AppActions.openEntry(selectedEntries[0].path, true));
+ openEntry(selectedEntries[0].path, true);
}
}
@@ -291,7 +293,7 @@ function FileMenu(props: Props) {
function openFile() {
onClose();
if (selectedFilePath) {
- return dispatch(AppActions.openEntry(selectedFilePath));
+ return openEntry(selectedFilePath);
}
}
diff --git a/app/components/menus/TagGroupMenu.tsx b/app/components/menus/TagGroupMenu.tsx
index ee4ea03e4..337baa50e 100644
--- a/app/components/menus/TagGroupMenu.tsx
+++ b/app/components/menus/TagGroupMenu.tsx
@@ -36,8 +36,8 @@ 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 TaggingActions from '-/reducers/tagging-actions';
import { useTranslation } from 'react-i18next';
+import { useTaggingActionsContext } from '-/hooks/useTaggingActionsContext';
interface Props {
classes?: any;
@@ -69,6 +69,8 @@ function TagGroupMenu(props: Props) {
showDeleteTagGroupDialog
} = props;
const { t } = useTranslation();
+
+ const { collectTagsFromLocation } = useTaggingActionsContext();
const dispatch: AppDispatch = useDispatch();
const maxSearchResults = useSelector(getMaxSearchResults);
@@ -76,7 +78,7 @@ function TagGroupMenu(props: Props) {
onClose();
if (selectedTagGroupEntry) {
- dispatch(TaggingActions.collectTagsFromLocation(selectedTagGroupEntry));
+ collectTagsFromLocation(selectedTagGroupEntry);
}
handleCloseTagGroupMenu();
dispatch(AppActions.tagLibraryChanged());
diff --git a/app/components/menus/TagMenu.tsx b/app/components/menus/TagMenu.tsx
index 83eeca897..7bb27dd34 100644
--- a/app/components/menus/TagMenu.tsx
+++ b/app/components/menus/TagMenu.tsx
@@ -34,8 +34,9 @@ import {
isReadOnlyMode
} from '-/reducers/app';
import { TS } from '-/tagspaces.namespace';
-import TaggingActions from '-/reducers/tagging-actions';
import { useTranslation } from 'react-i18next';
+import { useOpenedEntryContext } from '-/hooks/useOpenedEntryContext';
+import { useTaggingActionsContext } from '-/hooks/useTaggingActionsContext';
const isTagLibraryReadOnly =
window.ExtTagLibrary && window.ExtTagLibrary.length > 0;
@@ -61,6 +62,7 @@ function TagMenu(props: Props) {
const { t } = useTranslation();
const dispatch: AppDispatch = useDispatch();
+ const { addTags } = useTaggingActionsContext();
const readOnlyMode = useSelector(isReadOnlyMode);
const maxSearchResults: number = useSelector(getMaxSearchResults);
const selectedEntries = useSelector(getSelectedEntries);
@@ -90,7 +92,7 @@ function TagMenu(props: Props) {
function applyTag() {
const selectedEntryPaths = selectedEntries.map(entry => entry.path);
- dispatch(TaggingActions.addTags(selectedEntryPaths, [selectedTag]));
+ addTags(selectedEntryPaths, [selectedTag]);
onClose();
}
diff --git a/app/containers/MainPage.tsx b/app/containers/MainPage.tsx
index a6a8cbd28..d951bec46 100644
--- a/app/containers/MainPage.tsx
+++ b/app/containers/MainPage.tsx
@@ -51,7 +51,6 @@ import {
isKeysDialogOpened,
isLicenseDialogOpened,
isThirdPartyLibsDialogOpened,
- isEntryInFullWidth,
isLocationManagerPanelOpened,
isTagLibraryPanelOpened,
isSearchPanelOpened,
@@ -65,8 +64,6 @@ import {
isOpenLinkDialogOpened,
isReadOnlyMode,
isProgressOpened,
- getOpenedFiles,
- OpenedEntry,
isDeleteMultipleEntriesDialogOpened,
isImportKanBanDialogOpened,
getSelectedEntries,
@@ -94,7 +91,10 @@ import NewFileDialog from '-/components/dialogs/NewFileDialog';
import IsTruncatedConfirmDialog from '-/components/dialogs/IsTruncatedConfirmDialog';
import { styled, useTheme } from '@mui/material/styles';
import { useTranslation } from 'react-i18next';
-import { DescriptionContextProvider } from '-/components/hooks/DescriptionContextProvider';
+import { DescriptionContextProvider } from '-/hooks/DescriptionContextProvider';
+import { TaggingActionsContextProvider } from '-/hooks/TaggingActionsContextProvider';
+import { useOpenedEntryContext } from '-/hooks/useOpenedEntryContext';
+import { useFsActionsContext } from '-/hooks/useFsActionsContext';
const drawerWidth = 320;
const body = document.getElementsByTagName('body')[0];
@@ -139,10 +139,8 @@ interface Props {
isFirstRun: boolean;
setFirstRun: (isFirstRun: boolean) => void;
isDesktopMode: boolean;
- openedFiles: Array<OpenedEntry>;
isGeneratingThumbs: boolean;
// setGeneratingThumbnails: (isGenerating: boolean) => void;
- isEntryInFullWidth: boolean;
isReadOnlyMode: boolean;
isSettingsDialogOpened: boolean;
isNewEntryDialogOpened: boolean;
@@ -166,7 +164,6 @@ interface Props {
isEditTagDialogOpened: boolean;
keyBindings: any;
toggleEditTagDialog: (tag: TS.Tag) => void;
- setEntryFullWidth: (isFullWidth: boolean) => void;
loadParentDirectoryContent: () => void;
openLink: (linkURL: string, options?: any) => void;
saveFile: () => void; // needed by electron-menus
@@ -187,9 +184,6 @@ interface Props {
toggleProTeaser: () => void; // needed by electron-menus
// setLastSelectedEntry: (path: string) => void; // needed by electron-menus
setSelectedEntries: (selectedEntries: Array<Object>) => void; // needed by electron-menus
- openFsEntry: (fsEntry: TS.FileSystemEntry) => void; // needed by electron-menus
- openNextFile: (path?: string) => void; // needed by electron-menus
- openPrevFile: (path?: string) => void; // needed by electron-menus
openLocationManagerPanel: () => void;
openTagLibraryPanel: () => void;
// openSearchPanel: () => void;
@@ -211,11 +205,6 @@ interface Props {
autohide?: boolean
) => void;
reflectCreateEntries: (fsEntries: Array<TS.FileSystemEntry>) => void;
- loadDirectoryContent: (
- path: string,
- generateThumbnails: boolean,
- loadDirMeta?: boolean
- ) => void;
uploadFilesAPI: (
files: Array<File>,
destination: string,
@@ -227,7 +216,6 @@ interface Props {
toggleDeleteMultipleEntriesDialog: () => void;
selectedEntries: Array<any>;
deleteFile: (path: string, uuid: string) => void;
- deleteDirectory: (path: string) => void;
user: CognitoUserInterface;
setSearchQuery: (searchQuery: TS.SearchQuery) => void;
}
@@ -351,6 +339,15 @@ function ProTeaserDialogAsync(props) {
function MainPage(props: Props) {
const { t } = useTranslation();
+ const { deleteDirectory } = useFsActionsContext();
+ const {
+ openedEntries,
+ isEntryInFullWidth,
+ openFsEntry,
+ setEntryInFullWidth,
+ openNextFile,
+ openPrevFile
+ } = useOpenedEntryContext();
const theme = useTheme();
const percent = useRef<number | undefined>(undefined);
const [ignored, forceUpdate] = useReducer(x => x + 1, 0);
@@ -422,19 +419,26 @@ function MainPage(props: Props) {
if (!AppConfig.isCordova) {
updateDimensions();
}
- listen({ ...props, goBack, goForward });
+ listen({
+ ...props,
+ goBack,
+ goForward,
+ openFsEntry,
+ openNextFile,
+ openPrevFile
+ });
}, []);
useEffect(() => {
// setPercent(undefined);
- if (props.isEntryInFullWidth) {
+ if (isEntryInFullWidth) {
setDrawerOpened(false); // !props.isEntryInFullWidth);
}
- }, [props.isEntryInFullWidth]);
+ }, [isEntryInFullWidth]);
useEffect(() => {
updateDimensions();
- }, [props.openedFiles]);
+ }, [openedEntries]);
useEventListener('resize', () => {
if (!AppConfig.isCordova) {
@@ -455,10 +459,10 @@ function MainPage(props: Props) {
// console.log('Width: ' + width + ' Height: ' + height);
setDimensions({ width: w, height: h });
- if (props.openedFiles.length > 0 && !props.isEntryInFullWidth) {
+ if (openedEntries.length > 0 && !isEntryInFullWidth) {
const isFillWidth = h > w;
- if (isFillWidth !== props.isEntryInFullWidth) {
- props.setEntryFullWidth(isFillWidth);
+ if (isFillWidth !== isEntryInFullWidth) {
+ setEntryInFullWidth(isFillWidth);
}
}
};
@@ -513,14 +517,12 @@ function MainPage(props: Props) {
toggleOpenLinkDialog,
toggleProTeaser,
setFirstRun,
- loadDirectoryContent,
mainSplitSize,
- openedFiles,
openLink
} = props;
const { FILE } = NativeTypes;
- const isFileOpened = openedFiles.length > 0;
+ const isFileOpened = openedEntries.length > 0;
const setPercent = (p: number | undefined) => {
percent.current = p;
@@ -548,7 +550,7 @@ function MainPage(props: Props) {
return null;
};
}
- if (props.isEntryInFullWidth) {
+ if (isEntryInFullWidth) {
percent.current = undefined;
initialPrimarySize = '0%';
minPrimarySize = '0%';
@@ -569,7 +571,6 @@ function MainPage(props: Props) {
toggleDrawer={toggleDrawer}
toggleProTeaser={toggleProTeaser}
drawerOpened={drawerOpened}
- openedFiles={openedFiles}
goBack={goBack}
goForward={goForward}
openMoveCopyFilesDialog={() =>
@@ -578,11 +579,7 @@ function MainPage(props: Props) {
/>
{isFileOpened && (
<DescriptionContextProvider>
- <EntryContainer
- key="EntryContainerID"
- loadDirectoryContent={loadDirectoryContent}
- openedFiles={openedFiles}
- />
+ <EntryContainer key="EntryContainerID" />
</DescriptionContextProvider>
)}
</Split>
@@ -596,166 +593,167 @@ function MainPage(props: Props) {
keyMap={keyMap}
style={{ height: '100%' }}
>
- <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();
+ <TaggingActionsContextProvider>
+ <MoveOrCopyFilesDialog
+ open={moveCopyDialogOpened !== undefined}
+ onClose={() => {
+ setMoveCopyDialogOpened(undefined);
}}
+ selectedFiles={moveCopyDialogOpened}
/>
- )}
- {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.isNewFileDialogOpened && (
- <NewFileDialog
- open={props.isNewFileDialogOpened}
- onClose={toggleNewFileDialog}
+ {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}
/>
- )}
- <SettingsDialog
- open={props.isSettingsDialogOpened}
- onClose={toggleSettingsDialog}
- />
- {KanBanImportDialog && props.selectedEntries[0] && (
- <KanBanImportDialog
- open={props.isImportKanBanDialogOpened}
- onClose={props.toggleImportKanBanDialog}
+ {props.isNewFileDialogOpened && (
+ <NewFileDialog
+ open={props.isNewFileDialogOpened}
+ onClose={toggleNewFileDialog}
+ />
+ )}
+ <SettingsDialog
+ open={props.isSettingsDialogOpened}
+ onClose={toggleSettingsDialog}
/>
- )}
- {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 props.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);
+ {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);
});
- }
+ 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%'
}}
- cancelDialogTID="cancelDeleteFileDialog"
- confirmDialogTID="confirmDeleteFileDialog"
- confirmDialogContentTID="confirmDeleteDialogContent"
- />
- )}
- <PageNotification />
- <div
- style={{
- backgroundColor: theme.palette.background.default,
- height: '100%'
- }}
- >
- <style>
- {`
+ >
+ <style>
+ {`
body { background-color: ${
theme.palette.background.default
} !important;}
@@ -773,9 +771,7 @@ function MainPage(props: Props) {
.react-split .split-container {
--react-split-splitter: ${
- props.openedFiles.length < 1 || props.isEntryInFullWidth
- ? '0'
- : '3px'
+ openedEntries.length < 1 || isEntryInFullWidth ? '0' : '3px'
} !important;
}
.react-split .secondary .full-content {
@@ -783,43 +779,44 @@ function MainPage(props: Props) {
flex-direction: column;
}
`}
- </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
- })}
+ </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
+ })}
+ >
+ {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()}
- </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>
+ </>
+ )}
+ </div>
+ </TaggingActionsContextProvider>
</HotKeys>
</Root>
);
@@ -845,8 +842,6 @@ function mapStateToProps(state) {
isProgressDialogOpened: isProgressOpened(state),
isReadOnlyMode: isReadOnlyMode(state),
isGeneratingThumbs: isGeneratingThumbs(state),
- openedFiles: getOpenedFiles(state),
- isEntryInFullWidth: isEntryInFullWidth(state),
isDesktopMode: getDesktopMode(state),
keyBindings: getKeyBindingObject(state),
mainSplitSize: getMainVerticalSplitSize(state),
@@ -893,16 +888,10 @@ function mapDispatchToProps(dispatch) {
toggleOpenLinkDialog: AppActions.toggleOpenLinkDialog,
toggleProTeaser: AppActions.toggleProTeaser,
setSelectedEntries: AppActions.setSelectedEntries,
- // setGeneratingThumbnails: AppActions.setGeneratingThumbnails,
- openFsEntry: AppActions.openFsEntry,
- setEntryFullWidth: AppActions.setEntryFullWidth,
- openNextFile: AppActions.openNextFile,
- openPrevFile: AppActions.openPrevFile,
toggleShowUnixHiddenEntries: SettingsActions.toggleShowUnixHiddenEntries,
setMainVerticalSplitSize: SettingsActions.setMainVerticalSplitSize,
showNotification: AppActions.showNotification,
reflectCreateEntries: AppActions.reflectCreateEntries,
- loadDirectoryContent: AppActions.loadDirectoryContent,
openLocationManagerPanel: AppActions.openLocationManagerPanel,
openTagLibraryPanel: AppActions.openTagLibraryPanel,
// openSearchPanel: AppActions.openSearchPanel,
@@ -912,7 +901,6 @@ function mapDispatchToProps(dispatch) {
AppActions.toggleDeleteMultipleEntriesDialog,
setFirstRun: SettingsActions.setFirstRun,
uploadFilesAPI: IOActions.uploadFilesAPI,
- deleteDirectory: AppActions.deleteDirectory,
deleteFile: AppActions.deleteFile,
setSearchQuery: LocationIndexActions.setSearchQuery,
addExtensions: AppActions.addExtensions,
@@ -934,7 +922,6 @@ const areEqual = (prevProp, nextProp) =>
prevProp.isDeleteMultipleEntriesDialogOpened &&
nextProp.isDesktopMode === prevProp.isDesktopMode &&
nextProp.isEditTagDialogOpened === prevProp.isEditTagDialogOpened &&
- nextProp.isEntryInFullWidth === prevProp.isEntryInFullWidth &&
nextProp.isHelpFeedbackPanelOpened === prevProp.isHelpFeedbackPanelOpened &&
nextProp.isKeysDialogOpened === prevProp.isKeysDialogOpened &&
nextProp.isLicenseDialogOpened === prevProp.isLicenseDialogOpened &&
@@ -957,8 +944,7 @@ const areEqual = (prevProp, nextProp) =>
prevProp.isUploadProgressDialogOpened &&
nextProp.isImportKanBanDialogOpened === prevProp.isImportKanBanDialogOpened &&
JSON.stringify(nextProp.selectedEntries) ===
- JSON.stringify(prevProp.selectedEntries) &&
- JSON.stringify(nextProp.openedFiles) === JSON.stringify(prevProp.openedFiles);
+ JSON.stringify(prevProp.selectedEntries);
export default withDnDContext(
connect(mapStateToProps, mapDispatchToProps)(React.memo(MainPage, areEqual)) //translate(['core'], { wait: true })(React.memo(MainPage, areEqual)))
diff --git a/app/containers/Root.tsx b/app/containers/Root.tsx
index 778198ef6..9362a49aa 100644
--- a/app/containers/Root.tsx
+++ b/app/containers/Root.tsx
@@ -26,6 +26,8 @@ import App from '-/containers/App';
import MainPage from '-/containers/MainPage';
import TsAuth from '-/containers/TsAuth';
import init from '-/services/i18nInit';
+import { FsActionsContextProvider } from '-/hooks/FsActionsContextProvider';
+import { OpenedEntryContextProvider } from '-/hooks/OpenedEntryContextProvider';
type RootType = {
store: Store<{}>;
@@ -45,7 +47,11 @@ export default function Root({ store, persistor }: RootType) {
let appContent = (
<App>
- <MainPage />
+ <OpenedEntryContextProvider>
+ <FsActionsContextProvider>
+ <MainPage />
+ </FsActionsContextProvider>
+ </OpenedEntryContextProvider>
</App>
);
diff --git a/app/hooks/DescriptionContextProvider.tsx b/app/hooks/DescriptionContextProvider.tsx
new file mode 100644
index 000000000..046787744
--- /dev/null
+++ b/app/hooks/DescriptionContextProvider.tsx
@@ -0,0 +1,180 @@
+/**
+ * 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,
+ isReadOnlyMode,
+ OpenedEntry
+} from '-/reducers/app';
+import { Pro } from '-/pro';
+import { useTranslation } from 'react-i18next';
+import { useOpenedEntryContext } from '-/hooks/useOpenedEntryContext';
+
+type DescriptionContextData = {
+ description: string;
+ isSaveDescriptionConfirmOpened: boolean;
+ setSaveDescriptionConfirmOpened: (open: boolean) => void;
+ setDescription: (description: string) => void;
+ saveDescription: () => void;
+};
+
+export const DescriptionContext = createContext<DescriptionContextData>({
+ description: undefined,
+ isSaveDescriptionConfirmOpened: false,
+ setSaveDescriptionConfirmOpened: () => {},
+ setDescription: () => {},
+ saveDescription: () => {}
+});
+
+export type DescriptionContextProviderProps = {
+ children: React.ReactNode;
+};
+
+export const DescriptionContextProvider = ({
+ children
+}: DescriptionContextProviderProps) => {
+ const { t } = useTranslation();
+ const {
+ openedEntries,
+ addToEntryContainer,
+ updateOpenedFile,
+ reloadOpenedFile
+ } = useOpenedEntryContext();
+ const dispatch: AppDispatch = useDispatch();
+ const readOnlyMode = useSelector(isReadOnlyMode);
+ const openedFile = useRef<OpenedEntry>(openedEntries[0]);
+ const isChanged = useRef<boolean>(false);
+ const [
+ isSaveDescriptionConfirmOpened,
+ saveDescriptionConfirmOpened
+ ] = useState<boolean>(false);
+
+ useEffect(() => {
+ if (openedEntries && openedEntries.length > 0) {
+ if (
+ openedFile.current !== undefined &&
+ isChanged.current &&
+ openedFile.current.path !== openedEntries[0].path &&
+ openedFile.current.description !== openedEntries[0].description
+ ) {
+ // handle not saved changes
+ addToEntryContainer({ ...openedFile.current, editMode: false });
+ dispatch(AppActions.setSelectedEntries([]));
+ saveDescriptionConfirmOpened(true);
+ } else {
+ openedFile.current = openedEntries[0];
+ }
+ } else {
+ openedFile.current = undefined;
+ }
+ }, [openedEntries]);
+
+ const saveDescription = () => {
+ if (readOnlyMode) {
+ return;
+ }
+ if (!Pro) {
+ dispatch(
+ AppActions.showNotification(t('core:thisFunctionalityIsAvailableInPro'))
+ );
+ return;
+ }
+ if (!Pro.MetaOperations) {
+ dispatch(
+ AppActions.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'))
+ );
+ });
+ });
+ } else {
+ console.debug(
+ 'openedFile:' +
+ openedFile.current.path +
+ ' dont have locationId! Current Location can be changed. Trying to save opened file in current location'
+ );
+ saveMetaData();
+ }
+ }
+ };
+
+ function saveMetaData() {
+ return Pro.MetaOperations.saveFsEntryMeta(openedFile.current.path, {
+ description: openedFile.current.description
+ }).then(entryMeta => {
+ openedFile.current.description = undefined;
+ isChanged.current = false;
+ return updateOpenedFile(openedFile.current.path, entryMeta);
+ });
+ }
+
+ function setDescription(d: string) {
+ openedFile.current.description = d;
+ isChanged.current = true;
+ }
+
+ function setSaveDescriptionConfirmOpened(isOpened: boolean) {
+ if (!isOpened) {
+ isChanged.current = false;
+ reloadOpenedFile();
+ }
+ saveDescriptionConfirmOpened(isOpened);
+ }
+
+ const context = useMemo(() => {
+ return {
+ description: openedFile.current.description,
+ isSaveDescriptionConfirmOpened,
+ setSaveDescriptionConfirmOpened,
+ setDescription,
+ saveDescription
+ };
+ }, [openedFile.current, isSaveDescriptionConfirmOpened]);
+
+ return (
+ <DescriptionContext.Provider value={context}>
+ {children}
+ </DescriptionContext.Provider>
+ );
+};
diff --git a/app/hooks/FsActionsContextProvider.tsx b/app/hooks/FsActionsContextProvider.tsx
new file mode 100644
index 000000000..11ea92c54
--- /dev/null
+++ b/app/hooks/FsActionsContextProvider.tsx
@@ -0,0 +1,207 @@
+/**
+ * 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 } from 'react';
+import { useDispatch, useSelector } from 'react-redux';
+import {
+ actions as AppActions,
+ AppDispatch,
+ getDirectoryPath
+} from '-/reducers/app';
+import { useTranslation } from 'react-i18next';
+import PlatformIO from '-/services/platform-facade';
+import { extractDirectoryName } from '@tagspaces/tagspaces-common/paths';
+import { useOpenedEntryContext } from '-/hooks/useOpenedEntryContext';
+import GlobalSearch from '-/services/search-index';
+import { getUseTrashCan } from '-/reducers/settings';
+
+type FsActionsContextData = {
+ renameDirectory: (
+ directoryPath: string,
+ newDirectoryName: string
+ ) => Promise<string>;
+ createDirectory: (directoryPath: string, reflect?) => Promise<boolean>;
+ deleteDirectory: (directoryPath: string) => Promise<boolean>;
+};
+
+export const FsActionsContext = createContext<FsActionsContextData>({
+ renameDirectory: () => Promise.resolve(''),
+ createDirectory: () => Promise.resolve(false),
+ deleteDirectory: () => Promise.resolve(false)
+});
+
+export type FsActionsContextProviderProps = {
+ children: React.ReactNode;
+};
+
+export const FsActionsContextProvider = ({
+ children
+}: FsActionsContextProviderProps) => {
+ const { t } = useTranslation();
+ const {
+ openedEntries,
+ reflectRenameDirectory,
+ reflectDeleteDirectory
+ } = useOpenedEntryContext();
+ 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(() => {
+ reflectRenameDirectory(directoryPath, newDirPath);
+ GlobalSearch.getInstance().reflectRenameEntry(
+ directoryPath,
+ newDirPath
+ );
+ });
+ } else {
+ dispatch(AppActions.reflectRenameEntry(directoryPath, newDirPath));
+ }
+
+ dispatch(
+ AppActions.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
+ )
+ );
+ throw error;
+ });
+ }
+
+ function createDirectory(directoryPath: string, reflect = true) {
+ return PlatformIO.createDirectoryPromise(directoryPath)
+ .then(result => {
+ if (result !== undefined && result.dirPath !== undefined) {
+ // eslint-disable-next-line no-param-reassign
+ directoryPath = result.dirPath;
+ }
+ console.log(`Creating directory ${directoryPath} successful.`);
+ if (reflect) {
+ dispatch(AppActions.reflectCreateEntry(directoryPath, false));
+ }
+ dispatch(
+ AppActions.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
+ )
+ );
+ return false;
+ // dispatch stopLoadingAnimation
+ });
+ }
+
+ function deleteDirectory(directoryPath: string) {
+ return PlatformIO.deleteDirectoryPromise(directoryPath, useTrashCan)
+ .then(() => {
+ if (directoryPath === currentDirectoryPath) {
+ dispatch(AppActions.loadParentDirectoryContent());
+ GlobalSearch.getInstance().reflectDeleteEntry(directoryPath);
+ // close opened entries in deleted dir
+ reflectDeleteDirectory(directoryPath);
+ } else {
+ dispatch(AppActions.reflectDeleteEntry(directoryPath));
+ }
+ dispatch(
+ AppActions.showNotification(
+ t('deletingDirectorySuccessfull', {
+ dirPath: extractDirectoryName(
+ directoryPath,
+ PlatformIO.getDirSeparator()
+ )
+ }),
+ 'default',
+ true
+ )
+ );
+ return true;
+ })
+ .catch(error => {
+ console.warn('Error while deleting directory: ' + error);
+ dispatch(
+ AppActions.showNotification(
+ t('errorDeletingDirectoryAlert', {
+ dirPath: extractDirectoryName(
+ directoryPath,
+ PlatformIO.getDirSeparator()
+ )
+ }),
+ 'error',
+ true
+ )
+ );
+ return false;
+ // dispatch stopLoadingAnimation
+ });
+ }
+
+ const context = useMemo(() => {
+ return {
+ renameDirectory,
+ createDirectory,
+ deleteDirectory
+ };
+ }, [openedEntries]);
+
+ return (
+ <FsActionsContext.Provider value={context}>
+ {children}
+ </FsActionsContext.Provider>
+ );
+};
diff --git a/app/hooks/OpenedEntryContextProvider.tsx b/app/hooks/OpenedEntryContextProvider.tsx
new file mode 100644
index 000000000..033c32577
--- /dev/null
+++ b/app/hooks/OpenedEntryContextProvider.tsx
@@ -0,0 +1,925 @@
+/**
+ * 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 { 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 {
+ findExtensionsForEntry,
+ getAllPropertiesPromise,
+ getCleanLocationPath,
+ getNextFile,
+ getPrevFile,
+ getRelativeEntryPath,
+ loadJSONFile,
+ openURLExternally
+} from '-/services/utils-io';
+import {
+ actions as SettingsActions,
+ getFileOpenHistoryKey,
+ getFolderOpenHistoryKey,
+ getNewHTMLFileContent,
+ getSupportedFileTypes
+} from '-/reducers/settings';
+import { getCurrentLocation, getLocations } from '-/reducers/locations';
+import { clearURLParam, getURLParameter, updateHistory } from '-/utils/dom';
+import {
+ extractContainingDirectoryPath,
+ extractTagsAsObjects,
+ generateSharingLink,
+ getMetaFileLocationForDir,
+ getMetaFileLocationForFile,
+ normalizePath
+} from '@tagspaces/tagspaces-common/paths';
+import GlobalSearch from '-/services/search-index';
+import {
+ formatDateTime4Tag,
+ locationType
+} from '@tagspaces/tagspaces-common/misc';
+import { useTranslation } from 'react-i18next';
+import versionMeta from '-/version.json';
+import AppConfig from '-/AppConfig';
+import useFirstRender from '-/utils/useFirstRender';
+
+type OpenedEntryContextData = {
+ openedEntries: OpenedEntry[];
+ isEntryInFullWidth: boolean;
+ setEntryInFullWidth: (fullWidth: boolean) => void;
+ addToEntryContainer: (fsEntry: OpenedEntry) => void;
+ closeAllFiles: () => void;
+ reflectUpdateOpenedFileContent: (entryPath: string) => void;
+ reloadOpenedFile: () => void;
+ updateOpenedFile: (
+ entryPath: string,
+ fsEntryMeta: TS.FileSystemEntryMeta
+ ) => Promise<boolean>;
+ openEntry: (path?: string, showDetails?) => void;
+ openFsEntry: (fsEntry?: TS.FileSystemEntry, showDetails?) => void;
+ openNextFile: (path?: string) => void;
+ openPrevFile: (path?: string) => void;
+ toggleEntryFullWidth: () => void;
+ openLink: (url: string, options?) => void;
+ createFileAdvanced: (
+ targetPath: string,
+ fileName: string,
+ content: string,
+ fileType: 'md' | 'txt' | 'html'
+ ) => void;
+ createFile: () => void;
+ reflectRenameDirectory: (directoryPath: string, newDirPath: string) => void;
+ reflectDeleteDirectory: (directoryPath: string) => void;
+};
+
+export const OpenedEntryContext = createContext<OpenedEntryContextData>({
+ openedEntries: [],
+ isEntryInFullWidth: false,
+ setEntryInFullWidth: () => {},
+ addToEntryContainer: () => {},
+ closeAllFiles: () => {},
+ reflectUpdateOpenedFileContent: () => {},
+ reloadOpenedFile: () => {},
+ updateOpenedFile: () => Promise.resolve(false),
+ openEntry: () => {},
+ openFsEntry: () => {},
+ openNextFile: () => {},
+ openPrevFile: () => {},
+ toggleEntryFullWidth: () => {},
+ openLink: () => {},
+ createFile: () => {},
+ createFileAdvanced: () => {},
+ reflectRenameDirectory: () => {},
+ reflectDeleteDirectory: () => {}
+});
+
+export type OpenedEntryContextProviderProps = {
+ children: React.ReactNode;
+};
+
+export const OpenedEntryContextProvider = ({
+ children
+}: OpenedEntryContextProviderProps) => {
+ const dispatch: AppDispatch = useDispatch();
+ const { t } = useTranslation();
+ 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 fileOpenHistory = useSelector(getFileOpenHistoryKey);
+ const folderOpenHistory = useSelector(getFolderOpenHistoryKey);
+ const newHTMLFileContent = useSelector(getNewHTMLFileContent);
+ const initOpenLink = useSelector(getOpenLink);
+ const editedEntryPaths = useSelector(getEditedEntryPaths);
+ /* const checkForUpdates = useSelector(getCheckForUpdateOnStartup);
+ const firstRun = useSelector(isFirstRun);
+ const enableGlobalKeyboardShortcuts = useSelector(isGlobalKeyBindingEnabled);*/
+ const [openedEntries, setOpenedEntries] = useState([]);
+ const [isEntryInFullWidth, setEntryInFullWidth] = useState(false);
+ const firstRender = useFirstRender();
+
+ /**
+ * Handle openLink from initApp
+ */
+ useEffect(() => {
+ if (initOpenLink && initOpenLink.url) {
+ openLink(initOpenLink.url, initOpenLink.options);
+ }
+ }, [initOpenLink]);
+
+ /**
+ * 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;
+
+ if (openedEntries.some(entry => entry.path === oldFilePath)) {
+ const extractedTags = extractTagsAsObjects(
+ newFilePath,
+ AppConfig.tagDelimiter,
+ PlatformIO.getDirSeparator()
+ );
+
+ const newEntries = openedEntries.map(entry => {
+ if (entry.path !== oldFilePath) {
+ return entry;
+ }
+ const fileNameTags = entry.isFile ? extractedTags : []; // dirs dont have tags in filename
+ // const { url, ...rest } = entry;
+ const sidecarTags =
+ entry.tags && entry.tags.length > 0
+ ? entry.tags.filter(tag => tag.type !== 'plain')
+ : [];
+ return {
+ ...entry,
+ path: newFilePath, // TODO handle change extension case
+ tags: [
+ ...sidecarTags, // add only sidecar tags
+ ...fileNameTags
+ ]
+ // shouldReload: true
+ };
+ });
+ setOpenedEntries(newEntries);
+ }
+ } else if (action === 'delete') {
+ const filePath = editedEntryPaths[0].path;
+ if (
+ openedEntries &&
+ openedEntries.length > 0 &&
+ openedEntries.some(file => file.path === filePath)
+ ) {
+ closeAllFiles();
+ }
+ }
+ }
+ }, [editedEntryPaths]);
+
+ /*function initApp() {
+ disableBackGestureMac();
+ // migrate TagLibrary from redux state
+
+ dispatch(SettingsActions.setZoomRestoreApp());
+ dispatch(SettingsActions.upgradeSettings()); // TODO call this only on app version update
+ if (checkForUpdates) {
+ dispatch(SettingsActions.checkForUpdate());
+ }
+ if (firstRun) {
+ dispatch(AppActions.toggleOnboardingDialog());
+ dispatch(AppActions.toggleLicenseDialog());
+ }
+ setTimeout(() => {
+ PlatformIO.setGlobalShortcuts(enableGlobalKeyboardShortcuts);
+ PlatformIO.loadExtensions();
+ }, 1000);
+ const langURLParam = getURLParameter('locale');
+ if (
+ langURLParam &&
+ langURLParam.length > 1 &&
+ /^[a-zA-Z\-_]+$/.test('langURLParam')
+ ) {
+ i18n.changeLanguage(langURLParam).then(() => {
+ dispatch(SettingsActions.setLanguage(langURLParam));
+ PlatformIO.setLanguage(langURLParam);
+ return true;
+ });
+ }
+
+ 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;
+ setTimeout(() => {
+ openLink(window.location.href);
+ }, 1000);
+ } else if (cmdOpen) {
+ openDefaultLocation = false;
+ setTimeout(() => {
+ openLink(
+ // window.location.href.split('?')[0] +
+ 'ts://?cmdopen=' + cmdOpen,
+ { fullWidth: true }
+ );
+ }, 1000);
+ }
+ const defaultLocationId = getDefaultLocationId(state);
+ if (
+ openDefaultLocation &&
+ defaultLocationId &&
+ defaultLocationId.length > 0
+ ) {
+ dispatch(actions.openLocationById(defaultLocationId));
+ }
+ }*/
+
+ function addToEntryContainer(fsEntry: OpenedEntry) {
+ setOpenedEntries([fsEntry]); // [...openedEntries, fsEntry] // TODO uncomment for multiple file support
+ }
+
+ function closeOpenedEntries() {
+ setOpenedEntries([]);
+ }
+
+ function closeAllFiles() {
+ document.title = 'TagSpaces'; // TODO move to AppConfig
+ clearURLParam('tsepath');
+ closeOpenedEntries(); // [...openedEntries, fsEntry] // TODO uncomment for multiple file support
+ if (isEntryInFullWidth) {
+ setEntryInFullWidth(false);
+ }
+ }
+
+ function reflectUpdateOpenedFileContent(entryPath: string) {
+ if (openedEntries && openedEntries.length > 0) {
+ const openedFile: OpenedEntry = openedEntries.find(
+ obj => obj.path === entryPath
+ );
+ if (openedFile) {
+ openedFile.shouldReload = true;
+ addToEntryContainer(openedFile);
+ }
+ }
+ }
+
+ function reloadOpenedFile(): Promise<boolean> {
+ if (openedEntries && openedEntries.length > 0) {
+ const openedFile = openedEntries[0];
+ const metaFilePath = openedFile.isFile
+ ? getMetaFileLocationForFile(
+ openedFile.path,
+ PlatformIO.getDirSeparator()
+ )
+ : getMetaFileLocationForDir(
+ openedFile.path,
+ PlatformIO.getDirSeparator()
+ );
+ try {
+ return loadJSONFile(metaFilePath)
+ .then(fsEntryMeta => {
+ return updateOpenedFile(openedFile.path, {
+ ...fsEntryMeta,
+ editMode: false,
+ shouldReload: !openedFile.shouldReload
+ });
+ })
+ .catch(() =>
+ updateOpenedFile(openedFile.path, {
+ ...openedFile,
+ editMode: false,
+ shouldReload: !openedFile.shouldReload
+ })
+ );
+ } catch (e) {
+ return updateOpenedFile(openedFile.path, {
+ ...openedFile,
+ editMode: false,
+ shouldReload: !openedFile.shouldReload
+ });
+ }
+ }
+ return Promise.resolve(false);
+ }
+
+ function updateOpenedFile(
+ entryPath: string,
+ fsEntryMeta: TS.FileSystemEntryMeta
+ ): Promise<boolean> {
+ if (
+ openedEntries &&
+ openedEntries.length > 0 &&
+ openedEntries.some(obj => obj.path === entryPath)
+ ) {
+ return PlatformIO.getPropertiesPromise(entryPath)
+ .then(entryProps => {
+ if (entryProps) {
+ let entryForOpening: OpenedEntry;
+ const entryExist = openedEntries.find(
+ obj => obj.path === entryPath
+ );
+
+ if (!entryExist) {
+ entryForOpening = findExtensionsForEntry(
+ fsEntryMeta.id, //|| fsEntryMeta.uuid,
+ supportedFileTypes,
+ entryPath,
+ entryProps.isFile
+ );
+ } else {
+ entryForOpening = { ...entryExist };
+ }
+
+ /* if (fsEntryMeta.changed !== undefined) {
+ entryForOpening.changed = fsEntryMeta.changed;
+ } */
+ if (fsEntryMeta.editMode !== undefined) {
+ entryForOpening.editMode = fsEntryMeta.editMode;
+ }
+ entryForOpening.shouldReload = fsEntryMeta.shouldReload;
+ if (fsEntryMeta.color) {
+ if (fsEntryMeta.color === 'transparent') {
+ entryForOpening.color = undefined;
+ } else {
+ entryForOpening.color = fsEntryMeta.color;
+ }
+ }
+ if (fsEntryMeta.description !== undefined) {
+ entryForOpening.description = fsEntryMeta.description;
+ }
+ if (fsEntryMeta.perspective) {
+ entryForOpening.perspective = fsEntryMeta.perspective;
+ }
+ if (fsEntryMeta.tags) {
+ entryForOpening.tags = fsEntryMeta.tags;
+ }
+ if (fsEntryMeta.autoSave !== undefined) {
+ entryForOpening.isAutoSaveEnabled = fsEntryMeta.autoSave;
+ }
+ entryForOpening.lmdt = entryProps.lmdt;
+ entryForOpening.size = entryProps.size;
+ addToEntryContainer(entryForOpening);
+ }
+ return true;
+ })
+ .catch(err => {
+ console.error('updateOpenedFile ' + entryPath + ' not exist ' + err);
+ return Promise.resolve(false);
+ });
+ }
+ return Promise.resolve(false);
+ }
+
+ function openEntry(path?: string, showDetails = false) {
+ if (path === undefined) {
+ return openFsEntry(undefined, showDetails);
+ }
+ return getAllPropertiesPromise(path)
+ .then((fsEntry: TS.FileSystemEntry) => openFsEntry(fsEntry, showDetails))
+ .catch(error =>
+ console.warn(
+ 'Error getting properties for entry: ' + path + ' - ' + error
+ )
+ );
+ }
+
+ function openFsEntry(fsEntry?: TS.FileSystemEntry, showDetails = false) {
+ dispatch(SettingsActions.setShowDetails(showDetails));
+ if (fsEntry === undefined) {
+ if (lastSelectedEntry === undefined) {
+ return;
+ }
+ if (!lastSelectedEntry.isFile) {
+ dispatch(
+ AppActions.loadDirectoryContent(lastSelectedEntry.path, false)
+ );
+ return;
+ }
+ }
+ let entryForOpening: OpenedEntry;
+
+ /**
+ * check for editMode in order to show save changes dialog (shouldReload: false)
+ */
+ if (openedEntries.length > 0) {
+ const openFile = openedEntries[0];
+ if (openFile.editMode) {
+ entryForOpening = {
+ ...openFile,
+ shouldReload:
+ openFile.shouldReload !== undefined
+ ? !openFile.shouldReload
+ : undefined
+ }; // false };
+ addToEntryContainer(entryForOpening);
+ dispatch(
+ AppActions.showNotification(
+ `You can't open another file, because '${openFile.path}' is opened for editing`,
+ 'default',
+ true
+ )
+ );
+ return false;
+ }
+ }
+ // TODO decide to copy all props from {...fsEntry} into openedEntry
+ entryForOpening = findExtensionsForEntry(
+ fsEntry.uuid,
+ supportedFileTypes,
+ fsEntry.path,
+ fsEntry.isFile
+ );
+ if (PlatformIO.haveObjectStoreSupport() || PlatformIO.haveWebDavSupport()) {
+ const cleanedPath = fsEntry.path.startsWith('/')
+ ? fsEntry.path.substr(1)
+ : fsEntry.path;
+ entryForOpening.url = PlatformIO.getURLforPath(cleanedPath);
+ } else if (fsEntry.url) {
+ entryForOpening.url = fsEntry.url;
+ }
+ if (fsEntry.perspective) {
+ entryForOpening.perspective = fsEntry.perspective;
+ }
+ if (fsEntry.color) {
+ entryForOpening.color = fsEntry.color;
+ }
+ if (fsEntry.description) {
+ entryForOpening.description = fsEntry.description;
+ }
+ if (fsEntry.tags) {
+ entryForOpening.tags = fsEntry.tags;
+ }
+ if (fsEntry.lmdt) {
+ entryForOpening.lmdt = fsEntry.lmdt;
+ }
+ if (fsEntry.size) {
+ entryForOpening.size = fsEntry.size;
+ }
+ if (fsEntry.isNewFile) {
+ entryForOpening.editMode = true;
+ }
+ if (fsEntry.isAutoSaveEnabled !== undefined) {
+ entryForOpening.isAutoSaveEnabled = fsEntry.isAutoSaveEnabled;
+ } else if (fsEntry.meta && fsEntry.meta.autoSave) {
+ entryForOpening.isAutoSaveEnabled = fsEntry.meta.autoSave;
+ }
+
+ document.title = fsEntry.name + ' | ' + 'TagSpaces'; // TODO get it later from app config
+
+ if (currentLocation) {
+ entryForOpening.locationId = currentLocation.uuid;
+ updateHistory(currentLocation, currentDirectoryPath, fsEntry.path);
+ }
+
+ addToEntryContainer(entryForOpening);
+
+ // save in history
+ if (currentLocation) {
+ if (Pro) {
+ const relEntryPath = getRelativeEntryPath(
+ currentLocation,
+ fsEntry.path
+ );
+ const historyKeys = Pro.history.historyKeys;
+ if (fsEntry.isFile) {
+ Pro.history.saveHistory(
+ historyKeys.fileOpenKey,
+ {
+ path: fsEntry.path,
+ url: generateSharingLink(currentLocation.uuid, relEntryPath),
+ lid: currentLocation.uuid
+ },
+ fileOpenHistory
+ );
+ } else {
+ Pro.history.saveHistory(
+ historyKeys.folderOpenKey,
+ {
+ path: fsEntry.path,
+ url: generateSharingLink(
+ currentLocation.uuid,
+ relEntryPath,
+ relEntryPath
+ ),
+ lid: currentLocation.uuid
+ },
+ folderOpenHistory
+ );
+ }
+ }
+ }
+ }
+
+ function openNextFile(path?: string) {
+ const nextFile = getNextFile(
+ path,
+ lastSelectedEntry ? lastSelectedEntry.path : undefined,
+ searchMode
+ ? GlobalSearch.getInstance().getResults()
+ : currentDirectoryEntries
+ );
+ if (nextFile !== undefined) {
+ openFsEntry(nextFile);
+ // dispatch(actions.setLastSelectedEntry(nextFile.path));
+ dispatch(AppActions.setSelectedEntries([nextFile]));
+ return nextFile;
+ }
+ }
+
+ function openPrevFile(path?: string) {
+ const prevFile = getPrevFile(
+ path,
+ lastSelectedEntry ? lastSelectedEntry.path : undefined,
+ searchMode
+ ? GlobalSearch.getInstance().getResults()
+ : currentDirectoryEntries
+ );
+ if (prevFile !== undefined) {
+ openFsEntry(prevFile);
+ // dispatch(actions.setLastSelectedEntry(prevFile.path));
+ dispatch(AppActions.setSelectedEntries([prevFile]));
+ }
+ }
+
+ function toggleEntryFullWidth() {
+ setEntryInFullWidth(!isEntryInFullWidth);
+ }
+
+ function openLink(url: string, options = { fullWidth: true }) {
+ try {
+ const decodedURI = decodeURI(url);
+ const lid = getURLParameter('tslid', url);
+ const dPath = getURLParameter('tsdpath', url);
+ const ePath = getURLParameter('tsepath', url);
+ const cmdOpen = getURLParameter('cmdopen', url);
+ if (cmdOpen && cmdOpen.length > 0) {
+ const entryPath = decodeURIComponent(cmdOpen);
+ getAllPropertiesPromise(entryPath)
+ .then((fsEntry: TS.FileSystemEntry) => {
+ if (fsEntry.isFile) {
+ openFsEntry(fsEntry);
+ setEntryInFullWidth(options.fullWidth);
+ } else {
+ dispatch(
+ AppActions.loadDirectoryContent(fsEntry.path, false, true)
+ );
+ }
+ return true;
+ })
+ .catch(err => {
+ // console.log('Error opening from cmd ' + JSON.stringify(err));
+ dispatch(
+ AppActions.showNotification(
+ t('Missing file or folder'),
+ 'warning',
+ true
+ )
+ );
+ });
+ } else if (lid && lid.length > 0) {
+ const locationId = decodeURIComponent(lid);
+ const directoryPath = dPath && decodeURIComponent(dPath);
+ const entryPath = ePath && decodeURIComponent(ePath);
+ // Check for relative paths
+ const targetLocation: TS.Location = locations.find(
+ location => location.uuid === locationId
+ );
+ if (targetLocation) {
+ 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)
+ );
+ } else {
+ openLocationTimer = 0;
+ }
+ const locationPath = getCleanLocationPath(targetLocation);
+
+ // setTimeout is needed for case of a location switch, if no location swith the timer is 0
+ setTimeout(() => {
+ if (isCloudLocation) {
+ // PlatformIO.enableObjectStoreSupport(targetLocation).then(() => {
+ if (directoryPath && directoryPath.length > 0) {
+ const newRelDir = getRelativeEntryPath(
+ targetLocation,
+ directoryPath
+ );
+ const dirFullPath =
+ locationPath.length > 0
+ ? locationPath + '/' + newRelDir
+ : directoryPath;
+ dispatch(
+ AppActions.loadDirectoryContent(dirFullPath, false, true)
+ );
+ } else {
+ dispatch(
+ AppActions.loadDirectoryContent(locationPath, false, true)
+ );
+ }
+
+ if (entryPath) {
+ getAllPropertiesPromise(entryPath)
+ .then((fsEntry: TS.FileSystemEntry) => {
+ if (fsEntry) {
+ openFsEntry(fsEntry);
+ if (options.fullWidth) {
+ setEntryInFullWidth(true);
+ }
+ }
+ return true;
+ })
+ .catch(() =>
+ dispatch(
+ AppActions.showNotification(
+ t('core:invalidLink'),
+ 'warning',
+ true
+ )
+ )
+ );
+ }
+ // });
+ } else {
+ // local files case
+ if (directoryPath && directoryPath.length > 0) {
+ if (
+ directoryPath.includes('../') ||
+ directoryPath.includes('..\\')
+ ) {
+ dispatch(
+ AppActions.showNotification(
+ t('core:invalidLink'),
+ 'warning',
+ true
+ )
+ );
+ return true;
+ }
+ const dirFullPath =
+ locationPath + PlatformIO.getDirSeparator() + directoryPath;
+ dispatch(
+ AppActions.loadDirectoryContent(dirFullPath, false, true)
+ );
+ } else {
+ dispatch(
+ AppActions.loadDirectoryContent(locationPath, false, true)
+ );
+ }
+
+ if (entryPath && entryPath.length > 0) {
+ if (entryPath.includes('../') || entryPath.includes('..\\')) {
+ dispatch(
+ AppActions.showNotification(
+ t('core:invalidLink'),
+ 'warning',
+ true
+ )
+ );
+ return true;
+ }
+ const entryFullPath =
+ locationPath + PlatformIO.getDirSeparator() + entryPath;
+ getAllPropertiesPromise(entryFullPath)
+ .then((fsEntry: TS.FileSystemEntry) => {
+ if (fsEntry) {
+ openFsEntry(fsEntry);
+ if (options.fullWidth) {
+ setEntryInFullWidth(true);
+ }
+ }
+ return true;
+ })
+ .catch(() =>
+ dispatch(
+ AppActions.showNotification(
+ t('core:invalidLink'),
+ 'warning',
+ true
+ )
+ )
+ );
+ }
+ }
+ }, openLocationTimer);
+ } else {
+ dispatch(
+ AppActions.showNotification(t('core:invalidLink'), 'warning', true)
+ );
+ }
+ } else if (decodedURI.endsWith(location.pathname)) {
+ return true;
+ } else if (
+ // External URL case
+ decodedURI.startsWith('http://') ||
+ decodedURI.startsWith('https://') ||
+ decodedURI.startsWith('file://')
+ ) {
+ openURLExternally(decodedURI);
+ } else {
+ console.log('Not supported URL format: ' + decodedURI);
+ }
+ } catch (e) {
+ console.error('OpenLink:', e);
+ }
+ }
+
+ function createFile() {
+ if (currentDirectoryPath) {
+ const filePath =
+ currentDirectoryPath +
+ PlatformIO.getDirSeparator() +
+ 'textfile' +
+ AppConfig.beginTagContainer +
+ formatDateTime4Tag(new Date(), true) +
+ AppConfig.endTagContainer +
+ '.txt';
+ PlatformIO.saveFilePromise({ path: filePath }, '', true)
+ .then(() => {
+ dispatch(AppActions.reflectCreateEntry(filePath, true));
+ dispatch(
+ AppActions.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
+ )
+ );
+ });
+ } else {
+ dispatch(
+ AppActions.showNotification(t('core:firstOpenaFolder'), 'warning', true)
+ );
+ }
+ }
+
+ function createFileAdvanced(
+ targetPath: string,
+ fileName: string,
+ content: string,
+ fileType: 'md' | 'txt' | 'html'
+ ) {
+ const creationDate = new Date().toISOString();
+ const fileNameAndExt = fileName + '.' + fileType;
+ const creationMeta =
+ 'Created in ' +
+ versionMeta.name +
+ ' on ' +
+ creationDate.substring(0, 10) +
+ '.';
+ const filePath =
+ normalizePath(targetPath) + PlatformIO.getDirSeparator() + fileNameAndExt;
+ let fileContent = content;
+ if (fileType === 'html') {
+ fileContent =
+ newHTMLFileContent.split('<body></body>')[0] +
+ '<body data-createdwith="' +
+ versionMeta.name +
+ '" data-createdon="' +
+ creationDate +
+ '" >' +
+ content +
+ '\n<br />\n' +
+ creationMeta +
+ '\n';
+ '</body>' + newHTMLFileContent.split('<body></body>')[1];
+ } else if (fileType === 'md') {
+ fileContent = content + ' \n\n' + creationMeta + '\n';
+ }
+ PlatformIO.saveFilePromise({ path: filePath }, fileContent, false)
+ .then((fsEntry: TS.FileSystemEntry) => {
+ dispatch(AppActions.reflectCreateEntry(filePath, true));
+ openFsEntry(fsEntry);
+
+ // dispatch(actions.setSelectedEntries([fsEntry]));
+ dispatch(
+ AppActions.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
+ )
+ );
+ });
+ }
+
+ function reflectRenameDirectory(directoryPath, newDirPath) {
+ if (openedEntries && openedEntries.length > 0) {
+ if (openedEntries[0].path === directoryPath) {
+ const openedFile = openedEntries[0];
+ openedFile.path = newDirPath;
+ addToEntryContainer(openedFile);
+ }
+ }
+ }
+
+ function reflectDeleteDirectory(directoryPath) {
+ if (
+ openedEntries &&
+ openedEntries.length > 0 &&
+ openedEntries.some(
+ file =>
+ extractContainingDirectoryPath(
+ file.path,
+ PlatformIO.getDirSeparator()
+ ) === directoryPath
+ )
+ ) {
+ closeAllFiles();
+ }
+ }
+
+ const context = useMemo(() => {
+ return {
+ openedEntries,
+ isEntryInFullWidth,
+ setEntryInFullWidth,
+ addToEntryContainer,
+ closeAllFiles,
+ reflectUpdateOpenedFileContent,
+ reloadOpenedFile,
+ updateOpenedFile,
+ openEntry,
+ openFsEntry,
+ openNextFile,
+ openPrevFile,
+ toggleEntryFullWidth,
+ openLink,
+ createFile,
+ createFileAdvanced,
+ reflectRenameDirectory,
+ reflectDeleteDirectory
+ };
+ }, [openedEntries]);
+
+ return (
+ <OpenedEntryContext.Provider value={context}>
+ {children}
+ </OpenedEntryContext.Provider>
+ );
+};
diff --git a/app/hooks/TaggingActionsContextProvider.tsx b/app/hooks/TaggingActionsContextProvider.tsx
new file mode 100644
index 000000000..0e78e70c7
--- /dev/null
+++ b/app/hooks/TaggingActionsContextProvider.tsx
@@ -0,0 +1,838 @@
+/**
+ * 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 } from 'react';
+import { useDispatch, useSelector } from 'react-redux';
+import {
+ actions as AppActions,
+ AppDispatch,
+ isPersistTagsInSidecarFile
+} from '-/reducers/app';
+import mgrs from 'mgrs';
+import { Pro } from '-/pro';
+import { useTranslation } from 'react-i18next';
+import { TS } from '-/tagspaces.namespace';
+import OpenLocationCode from 'open-location-code-typescript';
+import { formatDateTime4Tag } from '@tagspaces/tagspaces-common/misc';
+import { getTagLibrary, mergeTagGroup } from '-/services/taglibrary-utils';
+import { isGeoTag } from '-/utils/geo';
+import {
+ getAddTagsToLibrary,
+ getGeoTaggingFormat,
+ getPrefixTagContainer,
+ getTagColor,
+ getTagDelimiter,
+ getTagTextColor
+} from '-/reducers/settings';
+import PlatformIO from '-/services/platform-facade';
+import {
+ generateFileName,
+ loadDirMetaDataPromise,
+ loadFileMetaDataPromise,
+ loadMetaDataPromise,
+ saveMetaDataPromise
+} from '-/services/utils-io';
+import {
+ extractContainingDirectoryPath,
+ extractFileName,
+ extractTags
+} from '@tagspaces/tagspaces-common/paths';
+import { useOpenedEntryContext } from '-/hooks/useOpenedEntryContext';
+import GlobalSearch from '-/services/search-index';
+import { getLocations } from '-/reducers/locations';
+
+type TaggingActionsContextData = {
+ addTags: (
+ paths: Array<string>,
+ tags: Array<TS.Tag>,
+ updateIndex?: boolean
+ ) => Promise<boolean>;
+ addTagsToEntry: (
+ path: string,
+ tags: Array<TS.Tag>,
+ updateIndex?: boolean
+ ) => Promise<boolean>;
+ editTagForEntry: (path: string, tag: TS.Tag, newTagTitle?: string) => void;
+ removeTags: (paths: Array<string>, tags?: Array<TS.Tag>) => Promise<boolean>;
+ removeTagsFromEntry: (path: string, tags?: Array<TS.Tag>) => Promise<boolean>;
+ removeAllTags: (paths: Array<string>) => Promise<boolean>;
+ collectTagsFromLocation: (tagGroup: TS.TagGroup) => void;
+};
+
+export const TaggingActionsContext = createContext<TaggingActionsContextData>({
+ addTags: () => Promise.resolve(false),
+ addTagsToEntry: () => Promise.resolve(false),
+ editTagForEntry: () => {},
+ removeTags: () => Promise.resolve(false),
+ removeTagsFromEntry: () => Promise.resolve(false),
+ removeAllTags: () => Promise.resolve(false),
+ collectTagsFromLocation: () => {}
+});
+
+export type TaggingActionsContextProviderProps = {
+ children: React.ReactNode;
+};
+
+export const TaggingActionsContextProvider = ({
+ children
+}: TaggingActionsContextProviderProps) => {
+ const { t } = useTranslation();
+ const { openedEntries, updateOpenedFile } = useOpenedEntryContext();
+ 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);
+
+ function addTags(
+ paths: Array<string>,
+ tags: Array<TS.Tag>,
+ updateIndex = true
+ ): Promise<boolean> {
+ let defaultTagLocation;
+ if (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(
+ t('core:thisFunctionalityIsAvailableInPro' as any) as string
+ )
+ );
+ }
+ } 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(
+ t('core:thisFunctionalityIsAvailableInPro' as any) as string
+ )
+ );
+ }
+ } 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 =>
+ addTagsToEntry(path, processedTags, updateIndex)
+ );
+
+ if (addTagsToLibrary) {
+ // collecting tags
+ // filter existed in tagLibrary
+ const uniqueTags: TS.Tag[] = [];
+ 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 || tagBackgroundColor,
+ textcolor: tag.textcolor || tagTextColor
+ });
+ }
+ return true;
+ });
+ if (uniqueTags.length > 0) {
+ const tagGroup = {
+ uuid: 'collected_tag_group_id', // uuid needs to be constant here (see mergeTagGroup)
+ title: t('core:collectedTags' as any) as string,
+ color: tagBackgroundColor,
+ textcolor: 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);
+ }
+
+ 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;
+ }
+
+ async function addTagsToEntry(
+ path: string,
+ tags: Array<TS.Tag>,
+ updateIndex = true
+ ): Promise<boolean> {
+ 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) {
+ // Handling adding tags in sidecar
+ if (fsEntryMeta) {
+ const uniqueTags = getNonExistingTags(
+ tags,
+ extractTags(path, tagDelimiter, PlatformIO.getDirSeparator()),
+ fsEntryMeta.tags
+ );
+ if (uniqueTags.length > 0) {
+ const newTags: TS.Tag[] = [...fsEntryMeta.tags, ...uniqueTags];
+ const updatedFsEntryMeta = {
+ ...fsEntryMeta,
+ tags: newTags
+ };
+ return saveMetaDataPromise(path, updatedFsEntryMeta)
+ .then(() => {
+ // TODO rethink this updateCurrentDirEntry and not need for KanBan
+ dispatch(
+ AppActions.reflectUpdateSidecarTags(path, newTags, updateIndex)
+ );
+ updateOpenedFile(path, {
+ id: 'opened_entry_id',
+ tags: newTags
+ });
+ 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
+ )
+ );
+ return false;
+ });
+ }
+ } else {
+ const newFsEntryMeta = { tags };
+ return saveMetaDataPromise(path, newFsEntryMeta)
+ .then(() => {
+ // TODO rethink this updateCurrentDirEntry and not need for KanBan
+ dispatch(
+ AppActions.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
+ )
+ );
+ return true;
+ });
+ }
+ } else if (fsEntryMeta) {
+ // Handling tags in filename by existing sidecar
+ const extractedTags = extractTags(
+ path,
+ 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,
+ tagDelimiter,
+ 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,
+ 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,
+ tagDelimiter,
+ 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}
+ */
+ async function editTagForEntry(
+ path: string,
+ tag: TS.Tag,
+ newTagTitle?: string
+ ) {
+ 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) {
+ tag.type = 'plain';
+ }
+ }
+ delete tag.description;
+ delete tag.functionality;
+ delete tag.path;
+ delete tag.id;
+
+ const extractedTags: string[] = extractTags(
+ path,
+ 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,
+ tagDelimiter,
+ prefixTagContainer
+ );
+ if (newFileName !== fileName) {
+ await 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(() => {
+ updateOpenedFile(path, {
+ id: '',
+ 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(
+ t('core:addingTagsFailed' as any) as string,
+ '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(t('core:addingTagsFailed'), 'error', true));
+ // eslint-disable-next-line no-param-reassign
+ tag.title = newTagTitle;
+ const fsEntryMeta = { tags: [tag] };
+ saveMetaDataPromise(path, fsEntryMeta)
+ .then(() => {
+ updateOpenedFile(path, {
+ id: '',
+ 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(
+ t('core:addingTagsFailed' as any) as string,
+ 'error',
+ true
+ )
+ );
+ });
+ });
+ }
+
+ if (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 || tagBackgroundColor,
+ textcolor: tag.textcolor || tagTextColor
+ });
+ }
+ if (uniqueTags.length > 0) {
+ const tagGroup = {
+ uuid: 'collected_tag_group_id', // uuid needs to be constant here (see mergeTagGroup)
+ title: t('core:collectedTags' as any) as string,
+ color: tagBackgroundColor,
+ textcolor: tagTextColor,
+ children: uniqueTags,
+ created_date: new Date().getTime(),
+ modified_date: new Date().getTime()
+ };
+ mergeTagGroup(tagGroup, getTagLibrary());
+ dispatch(AppActions.tagLibraryChanged());
+ }
+ }
+ }
+
+ async function removeTags(
+ paths: Array<string>,
+ tags?: Array<TS.Tag>
+ ): Promise<boolean> {
+ const promises = paths.map(path => removeTagsFromEntry(path, tags));
+ return Promise.all(promises).then(() => true);
+ }
+
+ /**
+ * @param path
+ * @param tags? if undefined will remove all tags
+ */
+ function removeTagsFromEntry(
+ path: string,
+ tags?: Array<TS.Tag>
+ ): Promise<boolean> {
+ 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]));
+ return updateOpenedFile(path, {
+ id: '',
+ tags: newTags
+ });
+ }
+ );
+ });
+ })
+ .catch(error => {
+ console.warn('Error removing tags for ' + path + ' with ' + error);
+ // dispatch(AppActions.showNotification(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(
+ t('core:removingSidecarTagsFailed' as any) as string,
+ '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,
+ 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,
+ tagDelimiter,
+ 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);
+ }
+ });
+ }
+ }
+
+ function removeAllTags(paths: Array<string>): Promise<boolean> {
+ return removeTags(paths);
+ }
+
+ function collectTagsFromLocation(tagGroup: TS.TagGroup) {
+ if (GlobalSearch.getInstance().getIndex().length < 1) {
+ dispatch(
+ AppActions.showNotification(
+ 'Please index location first',
+ 'error',
+ true
+ )
+ );
+ return true;
+ }
+
+ const uniqueTags = collectTagsFromIndex(
+ GlobalSearch.getInstance().getIndex(),
+ tagGroup
+ );
+ if (uniqueTags.length > 0) {
+ const changedTagGroup = {
+ ...tagGroup,
+ children: uniqueTags,
+ modified_date: new Date().getTime()
+ };
+ mergeTagGroup(changedTagGroup, getTagLibrary(), locations);
+ // dispatch(TagLibraryActions.mergeTagGroup(changedTagGroup));
+ }
+ }
+
+ function collectTagsFromIndex(locationIndex: any, tagGroup: any) {
+ const uniqueTags = [];
+ const defaultTagColor = tagBackgroundColor;
+ const defaultTagTextColor = 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;
+ }
+
+ const context = useMemo(() => {
+ return {
+ addTags,
+ addTagsToEntry,
+ editTagForEntry,
+ removeTags,
+ removeTagsFromEntry,
+ removeAllTags,
+ collectTagsFromLocation
+ };
+ }, [openedEntries]);
+
+ return (
+ <TaggingActionsContext.Provider value={context}>
+ {children}
+ </TaggingActionsContext.Provider>
+ );
+};
diff --git a/app/hooks/useDescriptionContext.tsx b/app/hooks/useDescriptionContext.tsx
new file mode 100644
index 000000000..568bc8ad9
--- /dev/null
+++ b/app/hooks/useDescriptionContext.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 { DescriptionContext } from './DescriptionContextProvider';
+
+export const useDescriptionContext = () => useContext(DescriptionContext);
diff --git a/app/hooks/useFsActionsContext.tsx b/app/hooks/useFsActionsContext.tsx
new file mode 100644
index 000000000..e0295040e
--- /dev/null
+++ b/app/hooks/useFsActionsContext.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 { FsActionsContext } from '-/hooks/FsActionsContextProvider';
+
+export const useFsActionsContext = () => useContext(FsActionsContext);
diff --git a/app/hooks/useOpenedEntryContext.tsx b/app/hooks/useOpenedEntryContext.tsx
new file mode 100644
index 000000000..707930328
--- /dev/null
+++ b/app/hooks/useOpenedEntryContext.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 { OpenedEntryContext } from '-/hooks/OpenedEntryContextProvider';
+
+export const useOpenedEntryContext = () => useContext(OpenedEntryContext);
diff --git a/app/hooks/useTaggingActionsContext.tsx b/app/hooks/useTaggingActionsContext.tsx
new file mode 100644
index 000000000..3b65060f4
--- /dev/null
+++ b/app/hooks/useTaggingActionsContext.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 { TaggingActionsContext } from '-/hooks/TaggingActionsContextProvider';
+
+export const useTaggingActionsContext = () => useContext(TaggingActionsContext);
diff --git a/app/perspectives/grid-perspective/components/CellContent.tsx b/app/perspectives/grid-perspective/components/CellContent.tsx
index 25c9488f1..d6dd7cb1b 100644
--- a/app/perspectives/grid-perspective/components/CellContent.tsx
+++ b/app/perspectives/grid-perspective/components/CellContent.tsx
@@ -47,7 +47,6 @@ import TagsPreview from '-/components/TagsPreview';
import PlatformIO from '-/services/platform-facade';
import EntryIcon from '-/components/EntryIcon';
import { TS } from '-/tagspaces.namespace';
-import TaggingActions from '-/reducers/tagging-actions';
import {
actions as AppActions,
AppDispatch,
@@ -66,6 +65,7 @@ import {
GridStyles
} from '-/perspectives/grid-perspective/components/styles.css';
import { useTranslation } from 'react-i18next';
+import { useTaggingActionsContext } from '-/hooks/useTaggingActionsContext';
const maxDescriptionPreviewLength = 100;
@@ -108,6 +108,7 @@ function CellContent(props: Props) {
} = props;
const { t } = useTranslation();
+ const { addTags, editTagForEntry } = useTaggingActionsContext();
const theme = useTheme();
const readOnlyMode = useSelector(isReadOnlyMode);
@@ -120,14 +121,14 @@ function CellContent(props: Props) {
// You can use the dispatch function to dispatch actions
const handleEditTag = (path: string, tag: TS.Tag, newTagTitle?: string) => {
- dispatch(TaggingActions.editTagForEntry(path, tag, newTagTitle));
+ editTagForEntry(path, tag, newTagTitle);
};
const handleAddTags = (
paths: Array<string>,
tags: Array<TS.Tag>,
updateIndex?
) => {
- dispatch(TaggingActions.addTags(paths, tags, updateIndex));
+ addTags(paths, tags, updateIndex);
};
const handleAddTag = (tag: TS.Tag, parentTagGroupUuid: TS.Uuid) => {
diff --git a/app/perspectives/grid-perspective/components/GridPagination.tsx b/app/perspectives/grid-perspective/components/GridPagination.tsx
index f11e09005..b245a5c94 100644
--- a/app/perspectives/grid-perspective/components/GridPagination.tsx
+++ b/app/perspectives/grid-perspective/components/GridPagination.tsx
@@ -62,6 +62,7 @@ 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';
interface Props {
isMetaLoaded: boolean;
@@ -109,7 +110,6 @@ interface Props {
setSelectedEntries: (selectedEntries: Array<TS.FileSystemEntry>) => void;
singleClickAction: string;
lastSelectedEntryPath: string;
- openEntry: (entryPath?: string) => void;
openFileNatively: (path?: string) => void;
loadDirectoryContent: (
path: string,
@@ -149,7 +149,6 @@ function GridPagination(props: Props) {
openRenameEntryDialog,
lastSelectedEntryPath,
lastBackgroundImageChange,
- openEntry,
openFileNatively,
loadDirectoryContent,
setFileContextMenuAnchorEl,
@@ -164,6 +163,7 @@ function GridPagination(props: Props) {
files,
lastSearchTimestamp
} = props;
+ const { openEntry } = useOpenedEntryContext();
const directoryContent: Array<TS.FileSystemEntry> = useSelector(
getDirectoryContent
@@ -529,22 +529,22 @@ function GridPagination(props: Props) {
</Typography>
)}
</Box>
- <Tooltip title={t('core:thumbnail')}>
- <div
- style={{
- borderRadius: 10,
- height: 100,
- width: 140,
- backgroundImage: 'url("' + folderTmbPath.current + '")',
- backgroundSize: 'cover', // cover contain
- backgroundRepeat: 'no-repeat',
- backgroundPosition: 'center center',
- position: 'absolute',
- top: 0,
- right: 0
- }}
- ></div>
- </Tooltip>
+ {/* <Tooltip title={t('core:thumbnail')}> */}
+ <div
+ style={{
+ borderRadius: 10,
+ height: 100,
+ width: 140,
+ backgroundImage: 'url("' + folderTmbPath.current + '")',
+ backgroundSize: 'cover', // cover contain
+ backgroundRepeat: 'no-repeat',
+ backgroundPosition: 'center center',
+ position: 'absolute',
+ top: 0,
+ right: 0
+ }}
+ ></div>
+ {/* </Tooltip> */}
</div>
</Grid>
)}
@@ -722,11 +722,9 @@ function mapStateToProps(state) {
function mapActionCreatorsToProps(dispatch) {
return bindActionCreators(
{
- // setMetaForCurrentDir: AppActions.setMetaForCurrentDir,
updateCurrentDirEntries: AppActions.updateCurrentDirEntries,
setIsMetaLoaded: AppActions.setIsMetaLoaded,
- loadDirectoryContent: AppActions.loadDirectoryContent,
- openEntry: AppActions.openEntry
+ loadDirectoryContent: AppActions.loadDirectoryContent
},
dispatch
);
diff --git a/app/perspectives/grid-perspective/components/MainContainer.tsx b/app/perspectives/grid-perspective/components/MainContainer.tsx
index 84dcabff7..8fbe24be9 100644
--- a/app/perspectives/grid-perspective/components/MainContainer.tsx
+++ b/app/perspectives/grid-perspective/components/MainContainer.tsx
@@ -56,6 +56,7 @@ 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';
interface Props {
currentDirectoryPath: string;
@@ -79,6 +80,7 @@ function getSettings(directoryMeta: TS.FileSystemEntryMeta): TS.FolderSettings {
function GridPerspective(props: Props) {
const { currentDirectoryPath, openRenameEntryDialog } = props;
+ const { openEntry, openPrevFile, openNextFile } = useOpenedEntryContext();
const dispatch: AppDispatch = useDispatch();
const {
@@ -546,8 +548,8 @@ function GridPerspective(props: Props) {
};
const keyBindingHandlers = {
- nextDocument: () => dispatch(AppActions.openNextFile()),
- prevDocument: () => dispatch(AppActions.openPrevFile()),
+ nextDocument: () => openNextFile(),
+ prevDocument: () => openPrevFile(),
selectAll: () => toggleSelectAllFiles(),
deleteDocument: () => {
if (fileOperationsEnabled(selectedEntries)) {
@@ -564,7 +566,7 @@ function GridPerspective(props: Props) {
},
openEntry: e => {
e.preventDefault();
- dispatch(AppActions.openEntry());
+ openEntry();
},
openFileExternally: () => {
handleOpenFileNatively();
diff --git a/app/perspectives/grid-perspective/components/MainToolbar.tsx b/app/perspectives/grid-perspective/components/MainToolbar.tsx
index bb5b8b39e..aa1f11b7a 100644
--- a/app/perspectives/grid-perspective/components/MainToolbar.tsx
+++ b/app/perspectives/grid-perspective/components/MainToolbar.tsx
@@ -54,6 +54,7 @@ import {
GridStyles
} from '-/perspectives/grid-perspective/components/styles.css';
import { useTranslation } from 'react-i18next';
+import { useOpenedEntryContext } from '-/hooks/useOpenedEntryContext';
interface Props {
prefixDataTID?: string;
@@ -79,6 +80,7 @@ function MainToolbar(props: Props) {
} = props;
const { t } = useTranslation();
+ const { openEntry } = useOpenedEntryContext();
const selectedEntries: Array<TS.FileSystemEntry> = useSelector(
getSelectedEntries
);
@@ -89,7 +91,7 @@ function MainToolbar(props: Props) {
const directoryPath = useSelector(getDirectoryPath);
function showProperties() {
- return dispatch(AppActions.openEntry(directoryPath, true));
+ return openEntry(directoryPath, true);
}
return (
diff --git a/app/perspectives/list/components/MainContainer.tsx b/app/perspectives/list/components/MainContainer.tsx
index 60dd7660a..18ca93755 100644
--- a/app/perspectives/list/components/MainContainer.tsx
+++ b/app/perspectives/list/components/MainContainer.tsx
@@ -56,6 +56,7 @@ 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';
interface Props {
currentDirectoryPath: string;
@@ -88,6 +89,7 @@ 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);
@@ -539,8 +541,8 @@ function ListPerspective(props: Props) {
};
const keyBindingHandlers = {
- nextDocument: () => dispatch(AppActions.openNextFile()),
- prevDocument: () => dispatch(AppActions.openPrevFile()),
+ nextDocument: () => openNextFile(),
+ prevDocument: () => openPrevFile(),
selectAll: () => toggleSelectAllFiles(),
deleteDocument: () => {
if (fileOperationsEnabled(selectedEntries)) {
@@ -557,7 +559,7 @@ function ListPerspective(props: Props) {
},
openEntry: e => {
e.preventDefault();
- dispatch(AppActions.openEntry());
+ openEntry();
},
openFileExternally: () => {
handleOpenFileNatively();
diff --git a/app/reducers/app.ts b/app/reducers/app.ts
index 8ec6fad0b..dda272271 100644
--- a/app/reducers/app.ts
+++ b/app/reducers/app.ts
@@ -68,6 +68,7 @@ import { actions as tagLibraryActions } from './taglibrary';
import {
actions as SettingsActions,
getCheckForUpdateOnStartup,
+ getPersistTagsInSidecarFile,
isFirstRun,
isGlobalKeyBindingEnabled
} from '-/reducers/settings';
@@ -97,6 +98,7 @@ 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',
LOGIN_SUCCESS: 'APP/LOGIN_SUCCESS',
LOGIN_FAILURE: 'APP/LOGIN_FAILURE',
LOGOUT: 'APP/LOGOUT',
@@ -110,10 +112,10 @@ export const types = {
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',
+ //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',
@@ -250,7 +252,6 @@ export const initialState = {
notificationType: '',
autohide: false
},
- openedFiles: [],
editTagDialogOpened: false,
aboutDialogOpened: false,
locationDialogOpened: false,
@@ -315,6 +316,15 @@ 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 };
}
@@ -442,9 +452,6 @@ export default (state: any = initialState, action: any) => {
}
return state;
}
- /* case types.SET_LAST_SELECTED_ENTRY: {
- return { ...state, lastSelectedEntry: action.entryPath };
- } */
case types.SET_SELECTED_ENTRIES: {
if (
JSON.stringify(action.selectedEntries) !==
@@ -674,12 +681,6 @@ export default (state: any = initialState, action: any) => {
}
};
}
- /*case types.SET_ISLOADING: {
- return {
- ...state,
- isLoading: action.isLoading
- };
- }*/
case types.SET_GENERATING_THUMBNAILS: {
if (action.isGeneratingThumbs !== state.isGeneratingThumbs) {
return {
@@ -689,28 +690,6 @@ export default (state: any = initialState, action: any) => {
}
return state;
}
- case types.OPEN_FILE: {
- return {
- ...state,
- openedFiles: [
- action.file
- // ...state.openedFiles // TODO uncomment for multiple file support
- ]
- /*...(action.file.path === state.currentDirectoryPath &&
- action.file.description && {
- currentDirectoryDescription: action.file.description
- })*/
- };
- }
- case types.TOGGLE_ENTRY_FULLWIDTH: {
- return { ...state, isEntryInFullWidth: !state.isEntryInFullWidth };
- }
- case types.SET_ENTRY_FULLWIDTH: {
- if (action.isEntryInFullWidth !== state.isEntryInFullWidth) {
- return { ...state, isEntryInFullWidth: action.isFullWidth };
- }
- return state;
- }
case types.UPDATE_THUMB_URL: {
const dirEntries = state.currentDirectoryEntries.map(entry => {
if (entry.path === action.filePath) {
@@ -742,21 +721,16 @@ export default (state: any = initialState, action: any) => {
const newDirectoryEntries = state.currentDirectoryEntries.filter(
entry => entry.path !== action.path
);
- const newOpenedFiles = state.openedFiles.filter(
- entry => entry.path !== action.path
- );
const editedEntryPaths = [{ action: 'delete', path: action.path }];
// check if currentDirectoryEntries or openedFiles changed
if (
- state.currentDirectoryEntries.length > newDirectoryEntries.length ||
- state.openedFiles.length > newOpenedFiles.length
+ state.currentDirectoryEntries.length > newDirectoryEntries.length
+ // || state.openedFiles.length > newOpenedFiles.length
) {
return {
...state,
editedEntryPaths,
- currentDirectoryEntries: newDirectoryEntries,
- openedFiles: newOpenedFiles,
- isEntryInFullWidth: false
+ currentDirectoryEntries: newDirectoryEntries
};
}
return {
@@ -768,24 +742,16 @@ export default (state: any = initialState, action: any) => {
const newDirectoryEntries = state.currentDirectoryEntries.filter(
entry => !action.paths.some(path => path === entry.path)
);
- const newOpenedFiles = state.openedFiles.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 ||
- state.openedFiles.length > newOpenedFiles.length
- ) {
+ if (state.currentDirectoryEntries.length > newDirectoryEntries.length) {
return {
...state,
editedEntryPaths,
- currentDirectoryEntries: newDirectoryEntries,
- openedFiles: newOpenedFiles,
- isEntryInFullWidth: false
+ currentDirectoryEntries: newDirectoryEntries
};
}
return {
@@ -894,55 +860,9 @@ export default (state: any = initialState, action: any) => {
...fileNameTags
]
};
- }),
- openedFiles: state.openedFiles.map(entry => {
- if (entry.path !== action.path) {
- return entry;
- }
- const fileNameTags = entry.isFile ? extractedTags : []; // dirs dont have tags in filename
- // const { url, ...rest } = entry;
- const sidecarTags =
- entry.tags && entry.tags.length > 0
- ? entry.tags.filter(tag => tag.type !== 'plain')
- : [];
- return {
- ...entry,
- path: action.newPath, // TODO handle change extension case
- tags: [
- ...sidecarTags, // add only sidecar tags
- ...fileNameTags
- ]
- // shouldReload: true
- };
})
};
}
- /* case types.REFLECT_UPDATE_SIDECARTAGS: {
- return {
- ...state,
- currentDirectoryEntries: state.currentDirectoryEntries.map(entry => {
- if (entry.path !== action.path) {
- return entry;
- }
- return {
- ...entry,
- tags: [
- ...entry.tags.filter(tag => tag.type === 'plain'),
- ...action.tags
- ]
- };
- }),
- openedFiles: state.openedFiles.map(entry => {
- if (entry.path !== action.path) {
- return entry;
- }
- return {
- ...entry,
- shouldReload: true
- };
- })
- };
- } */
case types.UPDATE_CURRENTDIR_ENTRIES: {
if (
state.currentDirectoryEntries &&
@@ -992,37 +912,6 @@ export default (state: any = initialState, action: any) => {
)
};
}
- /* case types.REFLECT_UPDATE_SIDECARMETA: {
- return {
- ...state,
- currentDirectoryEntries: state.currentDirectoryEntries.map(entry => {
- if (entry.path !== action.path) {
- return entry;
- }
- return {
- ...entry,
- ...action.entryMeta
- };
- }),
- openedFiles: state.openedFiles.map(entry => {
- if (entry.path !== action.path) {
- return entry;
- }
- return {
- ...entry,
- shouldReload: true
- };
- })
- };
- } */
- case types.CLOSE_ALL_FILES: {
- clearURLParam('tsepath');
- return {
- ...state,
- openedFiles: [],
- isEntryInFullWidth: false
- };
- }
case types.OPEN_LOCATIONMANAGER_PANEL: {
return {
...state,
@@ -1059,15 +948,6 @@ export default (state: any = initialState, action: any) => {
helpFeedbackPanelOpened: true
};
}
- /*case types.CLOSE_ALLVERTICAL_PANELS: {
- return {
- ...state,
- locationManagerPanelOpened: false,
- tagLibraryPanelOpened: false,
- searchPanelOpened: false,
- helpFeedbackPanelOpened: false
- };
- }*/
case types.ADD_EXTENSIONS: {
const extensions = mergeByProp(
state.extensions,
@@ -1165,6 +1045,11 @@ export const actions = {
lastThumbnailImageChange: lastThumbnailImageChange || new Date().getTime()
}),
loggedIn: user => ({ type: types.LOGIN_SUCCESS, user }),
+ openLink: (url: string, options = { fullWidth: true }) => ({
+ type: types.OPEN_LINK,
+ url,
+ options
+ }),
initApp: () => (dispatch: (action) => void, getState: () => any) => {
disableBackGestureMac();
// migrate TagLibrary from redux state
@@ -1337,18 +1222,6 @@ export const actions = {
type: types.SET_CURRENT_DIRECTORY_DIRS,
dirs
}),
- /*clearUploadDialog: () => (
- dispatch: (action) => void
- // getState: () => any
- ) => {
- // const currentLocation: Location = getState().locations.find(location => location.uuid === getCurrentLocationId(getState()))
- if (PlatformIO.haveObjectStoreSupport()) {
- // && currentLocation.type === locationType.TYPE_AMPLIFY) {
- dispatch(actions.clearUploadDialogInt());
- // const { currentDirectoryPath } = getState().app;
- // dispatch(actions.loadDirectoryContent(currentDirectoryPath, false));
- }
- },*/
clearUploadDialog: () => ({
type: types.CLEAR_UPLOAD_DIALOG
}),
@@ -1364,48 +1237,6 @@ export const actions = {
type: types.SET_ISLOADING,
isLoading
}),*/
- /* setMetaForCurrentDir: (metaFiles: Array<any>) => (
- dispatch: (action: any) => void,
- getState: () => any
- ) => {
- const state = getState();
- const {
- currentDirectoryPath,
- currentDirectoryColor,
- currentDirectoryPerspective
- } = state.app;
- if (
- metaFiles.some(metaFile => metaFile.path === AppConfig.metaFolderFile)
- // && !props.currentDirectoryColor
- ) {
- const metaFilePath = getMetaFileLocationForDir(
- currentDirectoryPath,
- PlatformIO.getDirSeparator()
- );
- loadJSONFile(metaFilePath)
- .then((fsEntryMeta: TS.FileSystemEntryMeta) => {
- if (
- fsEntryMeta.color &&
- currentDirectoryColor !== fsEntryMeta.color
- ) {
- dispatch(actions.setCurrentDirectoryColor(fsEntryMeta.color));
- }
- if (
- fsEntryMeta.perspective &&
- fsEntryMeta.perspective !== PerspectiveIDs.UNSPECIFIED &&
- currentDirectoryPerspective !== fsEntryMeta.perspective
- ) {
- dispatch(
- actions.setCurrentDirectoryPerspective(fsEntryMeta.perspective)
- );
- }
- return fsEntryMeta;
- })
- .catch(err => {
- console.error(err);
- });
- }
- }, */
loadParentDirectoryContent: () => (
dispatch: (action) => void,
getState: () => any
@@ -1467,20 +1298,16 @@ export const actions = {
) => (dispatch: (action) => void, getState: () => any) => {
const { settings } = getState();
- /* const { currentDirectoryPath } = getState().app;
- if (currentDirectoryPath !== directoryPath) {
- dispatch(actions.loadDirectorySuccessInt(directoryPath, [], true)); // this is to reset directoryContent (it will reset color too)
- } */
- // dispatch(actions.setCurrentDirectoryColor('')); // this is to reset color only
dispatch(actions.showNotification(i18n.t('core:loading'), 'info', false));
const currentLocation: TS.Location = getLocation(
getState(),
getState().app.currentLocationId
);
const resultsLimit = {
- maxLoops: currentLocation.maxLoops
- ? currentLocation.maxLoops
- : AppConfig.maxLoops,
+ maxLoops:
+ currentLocation && currentLocation.maxLoops
+ ? currentLocation.maxLoops
+ : AppConfig.maxLoops,
IsTruncated: false
};
PlatformIO.listDirectoryPromise(
@@ -1496,15 +1323,8 @@ export const actions = {
)
.then(results => {
if (resultsLimit.IsTruncated) {
- // TO DO OPEN ISTRUNCATED dialog
+ //OPEN ISTRUNCATED dialog
dispatch(actions.toggleTruncatedConfirmDialog());
- /*dispatch(
- actions.showNotification(
- i18n.t('warningDirectoryIsTruncated') + ': ' + directoryPath,
- 'error',
- false
- )
- );*/
}
updateHistory(currentLocation, directoryPath);
if (results !== undefined) {
@@ -1558,18 +1378,13 @@ export const actions = {
PlatformIO.getDirSeparator()
);
const fsEntryMeta = await loadJSONFile(metaFilePath);
- /* const fsEntryMeta = await loadMetaDataPromise(
- normalizePath(directoryPath) + PlatformIO.getDirSeparator()
- ); */
// console.debug('Loading meta succeeded for:' + directoryPath);
dispatch(
actions.loadDirectoryContentInt(
directoryPath,
generateThumbnails,
- fsEntryMeta /*{
- ...fsEntryMeta,
- description: getDescriptionPreview(fsEntryMeta.description, 200)
- }*/
+ fsEntryMeta
+ // description: getDescriptionPreview(fsEntryMeta.description, 200)
)
);
} catch (err) {
@@ -1589,27 +1404,6 @@ export const actions = {
directoryContent: Array<any>,
directoryMeta?: TS.FileSystemEntryMeta
) => (dispatch: (action) => void, getState: () => any) => {
- // const currentLocation: Location = getLocation(
- // getState(),
- // getState().app.currentLocationId
- // );
- // const { openedFiles } = getState().app;
- // const entryPath =
- // openedFiles && openedFiles.length > 0 && openedFiles[0].path;
- // updateHistory(currentLocation, directoryPath, entryPath);
- /* const { selectedEntries } = getState().app;
- if (selectedEntries.length > 0) {
- // check and remove obsolete selectedEntries
- const newSelectedEntries = selectedEntries.filter(
- (entry: FileSystemEntry) =>
- directoryContent.some(
- (fsEntry: FileSystemEntry) => fsEntry.path === entry.path
- )
- );
- if (newSelectedEntries.length !== selectedEntries.length) {
- dispatch(actions.setSelectedEntries(newSelectedEntries));
- }
- } */
const { settings } = getState();
dispatch(actions.hideNotifications(['error']));
dispatch(
@@ -1670,33 +1464,6 @@ export const actions = {
type: types.SET_GENERATING_THUMBNAILS,
isGeneratingThumbs
}),
- /* setGeneratingThumbnails: (isGeneratingThumbs: boolean) => (
- dispatch: (actions: Object) => void
- ) => {
- dispatch(actions.hideNotifications());
- if (isGeneratingThumbs) {
- dispatch(
- actions.showNotification(
- i18n.t('core:loadingOrGeneratingThumbnails'),
- 'info',
- true
- )
- );
- } else {
- console.log('Thumbnail generation ready');
- // dispatch(
- // actions.showNotification(
- // i18n.t('Thumbnail ready'),
- // 'info',
- // true
- // )
- // );
- }
- }, */
- /* setLastSelectedEntry: (entryPath: string | null) => ({
- type: types.SET_LAST_SELECTED_ENTRY,
- entryPath
- }), */
setCurrentDirectoryColor: (color: string) => ({
type: types.SET_CURRENDIRECTORYCOLOR,
color
@@ -1733,267 +1500,12 @@ export const actions = {
tagLibraryChanged: () => ({
type: types.SET_TAG_LIBRARY_CHANGED
}),
- deleteDirectory: (directoryPath: string) => (
- dispatch: (action) => void,
- getState: () => any
- ) => {
- const { settings } = getState();
- const { currentDirectoryPath, openedFiles } = getState().app;
- return PlatformIO.deleteDirectoryPromise(
- directoryPath,
- settings.useTrashCan
- )
- .then(() => {
- if (directoryPath === currentDirectoryPath) {
- dispatch(actions.loadParentDirectoryContent());
- GlobalSearch.getInstance().reflectDeleteEntry(directoryPath);
- // close opened entries in deleted dir
- if (
- openedFiles.length > 0 &&
- openedFiles.some(
- file =>
- extractContainingDirectoryPath(
- file.path,
- PlatformIO.getDirSeparator()
- ) === directoryPath
- )
- ) {
- dispatch(actions.closeAllFiles());
- }
- } else {
- dispatch(actions.reflectDeleteEntry(directoryPath));
- }
- dispatch(
- actions.showNotification(
- i18n.t('deletingDirectorySuccessfull', {
- dirPath: extractDirectoryName(
- directoryPath,
- PlatformIO.getDirSeparator()
- )
- }),
- 'default',
- true
- )
- );
- return true;
- })
- .catch(error => {
- console.warn('Error while deleting directory: ' + error);
- dispatch(
- actions.showNotification(
- i18n.t('errorDeletingDirectoryAlert', {
- dirPath: extractDirectoryName(
- directoryPath,
- PlatformIO.getDirSeparator()
- )
- }),
- 'error',
- true
- )
- );
- // dispatch stopLoadingAnimation
- });
- },
openDirectory: (directoryPath: string) => () => {
PlatformIO.openDirectory(directoryPath);
},
showInFileManager: (filePath: string) => () => {
PlatformIO.showInFileManager(filePath);
},
- renameDirectory: (directoryPath: string, newDirectoryName: string) => (
- dispatch: (action) => void,
- getState: () => any
- ) =>
- PlatformIO.renameDirectoryPromise(directoryPath, newDirectoryName)
- .then(newDirPath => {
- const { currentDirectoryPath, openedFiles } = getState().app;
- if (currentDirectoryPath === directoryPath) {
- dispatch(actions.loadDirectoryContent(newDirPath, false, true));
- if (openedFiles && openedFiles.length > 0) {
- if (openedFiles[0].path === directoryPath) {
- const openedFile = openedFiles[0];
- openedFile.path = newDirPath;
- dispatch(actions.addToEntryContainer(openedFile));
- }
- }
- GlobalSearch.getInstance().reflectRenameEntry(
- directoryPath,
- newDirPath
- );
- } else {
- dispatch(actions.reflectRenameEntry(directoryPath, newDirPath));
- }
-
- dispatch(
- actions.showNotification(
- `Renaming directory ${extractDirectoryName(
- directoryPath,
- PlatformIO.getDirSeparator()
- )} successful.`,
- 'default',
- true
- )
- );
- return true;
- })
- .catch(error => {
- console.warn('Error while renaming directory: ' + error);
- dispatch(
- actions.showNotification(
- `Error renaming directory '${extractDirectoryName(
- directoryPath,
- PlatformIO.getDirSeparator()
- )}'`,
- 'error',
- true
- )
- );
- throw error;
- }),
- createDirectory: (directoryPath: string, reflect = true) => (
- dispatch: (action) => void
- ) =>
- PlatformIO.createDirectoryPromise(directoryPath)
- .then(result => {
- if (result !== undefined && result.dirPath !== undefined) {
- // eslint-disable-next-line no-param-reassign
- directoryPath = result.dirPath;
- }
- console.log(`Creating directory ${directoryPath} successful.`);
- if (reflect) {
- dispatch(actions.reflectCreateEntry(directoryPath, false));
- }
- dispatch(
- actions.showNotification(
- `Creating directory ${extractDirectoryName(
- directoryPath,
- PlatformIO.getDirSeparator()
- )} successful.`,
- 'default',
- true
- )
- );
- return true;
- })
- .catch(error => {
- console.warn('Error creating directory: ' + error);
- dispatch(
- actions.showNotification(
- `Error creating directory '${extractDirectoryName(
- directoryPath,
- PlatformIO.getDirSeparator()
- )}'`,
- 'error',
- true
- )
- );
- return false;
- // dispatch stopLoadingAnimation
- }),
- createFile: () => (dispatch: (action) => void, getState: () => any) => {
- const { app } = getState();
- if (app.currentDirectoryPath) {
- const filePath =
- app.currentDirectoryPath +
- PlatformIO.getDirSeparator() +
- 'textfile' +
- AppConfig.beginTagContainer +
- formatDateTime4Tag(new Date(), true) +
- AppConfig.endTagContainer +
- '.txt';
- PlatformIO.saveFilePromise({ path: filePath }, '', true)
- .then(() => {
- dispatch(actions.reflectCreateEntry(filePath, true));
- dispatch(
- actions.showNotification(
- i18n.t('core:fileCreateSuccessfully'),
- 'info',
- true
- )
- );
- dispatch(actions.openEntry(filePath));
- return true;
- })
- .catch(err => {
- console.warn('File creation failed with ' + err);
- dispatch(
- actions.showNotification(
- i18n.t('core:errorCreatingFile'),
- 'warning',
- true
- )
- );
- });
- } else {
- dispatch(
- actions.showNotification(
- i18n.t('core:firstOpenaFolder'),
- 'warning',
- true
- )
- );
- }
- },
- createFileAdvanced: (
- targetPath: string,
- fileName: string,
- content: string,
- fileType: 'md' | 'txt' | 'html'
- ) => (dispatch: (action) => void, getState: () => any) => {
- const creationDate = new Date().toISOString();
- const fileNameAndExt = fileName + '.' + fileType;
- const creationMeta =
- 'Created in ' +
- versionMeta.name +
- ' on ' +
- creationDate.substring(0, 10) +
- '.';
- const filePath =
- normalizePath(targetPath) + PlatformIO.getDirSeparator() + fileNameAndExt;
- let fileContent = content;
- if (fileType === 'html') {
- const { newHTMLFileContent } = getState().settings;
- fileContent =
- newHTMLFileContent.split('<body></body>')[0] +
- '<body data-createdwith="' +
- versionMeta.name +
- '" data-createdon="' +
- creationDate +
- '" >' +
- content +
- '\n<br />\n' +
- creationMeta +
- '\n';
- '</body>' + newHTMLFileContent.split('<body></body>')[1];
- } else if (fileType === 'md') {
- fileContent = content + ' \n\n' + creationMeta + '\n';
- }
- PlatformIO.saveFilePromise({ path: filePath }, fileContent, false)
- .then((fsEntry: TS.FileSystemEntry) => {
- dispatch(actions.reflectCreateEntry(filePath, true));
- dispatch(actions.openFsEntry(fsEntry));
-
- // dispatch(actions.setSelectedEntries([fsEntry]));
- dispatch(
- actions.showNotification(
- `File '${fileNameAndExt}' created.`,
- 'default',
- true
- )
- );
- return true;
- })
- .catch(error => {
- console.warn('Error creating file: ' + error);
- dispatch(
- actions.showNotification(
- `Error creating file '${fileNameAndExt}'`,
- 'error',
- true
- )
- );
- });
- },
setSearchResults: (searchResults: Array<any> | []) => ({
type: types.SET_SEARCH_RESULTS,
searchResults
@@ -2263,301 +1775,10 @@ export const actions = {
notificationType: 'default',
autohide: true
}),
- addToEntryContainer: (fsEntry: OpenedEntry) => ({
- type: types.OPEN_FILE,
- file: fsEntry
- }),
- /* setFileDragged: (isFileDragged: boolean) => ({
- type: types.SET_FILEDRAGGED,
- isFileDragged
- }), */
setReadOnlyMode: (isReadOnlyMode: boolean) => ({
type: types.SET_READONLYMODE,
isReadOnlyMode
}),
- reflectUpdateOpenedFileContent: (entryPath: string) => (
- dispatch: (action) => void,
- getState: () => any
- ) => {
- const { openedFiles } = getState().app;
- if (openedFiles && openedFiles.length > 0) {
- const openedFile: OpenedEntry = openedFiles.find(
- obj => obj.path === entryPath
- );
- if (openedFile) {
- openedFile.shouldReload = true;
- dispatch(actions.addToEntryContainer(openedFile));
- }
- }
- },
- updateOpenedFile: (
- entryPath: string,
- fsEntryMeta: any // TS.FileSystemEntryMeta,
- // isFile: boolean = true
- ) => (dispatch: (action) => void, getState: () => any): Promise<boolean> => {
- const { openedFiles } = getState().app;
- if (openedFiles && openedFiles.length > 0) {
- return PlatformIO.getPropertiesPromise(entryPath)
- .then(entryProps => {
- if (entryProps) {
- const { supportedFileTypes } = getState().settings;
-
- let entryForOpening: OpenedEntry;
- const entryExist = openedFiles.find(obj => obj.path === entryPath);
-
- if (!entryExist) {
- entryForOpening = findExtensionsForEntry(
- fsEntryMeta.id || fsEntryMeta.uuid,
- supportedFileTypes,
- entryPath,
- entryProps.isFile
- );
- } else {
- entryForOpening = { ...entryExist };
- }
-
- /* if (fsEntryMeta.changed !== undefined) {
- entryForOpening.changed = fsEntryMeta.changed;
- } */
- if (fsEntryMeta.editMode !== undefined) {
- entryForOpening.editMode = fsEntryMeta.editMode;
- }
- entryForOpening.shouldReload = fsEntryMeta.shouldReload;
- if (fsEntryMeta.color) {
- if (fsEntryMeta.color === 'transparent') {
- entryForOpening.color = undefined;
- } else {
- entryForOpening.color = fsEntryMeta.color;
- }
- }
- if (fsEntryMeta.description !== undefined) {
- entryForOpening.description = fsEntryMeta.description;
- }
- if (fsEntryMeta.perspective) {
- entryForOpening.perspective = fsEntryMeta.perspective;
- }
- if (fsEntryMeta.tags) {
- entryForOpening.tags = fsEntryMeta.tags;
- }
- if (fsEntryMeta.autoSave !== undefined) {
- entryForOpening.isAutoSaveEnabled = fsEntryMeta.autoSave;
- }
- entryForOpening.lmdt = entryProps.lmdt;
- entryForOpening.size = entryProps.size;
- dispatch(actions.addToEntryContainer(entryForOpening));
- }
- return true;
- })
- .catch(err => {
- console.error('updateOpenedFile ' + entryPath + ' not exist ' + err);
- return Promise.resolve(false);
- });
- }
- return Promise.resolve(false);
- },
- openEntry: (path?: string, showDetails = false) => (
- dispatch: (action) => void
- ) => {
- if (path === undefined) {
- return dispatch(actions.openFsEntry(undefined, showDetails));
- }
- return getAllPropertiesPromise(path)
- .then((fsEntry: TS.FileSystemEntry) =>
- dispatch(actions.openFsEntry(fsEntry, showDetails))
- )
- .catch(error =>
- console.warn(
- 'Error getting properties for entry: ' + path + ' - ' + error
- )
- );
- },
- openFsEntry: (fsEntry?: TS.FileSystemEntry, showDetails = false) => (
- dispatch: (action) => void,
- getState: () => any
- ) => {
- dispatch(SettingsActions.setShowDetails(showDetails));
- if (fsEntry === undefined) {
- // eslint-disable-next-line no-param-reassign
- fsEntry = getLastSelectedEntry(getState());
- if (fsEntry === undefined) {
- return;
- }
- if (!fsEntry.isFile) {
- dispatch(actions.loadDirectoryContent(fsEntry.path, false));
- return;
- }
- }
- let entryForOpening: OpenedEntry;
- const { openedFiles } = getState().app;
-
- /**
- * check for editMode in order to show save changes dialog (shouldReload: false)
- */
- if (openedFiles.length > 0) {
- const openFile = openedFiles[0];
- if (openFile.editMode) {
- entryForOpening = {
- ...openFile,
- shouldReload:
- openFile.shouldReload !== undefined
- ? !openFile.shouldReload
- : undefined
- }; // false };
- dispatch(actions.addToEntryContainer(entryForOpening));
- dispatch(
- actions.showNotification(
- `You can't open another file, because '${openFile.path}' is opened for editing`,
- 'default',
- true
- )
- );
- return false;
- }
- }
-
- const { supportedFileTypes } = getState().settings;
- // TODO decide to copy all props from {...fsEntry} into openedEntry
- entryForOpening = findExtensionsForEntry(
- fsEntry.uuid,
- supportedFileTypes,
- fsEntry.path,
- fsEntry.isFile
- );
- if (PlatformIO.haveObjectStoreSupport() || PlatformIO.haveWebDavSupport()) {
- const cleanedPath = fsEntry.path.startsWith('/')
- ? fsEntry.path.substr(1)
- : fsEntry.path;
- entryForOpening.url = PlatformIO.getURLforPath(cleanedPath);
- } else if (fsEntry.url) {
- entryForOpening.url = fsEntry.url;
- }
- if (fsEntry.perspective) {
- entryForOpening.perspective = fsEntry.perspective;
- }
- if (fsEntry.color) {
- entryForOpening.color = fsEntry.color;
- }
- if (fsEntry.description) {
- entryForOpening.description = fsEntry.description;
- }
- if (fsEntry.tags) {
- entryForOpening.tags = fsEntry.tags;
- }
- if (fsEntry.lmdt) {
- entryForOpening.lmdt = fsEntry.lmdt;
- }
- if (fsEntry.size) {
- entryForOpening.size = fsEntry.size;
- }
- if (fsEntry.isNewFile) {
- entryForOpening.editMode = true;
- }
- if (fsEntry.isAutoSaveEnabled !== undefined) {
- entryForOpening.isAutoSaveEnabled = fsEntry.isAutoSaveEnabled;
- } else if (fsEntry.meta && fsEntry.meta.autoSave) {
- entryForOpening.isAutoSaveEnabled = fsEntry.meta.autoSave;
- }
-
- document.title = fsEntry.name + ' | ' + 'TagSpaces'; // TODO get it later from app config
-
- const currentLocation: TS.Location = getLocation(
- getState(),
- getState().app.currentLocationId
- );
-
- if (currentLocation) {
- entryForOpening.locationId = currentLocation.uuid;
- const { currentDirectoryPath } = getState().app;
- updateHistory(currentLocation, currentDirectoryPath, fsEntry.path);
- }
-
- dispatch(actions.addToEntryContainer(entryForOpening));
-
- // save in history
- if (currentLocation) {
- if (Pro) {
- const historyKeys = Pro.history.historyKeys;
- const relEntryPath = getRelativeEntryPath(
- currentLocation,
- fsEntry.path
- );
- if (fsEntry.isFile) {
- Pro.history.saveHistory(
- historyKeys.fileOpenKey,
- {
- path: fsEntry.path,
- url: generateSharingLink(currentLocation.uuid, relEntryPath),
- lid: currentLocation.uuid
- },
- getState().settings[historyKeys.fileOpenKey]
- );
- } else {
- Pro.history.saveHistory(
- historyKeys.folderOpenKey,
- {
- path: fsEntry.path,
- url: generateSharingLink(
- currentLocation.uuid,
- relEntryPath,
- relEntryPath
- ),
- lid: currentLocation.uuid
- },
- getState().settings[historyKeys.folderOpenKey]
- );
- }
- }
- }
- },
- toggleEntryFullWidth: () => ({
- type: types.TOGGLE_ENTRY_FULLWIDTH
- }),
- setEntryFullWidth: (isFullWidth: boolean) => ({
- type: types.SET_ENTRY_FULLWIDTH,
- isFullWidth
- }),
- openNextFile: (path?: string) => (
- dispatch: (action) => void,
- getState: () => any
- ) => {
- const lastSelectedEntry = getLastSelectedEntry(getState());
- const nextFile = getNextFile(
- path,
- lastSelectedEntry ? lastSelectedEntry.path : undefined,
- getState().app.searchMode
- ? GlobalSearch.getInstance().getResults()
- : getState().app.currentDirectoryEntries
- );
- if (nextFile !== undefined) {
- dispatch(actions.openFsEntry(nextFile));
- // dispatch(actions.setLastSelectedEntry(nextFile.path));
- dispatch(actions.setSelectedEntries([nextFile]));
- return nextFile;
- }
- },
- openPrevFile: (path?: string) => (
- dispatch: (action) => void,
- getState: () => any
- ) => {
- const lastSelectedEntry = getLastSelectedEntry(getState());
- const prevFile = getPrevFile(
- path,
- lastSelectedEntry ? lastSelectedEntry.path : undefined,
- getState().app.searchMode
- ? GlobalSearch.getInstance().getResults()
- : getState().app.currentDirectoryEntries
- );
- if (prevFile !== undefined) {
- dispatch(actions.openFsEntry(prevFile));
- // dispatch(actions.setLastSelectedEntry(prevFile.path));
- dispatch(actions.setSelectedEntries([prevFile]));
- }
- },
- closeAllFiles: () => (dispatch: (action) => void) => {
- document.title = 'TagSpaces'; // TODO move to AppConfig
- dispatch(actions.closeAllFilesInt());
- },
- closeAllFilesInt: () => ({ type: types.CLOSE_ALL_FILES }),
reflectDeleteEntryInt: (path: string) => ({
type: types.REFLECT_DELETE_ENTRY,
path
@@ -2676,16 +1897,8 @@ export const actions = {
.map(tag => tag.title)
.join()}`;
dispatch(actions.reflectEditedEntryPaths([{ action, path }])); //[{ [path]: tags }]));
- /**
- * if its have openedFiles updateCurrentDirEntry is called from FolderContainer (useEffect -> ... if (openedFile.changed)
- */
- /*if (
- openedFiles.length === 0 ||
- !openedFiles.some(obj => obj.path === path) ||
- selectedEntries.length > 1
- ) {*/
dispatch(actions.updateCurrentDirEntry(path, { tags }));
- // }
+
if (updateIndex) {
GlobalSearch.getInstance().reflectUpdateSidecarTags(path, tags);
}
@@ -2849,171 +2062,6 @@ export const actions = {
PlatformIO.openFile(selectedFile, warningOpeningFilesExternally);
}
},
- openLink: (url: string, options = { fullWidth: true }) => (
- dispatch: (action) => void,
- getState: () => any
- ) => {
- const decodedURI = decodeURI(url);
- const lid = getURLParameter('tslid', url);
- const dPath = getURLParameter('tsdpath', url);
- const ePath = getURLParameter('tsepath', url);
- const cmdOpen = getURLParameter('cmdopen', url);
- if (cmdOpen && cmdOpen.length > 0) {
- const entryPath = decodeURIComponent(cmdOpen);
- getAllPropertiesPromise(entryPath)
- .then((fsEntry: TS.FileSystemEntry) => {
- if (fsEntry.isFile) {
- dispatch(actions.openFsEntry(fsEntry));
- dispatch(actions.setEntryFullWidth(options.fullWidth));
- } else {
- dispatch(actions.loadDirectoryContent(fsEntry.path, false, true));
- }
- return true;
- })
- .catch(err => {
- // console.log('Error opening from cmd ' + JSON.stringify(err));
- dispatch(
- actions.showNotification(
- i18n.t('Missing file or folder'),
- 'warning',
- true
- )
- );
- });
- } else if (lid && lid.length > 0) {
- const locationId = decodeURIComponent(lid);
- const directoryPath = dPath && decodeURIComponent(dPath);
- const entryPath = ePath && decodeURIComponent(ePath);
- // Check for relative paths
- const targetLocation: TS.Location = getLocation(getState(), locationId);
- if (targetLocation) {
- let openLocationTimer = 1000;
- const isCloudLocation = targetLocation.type === locationType.TYPE_CLOUD;
- const { currentLocationId } = getState().app;
- let skipListingLocation = directoryPath && directoryPath.length > 0;
- if (targetLocation.uuid !== currentLocationId) {
- dispatch(actions.openLocation(targetLocation, skipListingLocation));
- } else {
- openLocationTimer = 0;
- }
- const locationPath = getCleanLocationPath(targetLocation);
-
- // setTimeout is needed for case of a location switch, if no location swith the timer is 0
- setTimeout(() => {
- if (isCloudLocation) {
- // PlatformIO.enableObjectStoreSupport(targetLocation).then(() => {
- if (directoryPath && directoryPath.length > 0) {
- const newRelDir = getRelativeEntryPath(
- targetLocation,
- directoryPath
- );
- const dirFullPath =
- locationPath.length > 0
- ? locationPath + '/' + newRelDir
- : directoryPath;
- dispatch(actions.loadDirectoryContent(dirFullPath, false, true));
- } else {
- dispatch(actions.loadDirectoryContent(locationPath, false, true));
- }
-
- if (entryPath) {
- getAllPropertiesPromise(entryPath)
- .then((fsEntry: TS.FileSystemEntry) => {
- if (fsEntry) {
- dispatch(actions.openFsEntry(fsEntry));
- if (options.fullWidth) {
- dispatch(actions.setEntryFullWidth(true));
- }
- }
- return true;
- })
- .catch(() =>
- dispatch(
- actions.showNotification(
- i18n.t('core:invalidLink'),
- 'warning',
- true
- )
- )
- );
- }
- // });
- } else {
- // local files case
- if (directoryPath && directoryPath.length > 0) {
- if (
- directoryPath.includes('../') ||
- directoryPath.includes('..\\')
- ) {
- dispatch(
- actions.showNotification(
- i18n.t('core:invalidLink'),
- 'warning',
- true
- )
- );
- return true;
- }
- const dirFullPath =
- locationPath + PlatformIO.getDirSeparator() + directoryPath;
- dispatch(actions.loadDirectoryContent(dirFullPath, false, true));
- } else {
- dispatch(actions.loadDirectoryContent(locationPath, false, true));
- }
-
- if (entryPath && entryPath.length > 0) {
- if (entryPath.includes('../') || entryPath.includes('..\\')) {
- dispatch(
- actions.showNotification(
- i18n.t('core:invalidLink'),
- 'warning',
- true
- )
- );
- return true;
- }
- const entryFullPath =
- locationPath + PlatformIO.getDirSeparator() + entryPath;
- getAllPropertiesPromise(entryFullPath)
- .then((fsEntry: TS.FileSystemEntry) => {
- if (fsEntry) {
- dispatch(actions.openFsEntry(fsEntry));
- if (options.fullWidth) {
- dispatch(actions.setEntryFullWidth(true));
- }
- }
- return true;
- })
- .catch(() =>
- dispatch(
- actions.showNotification(
- i18n.t('core:invalidLink'),
- 'warning',
- true
- )
- )
- );
- }
- }
- }, openLocationTimer);
- } else {
- dispatch(
- actions.showNotification(i18n.t('core:invalidLink'), 'warning', true)
- );
- }
- } else if (decodedURI.endsWith(location.pathname)) {
- return true;
- } else if (
- // External URL case
- decodedURI.startsWith('http://') ||
- decodedURI.startsWith('https://') ||
- decodedURI.startsWith('file://')
- ) {
- openURLExternally(decodedURI);
- } else {
- console.log('Not supported URL format: ' + decodedURI);
- }
- },
saveFile: () => (dispatch: (action) => void) => {
dispatch(
actions.showNotification(
@@ -3084,6 +2132,18 @@ export const getCurrentLocationPath = (state: any) => {
}
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) {
@@ -3158,15 +2218,9 @@ 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 getOpenedFiles = (state: any) => state.app.openedFiles;
+export const getOpenLink = (state: any) => state.app.openLink;
export const getNotificationStatus = (state: any) =>
state.app.notificationStatus;
-/*
-export const getSearchResultCount = (state: any) =>
- Object.keys(state.locationIndex.searchQuery).length === 0
- ? 0
- : state.app.currentDirectoryEntries.length;
-*/
export const getCurrentLocationId = (state: any) => state.app.currentLocationId;
export const isEntryInFullWidth = (state: any) => state.app.isEntryInFullWidth;
//export const isLoading = (state: any) => state.app.isLoading;
diff --git a/app/reducers/io-actions.ts b/app/reducers/io-actions.ts
index b74b0f4c1..7d951df29 100644
--- a/app/reducers/io-actions.ts
+++ b/app/reducers/io-actions.ts
@@ -37,12 +37,10 @@ import {
copyFilesPromise,
getThumbPath,
loadFileMetaDataPromise,
- renameFilesPromise,
- toFsEntry
+ renameFilesPromise
} from '-/services/utils-io';
import i18n from '../services/i18n';
import { Pro } from '../pro';
-import TaggingActions from './tagging-actions';
import PlatformIO from '-/services/platform-facade';
import { TS } from '-/tagspaces.namespace';
import { generateThumbnailPromise } from '-/services/thumbsgenerator';
@@ -55,7 +53,8 @@ const actions = {
EXIFDateTime: true,
IPTCDescription: true,
IPTCTags: true
- }
+ },
+ addTags?
) => (dispatch: (actions: any) => void, getState: () => any) => {
const { currentDirectoryEntries } = getState().app;
if (!Pro || !Pro.ContentExtractor) {
@@ -70,7 +69,7 @@ const actions = {
currentDirectoryEntries,
dispatch,
AppActions,
- TaggingActions,
+ addTags,
options
);
},
diff --git a/app/reducers/settings.ts b/app/reducers/settings.ts
index 818d0743b..447cc5bc7 100644
--- a/app/reducers/settings.ts
+++ b/app/reducers/settings.ts
@@ -33,6 +33,7 @@ import {
mergeByProp,
updateByProp
} from '-/services/utils-io';
+import { historyKeys } from '../../extensions/tagspacespro/modules/history';
export const types = {
UPGRADE_SETTINGS: 'SETTINGS/UPGRADE_SETTINGS',
@@ -845,6 +846,7 @@ export function getLastVersionPromise(): Promise<string> {
}
// Selectors
+export const getEntrySplitSize = (state: any) => state.settings.entrySplitSize;
export const getMapTileServer = (state: any): TS.MapTileServer =>
AppConfig.mapTileServers
? AppConfig.mapTileServers[0]
@@ -866,6 +868,10 @@ export const isRevisionsEnabled = (state: any) =>
export const isReorderTags = (state: any) => state.settings.reorderTags;
export const getPrefixTagContainer = (state: any) =>
state.settings.prefixTagContainer;
+export const getGeoTaggingFormat = (state: any) =>
+ state.settings.geoTaggingFormat;
+export const getAddTagsToLibrary = (state: any) =>
+ state.settings.addTagsToLibrary;
export const getWarningOpeningFilesExternally = (state: any) =>
state.settings.warningOpeningFilesExternally;
export const getCheckForUpdateOnStartup = (state: any) =>
@@ -896,7 +902,7 @@ export const getAppDataPath = (state: any) => state.settings.appDataPath;
export const getSupportedLanguages = (state: any) => state.settings.languages;
export const getCalculateTags = (state: any) => state.settings.calculateTags;
export const getUseTrashCan = (state: any) => state.settings.useTrashCan;
-export const getPersistTagsInSidecarFile = (state: any) =>
+export const getPersistTagsInSidecarFile = (state: any): boolean =>
AppConfig.useSidecarsForFileTaggingDisableSetting
? AppConfig.useSidecarsForFileTagging
: state.settings.persistTagsInSidecarFile;
@@ -920,8 +926,16 @@ export const getDefaultDarkTheme = (state: any) =>
state.settings.currentDarkTheme;
export const isGlobalKeyBindingEnabled = (state: any) =>
state.settings.enableGlobalKeyboardShortcuts;
+export const getFileOpenHistoryKey = (state: any) =>
+ state.settings[historyKeys.fileOpenKey];
+export const getFolderOpenHistoryKey = (state: any) =>
+ state.settings[historyKeys.folderOpenKey];
+export const getFileEditHistoryKey = (state: any) =>
+ state.settings[historyKeys.fileEditKey];
export const getMainVerticalSplitSize = (state: any) =>
state.settings.mainVSplitSize;
+export const getNewHTMLFileContent = (state: any) =>
+ state.settings.newHTMLFileContent;
export const getTagGroupCollapsed = (state: any) =>
state.settings.tagGroupCollapsed;
export const getTagDelimiter = (state: any) => state.settings.tagDelimiter;
diff --git a/app/reducers/tagging-actions.ts b/app/reducers/tagging-actions.ts
index 8c5f11ddc..9377717cd 100644
--- a/app/reducers/tagging-actions.ts
+++ b/app/reducers/tagging-actions.ts
@@ -1,4 +1,5 @@
-/**
+/*
+/!**
* TagSpaces - universal file and folder organizer
* Copyright (C) 2017-present TagSpaces UG (haftungsbeschraenkt)
*
@@ -14,7 +15,7 @@
* 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';
@@ -348,13 +349,13 @@ const actions = {
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
@@ -569,10 +570,10 @@ const actions = {
}
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
@@ -642,10 +643,10 @@ const actions = {
}
return Promise.resolve(true);
}
- /**
+ /!**
* return new file path
* @param isFile
- */
+ *!/
function removeTagsFromFilename(isFile: boolean = true): Promise<string> {
if (!isFile) {
return Promise.resolve(path);
@@ -706,7 +707,7 @@ const actions = {
dispatch: (action) => Promise<boolean>
): Promise<boolean> => {
return dispatch(actions.removeTags(paths));
- /*for (const path of paths) {
+ /!*for (const path of paths) {
const success = await dispatch(actions.removeAllTagsFromFilename(path));
if (success) {
await dispatch(actions.removeAllTagsFromMetaData(path));
@@ -714,9 +715,9 @@ const actions = {
return Promise.resolve(false);
}
}
- return Promise.resolve(true);*/
+ return Promise.resolve(true);*!/
},
- /*removeAllTagsFromFilename: (path: string) => (
+ /!*removeAllTagsFromFilename: (path: string) => (
dispatch: (action) => Promise<boolean>,
getState: () => any
): Promise<boolean> => {
@@ -785,7 +786,7 @@ const actions = {
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
@@ -916,3 +917,4 @@ function collectTagsFromIndex(
}
export default actions;
+*/
diff --git a/app/tagspaces.namespace.d.ts b/app/tagspaces.namespace.d.ts
index 969a3a45b..0484a9cb8 100644
--- a/app/tagspaces.namespace.d.ts
+++ b/app/tagspaces.namespace.d.ts
@@ -161,13 +161,15 @@ export namespace TS {
description?: string;
isFile?: boolean;
autoSave?: boolean;
+ editMode?: boolean;
+ shouldReload?: boolean;
tags?: Array<TS.Tag>;
tagGroups?: Array<TS.TagGroup>;
color?: string;
perspective?: string;
- appName: string;
- appVersion: string;
- lastUpdated: number;
+ appName?: string;
+ appVersion?: string;
+ lastUpdated?: number;
customOrder?: CustomOrder;
perspectiveSettings?: PerspectiveSettings;
}