TagSpaces is an offline, open source, document manager with tagging support
add saving revisions for the editable files, add auto save checkbox (#1862)
Stanimir858afbe82fb9
diff --git a/app/AppConfig.ts b/app/AppConfig.tsindex 85559d713..dba23faa2 100644--- a/app/AppConfig.ts+++ b/app/AppConfig.ts@@ -1,5 +1,30 @@import * as AppConfig from '@tagspaces/tagspaces-common/AppConfig';AppConfig.mainToolbarHeight = 101;+AppConfig.editableFiles = [+ 'txt',+ 'md',+ 'coffee',+ 'c',+ 'cpp',+ 'css',+ 'groovy',+ 'haxe',+ 'xml',+ 'java',+ 'js',+ 'json',+ 'less',+ 'markdown',+ 'mdown',+ 'php',+ 'pl',+ 'py',+ 'rb',+ 'ini',+ 'sh',+ 'sql',+ 'mhtml'+];export default AppConfig;diff --git a/app/components/EntryContainer.tsx b/app/components/EntryContainer.tsxindex dea2bcff5..935abe305 100644--- a/app/components/EntryContainer.tsx+++ b/app/components/EntryContainer.tsx@@ -56,6 +56,7 @@ import {NavigateToFolderIcon,CancelIcon} from '-/components/CommonIcons';+import HistoryIcon from '@mui/icons-material/History';import { Split } from 'ts-react-splitter';import { buffer } from '@tagspaces/tagspaces-common/misc';import AppConfig from '-/AppConfig';@@ -66,7 +67,8 @@ import {baseName,extractFileName,extractDirectoryName,- generateSharingLink+ generateSharingLink,+ getBackupFileLocation} from '@tagspaces/tagspaces-common/paths';import { ProTooltip } from '-/components/HelperComponents';import EntryProperties from '-/components/EntryProperties';@@ -80,7 +82,8 @@ import {isDesktopMode,getKeyBindingObject,getMapTileServer,- getCurrentLanguage+ getCurrentLanguage,+ isRevisionsEnabled} from '-/reducers/settings';import TaggingActions from '-/reducers/tagging-actions';import {@@ -94,6 +97,9 @@ import { TS } from '-/tagspaces.namespace';import FileView from '-/components/FileView';import { Pro } from '-/pro';import { actions as LocationActions } from '-/reducers/locations';+import Revisions from '-/components/Revisions';+import { Switch } from '@mui/material';+import useFirstRender from '-/utils/useFirstRender';const defaultSplitSize = '7.86%'; // '7.2%'; // 103;// const openedSplitSize = AppConfig.isElectron ? 560 : 360;@@ -182,6 +188,7 @@ interface Props {tileServer: TS.MapTileServer;switchLocationType: (locationId: string) => Promise<string | null>;switchCurrentLocationType: (currentLocationId) => Promise<boolean>;+ revisionsEnabled: boolean;}const historyKeys = Pro && Pro.history ? Pro.history.historyKeys : {};@@ -216,12 +223,18 @@ function EntryContainer(props: Props) {// const [percent, setPercent] = React.useState<number | undefined>(undefined);const percent = useRef<number | undefined>(undefined);+ const timer = useRef(null);const openedFile = openedFiles[0];+ const openedFilePath = useRef(openedFile.path);// const [currentEntry, setCurrentEntry] = useState<OpenedEntry>(openedFile);const [isPropertiesPanelVisible, setPropertiesPanelVisible] = useState<boolean>(false);++ const [isRevisionPanelVisible, setRevisionPanelVisible] = useState<boolean>(+ false+ );const [isFullscreen, setFullscreen] = useState<boolean>(false);// eslint-disable-next-line no-unused-varsconst [ignored, forceUpdate] = useReducer(x => x + 1, 0);@@ -248,6 +261,7 @@ function EntryContainer(props: Props) {HTMLDivElement>(null);const fileChanged = useRef<boolean>(false);+ const firstRender = useFirstRender();useEventListener('message', e => {if (typeof e.data === 'string') {@@ -319,6 +333,28 @@ function EntryContainer(props: Props) {}});+ useEffect(() => {+ if (openedFile.isAutoSaveEnabled) {+ if (fileChanged.current) {+ timer.current = setInterval(() => {+ if (openedFile.isAutoSaveEnabled && fileChanged.current) {+ startSavingFile();+ console.debug('autosave');+ }+ }, 40000);+ } else if (timer.current) {+ clearInterval(timer.current);+ }+ } else if (timer.current) {+ clearInterval(timer.current);+ }+ return () => {+ if (timer.current) {+ clearInterval(timer.current);+ }+ };+ }, [openedFile.isAutoSaveEnabled, fileChanged.current]);+useEffect(() => {if (fileViewer &&@@ -333,17 +369,17 @@ function EntryContainer(props: Props) {}, [settings.currentTheme]);useEffect(() => {- if (openedFiles.length > 0) {- if (- // openedFile.editMode &&- // openedFile.changed &&- fileChanged.current- // openedFile.shouldReload === false- ) {- setSaveBeforeReloadConfirmDialogOpened(true);- }+ // if (openedFiles.length > 0) {+ if (+ !firstRender &&+ // openedFile.editMode &&+ // openedFile.changed &&+ fileChanged.current+ // openedFile.shouldReload === false+ ) {+ setSaveBeforeReloadConfirmDialogOpened(true);}- }, [openedFiles, isReadOnlyMode]); // , settings]);+ }, [openedFilePath.current, isReadOnlyMode]); // , settings]);// always open for dirsconst isPropPanelVisible = openedFile.isFile@@ -545,16 +581,21 @@ function EntryContainer(props: Props) {try {// @ts-ignoreconst textContent = fileViewer.current.contentWindow.getContent();- setSavingInProgress(true);- saveFile(textContent).then(() => {- fileChanged.current = false;- showNotification(- i18n.t('core:fileSavedSuccessfully'),- NotificationTypes.default- );- // change state will not render DOT before file name too- setSavingInProgress(false);- });+ //check if file is changed+ if (fileChanged.current) {+ setSavingInProgress(true);+ saveFile(textContent).then(success => {+ if (success) {+ fileChanged.current = false;+ showNotification(+ i18n.t('core:fileSavedSuccessfully'),+ NotificationTypes.default+ );+ }+ // change state will not render DOT before file name too+ setSavingInProgress(false);+ });+ }} catch (e) {setSavingInProgress(false);console.debug('function getContent not exist for video file:', e);@@ -562,13 +603,28 @@ function EntryContainer(props: Props) {}};- const saveFile = (textContent: string) => {+ const saveFile = (textContent: string): Promise<boolean> => {return props.switchLocationType(openedFile.locationId)- .then(currentLocationId => {+ .then(async currentLocationId => {+ if (Pro && props.revisionsEnabled) {+ const id = await Pro.MetaOperations.getMetadataID(+ openedFile.path,+ openedFile.uuid+ );+ const targetPath = getBackupFileLocation(+ openedFile.path,+ id,+ PlatformIO.getDirSeparator()+ );+ await PlatformIO.copyFilePromiseOverwrite(+ openedFile.path,+ targetPath+ );+ }// TODO check for timestamp on filesystem and ask to overwrite the changes therereturn PlatformIO.saveTextFilePromise(- openedFile.path,+ { path: openedFile.path, lmdt: openedFile.lmdt },textContent,true)@@ -593,11 +649,14 @@ function EntryContainer(props: Props) {.catch(error => {// setSavingInProgress(false);showNotification(- i18n.t('core:errorSavingFile'),- NotificationTypes.error+ i18n.t('core:errorSavingFile') + ': ' + error.message,+ NotificationTypes.error,+ false);console.log('Error saving file ' + openedFile.path + ' - ' + error);- return props.switchCurrentLocationType(currentLocationId);+ return props+ .switchCurrentLocationType(currentLocationId)+ .then(() => false);});});};@@ -653,13 +712,18 @@ function EntryContainer(props: Props) {};const togglePanel = () => {- if (isPropPanelVisible) {+ if (isPropPanelVisible && !isRevisionPanelVisible) {closePanel();} else {openPanel();}};+ const toggleRevisions = () => {+ setRevisionPanelVisible(!isRevisionPanelVisible);+ openPanel();+ };+const openNextFile = () => {props.openNextFile(openedFile.path);};@@ -745,19 +809,48 @@ function EntryContainer(props: Props) {);};+ const isEditable = AppConfig.editableFiles.some(ext =>+ openedFile.path.endsWith(ext)+ );+const renderFileToolbar = classes => (<div className={classes.toolbar2}><div className={classes.flexLeft}><Tooltip title={i18n.t('core:toggleProperties')}><IconButtonaria-label={i18n.t('core:toggleProperties')}- onClick={togglePanel}+ onClick={() => {+ togglePanel();+ if (isRevisionPanelVisible) {+ setRevisionPanelVisible(false);+ }+ }}data-tid="fileContainerToggleProperties"size="large">- <DetailsIcon color={isPropPanelVisible ? 'primary' : 'action'} />+ <DetailsIcon+ color={+ isPropPanelVisible && !isRevisionPanelVisible+ ? 'primary'+ : 'action'+ }+ /></IconButton></Tooltip>+ {Pro && isEditable && props.revisionsEnabled && (+ <Tooltip title={i18n.t('core:editHistory')}>+ <IconButton+ aria-label={i18n.t('core:editHistory')}+ onClick={toggleRevisions}+ data-tid="editHistoryTID"+ size="large"+ >+ <HistoryIcon+ color={isRevisionPanelVisible ? 'primary' : 'action'}+ />+ </IconButton>+ </Tooltip>+ )}<Tooltip title={i18n.t('core:downloadFile')}><IconButtonaria-label={i18n.t('core:downloadFile')}@@ -1170,6 +1263,41 @@ function EntryContainer(props: Props) {alignItems: 'center'}}>+ {isEditable && props.revisionsEnabled && (+ <Tooltip title={i18n.t('core:autosave')}>+ <Switch+ data-tid="autoSaveTID"+ checked={+ openedFile.isAutoSaveEnabled !== undefined &&+ openedFile.isAutoSaveEnabled+ }+ onChange={(+ event: React.ChangeEvent<HTMLInputElement>+ ) => {+ const autoSave = event.target.checked;+ props+ .switchLocationType(openedFile.locationId)+ .then(currentLocationId => {+ Pro.MetaOperations.saveFsEntryMeta(+ openedFile.path,+ { autoSave }+ ).then(entryMeta => {+ updateOpenedFile(openedFile.path, entryMeta).then(+ () => {+ props.switchCurrentLocationType(+ currentLocationId+ );+ }+ );+ });+ });+ }}+ name="autoSave"+ color="primary"+ />+ </Tooltip>+ )}+{editingSupported && openedFile.editMode && (<ButtonGroup><Tooltip title={i18n.t('core:cancelEditing')}>@@ -1245,23 +1373,27 @@ function EntryContainer(props: Props) {}}>{openedFile.isFile ? renderFileToolbar(classes) : renderFolderToolbar()}- <EntryProperties- key={openedFile.path}- openedEntry={openedFile}- tagDelimiter={settings.tagDelimiter}- renameFile={renameFile}- renameDirectory={renameDirectory}- addTags={addTags}- removeTags={removeTags}- removeAllTags={removeAllTags}- updateOpenedFile={updateOpenedFile}- updateThumbnailUrl={updateThumbnailUrl}- showNotification={showNotification}- isReadOnlyMode={isReadOnlyMode}- currentDirectoryPath={currentDirectoryPath}- tileServer={tileServer}- sharingLink={sharingLink}- />+ {isRevisionPanelVisible ? (+ <Revisions />+ ) : (+ <EntryProperties+ key={openedFile.path}+ openedEntry={openedFile}+ tagDelimiter={settings.tagDelimiter}+ renameFile={renameFile}+ renameDirectory={renameDirectory}+ addTags={addTags}+ removeTags={removeTags}+ removeAllTags={removeAllTags}+ updateOpenedFile={updateOpenedFile}+ updateThumbnailUrl={updateThumbnailUrl}+ showNotification={showNotification}+ isReadOnlyMode={isReadOnlyMode}+ currentDirectoryPath={currentDirectoryPath}+ tileServer={tileServer}+ sharingLink={sharingLink}+ />+ )}</div>);@@ -1419,6 +1551,7 @@ function mapStateToProps(state) {keyBindings: getKeyBindingObject(state),isDesktopMode: isDesktopMode(state),tileServer: getMapTileServer(state),+ revisionsEnabled: isRevisionsEnabled(state),language: getCurrentLanguage(state)};}diff --git a/app/components/EntryProperties.tsx b/app/components/EntryProperties.tsxindex cd7c85c41..e8c1bdd6f 100644--- a/app/components/EntryProperties.tsx+++ b/app/components/EntryProperties.tsx@@ -71,9 +71,9 @@ import {convertMarkDown,fileNameValidation,dirNameValidation,- normalizeUrl,- getUuid+ normalizeUrl} from '-/services/utils-io';+import { getUuid } from '@tagspaces/tagspaces-common/utils-io';import { parseGeoLocation } from '-/utils/geo';import { Pro } from '../pro';import PlatformIO from '../services/platform-facade';@@ -104,6 +104,7 @@ import { actions as LocationActions } from '-/reducers/locations';import { actions as AppActions } from '-/reducers/app';import useFirstRender from '-/utils/useFirstRender';import SharingLinkDialog from '-/components/dialogs/SharingLinkDialog';+import { saveFsEntryMeta } from '../../extensions/tagspacespro/modules/metaoperations';const ThumbnailChooserDialog =Pro && Pro.UI ? Pro.UI.ThumbnailChooserDialog : false;@@ -362,10 +363,9 @@ function EntryProperties(props: Props) {props.switchLocationType(props.openedEntry.locationId).then(currentLocationId => {- Pro.MetaOperations.saveDescription(- currentEntry.path,- editDescription.current- )+ Pro.MetaOperations.saveFsEntryMeta(currentEntry.path, {+ description: editDescription.current+ }).then(entryMeta => {editDescription.current = undefined;props.updateOpenedFile(currentEntry.path, entryMeta);@@ -488,7 +488,7 @@ function EntryProperties(props: Props) {props.switchLocationType(props.openedEntry.locationId).then(currentLocationId => {- Pro.MetaOperations.saveColor(currentEntry.path, color)+ Pro.MetaOperations.saveFsEntryMeta(currentEntry.path, { color }).then(entryMeta => {// if (props.entryPath === props.currentDirectoryPath) {props.setLastBackgroundColorChange(diff --git a/app/components/FileView.tsx b/app/components/FileView.tsxindex ec246a777..e703e7ea4 100644--- a/app/components/FileView.tsx+++ b/app/components/FileView.tsx@@ -30,11 +30,11 @@ import { TS } from '-/tagspaces.namespace';interface Props {openedFile: OpenedEntry;- isFullscreen: boolean;+ isFullscreen?: boolean;fileViewer: MutableRefObject<HTMLIFrameElement>;fileViewerContainer: MutableRefObject<HTMLDivElement>;searchQuery: TS.SearchQuery;- toggleFullScreen: () => void;+ toggleFullScreen?: () => void;theme: any;currentTheme: string;}diff --git a/app/components/Revisions.tsx b/app/components/Revisions.tsxnew file mode 100644index 000000000..36497bef5--- /dev/null+++ b/app/components/Revisions.tsx@@ -0,0 +1,245 @@+/**+ * 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, { useEffect, useState } from 'react';+import {+ getBackupFileLocation,+ extractContainingDirectoryPath+} from '@tagspaces/tagspaces-common/paths';+import withStyles from '@mui/styles/withStyles';+import {+ actions as AppActions,+ getOpenedFiles,+ OpenedEntry+} from '-/reducers/app';+import { connect } from 'react-redux';+import { getCurrentLanguage } from '-/reducers/settings';+import PlatformIO from '-/services/platform-facade';+import { TS } from '-/tagspaces.namespace';+import { format, formatDistanceToNow } from 'date-fns';+import i18n from '-/services/i18n';+import { bindActionCreators } from 'redux';+import DeleteIcon from '@mui/icons-material/Delete';+import PreviewIcon from '@mui/icons-material/Preview';+import RestoreIcon from '@mui/icons-material/Restore';+import IconButton from '@mui/material/IconButton';+import AppConfig from '-/AppConfig';+import {+ Paper,+ Table,+ TableBody,+ TableCell,+ TableContainer,+ TableHead,+ TablePagination,+ TableRow+} from '@mui/material';+import { Pro } from '-/pro';+import FilePreviewDialog from '-/components/dialogs/FilePreviewDialog';++interface Props {+ // openedFile: OpenedEntry;+ openedFiles: Array<OpenedEntry>;+ openEntry: (path: string) => void;+ theme: any;+}++function Revisions(props: Props) {+ const [rows, setRows] = useState<Array<TS.FileSystemEntry>>();+ const [page, setPage] = React.useState<number>(0);+ const [rowsPerPage, setRowsPerPage] = React.useState<number>(5);+ const [previewDialogEntry, setPreviewDialogEntry] = useState<+ TS.FileSystemEntry+ >(undefined);+ const { openedFiles, theme } = props;+ // const [ignored, forceUpdate] = useReducer(x => x + 1, 0);++ useEffect(() => {+ // if no history item path - not loadHistoryItems for items in metaFolder+ const openedFile = openedFiles[0];+ if (openedFile && openedFile.path.indexOf(AppConfig.metaFolder) === -1) {+ loadHistoryItems(openedFile);+ }+ }, [openedFiles]);++ function loadHistoryItems(openedFile: OpenedEntry) {+ Pro.MetaOperations.getMetadataID(openedFile.path, openedFile.uuid).then(+ id => {+ openedFile.uuid = id;+ const backupFilePath = getBackupFileLocation(+ openedFile.path,+ openedFile.uuid,+ PlatformIO.getDirSeparator()+ );+ const backupPath = extractContainingDirectoryPath(+ backupFilePath,+ PlatformIO.getDirSeparator()+ );+ PlatformIO.listDirectoryPromise(backupPath, []).then(h =>+ setRows(h.sort((a, b) => (a.lmdt < b.lmdt ? 1 : -1)))+ );+ }+ );+ }++ const handleChangePage = (event: unknown, newPage: number) => {+ setPage(newPage);+ };++ const handleChangeRowsPerPage = (+ event: React.ChangeEvent<HTMLInputElement>+ ) => {+ setRowsPerPage(parseInt(event.target.value, 10));+ setPage(0);+ };++ function restoreRevision(revisionPath) {+ const openedFile = openedFiles[0];+ const targetPath = getBackupFileLocation(+ openedFile.path,+ openedFile.uuid,+ PlatformIO.getDirSeparator()+ );+ PlatformIO.copyFilePromiseOverwrite(openedFile.path, targetPath).then(+ () => {+ PlatformIO.copyFilePromiseOverwrite(+ revisionPath,+ openedFile.path+ ).then(() => props.openEntry(openedFile.path)); // loadHistoryItems(openedFile));+ }+ );+ }++ // Avoid a layout jump when reaching the last page with empty rows.+ /*const emptyRows =+ rows && page > 0 ? Math.max(0, (1 + page) * rowsPerPage - rows.length) : 0;*/++ return (+ <div>+ <h2>{i18n.t('revisions')}</h2>+ <TableContainer component={Paper}>+ <Table sx={{ minWidth: 650 }} aria-label="revisions table">+ <TableHead>+ <TableRow>+ <TableCell>File</TableCell>+ <TableCell align="right">Revision Date</TableCell>+ <TableCell align="right">Review/Delete</TableCell>+ </TableRow>+ </TableHead>+ <TableBody>+ {rows &&+ rows+ .slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)+ .map(row => (+ <TableRow+ key={row.path}+ sx={{ '&:last-child td, &:last-child th': { border: 0 } }}+ >+ <TableCell component="th" scope="row">+ {row.name}+ </TableCell>+ <TableCell+ align="right"+ title={format(row.lmdt, 'dd.MM.yyyy HH:mm:ss')}+ >+ {formatDistanceToNow(row.lmdt, {+ includeSeconds: true,+ addSuffix: true+ // locale: https://date-fns.org/v2.29.3/docs/formatDistanceToNow#usage+ })}+ </TableCell>+ <TableCell align="right">+ <IconButton+ aria-label={i18n.t('core:view')}+ onClick={() => setPreviewDialogEntry(row)}+ data-tid="viewRevisionTID"+ size="large"+ >+ <PreviewIcon color="primary" />+ </IconButton>+ <IconButton+ aria-label={i18n.t('core:restore')}+ onClick={() => restoreRevision(row.path)}+ data-tid="restoreRevisionTID"+ size="large"+ >+ <RestoreIcon color="primary" />+ </IconButton>+ <IconButton+ aria-label={i18n.t('core:delete')}+ onClick={() => {+ PlatformIO.deleteFilePromise(+ row.path,+ true+ ).then(() => loadHistoryItems(openedFiles[0]));+ }}+ data-tid="deleteRevisionTID"+ size="large"+ >+ <DeleteIcon color="primary" />+ </IconButton>+ </TableCell>+ </TableRow>+ ))}+ {/*{emptyRows > 0 && (+ <TableRow style={{ height: 53 * emptyRows }}>+ <TableCell colSpan={6} />+ </TableRow>+ )}*/}+ </TableBody>+ </Table>+ </TableContainer>+ {rows && rowsPerPage < rows.length && (+ <TablePagination+ rowsPerPageOptions={[5, 10, 25]}+ component="div"+ count={rows.length}+ rowsPerPage={rowsPerPage}+ page={page}+ onPageChange={handleChangePage}+ onRowsPerPageChange={handleChangeRowsPerPage}+ />+ )}+ <FilePreviewDialog+ fsEntry={previewDialogEntry}+ open={previewDialogEntry !== undefined}+ onClose={() => setPreviewDialogEntry(undefined)}+ />+ </div>+ );+}++function mapStateToProps(state) {+ return {+ language: getCurrentLanguage(state),+ openedFiles: getOpenedFiles(state)+ };+}++function mapActionCreatorsToProps(dispatch) {+ return bindActionCreators(+ {+ openEntry: AppActions.openEntry+ },+ dispatch+ );+}+export default connect(+ mapStateToProps,+ mapActionCreatorsToProps+)(withStyles(undefined, { withTheme: true })(Revisions));diff --git a/app/components/TagsSelect.tsx b/app/components/TagsSelect.tsxindex cf6f46736..b36c33ff2 100644--- a/app/components/TagsSelect.tsx+++ b/app/components/TagsSelect.tsx@@ -25,7 +25,7 @@ import { getTagColor, getTagTextColor } from '-/reducers/settings';import EntryTagMenu from '-/components/menus/EntryTagMenu';import { TS } from '-/tagspaces.namespace';import TagContainer from '-/components/TagContainer';-import { getUuid } from '-/services/utils-io';+import { getUuid } from '@tagspaces/tagspaces-common/utils-io';import { getAllTags } from '-/services/taglibrary-utils';import { Box } from '@mui/material';diff --git a/app/components/dialogs/CreateEditLocationDialog.tsx b/app/components/dialogs/CreateEditLocationDialog.tsxindex 2c6d04c42..96cbb2bf8 100644--- a/app/components/dialogs/CreateEditLocationDialog.tsx+++ b/app/components/dialogs/CreateEditLocationDialog.tsx@@ -74,7 +74,7 @@ import WebdavForm from '-/components/dialogs/WebdavForm';import useTheme from '@mui/styles/useTheme';import useMediaQuery from '@mui/material/useMediaQuery';import { loadLocationDataPromise } from '-/services/utils-io';-import { getUuid } from '-/services/utils-io';+import { getUuid } from '@tagspaces/tagspaces-common/utils-io';const styles: any = theme => ({formControl: {diff --git a/app/components/dialogs/CreateTagGroupDialog.tsx b/app/components/dialogs/CreateTagGroupDialog.tsxindex 73e0f9414..b9b6d7b10 100644--- a/app/components/dialogs/CreateTagGroupDialog.tsx+++ b/app/components/dialogs/CreateTagGroupDialog.tsx@@ -36,7 +36,7 @@ import { getLocations } from '-/reducers/locations';import DialogCloseButton from '-/components/dialogs/DialogCloseButton';import useTheme from '@mui/styles/useTheme';import useMediaQuery from '@mui/material/useMediaQuery';-import { getUuid } from '-/services/utils-io';+import { getUuid } from '@tagspaces/tagspaces-common/utils-io';interface Props {open: boolean;diff --git a/app/components/dialogs/FilePreviewDialog.tsx b/app/components/dialogs/FilePreviewDialog.tsxnew file mode 100644index 000000000..d49228756--- /dev/null+++ b/app/components/dialogs/FilePreviewDialog.tsx@@ -0,0 +1,229 @@+/**+ * 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, { MutableRefObject, useEffect, useRef, useState } from 'react';+import DialogContent from '@mui/material/DialogContent';+import DialogTitle from '@mui/material/DialogTitle';+import Dialog from '@mui/material/Dialog';+import DialogCloseButton from '-/components/dialogs/DialogCloseButton';+import { extractContainingDirectoryPath } from '@tagspaces/tagspaces-common/paths';+import { actions as AppActions, OpenedEntry } from '-/reducers/app';+import { TS } from '-/tagspaces.namespace';+import { findExtensionsForEntry } from '-/services/utils-io';+import {+ getCurrentLanguage,+ getCurrentTheme,+ getSupportedFileTypes+} from '-/reducers/settings';+import { connect } from 'react-redux';+import i18n from '-/services/i18n';+import FileView from '-/components/FileView';+import useEventListener from '-/utils/useEventListener';+import PlatformIO from '-/services/platform-facade';+import AppConfig from '-/AppConfig';+import { bindActionCreators } from 'redux';+import { actions as LocationActions } from '-/reducers/locations';++interface Props {+ open: boolean;+ onClose: () => void;+ fsEntry: TS.FileSystemEntry;+ supportedFileTypes: Array<any>;+ currentTheme: string;+ switchCurrentLocationType: (currentLocationId) => Promise<boolean>;+ switchLocationType: (locationId: string) => Promise<string | null>;+}++function FilePreviewDialog(props: Props) {+ const { open = false, onClose, fsEntry } = props;+ // const [fileOpenerURL, setFileOpenerURL] = useState<string>('about:blank');+ const fileViewer: MutableRefObject<HTMLIFrameElement> = useRef<+ HTMLIFrameElement+ >(null);+ const fileViewerContainer: MutableRefObject<HTMLDivElement> = useRef<+ HTMLDivElement+ >(null);++ const openedFile: OpenedEntry = fsEntry+ ? findExtensionsForEntry(+ fsEntry.uuid,+ props.supportedFileTypes,+ fsEntry.path,+ fsEntry.isFile+ )+ : undefined;++ useEventListener('message', e => {+ if (typeof e.data === 'string') {+ // console.log(e.data);+ try {+ const dataObj = JSON.parse(e.data);+ handleMessage(dataObj);+ } catch (ex) {+ console.debug(+ 'useEventListener message:' + e.data + ' parse error:',+ ex+ );+ }+ }+ });++ const handleMessage = (data: any) => {+ let message;+ let textFilePath;+ switch (data.command) { // todo use diff command+ case 'loadDefaultTextContent':+ if (!openedFile || !openedFile.path) {+ // || openedFile.changed) {+ break;+ }+ textFilePath = openedFile.path;++ if (+ fileViewer &&+ fileViewer.current &&+ fileViewer.current.contentWindow &&+ // @ts-ignore+ fileViewer.current.contentWindow.setTheme+ ) {+ // @ts-ignore call setContent from iframe+ fileViewer.current.contentWindow.setTheme(props.currentTheme);+ }+ // TODO make loading index.html for folders configurable+ // if (!this.state.currentEntry.isFile) {+ // textFilePath += '/index.html';+ // }+ props+ .switchLocationType(openedFile.locationId)+ .then(currentLocationId => {+ PlatformIO.loadTextFilePromise(+ textFilePath,+ data.preview ? data.preview : false+ )+ .then(content => {+ const UTF8_BOM = '\ufeff';+ if (content.indexOf(UTF8_BOM) === 0) {+ // eslint-disable-next-line no-param-reassign+ content = content.substr(1);+ }+ let fileDirectory = extractContainingDirectoryPath(+ textFilePath,+ PlatformIO.getDirSeparator()+ );+ if (AppConfig.isWeb) {+ fileDirectory =+ extractContainingDirectoryPath(+ // eslint-disable-next-line no-restricted-globals+ location.href,+ PlatformIO.getDirSeparator()+ ) ++ '/' ++ fileDirectory;+ }+ if (+ fileViewer &&+ fileViewer.current &&+ fileViewer.current.contentWindow &&+ // @ts-ignore+ fileViewer.current.contentWindow.setContent+ ) {+ // @ts-ignore call setContent from iframe+ fileViewer.current.contentWindow.setContent(+ content,+ fileDirectory,+ !openedFile.editMode+ );+ }+ if (currentLocationId) {+ return props.switchCurrentLocationType(currentLocationId);+ }+ })+ .catch(err => {+ console.warn('Error loading text content ' + err);+ if (currentLocationId) {+ return props.switchCurrentLocationType(currentLocationId);+ }+ });+ });+ break;+ }+ };++ if (!fsEntry) {+ return null;+ }++ return (+ <Dialog+ open={open}+ onClose={onClose}+ keepMounted+ scroll="paper"+ /*fullWidth={true}+ maxWidth="md"*/+ PaperProps={{ sx: { width: "100%", height: "100%" } }}+ BackdropProps={{ style: { backgroundColor: 'transparent' } }}+ >+ <DialogTitle data-tid="importDialogTitle">+ {/*{i18n.t('core:importDialogTitle')}*/}+ <DialogCloseButton onClose={onClose} />+ </DialogTitle>+ <DialogContent+ style={{+ marginLeft: 'auto',+ marginRight: 'auto',+ width: '90%',+ flexGrow: 1+ }}+ >+ <p>{props.fsEntry.path}</p>+ <FileView+ key="FileViewPreviewID"+ openedFile={openedFile}+ fileViewer={fileViewer}+ fileViewerContainer={fileViewerContainer}+ currentTheme={props.currentTheme}+ />+ </DialogContent>+ </Dialog>+ );+}++function mapStateToProps(state) {+ return {+ language: getCurrentLanguage(state),+ supportedFileTypes: getSupportedFileTypes(state),+ currentTheme: getCurrentTheme(state)+ };+}++function mapActionCreatorsToProps(dispatch) {+ return bindActionCreators(+ {+ switchCurrentLocationType: AppActions.switchCurrentLocationType,+ switchLocationType: LocationActions.switchLocationType+ },+ dispatch+ );+}++export default connect(+ mapStateToProps,+ mapActionCreatorsToProps+ // @ts-ignore+)(FilePreviewDialog);diff --git a/app/components/dialogs/settings/SettingsAdvanced.tsx b/app/components/dialogs/settings/SettingsAdvanced.tsxindex 5e871a03b..a436ca892 100644--- a/app/components/dialogs/settings/SettingsAdvanced.tsx+++ b/app/components/dialogs/settings/SettingsAdvanced.tsx@@ -73,6 +73,7 @@ interface Props {warningOpeningFilesExternally: boolean) => void;setSaveTagInLocation: (saveTagInLocation: boolean) => void;+ setRevisionsEnabled: (enabled: boolean) => void;showResetSettings: (showDialog: boolean) => void;tileServers: Array<TS.MapTileServer>;setGeoTaggingFormat: (geoTaggingFormat: string) => void;@@ -207,7 +208,25 @@ function SettingsAdvanced(props: Props) {</ListItem></>)}-+ <ListItem className={classes.listItem}>+ <ListItemText+ primary={+ <>+ {i18n.t('setRevisionsEnabled')}+ <InfoIcon tooltip={i18n.t('core:setRevisionsEnabledHelp')} />+ <ProLabel />+ </>+ }+ />+ <Switch+ data-tid="setRevisionsEnabledTID"+ disabled={!Pro}+ onClick={() =>+ props.setRevisionsEnabled(!props.settings.isRevisionsEnabled)+ }+ checked={props.settings.isRevisionsEnabled}+ />+ </ListItem><ListItem className={classes.listItem}><ListItemTextprimary={@@ -345,7 +364,8 @@ function mapActionCreatorsToProps(dispatch) {setEnableWS: SettingsActions.setEnableWS,setSaveTagInLocation: SettingsActions.setSaveTagInLocation,setGeoTaggingFormat: SettingsActions.setGeoTaggingFormat,- setHistory: SettingsActions.setHistory+ setHistory: SettingsActions.setHistory,+ setRevisionsEnabled: SettingsActions.setRevisionsEnabled},dispatch);diff --git a/app/components/dialogs/settings/SettingsDialog.tsx b/app/components/dialogs/settings/SettingsDialog.tsxindex 17cc02ac8..0eb78d68a 100644--- a/app/components/dialogs/settings/SettingsDialog.tsx+++ b/app/components/dialogs/settings/SettingsDialog.tsx@@ -45,7 +45,7 @@ import {import { clearAllURLParams } from '-/utils/dom';import SettingsAdvanced from '-/components/dialogs/settings/SettingsAdvanced';import DialogCloseButton from '-/components/dialogs/DialogCloseButton';-import { getUuid } from '-/services/utils-io';+import { getUuid } from '@tagspaces/tagspaces-common/utils-io';import Links from '-/content/links';const styles: any = () => ({diff --git a/app/containers/MainPage.tsx b/app/containers/MainPage.tsxindex 59645881d..21562a639 100644--- a/app/containers/MainPage.tsx+++ b/app/containers/MainPage.tsx@@ -91,7 +91,6 @@ import { actions as LocationIndexActions } from '-/reducers/location-index';import MoveOrCopyFilesDialog from '-/components/dialogs/MoveOrCopyFilesDialog';import PlatformIO from '-/services/platform-facade';import { Pro } from '-/pro';-import { getUuid } from '-/services/utils-io';const drawerWidth = 320;const body = document.getElementsByTagName('body')[0];@@ -749,7 +748,6 @@ function MainPage(props: Props) {open={props.isProTeaserVisible}onClose={toggleProTeaser}openURLExternally={openURLExternally}- // key={getUuid()} // TODO rethink to remove this/>)}{props.isUploadProgressDialogOpened && (diff --git a/app/locales/en/core.json b/app/locales/en/core.jsonindex a940e08b9..779ce0755 100644--- a/app/locales/en/core.json+++ b/app/locales/en/core.json@@ -728,5 +728,9 @@"qrCode": "QR Code","linkValidity": "Link validity time","linkValidityTooltip": "Time for which the link is valid",+ "revisions": "Revisions",+ "setRevisionsEnabled": "Enable Revisions",+ "setRevisionsEnabledHelp": "Save file edit change history",+ "autosave": "Auto save","-": "-"}diff --git a/app/package.json b/app/package.jsonindex 5401517d1..34a3a4cbb 100644--- a/app/package.json+++ b/app/package.json@@ -16,7 +16,7 @@"@tagspaces/extensions": "1.0.71"},"nodeDependencies": {- "@tagspaces/tagspaces-ws": "2.1.14",+ "@tagspaces/tagspaces-ws": "2.1.17","@tagspaces/extensions": "1.0.71","sharp": "0.31.3"}diff --git a/app/reducers/app.ts b/app/reducers/app.tsindex f3cf21e44..9dd323ec2 100644--- a/app/reducers/app.ts+++ b/app/reducers/app.ts@@ -53,11 +53,11 @@ import {loadJSONFile,merge,setLocationType,- getUuid,getRelativeEntryPath,getCleanLocationPath,updateFsEntries} from '-/services/utils-io';+import { getUuid } from '@tagspaces/tagspaces-common/utils-io';import i18n from '../services/i18n';import { Pro } from '../pro';import { actions as LocationIndexActions } from './location-index';@@ -160,6 +160,7 @@ export const NotificationTypes = {};export type OpenedEntry = {+ uuid: string;path: string;url?: string;size: number;@@ -170,6 +171,7 @@ export type OpenedEntry = {editingExtensionPath?: string;editingExtensionId?: string;isFile?: boolean;+ isAutoSaveEnabled?: boolean;color?: string;description?: string;perspective?: string;@@ -1651,7 +1653,7 @@ export const actions = {formatDateTime4Tag(new Date(), true) +AppConfig.endTagContainer +'.txt';- PlatformIO.saveFilePromise(filePath, '', true)+ PlatformIO.saveFilePromise({ path: filePath }, '', true).then(() => {dispatch(actions.reflectCreateEntry(filePath, true));dispatch(@@ -1731,7 +1733,7 @@ export const actions = {} else if (fileType === 'md') {fileContent = content + ' \n\n' + creationMeta + '\n';}- PlatformIO.saveFilePromise(filePath, fileContent, false)+ PlatformIO.saveFilePromise({ path: filePath }, fileContent, false).then((fsEntry: TS.FileSystemEntry) => {dispatch(actions.reflectCreateEntry(filePath, true));dispatch(actions.openFsEntry(fsEntry)); // TODO return fsEntry from saveFilePromise and simplify@@ -2017,7 +2019,7 @@ export const actions = {},updateOpenedFile: (entryPath: string,- fsEntryMeta: any // FileSystemEntryMeta,+ fsEntryMeta: any // TS.FileSystemEntryMeta,// isFile: boolean = true) => (dispatch: (action) => void, getState: () => any): Promise<boolean> => {const { openedFiles } = getState().app;@@ -2032,6 +2034,7 @@ export const actions = {if (!entryExist) {entryForOpening = findExtensionsForEntry(+ fsEntryMeta.id || fsEntryMeta.uuid,supportedFileTypes,entryPath,entryProps.isFile@@ -2063,6 +2066,11 @@ export const actions = {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;@@ -2131,6 +2139,7 @@ export const actions = {const { supportedFileTypes } = getState().settings;// TODO decide to copy all props from {...fsEntry} into openedEntryentryForOpening = findExtensionsForEntry(+ fsEntry.uuid,supportedFileTypes,fsEntry.path,fsEntry.isFile@@ -2164,6 +2173,11 @@ export const actions = {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 configdiff --git a/app/reducers/io-actions.ts b/app/reducers/io-actions.tsindex 2ff420eb1..e40b56c02 100644--- a/app/reducers/io-actions.ts+++ b/app/reducers/io-actions.ts@@ -263,7 +263,7 @@ const actions = {: event.target.result;try {const fsEntry: TS.FileSystemEntry = await PlatformIO.saveBinaryFilePromise(- fileTargetPath,+ { path: fileTargetPath },new Uint8Array(result),true,onUploadProgress@@ -335,7 +335,7 @@ const actions = {} else {// dispatch(AppActions.setProgress(filePath, progress));return PlatformIO.saveBinaryFilePromise(- filePath,+ { path: filePath },fileContent,true,onUploadProgressdiff --git a/app/reducers/locations.ts b/app/reducers/locations.tsindex d93a24894..d7d07e50d 100644--- a/app/reducers/locations.ts+++ b/app/reducers/locations.ts@@ -24,7 +24,7 @@ import { actions as AppActions } from '-/reducers/app';import i18n from '-/services/i18n';import PlatformIO from '-/services/platform-facade';import { TS } from '-/tagspaces.namespace';-import { getUuid } from '-/services/utils-io';+import { getUuid } from '@tagspaces/tagspaces-common/utils-io';export const types = {ADD_LOCATION: 'APP/ADD_LOCATION',diff --git a/app/reducers/settings-default.ts b/app/reducers/settings-default.tsindex d8d214750..5b5abdc95 100644--- a/app/reducers/settings-default.ts+++ b/app/reducers/settings-default.ts@@ -19,7 +19,7 @@import AppConfig from '-/AppConfig';import keyBindings from '-/reducers/keybindings-default';import { PerspectiveIDs } from '-/perspectives';-import { getUuid } from '-/services/utils-io';+import { getUuid } from '@tagspaces/tagspaces-common/utils-io';let desktopMode = !AppConfig.isMobile;if (window.ExtDisplayMode && window.ExtDisplayMode === 'mobile') {@@ -210,6 +210,14 @@ export default {fileOpenHistory: false,folderOpenHistory: false,fileEditHistory: false,+ isRevisionsEnabled:+ typeof window.ExtRevisionsEnabled === 'undefined'+ ? true+ : window.ExtRevisionsEnabled,+ isAutoSaveEnabled:+ typeof window.ExtAutoSaveEnabled === 'undefined'+ ? false+ : window.ExtAutoSaveEnabled,supportedLanguages: [{iso: 'en',diff --git a/app/reducers/settings.ts b/app/reducers/settings.tsindex 80d4c07e3..8911bc506 100644--- a/app/reducers/settings.ts+++ b/app/reducers/settings.ts@@ -26,7 +26,7 @@ import versionMeta from '-/version.json';import { actions as AppActions } from './app';import { TS } from '-/tagspaces.namespace';import { Pro } from '../pro';-import { getUuid } from '-/services/utils-io';+import { getUuid } from '@tagspaces/tagspaces-common/utils-io';export const types = {UPGRADE_SETTINGS: 'SETTINGS/UPGRADE_SETTINGS',@@ -56,6 +56,7 @@ export const types = {SET_USETRASHCAN: 'SETTINGS/SET_USETRASHCAN',SET_PERSISTTAGSINSIDECARFILE: 'SETTINGS/SET_PERSISTTAGSINSIDECARFILE',SET_ADDTAGSTOLIBRARY: 'SETTINGS/SET_ADDTAGSTOLIBRARY',+ SET_REVISIONS_ENABLED: 'SETTINGS/SET_REVISIONS_ENABLED',SET_USEGENERATETHUMBNAILS: 'SETTINGS/SET_USEGENERATETHUMBNAILS',SET_USETEXTEXTRACTION: 'SETTINGS/SET_USETEXTEXTRACTION',SET_TAGCOLOR: 'SETTINGS/SET_TAGCOLOR',@@ -214,6 +215,9 @@ export default (state: any = defaultSettings, action: any) => {case types.SET_ADDTAGSTOLIBRARY: {return { ...state, addTagsToLibrary: action.addTagsToLibrary };}+ case types.SET_REVISIONS_ENABLED: {+ return { ...state, isRevisionsEnabled: action.enabled };+ }case types.SET_USEGENERATETHUMBNAILS: {return { ...state, useGenerateThumbnails: action.useGenerateThumbnails };}@@ -549,6 +553,10 @@ export const actions = {type: types.SET_ADDTAGSTOLIBRARY,addTagsToLibrary}),+ setRevisionsEnabled: (enabled: boolean) => ({+ type: types.SET_REVISIONS_ENABLED,+ enabled+ }),setUseGenerateThumbnails: (useGenerateThumbnails: boolean) => ({type: types.SET_USEGENERATETHUMBNAILS,useGenerateThumbnails@@ -736,6 +744,8 @@ export const getDesktopMode = (state: any) => {}return window.ExtDisplayMode !== 'mobile';};+export const isRevisionsEnabled = (state: any) =>+ state.settings.isRevisionsEnabled;export const getWarningOpeningFilesExternally = (state: any) =>state.settings.warningOpeningFilesExternally;export const getCheckForUpdateOnStartup = (state: any) =>diff --git a/app/reducers/taglibrary-default.ts b/app/reducers/taglibrary-default.tsindex 7c01479fa..8ba24860d 100644--- a/app/reducers/taglibrary-default.ts+++ b/app/reducers/taglibrary-default.ts@@ -16,7 +16,7 @@**/-import { getUuid } from '-/services/utils-io';+import { getUuid } from '@tagspaces/tagspaces-common/utils-io';export default [{diff --git a/app/reducers/taglibrary.ts b/app/reducers/taglibrary.tsindex 4101cdf3f..0cc5d9a64 100644--- a/app/reducers/taglibrary.ts+++ b/app/reducers/taglibrary.ts@@ -22,7 +22,8 @@ import {prepareTagGroupForExport} from '@tagspaces/tagspaces-common/misc';import AppConfig from '-/AppConfig';-import { getUuid, parseNewTags, saveAsTextFile } from '-/services/utils-io';+import { getUuid } from '@tagspaces/tagspaces-common/utils-io';+import { parseNewTags, saveAsTextFile } from '-/services/utils-io';import versionMeta from '../version.json';import defaultTagLibrary from './taglibrary-default';import { TS } from '-/tagspaces.namespace';diff --git a/app/services/platform-facade.ts b/app/services/platform-facade.tsindex 171fe7ee9..14be350d5 100644--- a/app/services/platform-facade.ts+++ b/app/services/platform-facade.ts@@ -354,21 +354,27 @@ export default class PlatformFacade {): Promise<any> => platformGetLocalFileContentPromise(filePath, type);static saveFilePromise = (- filePath: string,+ param: any,content: any,overwrite: boolean): Promise<any> => {- PlatformFacade.ignoreByWatcher(filePath);+ PlatformFacade.ignoreByWatcher(param.path);- return platformSaveFilePromise(filePath, content, overwrite).then(+ return platformSaveFilePromise(param, content, overwrite).then(result => {- PlatformFacade.deignoreByWatcher(filePath);+ PlatformFacade.deignoreByWatcher(param.path);return result;});};- static saveTextFilePlatform = (+ /**+ * @deprecated use saveTextFilePromise instead+ * @param param+ * @param content+ * @param overwrite+ */+ /*static saveTextFilePlatform = (param: any,content: string,overwrite: boolean@@ -376,32 +382,32 @@ export default class PlatformFacade {PlatformFacade.ignoreByWatcher(param.path);return PlatformFacade.saveTextFilePromise(- param.path,+ param,content,overwrite).then(result => {PlatformFacade.deignoreByWatcher(param.path);return result;});- };+ };*/static saveTextFilePromise = (- filePath: string,+ param: any,content: string,overwrite: boolean): Promise<any> => {- PlatformFacade.ignoreByWatcher(filePath);+ PlatformFacade.ignoreByWatcher(param.path);- return platformSaveTextFilePromise(filePath, content, overwrite).then(+ return platformSaveTextFilePromise(param, content, overwrite).then(result => {- PlatformFacade.deignoreByWatcher(filePath);+ PlatformFacade.deignoreByWatcher(param.path);return result;});};static saveBinaryFilePromise = (- filePath: string,+ param: any,content: any,overwrite: boolean,onUploadProgress?: (@@ -409,15 +415,15 @@ export default class PlatformFacade {response: any // AWS.Response<AWS.S3.PutObjectOutput, AWS.AWSError>) => void): Promise<TS.FileSystemEntry> => {- PlatformFacade.ignoreByWatcher(filePath);+ PlatformFacade.ignoreByWatcher(param.path);return platformSaveBinaryFilePromise(- filePath,+ param,content,overwrite,onUploadProgress).then(succeeded => {- PlatformFacade.deignoreByWatcher(filePath);+ PlatformFacade.deignoreByWatcher(param.path);return succeeded;});};diff --git a/app/services/taglibrary-utils.ts b/app/services/taglibrary-utils.tsindex 8f4c2f2d5..e638a3d92 100644--- a/app/services/taglibrary-utils.ts+++ b/app/services/taglibrary-utils.ts@@ -7,7 +7,8 @@ import {prepareTagGroupForExport} from '@tagspaces/tagspaces-common/misc';import versionMeta from '-/version.json';-import { getUuid, parseNewTags, saveAsTextFile } from '-/services/utils-io';+import { getUuid } from '@tagspaces/tagspaces-common/utils-io';+import { parseNewTags, saveAsTextFile } from '-/services/utils-io';import AppConfig from '-/AppConfig';import defaultTagLibrary from '../reducers/taglibrary-default';diff --git a/app/services/thumbsgenerator.ts b/app/services/thumbsgenerator.tsindex d69dc63ab..b5dddaac2 100644--- a/app/services/thumbsgenerator.ts+++ b/app/services/thumbsgenerator.ts@@ -123,7 +123,7 @@ function saveThumbnailPromise(filePath, dataURL) {}const baseString = dataURL.split(',').pop();const content = base64ToArrayBuffer(baseString);- return PlatformIO.saveBinaryFilePromise(filePath, content, true)+ return PlatformIO.saveBinaryFilePromise({ path: filePath }, content, true).then(() => filePath).catch(error => {console.warn(diff --git a/app/services/utils-io.ts b/app/services/utils-io.tsindex 5035044cf..e3ca59ce9 100644--- a/app/services/utils-io.ts+++ b/app/services/utils-io.ts@@ -16,7 +16,7 @@**/-import { v1 as uuidv1, v4 as uuidv4 } from 'uuid';+import { getUuid } from '@tagspaces/tagspaces-common/utils-io';import { marked } from 'marked';import DOMPurify from 'dompurify';import {@@ -108,7 +108,7 @@ export function enhanceDirectoryContent(return true;}- const enhancedEntry = enhanceEntry(+ const enhancedEntry: TS.FileSystemEntry = enhanceEntry(entry,AppConfig.tagDelimiter,PlatformIO.getDirSeparator()@@ -385,6 +385,7 @@ export function findExtensionPathForId(extensionId: string): string {}export function findExtensionsForEntry(+ uuid: string,supportedFileTypes: Array<any>,entryPath: string,isFile = true@@ -397,6 +398,7 @@ export function findExtensionsForEntry(? findExtensionPathForId('@tagspaces/extensions/text-viewer'): 'about:blank';const fileForOpening: OpenedEntry = {+ uuid: uuid,path: entryPath,viewingExtensionPath,viewingExtensionId: '',@@ -520,7 +522,7 @@ async function persistIndex(param: string | any, directoryIndex: any) {}const folderIndexPath =metaDirectory + PlatformIO.getDirSeparator() + AppConfig.folderIndexFile; // getMetaIndexFilePath(directoryPath);- return PlatformIO.saveTextFilePlatform(+ return PlatformIO.saveTextFilePromise({ ...param, path: folderIndexPath },JSON.stringify(directoryIndex), // relativeIndex),true@@ -908,7 +910,7 @@ export function cleanMetaData(if (metaData.perspective) {cleanedMeta.perspective = metaData.perspective;}- if (metaData.color) {+ if (metaData.color && metaData.color !== 'transparent') {cleanedMeta.color = metaData.color;}if (metaData.description) {@@ -920,6 +922,9 @@ export function cleanMetaData(if (metaData.customOrder) {cleanedMeta.customOrder = metaData.customOrder;}+ if (metaData.autoSave) {+ cleanedMeta.autoSave = metaData.autoSave;+ }/*if (metaData.perspectiveSettings) { // clean perspectiveSettings !== defaultSettingsObject.keys(metaData.perspectiveSettings).forEach(perspective => {if (!cleanedMeta.perspectiveSettings) {@@ -1023,7 +1028,11 @@ export async function saveLocationDataPromise(appVersion: versionMeta.version,lastUpdated: new Date().toJSON()});- return PlatformIO.saveTextFilePromise(metaFilePath, content, true);+ return PlatformIO.saveTextFilePromise(+ { path: metaFilePath },+ content,+ true+ );}return Promise.reject(new Error('file not found' + path));}@@ -1074,11 +1083,12 @@ export async function saveMetaDataPromise(PlatformIO.getDirSeparator());}- cleanedMetaData.appName = versionMeta.name;- cleanedMetaData.appVersion = versionMeta.version;- cleanedMetaData.lastUpdated = new Date().toJSON();- const content = JSON.stringify(cleanedMetaData);- return PlatformIO.saveTextFilePromise(metaFilePath, content, true);+ const content = JSON.stringify(mergeFsEntryMeta(cleanedMetaData));+ return PlatformIO.saveTextFilePromise(+ { path: metaFilePath },+ content,+ true+ );}return Promise.reject(new Error('file not found' + path));}@@ -1124,7 +1134,11 @@ export function setFolderBackgroundPromise(.then(base64Image => {if (base64Image) {const data = base64ToArrayBuffer(base64Image.split(',').pop());- return PlatformIO.saveBinaryFilePromise(folderBgndPath, data, true)+ return PlatformIO.saveBinaryFilePromise(+ { path: folderBgndPath },+ data,+ true+ ).then(() => {// props.setLastBackgroundImageChange(new Date().getTime());return directoryPath;@@ -1401,10 +1415,6 @@ export function setLocationType(location: TS.Location): Promise<boolean> {return Promise.resolve(false);}-export function getUuid(version = 4): string {- return version === 4 ? uuidv4() : uuidv1();-}-export function getCleanLocationPath(location: TS.Location): string {let locationPath = PlatformIO.getLocationPath(location);locationPath = cleanTrailingDirSeparator(locationPath);@@ -1447,3 +1457,34 @@ export function updateFsEntries(};});}++export function mergeFsEntryMeta(props: any = {}): TS.FileSystemEntryMeta {+ return {+ id: props.id || getUuid(),+ appName: versionMeta.name,+ appVersion: versionMeta.version,+ description: '',+ lastUpdated: new Date().getTime(),+ tags: [],+ ...props+ };+}++export function createFsEntryMeta(+ path: string,+ props: any = {}+): Promise<string> {+ const newFsEntryMeta: TS.FileSystemEntryMeta = mergeFsEntryMeta(props);+ return saveMetaDataPromise(path, newFsEntryMeta)+ .then(() => newFsEntryMeta.id)+ .catch(error => {+ console.error(+ 'Error saveMetaDataPromise for ' ++ path ++ ' orphan id: ' ++ newFsEntryMeta.id,+ error+ );+ return newFsEntryMeta.id;+ });+}diff --git a/app/tagspaces.d.ts b/app/tagspaces.d.tsindex d23ad94f5..3d3e334b7 100644--- a/app/tagspaces.d.ts+++ b/app/tagspaces.d.ts@@ -57,6 +57,8 @@ declare interface Window {ExtPrivacyURL?: string;ExtImprintURL?: string;ExtCheckForUpdatesOnStartup?: boolean;+ ExtRevisionsEnabled?: boolean;+ ExtAutoSaveEnabled?: boolean;__REDUX_DEVTOOLS_EXTENSION_COMPOSE__?: any;plugins?: any; // needed for CordovaresolveLocalFileSystemURL?: any; // needed for Cordovadiff --git a/app/tagspaces.namespace.d.ts b/app/tagspaces.namespace.d.tsindex 5c52d184f..a12d1c21e 100644--- a/app/tagspaces.namespace.d.ts+++ b/app/tagspaces.namespace.d.ts@@ -114,6 +114,7 @@ export namespace TS {name: string;isFile: boolean;isNewFile?: boolean;+ isAutoSaveEnabled?: boolean; // common with OpenedEntryextension?: string;thumbPath?: string;color?: string;@@ -130,16 +131,17 @@ export namespace TS {}interface FileSystemEntryMeta {- id?: string;+ id: string;description?: string;isFile?: boolean;+ autoSave?: boolean;tags?: Array<TS.Tag>;tagGroups?: Array<TS.TagGroup>;color?: string;perspective?: string;appName: string;appVersion: string;- lastUpdated: string;+ lastUpdated: number;customOrder?: CustomOrder;perspectiveSettings?: PerspectiveSettings;}diff --git a/app/utils/metaoperations.ts b/app/utils/metaoperations.tsindex 42cdc14f4..4a4491e8a 100644--- a/app/utils/metaoperations.ts+++ b/app/utils/metaoperations.ts@@ -1,4 +1,8 @@-import { loadMetaDataPromise, saveMetaDataPromise } from '-/services/utils-io';+import {+ loadMetaDataPromise,+ mergeFsEntryMeta,+ saveMetaDataPromise+} from '-/services/utils-io';import { TS } from '-/tagspaces.namespace';// eslint-disable-next-line import/prefer-default-export@@ -33,14 +37,9 @@ export function savePerspective(return true;}).catch(() => {- const newFsEntryMeta: TS.FileSystemEntryMeta = {- appName: '',- appVersion: '',- description: '',- lastUpdated: '',- tags: undefined,+ const newFsEntryMeta: TS.FileSystemEntryMeta = mergeFsEntryMeta({perspective- };+ });saveMetaDataPromise(path, newFsEntryMeta).then(() => {resolve(newFsEntryMeta);diff --git a/package-lock.json b/package-lock.jsonindex bcd00f0cb..ce4b0f14a 100644--- a/package-lock.json+++ b/package-lock.json@@ -21,7 +21,7 @@"@mui/styles": "5.10.15","@mui/x-date-pickers": "^5.0.8","@tagspaces/tagspaces-md": "2.1.6",- "@tagspaces/tagspaces-platforms": "2.1.14",+ "@tagspaces/tagspaces-platforms": "2.1.17","aws-amplify": "^4.3.8","aws-sdk": "^2.1036.0","babel-polyfill": "^6.26.0",@@ -13823,9 +13823,9 @@}},"node_modules/@tagspaces/tagspaces-platforms": {- "version": "2.1.14",- "resolved": "https://registry.npmjs.org/@tagspaces/tagspaces-platforms/-/tagspaces-platforms-2.1.14.tgz",- "integrity": "sha512-c/VjKn4H9XEKGUzauNRA25q9eaHDzeLvdjNxLcFNmRbkqAYy4KSj5aAvqEf+eAi26r69YdeZV0KMoAo6ZNEJMA==",+ "version": "2.1.17",+ "resolved": "https://registry.npmjs.org/@tagspaces/tagspaces-platforms/-/tagspaces-platforms-2.1.17.tgz",+ "integrity": "sha512-Eq8tWNL9tiMQ5WW0TEkSMXCfkrVuPxlOuVyNHAeHByeqx1e7BqF/BfA5gOrq4y8J4l5MrkR12KdNmtaS9w7JQQ==","hasInstallScript": true},"node_modules/@testim/chrome-version": {@@ -59523,9 +59523,9 @@}},"@tagspaces/tagspaces-platforms": {- "version": "2.1.14",- "resolved": "https://registry.npmjs.org/@tagspaces/tagspaces-platforms/-/tagspaces-platforms-2.1.14.tgz",- "integrity": "sha512-c/VjKn4H9XEKGUzauNRA25q9eaHDzeLvdjNxLcFNmRbkqAYy4KSj5aAvqEf+eAi26r69YdeZV0KMoAo6ZNEJMA=="+ "version": "2.1.17",+ "resolved": "https://registry.npmjs.org/@tagspaces/tagspaces-platforms/-/tagspaces-platforms-2.1.17.tgz",+ "integrity": "sha512-Eq8tWNL9tiMQ5WW0TEkSMXCfkrVuPxlOuVyNHAeHByeqx1e7BqF/BfA5gOrq4y8J4l5MrkR12KdNmtaS9w7JQQ=="},"@testim/chrome-version": {"version": "1.1.3",diff --git a/package.json b/package.jsonindex 256aab512..9bff1bacc 100644--- a/package.json+++ b/package.json@@ -159,7 +159,7 @@"@mui/styles": "5.10.15","@mui/x-date-pickers": "^5.0.8","@tagspaces/tagspaces-md": "2.1.6",- "@tagspaces/tagspaces-platforms": "2.1.14",+ "@tagspaces/tagspaces-platforms": "2.1.17","aws-amplify": "^4.3.8","aws-sdk": "^2.1036.0","babel-polyfill": "^6.26.0",