TagSpaces is an offline, open source, document manager with tagging support
typescript migration
Ilian Sapundshiev972854803e9b
diff --git a/app/components/AppOnboarding.tsx b/app/components/AppOnboarding.tsxindex e228f2896..cafebfd98 100644--- a/app/components/AppOnboarding.tsx+++ b/app/components/AppOnboarding.tsx@@ -21,11 +21,11 @@ import Joyride from 'react-joyride';import i18n from '../services/i18n';class AppOnboarding extends Component {- state = {- run: false- };+ state = {+ run: false+ };- /* componentDidMount() {+ /* componentDidMount() {setTimeout(() => {this.setState({run: true@@ -33,26 +33,27 @@ class AppOnboarding extends Component {}, 1000);} */- callback = data => {- // const { action, index, type } = data;- };+ callback = data => {+ // const { action, index, type } = data;+ };- render() {- const { run } = this.state;- const steps = [- {- target: '[data-tid=createNewLocation]',- content: i18n.t('welcomeContent'),- placement: 'bottom'- },- {- target: '[data-tid=aboutTagSpaces]',- content: 'Hello world',- placement: 'bottom'- }- ];- return <Joyride steps={steps} run={run} callback={this.callback} />;- }+ render() {+ const { run } = this.state;+ const steps = [+ {+ target: '[data-tid=createNewLocation]',+ content: i18n.t('welcomeContent'),+ placement: 'bottom'+ },+ {+ target: '[data-tid=aboutTagSpaces]',+ content: 'Hello world',+ placement: 'bottom'+ }+ ];+ // @ts-ignore+ return <Joyride steps={steps} run={run} callback={this.callback} />;+ }}export default AppOnboarding;diff --git a/app/components/CustomLogo.tsx b/app/components/CustomLogo.tsxindex 369fdcd2a..2e8c2a0c6 100644--- a/app/components/CustomLogo.tsx+++ b/app/components/CustomLogo.tsx@@ -42,9 +42,9 @@ const AppVersionBadge = withStyles(theme => ({}}))(Badge);-type Props = {- toggleAboutDialog: () => void-};+interface Props {+ toggleAboutDialog: () => void;+}let logo = Pro ? Pro.TextLogoIcon : TextLogoIcon;// logo = 'assets/images/custom-logo.svg';diff --git a/app/components/HelpFeedbackPanel.tsx b/app/components/HelpFeedbackPanel.tsxindex 45aea5f47..bb30f6d87 100644--- a/app/components/HelpFeedbackPanel.tsx+++ b/app/components/HelpFeedbackPanel.tsx@@ -20,7 +20,6 @@ import React from 'react';import { withStyles } from '@material-ui/core/styles';import classNames from 'classnames';import Typography from '@material-ui/core/Typography';-import Card from '@material-ui/core/Card';import CardActions from '@material-ui/core/CardActions';import CardContent from '@material-ui/core/CardContent';import Button from '@material-ui/core/Button';@@ -49,16 +48,16 @@ import AppConfig from '../config';import i18n from '../services/i18n';import { Pro } from '../pro';-type Props = {- classes: Object,- openURLExternally: (url: string) => void,- openFileNatively: (url: string) => void,- toggleAboutDialog: () => void,- toggleKeysDialog: () => void,- toggleOnboardingDialog: () => void,- toggleProTeaser: () => void,- style: Object-};+interface Props {+ classes?: any;+ openURLExternally: (url: string) => void;+ openFileNatively: (url: string) => void;+ toggleAboutDialog?: () => void;+ toggleKeysDialog: () => void;+ toggleOnboardingDialog: () => void;+ toggleProTeaser: () => void;+ style?: any;+}class HelpFeedbackPanel extends React.Component<Props> {render() {@@ -77,7 +76,7 @@ class HelpFeedbackPanel extends React.Component<Props> {<CustomLogo /><TypographyclassName={classNames(classes.panelTitle, classes.header)}- type="subtitle1"+ variant="subtitle1">Help & Feedback</Typography>@@ -209,7 +208,7 @@ class HelpFeedbackPanel extends React.Component<Props> {<divonClick={toggleProTeaser}role="button"- tabIndex="0"+ tabIndex={0}style={{backgroundColor: 'rgba(29, 209, 159, 0.08)',textAlign: 'center'diff --git a/app/components/PerspectiveManager.tsx b/app/components/PerspectiveManager.tsxindex a911405d7..dbb58e89d 100644--- a/app/components/PerspectiveManager.tsx+++ b/app/components/PerspectiveManager.tsx@@ -19,13 +19,11 @@import React from 'react';import { withStyles } from '@material-ui/core/styles';import Typography from '@material-ui/core/Typography';-// import Button from '@material-ui/Button';-// import { history } from '../store/configureStore';import styles from './SidePanels.css';type Props = {- classes: Object,- style: Object+ classes: any;+ style: any;};type State = {};@@ -36,9 +34,7 @@ class PerspectiveManager extends React.Component<Props, State> {return (<div className={classes.panel} style={this.props.style}>- <Typography className={classes.panelTitle} type="subtitle1">- Perspectives- </Typography>+ <Typography className={classes.panelTitle}>Perspectives</Typography></div>);}diff --git a/app/components/SidePanels.css.tsx b/app/components/SidePanels.css.tsxindex fe3731907..040aa2303 100644--- a/app/components/SidePanels.css.tsx+++ b/app/components/SidePanels.css.tsx@@ -17,115 +17,116 @@*/import AppConfig from '../config';-export default theme => ({- panel: {- height: '100%',- maxHeight: '100%',- padding: 5,- paddingBottom: 50,- overflowY: 'hidden',- backgroundColor: theme.palette.background.default- },- fontIcon: {- color: theme.palette.text.primary- },- header: {- color: theme.palette.text.primary- },- icon: {- margin: theme.spacing(1)- },- locationListArea: {- // paddingRight: 10, // place for scroll- paddingTop: 0,- marginTop: 0,- overflowY: AppConfig.isFirefox ? 'auto' : 'overlay'- },- helpFeedbackArea: {- paddingTop: 0,- marginTop: 0,- height: 'calc(100% - 110px)',- maxHeight: 'calc(100% - 110px)',- overflowY: AppConfig.isFirefox ? 'auto' : 'overlay'- },- taggroupsArea: {- paddingTop: 0,- marginTop: 0,- height: 'calc(100% - 110px)',- maxHeight: 'calc(100% - 110px)',- overflowY: AppConfig.isFirefox ? 'auto' : 'overlay'- },- searchArea: {- paddingTop: 0,- paddingLeft: 5,- marginTop: 0,- height: 'calc(100% - 110px)',- maxHeight: 'calc(100% - 110px)',- overflowY: AppConfig.isFirefox ? 'auto' : 'overlay'- },- topShadow: {- borderTop: '1px solid lightgray',- height: 10,- boxShadow: '0px -7px 20px 0px rgba(255, 255, 255, 1)'- },- listItem: {- paddingLeft: 0,- paddingTop: 2,- paddingBottom: 2,- paddingRight: 0,- borderRadius: 5,- backgroundColor: 'transparent'- },- listItemSelected: {- paddingLeft: 0,- paddingRight: 0,- paddingTop: 2,- paddingBottom: 2,- borderRadius: 5,- backgroundColor: theme.palette.primary.light- },- panelTitle: {- textTransform: 'uppercase',- flex: 1,- paddingLeft: 5,- paddingTop: 12- },- nested: {- paddingLeft: theme.spacing(4)- },- listItemTitleText: {- fontWeight: 'bold'- },- hiddenFileInput: {- display: 'none'- },- toolbar: {- display: 'flex'- },- formControl: {- width: '100%',- marginBottom: 10- },- mainActionButton: {- marginTop: 10,- marginLeft: 0,- paddingLeft: 8- },- leftIcon: {- marginRight: theme.spacing(1)- },- badge: {- display: 'inline-block',- minWidth: 10,- padding: '3px 7px',- fontSize: 10,- fontWeight: 'normal',- color: '#ffffff',- lineHeight: 1,- verticalAlign: 'middle',- whiteSpace: 'nowrap',- textAlign: 'center',- backgroundColor: '#bbbbbb',- borderRadius: 10- }-});+export default (theme: any) =>+ ({+ panel: {+ height: '100%',+ maxHeight: '100%',+ padding: 5,+ paddingBottom: 50,+ overflowY: 'hidden',+ backgroundColor: theme.palette.background.default+ },+ fontIcon: {+ color: theme.palette.text.primary+ },+ header: {+ color: theme.palette.text.primary+ },+ icon: {+ margin: theme.spacing(1)+ },+ locationListArea: {+ // paddingRight: 10, // place for scroll+ paddingTop: 0,+ marginTop: 0,+ overflowY: AppConfig.isFirefox ? 'auto' : 'overlay'+ },+ helpFeedbackArea: {+ paddingTop: 0,+ marginTop: 0,+ height: 'calc(100% - 110px)',+ maxHeight: 'calc(100% - 110px)',+ overflowY: AppConfig.isFirefox ? 'auto' : 'overlay'+ },+ taggroupsArea: {+ paddingTop: 0,+ marginTop: 0,+ height: 'calc(100% - 110px)',+ maxHeight: 'calc(100% - 110px)',+ overflowY: AppConfig.isFirefox ? 'auto' : 'overlay'+ },+ searchArea: {+ paddingTop: 0,+ paddingLeft: 5,+ marginTop: 0,+ height: 'calc(100% - 110px)',+ maxHeight: 'calc(100% - 110px)',+ overflowY: AppConfig.isFirefox ? 'auto' : 'overlay'+ },+ topShadow: {+ borderTop: '1px solid lightgray',+ height: 10,+ boxShadow: '0px -7px 20px 0px rgba(255, 255, 255, 1)'+ },+ listItem: {+ paddingLeft: 0,+ paddingTop: 2,+ paddingBottom: 2,+ paddingRight: 0,+ borderRadius: 5,+ backgroundColor: 'transparent'+ },+ listItemSelected: {+ paddingLeft: 0,+ paddingRight: 0,+ paddingTop: 2,+ paddingBottom: 2,+ borderRadius: 5,+ backgroundColor: theme.palette.primary.light+ },+ panelTitle: {+ textTransform: 'uppercase',+ flex: 1,+ paddingLeft: 5,+ paddingTop: 12+ },+ nested: {+ paddingLeft: theme.spacing(4)+ },+ listItemTitleText: {+ fontWeight: 'bold'+ },+ hiddenFileInput: {+ display: 'none'+ },+ toolbar: {+ display: 'flex'+ },+ formControl: {+ width: '100%',+ marginBottom: 10+ },+ mainActionButton: {+ marginTop: 10,+ marginLeft: 0,+ paddingLeft: 8+ },+ leftIcon: {+ marginRight: theme.spacing(1)+ },+ badge: {+ display: 'inline-block',+ minWidth: 10,+ padding: '3px 7px',+ fontSize: 10,+ fontWeight: 'normal',+ color: '#ffffff',+ lineHeight: 1,+ verticalAlign: 'middle',+ whiteSpace: 'nowrap',+ textAlign: 'center',+ backgroundColor: '#bbbbbb',+ borderRadius: 10+ }+ } as any);diff --git a/app/components/TagContainer.tsx b/app/components/TagContainer.tsxindex 31828a7da..6574c31cb 100644--- a/app/components/TagContainer.tsx+++ b/app/components/TagContainer.tsx@@ -28,185 +28,189 @@ import { TagGroup, Tag, getAllTags } from '../reducers/taglibrary';import { getTagColor, getTagTextColor } from '../reducers/settings';import { isPlusCode } from '../utils/misc';import { isDateTimeTag } from '../utils/dates';+import { FileSystemEntry } from '-/services/utils-io';-type Props = {- tag: Tag;- allTags: Array<Tag>;- key: string;- defaultTextColor: string;- defaultBackgroundColor: string;- tagGroup: TagGroup;- handleTagMenu: (event: Object, tag: Tag, tagGroup: TagGroup) => void; // TODO refactor- handleTagMenu: (event: Object, tag: Tag, entryPath: string) => void;- handleRemoveTag: (event: Object, tag: Tag) => void;- isDragging: boolean;- tagMode: 'default' | 'display' | 'remove';- entryPath: string;- deleteIcon: Object;- addTags: (paths: Array<string>, tags: Array<Tag>) => void;- // removeTags: (paths: Array<string>, tags: Array<Tag>) => void,- selectedEntries: Array<Object>;-};+interface Props {+ tag: Tag;+ allTags?: Array<Tag>;+ key?: string;+ defaultTextColor?: string;+ defaultBackgroundColor?: string;+ tagGroup?: TagGroup;+ handleTagMenu?: (+ event: Object,+ tag: Tag,+ tagGroup: TagGroup | string+ ) => void; // TODO refactor+ handleRemoveTag?: (event: Object, tag: Tag) => void;+ isDragging?: boolean;+ tagMode?: 'default' | 'display' | 'remove';+ entryPath?: string;+ deleteIcon?: Object;+ addTags?: (paths: Array<string>, tags: Array<Tag>) => void;+ moveTag?: () => void;+ selectedEntries?: Array<FileSystemEntry>;+}const TagContainer = React.memo((props: Props) => {- const {- key,- tag,- deleteIcon,- isDragging,- defaultTextColor,- defaultBackgroundColor,- tagGroup,- entryPath,- allTags,- handleRemoveTag,- handleTagMenu,- selectedEntries,- addTags,- tagMode- } = props;+ const {+ key,+ tag,+ deleteIcon,+ isDragging,+ defaultTextColor,+ defaultBackgroundColor,+ tagGroup,+ entryPath,+ allTags,+ handleRemoveTag,+ handleTagMenu,+ selectedEntries,+ addTags,+ tagMode+ } = props;- let textColor = tag.textcolor || defaultTextColor;- let backgroundColor = tag.color || defaultBackgroundColor;- const titleOrig = tag.title;- let title = titleOrig;+ let textColor = tag.textcolor || defaultTextColor;+ let backgroundColor = tag.color || defaultBackgroundColor;+ const titleOrig = tag.title;+ let title = titleOrig;- // Check if tag is plus code- let isGeoTag = false;- let isTagDate = false;- if (!tagGroup) {- isGeoTag = isPlusCode(title); // || isLatLong- isTagDate = !isGeoTag && isDateTimeTag(title);- }- if (isTagDate && title.length > 8) {- title = title.substr(0, 8) + '...';- }+ // Check if tag is plus code+ let isGeoTag = false;+ let isTagDate = false;+ if (!tagGroup) {+ isGeoTag = isPlusCode(title); // || isLatLong+ isTagDate = !isGeoTag && isDateTimeTag(title);+ }+ if (isTagDate && title.length > 8) {+ title = title.substr(0, 8) + '...';+ }- allTags.some((currentTag: Tag) => {- if (currentTag.title === title) {- textColor = currentTag.textcolor;- backgroundColor = currentTag.color;- return true;- }- return false;- });+ allTags.some((currentTag: Tag) => {+ if (currentTag.title === title) {+ textColor = currentTag.textcolor;+ backgroundColor = currentTag.color;+ return true;+ }+ return false;+ });- let description = tag.title;- if (tag.description) {- description = tag.title + ' - ' + tag.description;- }+ let description = tag.title;+ if (tag.description) {+ description = tag.title + ' - ' + tag.description;+ }- return (- <div- role="presentation"- data-tid={'tagContainer_' + title.replace(/ /g, '_')}- key={key || tag.id || uuidv1()}- onClick={event => {- if (event.ctrlKey && addTags) {- const selectedEntryPaths = [];- selectedEntries.map(entry => selectedEntryPaths.push(entry.path));- addTags(selectedEntryPaths, [tag]);- // Removing tags doesn't seem to work correctly here, yet. Using sidecar tagging, but the removeTagsFromEntry function in tagging.actions.js- // doesn't recignize it correctly, thinking it's a plain tag and thus tries to rename the files- // } else if (event.shiftKey) {- // const selectedEntryPaths = [];- // selectedEntries.map(entry => selectedEntryPaths.push(entry.path));- // removeTags(selectedEntryPaths, [tag]);- } else if (handleTagMenu) {- handleTagMenu(event, tag, entryPath || tagGroup);- }- }}- onContextMenu={event => {- if (handleTagMenu) {- handleTagMenu(event, tag, entryPath || tagGroup);- }- }}- onDoubleClick={event => {- if (handleTagMenu) {- handleTagMenu(event, tag, entryPath || tagGroup);- }- }}- style={{- backgroundColor: 'transparent',- display: 'inline-block'- }}- >- <Button- title={description}- size="small"- style={{- opacity: isDragging ? 0.5 : 1,- fontSize: 13,- textTransform: 'none',- color: textColor,- backgroundColor,- minHeight: 0,- minWidth: 0,- margin: 2,- paddingTop: 0,- paddingBottom: 0,- paddingRight: 0,- paddingLeft: 5,- borderRadius: 5- }}- >- <span style={{ flexGrow: '1' }}>- {isGeoTag && (- <PlaceIcon- style={{- color: tag.textColor,- fontSize: 18,- marginBottom: -5- }}- />- )}- {isTagDate && (- <DateIcon- style={{- color: tag.textColor,- fontSize: 18,- marginBottom: -5,- marginRight: 4- }}- />- )}- {!isGeoTag && title}- </span>- {tagMode === 'remove' ? (- deleteIcon || (- <RemoveTagIcon- data-tid={'tagRemoveButton_' + title.replace(/ /g, '_')}- style={{- color: tag.textColor,- fontSize: 20,- marginBottom: -5- }}- onClick={event => handleRemoveTag(event, tag)}- />- )- ) : (- <MoreVertIcon- data-tid={'tagMoreButton_' + title.replace(/ /g, '_')}- style={{- color: tag.textColor,- marginLeft: -5,- marginRight: -5,- top: 0- }}- />- )}- </Button>- </div>- );+ return (+ <div+ role="presentation"+ data-tid={'tagContainer_' + title.replace(/ /g, '_')}+ key={key || tag.id || uuidv1()}+ onClick={event => {+ if (event.ctrlKey && addTags) {+ const selectedEntryPaths = [];+ selectedEntries.map(entry => selectedEntryPaths.push(entry.path));+ addTags(selectedEntryPaths, [tag]);+ // Removing tags doesn't seem to work correctly here, yet. Using sidecar tagging, but the removeTagsFromEntry function in tagging.actions.js+ // doesn't recignize it correctly, thinking it's a plain tag and thus tries to rename the files+ // } else if (event.shiftKey) {+ // const selectedEntryPaths = [];+ // selectedEntries.map(entry => selectedEntryPaths.push(entry.path));+ // removeTags(selectedEntryPaths, [tag]);+ } else if (handleTagMenu) {+ handleTagMenu(event, tag, entryPath || tagGroup);+ }+ }}+ onContextMenu={event => {+ if (handleTagMenu) {+ handleTagMenu(event, tag, entryPath || tagGroup);+ }+ }}+ onDoubleClick={event => {+ if (handleTagMenu) {+ handleTagMenu(event, tag, entryPath || tagGroup);+ }+ }}+ style={{+ backgroundColor: 'transparent',+ display: 'inline-block'+ }}+ >+ <Button+ title={description}+ size="small"+ style={{+ opacity: isDragging ? 0.5 : 1,+ fontSize: 13,+ textTransform: 'none',+ color: textColor,+ backgroundColor,+ minHeight: 0,+ minWidth: 0,+ margin: 2,+ paddingTop: 0,+ paddingBottom: 0,+ paddingRight: 0,+ paddingLeft: 5,+ borderRadius: 5+ }}+ >+ <span style={{ flexGrow: 1 }}>+ {isGeoTag && (+ <PlaceIcon+ style={{+ color: tag.textcolor,+ fontSize: 18,+ marginBottom: -5+ }}+ />+ )}+ {isTagDate && (+ <DateIcon+ style={{+ color: tag.textcolor,+ fontSize: 18,+ marginBottom: -5,+ marginRight: 4+ }}+ />+ )}+ {!isGeoTag && title}+ </span>+ {tagMode === 'remove' ? (+ deleteIcon || (+ <RemoveTagIcon+ data-tid={'tagRemoveButton_' + title.replace(/ /g, '_')}+ style={{+ color: tag.textcolor,+ fontSize: 20,+ marginBottom: -5+ }}+ onClick={event => handleRemoveTag(event, tag)}+ />+ )+ ) : (+ <MoreVertIcon+ data-tid={'tagMoreButton_' + title.replace(/ /g, '_')}+ style={{+ color: tag.textcolor,+ marginLeft: -5,+ marginRight: -5,+ top: 0+ }}+ />+ )}+ </Button>+ </div>+ );});function mapStateToProps(state) {- return {- allTags: getAllTags(state),- defaultBackgroundColor: getTagColor(state),- defaultTextColor: getTagTextColor(state)- // selectedEntries: getSelectedEntries(state)- };+ return {+ allTags: getAllTags(state),+ defaultBackgroundColor: getTagColor(state),+ defaultTextColor: getTagTextColor(state)+ // selectedEntries: getSelectedEntries(state)+ };}export default connect(mapStateToProps)(TagContainer);diff --git a/app/components/TagContainerDnd.tsx b/app/components/TagContainerDnd.tsxindex 0c67ea2b0..6f3c6a9b7 100644--- a/app/components/TagContainerDnd.tsx+++ b/app/components/TagContainerDnd.tsx@@ -22,63 +22,63 @@ import { ConnectDragPreview, ConnectDragSource } from 'react-dnd';import DragItemTypes from './DragItemTypes';import TagContainer from './TagContainer';import { TagGroup, Tag } from '../reducers/taglibrary';+import { FileSystemEntry } from '-/services/utils-io';const boxSource = {- beginDrag(props) {- // console.log('beginDrag', props);- return {- tagId: props.tag.id,- tag: props.tag,- sourceTagGroupId: props.tagGroup ? props.tagGroup.uuid : undefined- };- },+ beginDrag(props) {+ // console.log('beginDrag', props);+ return {+ tagId: props.tag.id,+ tag: props.tag,+ sourceTagGroupId: props.tagGroup ? props.tagGroup.uuid : undefined+ };+ },- endDrag(props, monitor) {- const item = monitor.getItem();- const dropResult = monitor.getDropResult();+ endDrag(props, monitor) {+ const item = monitor.getItem();+ const dropResult = monitor.getDropResult();- // console.log('DropRESULT: ', dropResult);- // console.log('item: ', item);- if (- dropResult &&- dropResult.tagGroupId &&- dropResult.tagGroupId !== item.sourceTagGroupId &&- props.moveTag- ) {- // console.log(`Dropped ${item.tagId} from ${item.sourceTagGroupId} into ${dropResult.tagGroupId}!`);- props.moveTag(item.tagId, item.sourceTagGroupId, dropResult.tagGroupId);- } else if (dropResult && dropResult.entryPath && props.addTags) {- // console.log(`Dropped item: ${item.tag.title} onto file: ${dropResult.entryPath}!`);- if (- props.selectedEntries.some(entry => entry.path === dropResult.entryPath)- ) {- const selectedEntryPaths = [];- props.selectedEntries.map(entry => selectedEntryPaths.push(entry.path));- props.addTags(selectedEntryPaths, [item.tag]);- } else {- props.addTags([dropResult.entryPath], [item.tag]);- }- }- }+ // console.log('DropRESULT: ', dropResult);+ // console.log('item: ', item);+ if (+ dropResult &&+ dropResult.tagGroupId &&+ dropResult.tagGroupId !== item.sourceTagGroupId &&+ props.moveTag+ ) {+ // console.log(`Dropped ${item.tagId} from ${item.sourceTagGroupId} into ${dropResult.tagGroupId}!`);+ props.moveTag(item.tagId, item.sourceTagGroupId, dropResult.tagGroupId);+ } else if (dropResult && dropResult.entryPath && props.addTags) {+ // console.log(`Dropped item: ${item.tag.title} onto file: ${dropResult.entryPath}!`);+ if (+ props.selectedEntries.some(entry => entry.path === dropResult.entryPath)+ ) {+ const selectedEntryPaths = [];+ props.selectedEntries.map(entry => selectedEntryPaths.push(entry.path));+ props.addTags(selectedEntryPaths, [item.tag]);+ } else {+ props.addTags([dropResult.entryPath], [item.tag]);+ }+ }+ }};-type Props = {- tag: Tag;- key: string;- tagGroup: TagGroup;- handleTagMenu: (event: Object, tag: Tag, tagGroup: TagGroup) => void; // TODO refactor- handleTagMenu: (event: Object, tag: Tag, entryPath: string) => void;- handleRemoveTag: (event: Object, tag: Tag) => void;- isDragging: boolean;- tagMode?: 'default' | 'display' | 'remove';- entryPath?: string;- addTags: (paths: Array<string>, tags: Array<Tag>) => void;- moveTag: () => void;- connectDragSource: ConnectDragSource;- connectDragPreview: ConnectDragPreview;- deleteIcon: Object;- selectedEntries: Array<string>;-};+interface Props {+ tag: Tag;+ key: string;+ tagGroup?: TagGroup;+ handleTagMenu: (event: Object, tag: Tag, param: any) => void;+ handleRemoveTag?: (event: Object, tag: Tag) => void;+ isDragging?: boolean;+ tagMode?: 'default' | 'display' | 'remove';+ entryPath?: string;+ addTags?: (paths: Array<string>, tags: Array<Tag>) => void;+ moveTag?: () => void;+ connectDragSource?: ConnectDragSource;+ connectDragPreview?: ConnectDragPreview;+ deleteIcon?: Object;+ selectedEntries: Array<FileSystemEntry>;+}// class TagContainerDnd extends React.PureComponent<Props> {// // componentDidMount() {@@ -112,40 +112,40 @@ type Props = {// render() {const TagContainerDnd = (props: Props) => {- const {- key,- tag,- tagGroup,- entryPath,- handleTagMenu,- deleteIcon,- selectedEntries,- isDragging,- connectDragSource,- addTags,- tagMode- } = props;+ const {+ key,+ tag,+ tagGroup,+ entryPath,+ handleTagMenu,+ deleteIcon,+ selectedEntries,+ isDragging,+ connectDragSource,+ addTags,+ tagMode+ } = props;- return connectDragSource(- <span>- <TagContainer- key={key}- tag={tag}- tagGroup={tagGroup}- handleTagMenu={handleTagMenu}- deleteIcon={deleteIcon}- addTags={addTags}- tagMode={tagMode}- entryPath={entryPath}- isDragging={isDragging}- selectedEntries={selectedEntries}- />- </span>- );+ return connectDragSource(+ <span>+ <TagContainer+ key={key}+ tag={tag}+ tagGroup={tagGroup}+ handleTagMenu={handleTagMenu}+ deleteIcon={deleteIcon}+ addTags={addTags}+ tagMode={tagMode}+ entryPath={entryPath}+ isDragging={isDragging}+ selectedEntries={selectedEntries}+ />+ </span>+ );};export default DragSource(DragItemTypes.TAG, boxSource, (connect, monitor) => ({- connectDragSource: connect.dragSource(),- connectDragPreview: connect.dragPreview(),- isDragging: monitor.isDragging()+ connectDragSource: connect.dragSource(),+ connectDragPreview: connect.dragPreview(),+ isDragging: monitor.isDragging()}))(TagContainerDnd);diff --git a/app/components/TagsSelect.tsx b/app/components/TagsSelect.tsxindex b7cd6003d..5487c06b3 100644--- a/app/components/TagsSelect.tsx+++ b/app/components/TagsSelect.tsx@@ -27,278 +27,279 @@ import MenuItem from '@material-ui/core/MenuItem';import CreatableSelect from 'react-select/creatable';import NoSsr from '@material-ui/core/NoSsr';import TextField from '@material-ui/core/TextField';-import i18n from '../services/i18n';import { Tag, getAllTags } from '../reducers/taglibrary';import { getTagColor, getTagTextColor } from '../reducers/settings';import TagContainer from './TagContainer';-const styles = theme => ({- root: {- flexGrow: 1- // height: 250,- /* '& div': { //https://github.com/JedWatson/react-select/issues/1085+const styles: any = (theme: any) => ({+ root: {+ flexGrow: 1+ // height: 250,+ /* '& div': { //https://github.com/JedWatson/react-select/issues/1085zIndex: 1} */- },- input: {- display: 'flex',- padding: 0,- height: 'auto'- },- valueContainer: {- display: 'flex',- flexWrap: 'wrap',- flex: 1,- alignItems: 'center',- overflow: 'hidden'- },- noOptionsMessage: {- padding: theme.spacing(1, 2)- },- singleValue: {- fontSize: 16- },- placeholder: {- position: 'absolute',- left: 2,- bottom: 6,- fontSize: 16- },- paper: {- position: 'absolute',- zIndex: 2,- marginTop: theme.spacing(1),- left: 0,- right: 0- }+ },+ input: {+ display: 'flex',+ padding: 0,+ height: 'auto'+ },+ valueContainer: {+ display: 'flex',+ flexWrap: 'wrap',+ flex: 1,+ alignItems: 'center',+ overflow: 'hidden'+ },+ noOptionsMessage: {+ padding: theme.spacing(1, 2)+ },+ singleValue: {+ fontSize: 16+ },+ placeholder: {+ position: 'absolute',+ left: 2,+ bottom: 6,+ fontSize: 16+ },+ paper: {+ position: 'absolute',+ zIndex: 2,+ marginTop: theme.spacing(1),+ left: 0,+ right: 0+ }});function NoOptionsMessage(props) {- return (- <Typography- color="textSecondary"- style={{ display: 'block' }}- className={props.selectProps.classes.noOptionsMessage}- {...props.innerProps}- >- {props.children}- </Typography>- );+ return (+ <Typography+ color="textSecondary"+ style={{ display: 'block' }}+ className={props.selectProps.classes.noOptionsMessage}+ {...props.innerProps}+ >+ {props.children}+ </Typography>+ );}function inputComponent({ inputRef, ...props }) {- return <div ref={inputRef} {...props} />;+ return <div ref={inputRef} {...props} />;}function Control(props) {- const {- children,- innerProps,- innerRef,- selectProps: { classes, TextFieldProps }- } = props;+ const {+ children,+ innerProps,+ innerRef,+ selectProps: { classes, TextFieldProps }+ } = props;- return (- <TextField- fullWidth- InputProps={{- inputComponent,- inputProps: {- className: classes.input,- ref: innerRef,- children,- ...innerProps- }- }}- {...TextFieldProps}- />- );+ return (+ <TextField+ fullWidth+ InputProps={{+ inputComponent,+ inputProps: {+ className: classes.input,+ ref: innerRef,+ children,+ ...innerProps+ }+ }}+ {...TextFieldProps}+ />+ );}function Option(props) {- return (- <MenuItem- ref={props.innerRef}- selected={props.isFocused}- component="div"- style={{- fontWeight: props.isSelected ? 500 : 400- }}- {...props.innerProps}- >- {props.children}- </MenuItem>- );+ return (+ <MenuItem+ ref={props.innerRef}+ selected={props.isFocused}+ component="div"+ style={{+ fontWeight: props.isSelected ? 500 : 400+ }}+ {...props.innerProps}+ >+ {props.children}+ </MenuItem>+ );}function Placeholder(props) {- return (- <Typography- color="textSecondary"- style={{ display: 'block' }}- className={props.selectProps.classes.placeholder}- {...props.innerProps}- >- {props.children}- </Typography>- );+ return (+ <Typography+ color="textSecondary"+ style={{ display: 'block' }}+ className={props.selectProps.classes.placeholder}+ {...props.innerProps}+ >+ {props.children}+ </Typography>+ );}function SingleValue(props) {- return (- <Typography- className={props.selectProps.classes.singleValue}- {...props.innerProps}- >- {props.children}- </Typography>- );+ return (+ <Typography+ className={props.selectProps.classes.singleValue}+ {...props.innerProps}+ >+ {props.children}+ </Typography>+ );}function ValueContainer(props) {- return (- <div className={props.selectProps.classes.valueContainer}>- {props.children}- </div>- );+ return (+ <div className={props.selectProps.classes.valueContainer}>+ {props.children}+ </div>+ );}function MultiValue(props) {- return (- <TagContainer- key={props.data.id || props.data.title}- tag={props.data}- tagMode={'remove'}- deleteIcon={<CloseIcon {...props.removeProps} />}- />- );+ return (+ <TagContainer+ key={props.data.id || props.data.title}+ tag={props.data}+ tagMode={'remove'}+ deleteIcon={<CloseIcon {...props.removeProps} />}+ />+ );}function Menu(props) {- return (- <Paper- elevation={22}- square- className={props.selectProps.classes.paper}- {...props.innerProps}- >- {props.children}- </Paper>- );+ return (+ <Paper+ elevation={22}+ square+ className={props.selectProps.classes.paper}+ {...props.innerProps}+ >+ {props.children}+ </Paper>+ );}const components = {- Control,- Menu,- MultiValue,- NoOptionsMessage,- Option,- Placeholder,- SingleValue,- ValueContainer+ Control,+ Menu,+ MultiValue,+ NoOptionsMessage,+ Option,+ Placeholder,+ SingleValue,+ ValueContainer};-type Props = {- classes: Object;- theme: Object;- tags: Array<tag>;- tagSearchType: string;- handleChange: () => void;- allTags: Array<Tag>;- isReadOnlyMode?: boolean;- placeholderText: string;-};+interface Props {+ classes: any;+ theme: any;+ tags: Array<Tag>;+ tagSearchType: string;+ defaultBackgroundColor?: string;+ defaultTextColor?: string;+ handleChange: (param1: any, param2: any, param3: any) => void;+ allTags: Array<Tag>;+ isReadOnlyMode?: boolean;+ placeholderText: string;+}const TagsSelect = (props: Props) => {- function handleChange(newValue: any, actionMeta: any) {- if (actionMeta.action === 'select-option') {- props.handleChange(props.tagSearchType, newValue, actionMeta.action);- } else if (actionMeta.action === 'create-option') {- props.allTags.push(newValue);- props.handleChange(props.tagSearchType, newValue, actionMeta.action);- } else if (actionMeta.action === 'remove-value') {- props.handleChange(props.tagSearchType, newValue, actionMeta.action);- } else if (actionMeta.action === 'clear') {- props.handleChange(props.tagSearchType, [], actionMeta.action);- }- }+ function handleChange(newValue: any, actionMeta: any) {+ if (actionMeta.action === 'select-option') {+ props.handleChange(props.tagSearchType, newValue, actionMeta.action);+ } else if (actionMeta.action === 'create-option') {+ props.allTags.push(newValue);+ props.handleChange(props.tagSearchType, newValue, actionMeta.action);+ } else if (actionMeta.action === 'remove-value') {+ props.handleChange(props.tagSearchType, newValue, actionMeta.action);+ } else if (actionMeta.action === 'clear') {+ props.handleChange(props.tagSearchType, [], actionMeta.action);+ }+ }- function isValidNewOption(inputValue, selectValue, selectOptions) {- const trimmedInput = inputValue.trim();- return (- trimmedInput.trim().length > 0 &&- !trimmedInput.includes(' ') &&- !trimmedInput.includes('#') &&- !trimmedInput.includes(',') &&- !selectOptions.find(option => option.name === inputValue)- );- }+ function isValidNewOption(inputValue, selectValue, selectOptions) {+ const trimmedInput = inputValue.trim();+ return (+ trimmedInput.trim().length > 0 &&+ !trimmedInput.includes(' ') &&+ !trimmedInput.includes('#') &&+ !trimmedInput.includes(',') &&+ !selectOptions.find(option => option.name === inputValue)+ );+ }- const {- classes,- theme,- allTags,- tags,- defaultBackgroundColor,- defaultTextColor,- isReadOnlyMode = false,- placeholderText = ''- } = props;+ const {+ classes,+ theme,+ allTags,+ tags,+ defaultBackgroundColor,+ defaultTextColor,+ isReadOnlyMode = false,+ placeholderText = ''+ } = props;- const selectStyles = {- input: base => ({- ...base,- color: theme.palette.text.primary,- '& input': {- font: 'inherit'- }- })- };+ const selectStyles = {+ input: base => ({+ ...base,+ color: theme.palette.text.primary,+ '& input': {+ font: 'inherit'+ }+ })+ };- return (- <div className={classes.root}>- <NoSsr>- <CreatableSelect- isClearable={false}- isDisabled={isReadOnlyMode}- classes={classes}- options={allTags}- getOptionLabel={option => option.title}- getOptionValue={option => option.id || option.title}- isValidNewOption={isValidNewOption}- getNewOptionData={(inputValue, optionLabel) => ({- id: uuidv1(),- title: optionLabel,- color: defaultBackgroundColor,- textcolor: defaultTextColor- })}- styles={selectStyles}- fullWidth={true}- components={components}- /* textFieldProps={{+ return (+ <div className={classes.root}>+ <NoSsr>+ <CreatableSelect+ isClearable={false}+ isDisabled={isReadOnlyMode}+ classes={classes}+ options={allTags}+ getOptionLabel={option => option.title}+ getOptionValue={option => option.id || option.title}+ isValidNewOption={isValidNewOption}+ getNewOptionData={(inputValue, optionLabel) => ({+ id: uuidv1(),+ title: optionLabel,+ color: defaultBackgroundColor,+ textcolor: defaultTextColor+ })}+ styles={selectStyles}+ fullWidth={true}+ components={components}+ /* textFieldProps={{label: 'title',InputLabelProps: {shrink: true,},}} */- value={tags}- onChange={handleChange}- placeholder={placeholderText}- isMulti- formatCreateLabel={label => label}- // isSearchable- />- </NoSsr>- </div>- );+ value={tags}+ onChange={handleChange}+ placeholder={placeholderText}+ isMulti+ formatCreateLabel={label => label}+ // isSearchable+ />+ </NoSsr>+ </div>+ );};const mapStateToProps = state => ({- allTags: getAllTags(state),- defaultBackgroundColor: getTagColor(state),- defaultTextColor: getTagTextColor(state)+ allTags: getAllTags(state),+ defaultBackgroundColor: getTagColor(state),+ defaultTextColor: getTagTextColor(state)});export default connect(mapStateToProps)(- withStyles(styles, { withTheme: true })(TagsSelect)+ withStyles(styles, { withTheme: true })(TagsSelect));diff --git a/app/components/TargetFileBox.tsx b/app/components/TargetFileBox.tsxindex 291382848..c75d54537 100644--- a/app/components/TargetFileBox.tsx+++ b/app/components/TargetFileBox.tsx@@ -21,7 +21,7 @@ import { DropTarget } from 'react-dnd';import { withStyles } from '@material-ui/core/styles/index';import i18n from '../services/i18n';-const styles = theme => ({+const styles: any = (theme: any) => ({dropzone: {margin: 5,position: 'absolute',@@ -53,13 +53,13 @@ const boxTarget = {}};-type Props = {- classes: Object,- canDrop: boolean,- isOver: boolean,- connectDropTarget: Object,- children: Object-};+interface Props {+ classes?: any;+ canDrop: boolean;+ isOver: boolean;+ connectDropTarget: any;+ children: Object;+}const TargetFileBox = (props: Props) => {const { classes, canDrop, isOver, connectDropTarget, children } = props;diff --git a/app/components/dialogs/ColorPickerDialog.tsx b/app/components/dialogs/ColorPickerDialog.tsxindex 271c79cc7..1db825e2c 100644--- a/app/components/dialogs/ColorPickerDialog.tsx+++ b/app/components/dialogs/ColorPickerDialog.tsx@@ -55,7 +55,7 @@ const presetColors = [];interface Props {- classes: Object;+ classes: any;open: boolean;color: string;setColor: (color: string) => void;@@ -84,7 +84,7 @@ const ColorPickerDialog = (props: Props) => {props.onClose();}- function handleChangeComplete(newColor: Object) {+ function handleChangeComplete(newColor: any) {setColor(newColor.rgb);setColorHex(newColor.hex);}diff --git a/app/components/dialogs/CreateDialog.tsx b/app/components/dialogs/CreateDialog.tsxindex 0b7c14ad7..2e7fa61f7 100644--- a/app/components/dialogs/CreateDialog.tsx+++ b/app/components/dialogs/CreateDialog.tsx@@ -44,7 +44,7 @@ import { formatDateTime4Tag } from '../../utils/misc';// return <Slide direction="down" ref={ref} {...props} />;// });-const styles = () => ({+const styles: any = () => ({root: {dispatch: 'flex',minWidth: 200,@@ -65,18 +65,19 @@ const styles = () => ({});type Props = {- open: boolean,- classes: Object,- selectedDirectoryPath: string,- showNotification: (message: string, type: string, autohide: boolean) => void,- reflectCreateEntry: (path: string, isFile: boolean) => void,+ open: boolean;+ classes: any;+ selectedDirectoryPath: string;+ chooseDirectoryPath: (path: string) => void;+ showNotification: (message: string, type: string, autohide: boolean) => void;+ reflectCreateEntry: (path: string, isFile: boolean) => void;createFileAdvanced: (targetPath: string,fileName: string,content: string,fileType: string- ) => void,- onClose: () => void+ ) => void;+ onClose: () => void;};const CreateDialog = (props: Props) => {@@ -169,7 +170,7 @@ const CreateDialog = (props: Props) => {// });// }- function handleFileInputChange(selection: Object) {+ function handleFileInputChange(selection: any) {// console.log("Selected File: "+JSON.stringify(selection.currentTarget.files[0]));const file = selection.currentTarget.files[0];const filePath =@@ -178,7 +179,7 @@ const CreateDialog = (props: Props) => {decodeURIComponent(file.name);const reader = new FileReader();- reader.onload = event => {+ reader.onload = (event: any) => {PlatformIO.getPropertiesPromise(filePath).then(entryProps => {if (entryProps) {@@ -288,6 +289,7 @@ const CreateDialog = (props: Props) => {<inputstyle={{ display: 'none' }}ref={input => {+ // @ts-ignorefileInput = input;}}accept="*"diff --git a/app/components/dialogs/CreateDirectoryDialog.tsx b/app/components/dialogs/CreateDirectoryDialog.tsxindex fb7771db2..4dc6b459f 100644--- a/app/components/dialogs/CreateDirectoryDialog.tsx+++ b/app/components/dialogs/CreateDirectoryDialog.tsx@@ -31,12 +31,13 @@ import i18n from '../../services/i18n';import AppConfig from '../../config';import { actions as AppActions } from '../../reducers/app';-type Props = {- open: boolean,- onClose: () => void,- selectedDirectoryPath: string,- createDirectory: (directoryPath: string) => void-};+interface Props {+ open: boolean;+ onClose: () => void;+ fullScreen?: boolean;+ selectedDirectoryPath: string;+ createDirectory: (directoryPath: string) => void;+}const CreateDirectoryDialog = (props: Props) => {const [inputError, setInputError] = useState(false);diff --git a/app/components/dialogs/CreateTagGroupDialog.tsx b/app/components/dialogs/CreateTagGroupDialog.tsxindex e7f87d412..f262f6343 100644--- a/app/components/dialogs/CreateTagGroupDialog.tsx+++ b/app/components/dialogs/CreateTagGroupDialog.tsx@@ -31,219 +31,220 @@ import i18n from '../../services/i18n';import TransparentBackground from '../TransparentBackground';interface Props {- open: boolean;- onClose: () => void;- createTagGroup: (tagGroup: TagGroup) => void;- fullScreen: boolean;- color: string;- textcolor: string;+ open: boolean;+ onClose: () => void;+ createTagGroup: (tagGroup: TagGroup) => void;+ fullScreen?: boolean;+ color: string;+ textcolor: string;}interface State {- inputError: boolean;- displayColorPicker: boolean;- displayTextColorPicker: boolean;- disableConfirmButton: boolean;- uuid: string;- title: string;- color: string;- textcolor: string;- children: string;- expanded: boolean;+ inputError: boolean;+ displayColorPicker: boolean;+ displayTextColorPicker: boolean;+ disableConfirmButton: boolean;+ uuid: string;+ title: string;+ color: string;+ textcolor: string;+ children: string;+ expanded: boolean;}class CreateTagGroupDialog extends React.Component<Props, State> {- state = {- displayColorPicker: false,- displayTextColorPicker: false,- inputError: false,- disableConfirmButton: true,- title: '',- children: '',- color: this.props.color,- textcolor: this.props.textcolor,- expanded: true,- uuid: ''- };-- handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {- const target = event.target;- const value = target.type === 'checkbox' ? target.checked : target.value;- const name = target.name;-- this.setState(- {- [name]: value- },- this.handleValidation- );- };-- handleValidation() {- if (this.state.title.length > 0) {- this.setState({ inputError: false, disableConfirmButton: false });- } else {- this.setState({ inputError: true, disableConfirmButton: true });- }- }-- onConfirm = () => {- if (!this.state.disableConfirmButton) {- this.props.createTagGroup({- uuid: this.state.uuid,- title: this.state.title,- expanded: true,- color: this.state.color,- textcolor: this.state.textcolor,- children: []- });- this.setState({ inputError: false, disableConfirmButton: true });- this.props.onClose();- }- };-- toggleDefaultTagBackgroundColorPicker = () => {- this.setState(prevState => ({- displayColorPicker: !prevState.displayColorPicker- }));- };-- toggleDefaultTagTextColorPicker = () => {- this.setState(prevState => ({- displayTextColorPicker: !prevState.displayTextColorPicker- }));- };-- handleChangeColor = (color: string) => {- this.setState({ color });- };-- handleChangeTextColor = (color: string) => {- this.setState({ textcolor: color });- };-- render() {- const { fullScreen, open, onClose } = this.props;-- const styles = {- color: {- width: '100%',- height: 30,- borderRadius: 2,- borderWidth: 1,- borderStyle: 'solid',- borderColor: 'gray',- background: this.state.color- },- textcolor: {- width: '100%',- height: 30,- borderRadius: 2,- borderWidth: 1,- borderStyle: 'solid',- borderColor: 'gray',- background: this.state.textcolor- },- swatch: {- padding: '5px',- borderRadius: '1px',- boxShadow: '0 0 0 1px rgba(0,0,0,.1)',- display: 'inline-block',- cursor: 'pointer'- },- helpText: {- marginBottom: '5px',- fontSize: '1rem'- }- };-- return (- <Dialog- open={open}- onClose={onClose}- fullScreen={fullScreen}- keepMounted- scroll="paper"- // onKeyDown={confirmFunction}- >- <DialogTitle>{i18n.t('core:createTagGroupTitle')}</DialogTitle>- <DialogContent>- <FormControl fullWidth={true} error={this.state.inputError}>- <TextField- fullWidth={true}- error={this.state.inputError}- autoFocus- name="title"- label={i18n.t('core:createTagGroupName')}- value={this.state.title}- onChange={this.handleInputChange}- data-tid="createTagGroupInput"- />- {this.state.inputError && (- <FormHelperText>- {i18n.t('core:taggroupTitleHelper')}- </FormHelperText>- )}- </FormControl>- <FormControl fullWidth={true}>- <FormHelperText style={styles.helpText}>- {i18n.t('core:tagBackgroundColor')}- </FormHelperText>- <TransparentBackground>- <Button- onClick={this.toggleDefaultTagBackgroundColorPicker}- data-tid="createTagGroupBackgroundColor"- style={styles.color}- role="presentation"- >- - </Button>- </TransparentBackground>- <ColorPickerDialog- open={this.state.displayColorPicker}- setColor={this.handleChangeColor}- onClose={this.toggleDefaultTagBackgroundColorPicker}- color={this.state.color}- />- </FormControl>- <FormControl fullWidth={true}>- <FormHelperText style={styles.helpText}>- {i18n.t('core:tagForegroundColor')}- </FormHelperText>- <TransparentBackground>- <Button- onClick={this.toggleDefaultTagTextColorPicker}- data-tid="createTagGroupForegroundColor"- style={styles.textcolor}- role="presentation"- >- - </Button>- </TransparentBackground>- <ColorPickerDialog- open={this.state.displayTextColorPicker}- setColor={this.handleChangeTextColor}- onClose={this.toggleDefaultTagTextColorPicker}- color={this.state.textcolor}- />- </FormControl>- </DialogContent>- <DialogActions>- <Button onClick={this.props.onClose} color="primary">- {i18n.t('core:cancel')}- </Button>- <Button- disabled={this.state.disableConfirmButton}- onClick={this.onConfirm}- data-tid="createTagGroupConfirmButton"- color="primary"- >- {i18n.t('core:ok')}- </Button>- </DialogActions>- </Dialog>- );- }+ state = {+ displayColorPicker: false,+ displayTextColorPicker: false,+ inputError: false,+ disableConfirmButton: true,+ title: '',+ children: '',+ color: this.props.color,+ textcolor: this.props.textcolor,+ expanded: true,+ uuid: ''+ };++ handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {+ const target = event.target;+ const value = target.type === 'checkbox' ? target.checked : target.value;+ const name = target.name;++ this.setState(+ // @ts-ignore+ {+ [name]: value+ },+ this.handleValidation+ );+ };++ handleValidation() {+ if (this.state.title.length > 0) {+ this.setState({ inputError: false, disableConfirmButton: false });+ } else {+ this.setState({ inputError: true, disableConfirmButton: true });+ }+ }++ onConfirm = () => {+ if (!this.state.disableConfirmButton) {+ this.props.createTagGroup({+ uuid: this.state.uuid,+ title: this.state.title,+ expanded: true,+ color: this.state.color,+ textcolor: this.state.textcolor,+ children: []+ });+ this.setState({ inputError: false, disableConfirmButton: true });+ this.props.onClose();+ }+ };++ toggleDefaultTagBackgroundColorPicker = () => {+ this.setState(prevState => ({+ displayColorPicker: !prevState.displayColorPicker+ }));+ };++ toggleDefaultTagTextColorPicker = () => {+ this.setState(prevState => ({+ displayTextColorPicker: !prevState.displayTextColorPicker+ }));+ };++ handleChangeColor = (color: string) => {+ this.setState({ color });+ };++ handleChangeTextColor = (color: string) => {+ this.setState({ textcolor: color });+ };++ render() {+ const { fullScreen, open, onClose } = this.props;++ const styles = {+ color: {+ width: '100%',+ height: 30,+ borderRadius: 2,+ borderWidth: 1,+ borderStyle: 'solid',+ borderColor: 'gray',+ background: this.state.color+ },+ textcolor: {+ width: '100%',+ height: 30,+ borderRadius: 2,+ borderWidth: 1,+ borderStyle: 'solid',+ borderColor: 'gray',+ background: this.state.textcolor+ },+ swatch: {+ padding: '5px',+ borderRadius: '1px',+ boxShadow: '0 0 0 1px rgba(0,0,0,.1)',+ display: 'inline-block',+ cursor: 'pointer'+ },+ helpText: {+ marginBottom: '5px',+ fontSize: '1rem'+ }+ };++ return (+ <Dialog+ open={open}+ onClose={onClose}+ fullScreen={fullScreen}+ keepMounted+ scroll="paper"+ // onKeyDown={confirmFunction}+ >+ <DialogTitle>{i18n.t('core:createTagGroupTitle')}</DialogTitle>+ <DialogContent>+ <FormControl fullWidth={true} error={this.state.inputError}>+ <TextField+ fullWidth={true}+ error={this.state.inputError}+ autoFocus+ name="title"+ label={i18n.t('core:createTagGroupName')}+ value={this.state.title}+ onChange={this.handleInputChange}+ data-tid="createTagGroupInput"+ />+ {this.state.inputError && (+ <FormHelperText>+ {i18n.t('core:taggroupTitleHelper')}+ </FormHelperText>+ )}+ </FormControl>+ <FormControl fullWidth={true}>+ <FormHelperText style={styles.helpText}>+ {i18n.t('core:tagBackgroundColor')}+ </FormHelperText>+ <TransparentBackground>+ <Button+ onClick={this.toggleDefaultTagBackgroundColorPicker}+ data-tid="createTagGroupBackgroundColor"+ style={styles.color}+ role="presentation"+ >+ + </Button>+ </TransparentBackground>+ <ColorPickerDialog+ open={this.state.displayColorPicker}+ setColor={this.handleChangeColor}+ onClose={this.toggleDefaultTagBackgroundColorPicker}+ color={this.state.color}+ />+ </FormControl>+ <FormControl fullWidth={true}>+ <FormHelperText style={styles.helpText}>+ {i18n.t('core:tagForegroundColor')}+ </FormHelperText>+ <TransparentBackground>+ <Button+ onClick={this.toggleDefaultTagTextColorPicker}+ data-tid="createTagGroupForegroundColor"+ style={styles.textcolor}+ role="presentation"+ >+ + </Button>+ </TransparentBackground>+ <ColorPickerDialog+ open={this.state.displayTextColorPicker}+ setColor={this.handleChangeTextColor}+ onClose={this.toggleDefaultTagTextColorPicker}+ color={this.state.textcolor}+ />+ </FormControl>+ </DialogContent>+ <DialogActions>+ <Button onClick={this.props.onClose} color="primary">+ {i18n.t('core:cancel')}+ </Button>+ <Button+ disabled={this.state.disableConfirmButton}+ onClick={this.onConfirm}+ data-tid="createTagGroupConfirmButton"+ color="primary"+ >+ {i18n.t('core:ok')}+ </Button>+ </DialogActions>+ </Dialog>+ );+ }}export default CreateTagGroupDialog;diff --git a/app/components/dialogs/CreateTagsDialog.tsx b/app/components/dialogs/CreateTagsDialog.tsxindex fd2f4a4a5..2e97ceb3d 100644--- a/app/components/dialogs/CreateTagsDialog.tsx+++ b/app/components/dialogs/CreateTagsDialog.tsx@@ -29,106 +29,107 @@ import i18n from '../../services/i18n';import { TagGroup } from '../../reducers/taglibrary';interface Props {- open: boolean;- onClose: () => void;- addTag: (tags: string, uuid: string) => void;- fullScreen: boolean;- selectedTagGroupEntry: TagGroup;+ open: boolean;+ onClose: () => void;+ addTag: (tags: string, uuid: string) => void;+ fullScreen?: boolean;+ selectedTagGroupEntry: TagGroup;}interface State {- inputError: boolean;- disableConfirmButton: boolean;- open: boolean;- tagTitle: string;+ inputError: boolean;+ disableConfirmButton: boolean;+ open: boolean;+ tagTitle: string;}class CreateTagsDialog extends React.Component<Props, State> {- state = {- inputError: false,- disableConfirmButton: true,- open: false,- tagTitle: ''- };+ state = {+ inputError: false,+ disableConfirmButton: true,+ open: false,+ tagTitle: ''+ };- handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {- const target = event.target;- const value = target.type === 'checkbox' ? target.checked : target.value;- const name = target.name;+ handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {+ const target = event.target;+ const value = target.type === 'checkbox' ? target.checked : target.value;+ const name = target.name;- this.setState(- {- [name]: value- },- this.handleValidation- );- };+ this.setState(+ // @ts-ignore+ {+ [name]: value+ },+ this.handleValidation+ );+ };- handleValidation() {- const tagCheck = RegExp(/^[^\#\/\\[\]]{1,}$/);- if (this.state.tagTitle && tagCheck.test(this.state.tagTitle)) {- this.setState({ inputError: false, disableConfirmButton: false });- } else {- this.setState({ inputError: true, disableConfirmButton: true });- }- }+ handleValidation() {+ const tagCheck = RegExp(/^[^\#\/\\[\]]{1,}$/);+ if (this.state.tagTitle && tagCheck.test(this.state.tagTitle)) {+ this.setState({ inputError: false, disableConfirmButton: false });+ } else {+ this.setState({ inputError: true, disableConfirmButton: true });+ }+ }- onConfirm = () => {- if (!this.state.disableConfirmButton) {- this.setState({ open: false, disableConfirmButton: true });- this.props.addTag(- this.state.tagTitle,- this.props.selectedTagGroupEntry.uuid- );- this.props.onClose();- }- };+ onConfirm = () => {+ if (!this.state.disableConfirmButton) {+ this.setState({ open: false, disableConfirmButton: true });+ this.props.addTag(+ this.state.tagTitle,+ this.props.selectedTagGroupEntry.uuid+ );+ this.props.onClose();+ }+ };- render() {- const { fullScreen, open, onClose } = this.props;+ render() {+ const { fullScreen, open, onClose } = this.props;- return (- <Dialog- open={open}- onClose={onClose}- fullScreen={fullScreen}- keepMounted- scroll="paper"- >- <DialogTitle>{i18n.t('core:addTagsToGroupTitle')}</DialogTitle>- <DialogContent style={{ minWidth: 400 }}>- <FormControl fullWidth={true} error={this.state.inputError}>- <TextField- error={this.state.inputError}- name="tagTitle"- autoFocus- label={i18n.t('core:addTagsToGroupTagsPlaceholder')}- onChange={this.handleInputChange}- value={this.state.tagTitle}- data-tid="addTagsInput"- fullWidth={true}- />- {this.state.inputError && (- <FormHelperText>{i18n.t('core:tagTitleHelper')}</FormHelperText>- )}- </FormControl>- </DialogContent>- <DialogActions>- <Button onClick={this.props.onClose} color="primary">- {i18n.t('core:cancel')}- </Button>- <Button- disabled={this.state.disableConfirmButton}- onClick={this.onConfirm}- data-tid="createTagsConfirmButton"- color="primary"- >- {i18n.t('core:ok')}- </Button>- </DialogActions>- </Dialog>- );- }+ return (+ <Dialog+ open={open}+ onClose={onClose}+ fullScreen={fullScreen}+ keepMounted+ scroll="paper"+ >+ <DialogTitle>{i18n.t('core:addTagsToGroupTitle')}</DialogTitle>+ <DialogContent style={{ minWidth: 400 }}>+ <FormControl fullWidth={true} error={this.state.inputError}>+ <TextField+ error={this.state.inputError}+ name="tagTitle"+ autoFocus+ label={i18n.t('core:addTagsToGroupTagsPlaceholder')}+ onChange={this.handleInputChange}+ value={this.state.tagTitle}+ data-tid="addTagsInput"+ fullWidth={true}+ />+ {this.state.inputError && (+ <FormHelperText>{i18n.t('core:tagTitleHelper')}</FormHelperText>+ )}+ </FormControl>+ </DialogContent>+ <DialogActions>+ <Button onClick={this.props.onClose} color="primary">+ {i18n.t('core:cancel')}+ </Button>+ <Button+ disabled={this.state.disableConfirmButton}+ onClick={this.onConfirm}+ data-tid="createTagsConfirmButton"+ color="primary"+ >+ {i18n.t('core:ok')}+ </Button>+ </DialogActions>+ </Dialog>+ );+ }}export default CreateTagsDialog;diff --git a/app/components/dialogs/Dialogs.css.tsx b/app/components/dialogs/Dialogs.css.tsxindex 39afe5423..80acd16ee 100644--- a/app/components/dialogs/Dialogs.css.tsx+++ b/app/components/dialogs/Dialogs.css.tsx@@ -16,12 +16,12 @@**/-export default (theme: Object) => ({- panel: {- height: '100%',- maxHeight: '100%',- padding: 5,- overflowY: 'hidden',- backgroundColor: theme.palette.background.default- }+export default (theme: any) => ({+ panel: {+ height: '100%',+ maxHeight: '100%',+ padding: 5,+ overflowY: 'hidden',+ backgroundColor: theme.palette.background.default+ }});diff --git a/app/components/dialogs/EditTagDialog.tsx b/app/components/dialogs/EditTagDialog.tsxindex f7b0bda2d..7f425ef5c 100644--- a/app/components/dialogs/EditTagDialog.tsx+++ b/app/components/dialogs/EditTagDialog.tsx@@ -32,256 +32,258 @@ import i18n from '../../services/i18n';import { Tag, TagGroup } from '../../reducers/taglibrary';interface Props {- open: boolean;- onClose: () => void;- editTag: (tag: Tag, tagGroupId: string) => void;- selectedTag: Tag;- selectedTagGroupEntry: TagGroup;+ open: boolean;+ fullScreen?: boolean;+ onClose: () => void;+ editTag: (tag: Tag, tagGroupId: string) => void;+ selectedTag: Tag;+ selectedTagGroupEntry: TagGroup;}interface State {- inputError: boolean;- displayColorPicker: boolean;- displayTextColorPicker: boolean;- disableConfirmButton: boolean;- title: string;- color: string;- textcolor: string;- modifiedDate: string;+ inputError: boolean;+ displayColorPicker: boolean;+ displayTextColorPicker: boolean;+ disableConfirmButton: boolean;+ title: string;+ color: string;+ textcolor: string;+ modifiedDate: string;}class EditTagDialog extends React.Component<Props, State> {- state = {- displayColorPicker: false,- displayTextColorPicker: false,- inputError: false,- disableConfirmButton: true,- title: '',- color: '',- textcolor: '',- modifiedDate: ''- };+ state = {+ displayColorPicker: false,+ displayTextColorPicker: false,+ inputError: false,+ disableConfirmButton: true,+ title: '',+ color: '',+ textcolor: '',+ modifiedDate: ''+ };- componentWillReceiveProps = ({ open, selectedTag }: Props) => {- if (open === true) {- this.setState({- disableConfirmButton: !selectedTag.title,- title: selectedTag.title,- color: selectedTag.color,- textcolor: selectedTag.textcolor,- modifiedDate: selectedTag.modified_date- });- }- };+ componentWillReceiveProps = ({ open, selectedTag }: Props) => {+ if (open === true) {+ this.setState({+ disableConfirmButton: !selectedTag.title,+ title: selectedTag.title,+ color: selectedTag.color,+ textcolor: selectedTag.textcolor,+ modifiedDate: selectedTag.modified_date+ });+ }+ };- handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {- const target = event.target;- const value = target.type === 'checkbox' ? target.checked : target.value;- const name = target.name;+ handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {+ const target = event.target;+ const value = target.type === 'checkbox' ? target.checked : target.value;+ const name = target.name;- this.setState(- {- [name]: value- },- this.handleValidation- );- };+ this.setState(+ // @ts-ignore+ {+ [name]: value+ },+ this.handleValidation+ );+ };- handleValidation() {- const tagCheck = RegExp(/^[^\#\/\\ \[\]]{1,}$/);- if (this.state.title && tagCheck.test(this.state.title)) {- this.setState({ inputError: false, disableConfirmButton: false });- } else {- this.setState({ inputError: true, disableConfirmButton: true });- }- }+ handleValidation() {+ const tagCheck = RegExp(/^[^\#\/\\ \[\]]{1,}$/);+ if (this.state.title && tagCheck.test(this.state.title)) {+ this.setState({ inputError: false, disableConfirmButton: false });+ } else {+ this.setState({ inputError: true, disableConfirmButton: true });+ }+ }- onConfirm = () => {- if (- !this.state.disableConfirmButton &&- this.props.editTag &&- this.props.selectedTagGroupEntry &&- this.props.selectedTag- ) {- this.props.editTag(- {- ...this.props.selectedTag,- title: this.state.title,- color: this.state.color,- textcolor: this.state.textcolor- },- this.props.selectedTagGroupEntry.uuid- );- this.setState({ inputError: false, disableConfirmButton: true });- this.props.onClose();- }- };+ onConfirm = () => {+ if (+ !this.state.disableConfirmButton &&+ this.props.editTag &&+ this.props.selectedTagGroupEntry &&+ this.props.selectedTag+ ) {+ this.props.editTag(+ {+ ...this.props.selectedTag,+ title: this.state.title,+ color: this.state.color,+ textcolor: this.state.textcolor+ },+ this.props.selectedTagGroupEntry.uuid+ );+ this.setState({ inputError: false, disableConfirmButton: true });+ this.props.onClose();+ }+ };- toggleDefaultTagBackgroundColorPicker = () => {- this.setState({- displayColorPicker: !this.state.displayColorPicker- });- };+ toggleDefaultTagBackgroundColorPicker = () => {+ this.setState({+ displayColorPicker: !this.state.displayColorPicker+ });+ };- toggleDefaultTagTextColorPicker = () => {- this.setState({- displayTextColorPicker: !this.state.displayTextColorPicker- });- };+ toggleDefaultTagTextColorPicker = () => {+ this.setState({+ displayTextColorPicker: !this.state.displayTextColorPicker+ });+ };- handleChangeColor = (color: string) => {- this.setState({ color });- };+ handleChangeColor = (color: string) => {+ this.setState({ color });+ };- handleChangeTextColor = (color: string) => {- this.setState({ textcolor: color });- };+ handleChangeTextColor = (color: string) => {+ this.setState({ textcolor: color });+ };- render() {- const { color, textcolor, modifiedDate } = this.state;- const { fullScreen, open, onClose } = this.props;- const styles = {- color: {- width: '100%',- height: 30,- borderRadius: 2,- borderWidth: 1,- borderStyle: 'solid',- borderColor: 'gray',- padding: '5px',- background: color- },- textcolor: {- width: '100%',- height: 30,- borderRadius: 2,- borderWidth: 1,- borderStyle: 'solid',- borderColor: 'gray',- padding: '5px',- background: textcolor- },- helpText: {- marginBottom: '5px',- fontSize: '1rem'- }- };+ render() {+ const { color, textcolor, modifiedDate } = this.state;+ const { fullScreen, open, onClose } = this.props;+ const styles = {+ color: {+ width: '100%',+ height: 30,+ borderRadius: 2,+ borderWidth: 1,+ borderStyle: 'solid',+ borderColor: 'gray',+ padding: '5px',+ background: color+ },+ textcolor: {+ width: '100%',+ height: 30,+ borderRadius: 2,+ borderWidth: 1,+ borderStyle: 'solid',+ borderColor: 'gray',+ padding: '5px',+ background: textcolor+ },+ helpText: {+ marginBottom: '5px',+ fontSize: '1rem'+ }+ };- return (- <Dialog- open={open}- fullScreen={fullScreen}- onClose={onClose}- keepMounted- scroll="paper"- // onEnterKey={(event) => onEnterKeyHandler(event, this.addTags)}- >- <DialogTitle style={{ overflow: 'visible' }}>- {i18n.t('core:editTagTitle')}- {` '${this.state.title}'`}- </DialogTitle>- <DialogContent style={{ overflow: 'visible' }}>- <FormControl- fullWidth={true}- error={this.state.inputError}- style={{ overflow: 'visible' }}- >- {modifiedDate && (- <div- className="tag-date"- style={{- fontSize: 12,- position: 'relative',- bottom: 20,- color: '#808080'- }}- >- <span className="text" style={{ fontWeight: 600 }}>{`${i18n.t(- 'core:modifiedDate'- )}: `}</span>- <time>{format(new Date(modifiedDate), 'yyyy-mm-dd')}</time>- </div>- )}- <TextField- error={this.state.inputError}- margin="dense"- name="title"- autoFocus- label={i18n.t('core:editTag')}- onChange={this.handleInputChange}- value={this.state.title}- data-tid="editTagInput"- fullWidth={true}- />- {this.state.inputError && (- <FormHelperText style={styles.helpText}>- {i18n.t('core:tagTitleHelper')}- </FormHelperText>- )}- </FormControl>- <FormControl fullWidth={true}>- <FormHelperText style={styles.helpText}>- {i18n.t('core:tagBackgroundColor')}- </FormHelperText>- <TransparentBackground>- <Button- onClick={this.toggleDefaultTagBackgroundColorPicker}- data-tid="tagBackgroundColorEditTagDialog"- style={styles.color}- role="presentation"- >- - </Button>- </TransparentBackground>- <ColorPickerDialog- open={this.state.displayColorPicker}- setColor={this.handleChangeColor}- onClose={this.toggleDefaultTagBackgroundColorPicker}- color={this.state.color}- />- </FormControl>- <FormControl fullWidth={true}>- <FormHelperText style={styles.helpText}>- {i18n.t('core:tagForegroundColor')}- </FormHelperText>- <TransparentBackground>- <Button- onClick={this.toggleDefaultTagTextColorPicker}- data-tid="tagForegroundColorEditTagDialog"- style={styles.textcolor}- role="presentation"- >- - </Button>- </TransparentBackground>- <ColorPickerDialog- open={this.state.displayTextColorPicker}- setColor={this.handleChangeTextColor}- onClose={this.toggleDefaultTagTextColorPicker}- color={this.state.textcolor}- />- </FormControl>- </DialogContent>- <DialogActions>- <Button- onClick={this.props.onClose}- data-tid="closeEditTagDialog"- color="primary"- >- {i18n.t('core:cancel')}- </Button>- <Button- disabled={this.state.disableConfirmButton}- onClick={this.onConfirm}- data-tid="editTagConfirm"- color="primary"- >- {i18n.t('core:ok')}- </Button>- </DialogActions>- </Dialog>- );- }+ return (+ <Dialog+ open={open}+ fullScreen={fullScreen}+ onClose={onClose}+ keepMounted+ scroll="paper"+ // onEnterKey={(event) => onEnterKeyHandler(event, this.addTags)}+ >+ <DialogTitle style={{ overflow: 'visible' }}>+ {i18n.t('core:editTagTitle')}+ {` '${this.state.title}'`}+ </DialogTitle>+ <DialogContent style={{ overflow: 'visible' }}>+ <FormControl+ fullWidth={true}+ error={this.state.inputError}+ style={{ overflow: 'visible' }}+ >+ {modifiedDate && (+ <div+ className="tag-date"+ style={{+ fontSize: 12,+ position: 'relative',+ bottom: 20,+ color: '#808080'+ }}+ >+ <span className="text" style={{ fontWeight: 600 }}>{`${i18n.t(+ 'core:modifiedDate'+ )}: `}</span>+ <time>{format(new Date(modifiedDate), 'yyyy-mm-dd')}</time>+ </div>+ )}+ <TextField+ error={this.state.inputError}+ margin="dense"+ name="title"+ autoFocus+ label={i18n.t('core:editTag')}+ onChange={this.handleInputChange}+ value={this.state.title}+ data-tid="editTagInput"+ fullWidth={true}+ />+ {this.state.inputError && (+ <FormHelperText style={styles.helpText}>+ {i18n.t('core:tagTitleHelper')}+ </FormHelperText>+ )}+ </FormControl>+ <FormControl fullWidth={true}>+ <FormHelperText style={styles.helpText}>+ {i18n.t('core:tagBackgroundColor')}+ </FormHelperText>+ <TransparentBackground>+ <Button+ onClick={this.toggleDefaultTagBackgroundColorPicker}+ data-tid="tagBackgroundColorEditTagDialog"+ style={styles.color}+ role="presentation"+ >+ + </Button>+ </TransparentBackground>+ <ColorPickerDialog+ open={this.state.displayColorPicker}+ setColor={this.handleChangeColor}+ onClose={this.toggleDefaultTagBackgroundColorPicker}+ color={this.state.color}+ />+ </FormControl>+ <FormControl fullWidth={true}>+ <FormHelperText style={styles.helpText}>+ {i18n.t('core:tagForegroundColor')}+ </FormHelperText>+ <TransparentBackground>+ <Button+ onClick={this.toggleDefaultTagTextColorPicker}+ data-tid="tagForegroundColorEditTagDialog"+ style={styles.textcolor}+ role="presentation"+ >+ + </Button>+ </TransparentBackground>+ <ColorPickerDialog+ open={this.state.displayTextColorPicker}+ setColor={this.handleChangeTextColor}+ onClose={this.toggleDefaultTagTextColorPicker}+ color={this.state.textcolor}+ />+ </FormControl>+ </DialogContent>+ <DialogActions>+ <Button+ onClick={this.props.onClose}+ data-tid="closeEditTagDialog"+ color="primary"+ >+ {i18n.t('core:cancel')}+ </Button>+ <Button+ disabled={this.state.disableConfirmButton}+ onClick={this.onConfirm}+ data-tid="editTagConfirm"+ color="primary"+ >+ {i18n.t('core:ok')}+ </Button>+ </DialogActions>+ </Dialog>+ );+ }}export default EditTagDialog;diff --git a/app/components/dialogs/EditTagGroupDialog.tsx b/app/components/dialogs/EditTagGroupDialog.tsxindex 7902ea5e2..93787ca3d 100644--- a/app/components/dialogs/EditTagGroupDialog.tsx+++ b/app/components/dialogs/EditTagGroupDialog.tsx@@ -33,280 +33,282 @@ import i18n from '../../services/i18n';import TransparentBackground from '../TransparentBackground';interface Props {- open: boolean;- editTagGroup: (tagGroup: TagGroup) => void;- selectedTagGroupEntry: TagGroup;- onClose: () => void;+ open: boolean;+ fullScreen?: boolean;+ editTagGroup: (tagGroup: TagGroup) => void;+ selectedTagGroupEntry: TagGroup;+ onClose: () => void;}interface State {- inputError: boolean;- displayColorPicker: boolean;- displayTextColorPicker: boolean;- disableConfirmButton: boolean;- title: string;- applyChanges: boolean;- color: string;- textcolor: string;- modifiedDate: string;+ inputError: boolean;+ displayColorPicker: boolean;+ displayTextColorPicker: boolean;+ disableConfirmButton: boolean;+ title: string;+ applyChanges: boolean;+ color: string;+ textcolor: string;+ modifiedDate: string;}class EditTagGroupDialog extends React.Component<Props, State> {- state = {- displayColorPicker: false,- displayTextColorPicker: false,- inputError: false,- disableConfirmButton: true,- applyChanges: false,- title: '',- color: '',- textcolor: '',- modifiedDate: ''- };+ state = {+ displayColorPicker: false,+ displayTextColorPicker: false,+ inputError: false,+ disableConfirmButton: true,+ applyChanges: false,+ title: '',+ color: '',+ textcolor: '',+ modifiedDate: ''+ };- componentWillReceiveProps = ({ open, selectedTagGroupEntry }) => {- if (open === true) {- this.setState({- disableConfirmButton: !selectedTagGroupEntry.title,- applyChanges: false,- title: selectedTagGroupEntry.title,- color: selectedTagGroupEntry.color,- textcolor: selectedTagGroupEntry.textcolor,- modifiedDate: selectedTagGroupEntry.modified_date- });- }- };+ componentWillReceiveProps = ({ open, selectedTagGroupEntry }) => {+ if (open === true) {+ this.setState({+ disableConfirmButton: !selectedTagGroupEntry.title,+ applyChanges: false,+ title: selectedTagGroupEntry.title,+ color: selectedTagGroupEntry.color,+ textcolor: selectedTagGroupEntry.textcolor,+ modifiedDate: selectedTagGroupEntry.modified_date+ });+ }+ };- handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {- const target = event.target;- const value = target.type === 'checkbox' ? target.checked : target.value;- const name = target.name;+ handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {+ const target = event.target;+ const value = target.type === 'checkbox' ? target.checked : target.value;+ const name = target.name;- this.setState(- {- [name]: value- },- this.handleValidation- );- };+ this.setState(+ // @ts-ignore+ {+ [name]: value+ },+ this.handleValidation+ );+ };- handleValidation() {- if (this.state.title && this.state.title.length > 0) {- this.setState({ inputError: false, disableConfirmButton: false });- } else {- this.setState({ inputError: true, disableConfirmButton: true });- }- }+ handleValidation() {+ if (this.state.title && this.state.title.length > 0) {+ this.setState({ inputError: false, disableConfirmButton: false });+ } else {+ this.setState({ inputError: true, disableConfirmButton: true });+ }+ }- onConfirm = () => {- const { disableConfirmButton, applyChanges } = this.state;- const { selectedTagGroupEntry } = this.props;- if (disableConfirmButton) {- return;- }+ onConfirm = () => {+ const { disableConfirmButton, applyChanges } = this.state;+ const { selectedTagGroupEntry } = this.props;+ if (disableConfirmButton) {+ return;+ }- if (selectedTagGroupEntry && selectedTagGroupEntry.children) {- this.props.editTagGroup({- ...selectedTagGroupEntry,- title: this.state.title,- color: this.state.color,- textcolor: this.state.textcolor,- children: selectedTagGroupEntry.children.map(tag => ({- ...tag,- color: applyChanges ? this.state.color : tag.color,- textcolor: applyChanges ? this.state.textcolor : tag.textcolor,- style: tag.style- }))- });- this.setState({ inputError: false, disableConfirmButton: true });- this.props.onClose();- }- };+ if (selectedTagGroupEntry && selectedTagGroupEntry.children) {+ this.props.editTagGroup({+ ...selectedTagGroupEntry,+ title: this.state.title,+ color: this.state.color,+ textcolor: this.state.textcolor,+ children: selectedTagGroupEntry.children.map(tag => ({+ ...tag,+ color: applyChanges ? this.state.color : tag.color,+ textcolor: applyChanges ? this.state.textcolor : tag.textcolor,+ style: tag.style+ }))+ });+ this.setState({ inputError: false, disableConfirmButton: true });+ this.props.onClose();+ }+ };- toggleDefaultTagBackgroundColorPicker = () => {- this.setState({ displayColorPicker: !this.state.displayColorPicker });- };+ toggleDefaultTagBackgroundColorPicker = () => {+ this.setState({ displayColorPicker: !this.state.displayColorPicker });+ };- toggleDefaultTagTextColorPicker = () => {- this.setState({- displayTextColorPicker: !this.state.displayTextColorPicker- });- };+ toggleDefaultTagTextColorPicker = () => {+ this.setState({+ displayTextColorPicker: !this.state.displayTextColorPicker+ });+ };- handleChangeColor = (color: string) => {- this.setState({ color });- };+ handleChangeColor = (color: string) => {+ this.setState({ color });+ };- handleChangeTextColor = (color: string) => {- this.setState({ textcolor: color });- };+ handleChangeTextColor = (color: string) => {+ this.setState({ textcolor: color });+ };- setApplyChanges = (applyColorChanges: boolean) => {- this.setState({ applyChanges: applyColorChanges });- };+ setApplyChanges = (applyColorChanges: boolean) => {+ this.setState({ applyChanges: applyColorChanges });+ };- renderTitle = () => (- <DialogTitle style={{ overflow: 'visible' }}>- {i18n.t('core:editTagGroupTitle')}- {` '${this.state.title}'`}- </DialogTitle>- );+ renderTitle = () => (+ <DialogTitle style={{ overflow: 'visible' }}>+ {i18n.t('core:editTagGroupTitle')}+ {` '${this.state.title}'`}+ </DialogTitle>+ );- renderContent = () => {- const { color, textcolor, modifiedDate } = this.state;- const styles = {- color: {- width: '100%',- height: 30,- borderRadius: 2,- borderWidth: 1,- borderStyle: 'solid',- borderColor: 'gray',- padding: '5px',- background: color- },- textcolor: {- width: '100%',- height: 30,- borderRadius: 2,- borderWidth: 1,- borderStyle: 'solid',- borderColor: 'gray',- padding: '5px',- background: textcolor- },- helpText: {- marginBottom: '5px',- fontSize: '1rem'- }- };+ renderContent = () => {+ const { color, textcolor, modifiedDate } = this.state;+ const styles = {+ color: {+ width: '100%',+ height: 30,+ borderRadius: 2,+ borderWidth: 1,+ borderStyle: 'solid',+ borderColor: 'gray',+ padding: '5px',+ background: color+ },+ textcolor: {+ width: '100%',+ height: 30,+ borderRadius: 2,+ borderWidth: 1,+ borderStyle: 'solid',+ borderColor: 'gray',+ padding: '5px',+ background: textcolor+ },+ helpText: {+ marginBottom: '5px',+ fontSize: '1rem'+ }+ };- return (- <DialogContent style={{ overflow: 'visible' }}>- <FormControl- fullWidth={true}- error={this.state.inputError}- style={{ overflow: 'visible' }}- >- {modifiedDate && (- <div- className="tag-date"- style={{- fontSize: 12,- position: 'relative',- bottom: 20,- color: '#808080'- }}- >- <span className="text" style={{ fontWeight: 600 }}>{`${i18n.t(- 'core:modifiedDate'- )}: `}</span>- <time>{format(new Date(modifiedDate), 'yyyy-mm-dd')}</time>- </div>- )}- <TextField- error={this.state.inputError}- margin="dense"- name="title"- autoFocus- label={i18n.t('core:editTagGroupNewName')}- onChange={this.handleInputChange}- value={this.state.title}- data-tid="editTagGroupInput"- fullWidth={true}- />- {this.state.inputError && (- <FormHelperText>- {i18n.t('core:taggroupTitleHelper')}- </FormHelperText>- )}- </FormControl>- <FormControl fullWidth={true}>- <FormHelperText style={styles.helpText}>- {i18n.t('core:tagBackgroundColor')}- </FormHelperText>- <TransparentBackground>- <Button- onClick={this.toggleDefaultTagBackgroundColorPicker}- data-tid="editTagGroupBackgroundColor"- style={styles.color}- >- - </Button>- </TransparentBackground>- <ColorPickerDialog- open={this.state.displayColorPicker}- setColor={this.handleChangeColor}- onClose={this.toggleDefaultTagBackgroundColorPicker}- color={this.state.color}- />- </FormControl>- <FormControl fullWidth={true}>- <FormHelperText style={styles.helpText}>- {i18n.t('core:tagForegroundColor')}- </FormHelperText>- <TransparentBackground>- <Button- onClick={this.toggleDefaultTagTextColorPicker}- data-tid="editTagGroupForegroundColor"- style={styles.textcolor}- role="presentation"- >- - </Button>- </TransparentBackground>- <ColorPickerDialog- open={this.state.displayTextColorPicker}- setColor={this.handleChangeTextColor}- onClose={this.toggleDefaultTagTextColorPicker}- color={this.state.textcolor}- />- </FormControl>- <FormControl>- <FormHelperText style={styles.helpText}>- {i18n.t('core:colorChangesToAllTags')}- </FormHelperText>- <Switch- data-tid="editTagGroupSwitch"- onClick={() => this.setApplyChanges(!this.state.applyChanges)}- checked={this.state.applyChanges}- />- </FormControl>- </DialogContent>- );- };+ return (+ <DialogContent style={{ overflow: 'visible' }}>+ <FormControl+ fullWidth={true}+ error={this.state.inputError}+ style={{ overflow: 'visible' }}+ >+ {modifiedDate && (+ <div+ className="tag-date"+ style={{+ fontSize: 12,+ position: 'relative',+ bottom: 20,+ color: '#808080'+ }}+ >+ <span className="text" style={{ fontWeight: 600 }}>{`${i18n.t(+ 'core:modifiedDate'+ )}: `}</span>+ <time>{format(new Date(modifiedDate), 'yyyy-mm-dd')}</time>+ </div>+ )}+ <TextField+ error={this.state.inputError}+ margin="dense"+ name="title"+ autoFocus+ label={i18n.t('core:editTagGroupNewName')}+ onChange={this.handleInputChange}+ value={this.state.title}+ data-tid="editTagGroupInput"+ fullWidth={true}+ />+ {this.state.inputError && (+ <FormHelperText>+ {i18n.t('core:taggroupTitleHelper')}+ </FormHelperText>+ )}+ </FormControl>+ <FormControl fullWidth={true}>+ <FormHelperText style={styles.helpText}>+ {i18n.t('core:tagBackgroundColor')}+ </FormHelperText>+ <TransparentBackground>+ <Button+ onClick={this.toggleDefaultTagBackgroundColorPicker}+ data-tid="editTagGroupBackgroundColor"+ style={styles.color}+ >+ + </Button>+ </TransparentBackground>+ <ColorPickerDialog+ open={this.state.displayColorPicker}+ setColor={this.handleChangeColor}+ onClose={this.toggleDefaultTagBackgroundColorPicker}+ color={this.state.color}+ />+ </FormControl>+ <FormControl fullWidth={true}>+ <FormHelperText style={styles.helpText}>+ {i18n.t('core:tagForegroundColor')}+ </FormHelperText>+ <TransparentBackground>+ <Button+ onClick={this.toggleDefaultTagTextColorPicker}+ data-tid="editTagGroupForegroundColor"+ style={styles.textcolor}+ role="presentation"+ >+ + </Button>+ </TransparentBackground>+ <ColorPickerDialog+ open={this.state.displayTextColorPicker}+ setColor={this.handleChangeTextColor}+ onClose={this.toggleDefaultTagTextColorPicker}+ color={this.state.textcolor}+ />+ </FormControl>+ <FormControl>+ <FormHelperText style={styles.helpText}>+ {i18n.t('core:colorChangesToAllTags')}+ </FormHelperText>+ <Switch+ data-tid="editTagGroupSwitch"+ onClick={() => this.setApplyChanges(!this.state.applyChanges)}+ checked={this.state.applyChanges}+ />+ </FormControl>+ </DialogContent>+ );+ };- renderActions = () => (- <DialogActions>- <Button onClick={this.props.onClose} color="primary">- {i18n.t('core:cancel')}- </Button>- <Button- disabled={this.state.disableConfirmButton}- onClick={this.onConfirm}- data-tid="editTagGroupConfirmButton"- color="primary"- >- {i18n.t('core:ok')}- </Button>- </DialogActions>- );+ renderActions = () => (+ <DialogActions>+ <Button onClick={this.props.onClose} color="primary">+ {i18n.t('core:cancel')}+ </Button>+ <Button+ disabled={this.state.disableConfirmButton}+ onClick={this.onConfirm}+ data-tid="editTagGroupConfirmButton"+ color="primary"+ >+ {i18n.t('core:ok')}+ </Button>+ </DialogActions>+ );- render() {- const { onClose, open, fullScreen } = this.props;- return (- <Dialog- open={open}- fullScreen={fullScreen}- onClose={onClose}- // onEnterKey={(event) => onEnterKeyHandler(event, this.onConfirm)}- >- {this.renderTitle()}- {this.renderContent()}- {this.renderActions()}- </Dialog>- );- }+ render() {+ const { onClose, open, fullScreen } = this.props;+ return (+ <Dialog+ open={open}+ fullScreen={fullScreen}+ onClose={onClose}+ // onEnterKey={(event) => onEnterKeyHandler(event, this.onConfirm)}+ >+ {this.renderTitle()}+ {this.renderContent()}+ {this.renderActions()}+ </Dialog>+ );+ }}export default EditTagGroupDialog;diff --git a/app/components/dialogs/GenericDialog.tsx b/app/components/dialogs/GenericDialog.tsxindex 24f021714..727387f67 100644--- a/app/components/dialogs/GenericDialog.tsx+++ b/app/components/dialogs/GenericDialog.tsx@@ -20,74 +20,74 @@ import React from 'react';import Dialog from '@material-ui/core/Dialog';import Slide from '@material-ui/core/Slide';-export function DialogTransition(props: Object) {- return <Slide direction="down" {...props} />;+export function DialogTransition(props: any) {+ return <Slide direction="down" {...props} />;}-type Props = {- open: boolean,- fullScreen?: boolean,- onClose: () => void,- onBackdropClick?: () => void,- onEnterKey?: () => void,- renderTitle?: () => Object,- renderContent: () => Object,- renderActions?: () => Object-};+interface Props {+ open: boolean;+ fullScreen?: boolean;+ onClose: () => void;+ onBackdropClick?: () => void;+ onEnterKey?: () => void;+ renderTitle?: () => Object;+ renderContent: () => Object;+ renderActions?: () => Object;+}export function onEnterKeyHandler(event: any, confirmFunction: () => void) {- if (event.key === 'Enter' || event.keyCode === 13) {- confirmFunction();- }+ if (event.key === 'Enter' || event.keyCode === 13) {+ confirmFunction();+ }}const GenericDialog = (props: Props) => {- // function renderTitle() {- // return (- // <DialogTitle>Dialog</DialogTitle>- // );- // }+ // function renderTitle() {+ // return (+ // <DialogTitle>Dialog</DialogTitle>+ // );+ // }- // function renderContent() {- // return (- // <DialogContent>- // <DialogContentText>- // Some content- // </DialogContentText>- // </DialogContent>- // );- // }+ // function renderContent() {+ // return (+ // <DialogContent>+ // <DialogContentText>+ // Some content+ // </DialogContentText>+ // </DialogContent>+ // );+ // }- // function renderActions() {- // return (- // <DialogActions>- // <Button onClick={props.onClose} color="primary">- // {i18n.t('core:cancel')}- // </Button>- // </DialogActions>- // );- // }+ // function renderActions() {+ // return (+ // <DialogActions>+ // <Button onClick={props.onClose} color="primary">+ // {i18n.t('core:cancel')}+ // </Button>+ // </DialogActions>+ // );+ // }- const { fullScreen, open, onEnterKey, onClose, onBackdropClick } = props;- return (- <Dialog- fullScreen={fullScreen}- open={open}- TransitionComponent={DialogTransition}- keepMounted- scroll="paper"- onClose={onClose}- onBackdropClick={onBackdropClick && onClose}- // onEscapeKeyDown={onClose}- onKeyDown={- onEnterKey || (event => onEnterKeyHandler(event, props.onClose))- }- >- {props.renderTitle && props.renderTitle()}- {props.renderContent && props.renderContent()}- {props.renderActions && props.renderActions()}- </Dialog>- );+ const { fullScreen, open, onEnterKey, onClose, onBackdropClick } = props;+ return (+ <Dialog+ fullScreen={fullScreen}+ open={open}+ TransitionComponent={DialogTransition}+ keepMounted+ scroll="paper"+ onClose={onClose}+ onBackdropClick={onBackdropClick && onClose}+ // onEscapeKeyDown={onClose}+ onKeyDown={+ onEnterKey || (event => onEnterKeyHandler(event, props.onClose))+ }+ >+ {props.renderTitle && props.renderTitle()}+ {props.renderContent && props.renderContent()}+ {props.renderActions && props.renderActions()}+ </Dialog>+ );};export default GenericDialog;diff --git a/app/components/dialogs/KeyboardDialog.tsx b/app/components/dialogs/KeyboardDialog.tsxindex 9e78760b6..8c4e92275 100644--- a/app/components/dialogs/KeyboardDialog.tsx+++ b/app/components/dialogs/KeyboardDialog.tsx@@ -33,72 +33,72 @@ import i18n from '../../services/i18n';import { getKeyBindingObject } from '../../reducers/settings';const styles = theme => ({- root: {- minWidth: 350- },- shortcutKey: {- backgroundColor: '#D6D6D6',- font: 'Console',- fontFamily: 'monospace',- padding: '5px',- borderRadius: '5px'- }+ root: {+ minWidth: 350+ },+ shortcutKey: {+ backgroundColor: '#D6D6D6',+ font: 'Console',+ fontFamily: 'monospace',+ padding: '5px',+ borderRadius: '5px'+ }});-type Props = {- open: boolean,- classes: Object,- fullScreen: boolean,- keyBindings: Array<Object>,- onClose: () => void-};+interface Props {+ open: boolean;+ classes: any;+ fullScreen: boolean;+ keyBindings: Array<any>;+ onClose: () => void;+}const KeyboardDialog = (props: Props) => {- const { open, onClose, fullScreen } = props;- return (- <Dialog- open={open}- onClose={onClose}- fullScreen={fullScreen}- keepMounted- scroll="paper"- >- <DialogTitle>{i18n.t('core:shortcutKeys')}</DialogTitle>- <DialogContent- className={props.classes.root}- data-tid="keyboardShortCutsDialog"- >- <List dense={false}>- {props.keyBindings &&- Object.keys(props.keyBindings).map(shortcutKey => (- <ListItem key={shortcutKey}>- <ListItemText primary={i18n.t('core:' + shortcutKey)} />- <ListItemSecondaryAction className={props.classes.shortcutKey}>- {props.keyBindings[shortcutKey]}- </ListItemSecondaryAction>- </ListItem>- ))}- </List>- </DialogContent>- <DialogActions>- <Button- data-tid="closeKeyboardDialog"- onClick={props.onClose}- color="primary"- >- {i18n.t('core:ok')}- </Button>- </DialogActions>- </Dialog>- );+ const { open, onClose, fullScreen } = props;+ return (+ <Dialog+ open={open}+ onClose={onClose}+ fullScreen={fullScreen}+ keepMounted+ scroll="paper"+ >+ <DialogTitle>{i18n.t('core:shortcutKeys')}</DialogTitle>+ <DialogContent+ className={props.classes.root}+ data-tid="keyboardShortCutsDialog"+ >+ <List dense={false}>+ {props.keyBindings &&+ Object.keys(props.keyBindings).map(shortcutKey => (+ <ListItem key={shortcutKey}>+ <ListItemText primary={i18n.t('core:' + shortcutKey)} />+ <ListItemSecondaryAction className={props.classes.shortcutKey}>+ {props.keyBindings[shortcutKey]}+ </ListItemSecondaryAction>+ </ListItem>+ ))}+ </List>+ </DialogContent>+ <DialogActions>+ <Button+ data-tid="closeKeyboardDialog"+ onClick={props.onClose}+ color="primary"+ >+ {i18n.t('core:ok')}+ </Button>+ </DialogActions>+ </Dialog>+ );};function mapStateToProps(state) {- return {- keyBindings: getKeyBindingObject(state)- };+ return {+ keyBindings: getKeyBindingObject(state)+ };}export default connect(mapStateToProps)(- withMobileDialog()(withStyles(styles)(KeyboardDialog))+ withMobileDialog()(withStyles(styles)(KeyboardDialog)));diff --git a/app/components/dialogs/LocalForm.tsx b/app/components/dialogs/LocalForm.tsxindex a0fdd98c4..b3921db85 100644--- a/app/components/dialogs/LocalForm.tsx+++ b/app/components/dialogs/LocalForm.tsx@@ -32,10 +32,10 @@ import { extractDirectoryName } from '../../utils/paths';import PlatformIO from '../../services/platform-io';type Props = {- state: Object,- handleChange: () => void,- handleInputChange: () => void,- showSelectDirectoryDialog: () => void+ state: any;+ handleChange: (param1: string, param2: string) => void;+ handleInputChange: () => void;+ showSelectDirectoryDialog: () => void;};class LocalForm extends React.Component<Props> {@@ -90,6 +90,7 @@ class LocalForm extends React.Component<Props> {requiredmargin="dense"name="path"+ // @ts-ignorelabel={i18n.t('core:createLocationPath')}fullWidth={true}data-tid="locationPath"diff --git a/app/components/dialogs/ObjectStoreForm.tsx b/app/components/dialogs/ObjectStoreForm.tsxindex fcbce1ffe..16c3d0bbe 100644--- a/app/components/dialogs/ObjectStoreForm.tsx+++ b/app/components/dialogs/ObjectStoreForm.tsx@@ -55,7 +55,7 @@ export const suggestions = [{ label: 'sa-east-1 (South America São Paulo)', value: 'sa-east-1' }];-const styles = theme => ({+const styles: any = (theme: any) => ({root: {flexGrow: 1,height: 250@@ -201,13 +201,13 @@ const components = {ValueContainer};-type Props = {- state: Object,- handleChange: () => void,- handleInputChange: () => void,- classes: Object,- theme: Object-};+interface Props {+ state: any;+ handleChange: (name: string, value: any) => void;+ handleInputChange: () => void;+ classes: any;+ theme: any;+}class ObjectStoreForm extends React.Component<Props> {handleChange = name => value => {@@ -249,6 +249,7 @@ class ObjectStoreForm extends React.Component<Props> {requiredmargin="dense"name="storeName"+ // @ts-ignorelabel={i18n.t('core:createLocationName')}fullWidth={true}data-tid="locationName"@@ -268,6 +269,7 @@ class ObjectStoreForm extends React.Component<Props> {<Inputmargin="dense"name="storePath"+ // @ts-ignorelabel={i18n.t('core:createLocationPath')}fullWidth={true}data-tid="locationPath"@@ -287,6 +289,7 @@ class ObjectStoreForm extends React.Component<Props> {<Inputmargin="dense"name="accessKeyId"+ // @ts-ignorelabel={i18n.t('core:accessKeyId')}fullWidth={true}data-tid="accessKeyId"@@ -307,6 +310,7 @@ class ObjectStoreForm extends React.Component<Props> {margin="dense"name="secretAccessKey"type="password"+ // @ts-ignorelabel={i18n.t('core:secretAccessKey')}fullWidth={true}data-tid="secretAccessKey"@@ -329,6 +333,7 @@ class ObjectStoreForm extends React.Component<Props> {requiredmargin="dense"name="bucketName"+ // @ts-ignorelabel={i18n.t('core:bucketName')}fullWidth={true}data-tid="bucketName"diff --git a/app/components/dialogs/OnboardingDialog.tsx b/app/components/dialogs/OnboardingDialog.tsxindex 2ba3b3720..ce2c3fa2c 100644--- a/app/components/dialogs/OnboardingDialog.tsx+++ b/app/components/dialogs/OnboardingDialog.tsx@@ -49,22 +49,21 @@ import {import { actions as AppActions } from '../../reducers/app';import AppConfig from '../../config';-type Props = {- classes: Object,- open: boolean,- isPersistTagsInSidecar: boolean,- fullScreen: boolean,- currentTheme: string,+interface Props {+ classes: any;+ open: boolean;+ isPersistTagsInSidecar: boolean;+ fullScreen: boolean;+ currentTheme: string;// setFirstRun: (isFirstRun: boolean) => void,- setPersistTagsInSidecarFile: (isPersistTagsInSidecar: boolean) => void,- setCurrentTheme: () => void,- openURLExternally: (url: string) => void,- onClose: () => void-};+ setPersistTagsInSidecarFile: (isPersistTagsInSidecar: boolean) => void;+ setCurrentTheme: (theme: string) => void;+ openURLExternally: (url: string) => void;+ onClose: () => void;+}const OnboardingDialog = (props: Props) => {const [activeStep, setActiveStep] = useState(0);- const [isPersistTagsInSidecar, setIsPersistTagInSidecar] = useState(false);const { fullScreen, open, onClose } = props;let maxSteps = 5;@@ -77,8 +76,8 @@ const OnboardingDialog = (props: Props) => {setActiveStep(activeStep => activeStep - 1);}- function handleStepChange(activeStep) {- setActiveStep({ activeStep });+ function handleStepChange(activeStep: number) {+ setActiveStep(activeStep);}function toggleTaggingType() {@@ -149,7 +148,7 @@ const OnboardingDialog = (props: Props) => {Choose your the default tagging method for files</Typography><Typography variant="h5"> </Typography>- <Typography variant="body">+ <Typography variant="body1">Core functionality of the application the ability to add tags tofiles and folders. Here you can choose how tags will applied onfiles.@@ -161,7 +160,6 @@ const OnboardingDialog = (props: Props) => {<RadioGrouparia-label="Gender"name="isPersistTagsInSidecar"- // value={this.props.isPersistTagsInSidecar}onChange={toggleTaggingType}><FormControlLabel@@ -205,7 +203,7 @@ const OnboardingDialog = (props: Props) => {/></RadioGroup></FormControl>- <Typography variant="body">+ <Typography variant="body1">You can always revise you decision and change the tagging method.But tags already tagged by renaming the files will stay renamedand the created sidecar file containing tags will stay.@@ -324,4 +322,5 @@ function mapActionCreatorsToProps(dispatch) {export default connect(mapStateToProps,mapActionCreatorsToProps+ // @ts-ignore)(withMobileDialog()(OnboardingDialog));diff --git a/app/components/dialogs/ProTeaserDialog.tsx b/app/components/dialogs/ProTeaserDialog.tsxindex 5d7eac954..155ea195d 100644--- a/app/components/dialogs/ProTeaserDialog.tsx+++ b/app/components/dialogs/ProTeaserDialog.tsx@@ -35,16 +35,16 @@ import EnterpriseImage from '../../assets/images/world-undraw.svg';import i18n from '../../services/i18n';import AppConfig from '../../config';-type Props = {- open: boolean,- fullScreen: boolean,- openURLExternally: (url: string) => void,- onClose: () => void-};+interface Props {+ open: boolean;+ fullScreen: boolean;+ openURLExternally: (url: string) => void;+ onClose: () => void;+}-type State = {- activeStep: number-};+interface State {+ activeStep: number;+}class ProTeaserDialog extends React.Component<Props, State> {state = {@@ -71,7 +71,7 @@ class ProTeaserDialog extends React.Component<Props, State> {render() {const { activeStep } = this.state;- const slideStyles = {+ const slideStyles: any = {padding: 5,textAlign: 'left'};diff --git a/app/components/dialogs/RenameFileDialog.tsx b/app/components/dialogs/RenameFileDialog.tsxindex d5e09a365..b254c25de 100644--- a/app/components/dialogs/RenameFileDialog.tsx+++ b/app/components/dialogs/RenameFileDialog.tsx@@ -28,187 +28,188 @@ import DialogTitle from '@material-ui/core/DialogTitle';import { withStyles } from '@material-ui/core/styles';import FormControl from '@material-ui/core/FormControl';import FormHelperText from '@material-ui/core/FormHelperText';-import { onEnterKeyHandler, DialogTransition } from './GenericDialog';+import { DialogTransition } from './GenericDialog';import AppConfig from '../../config';import i18n from '../../services/i18n';import {- extractFileName,- extractContainingDirectoryPath+ extractFileName,+ extractContainingDirectoryPath} from '../../utils/paths';import { actions as AppActions } from '../../reducers/app';interface Props {- open: boolean;- selectedFilePath: string;- classes: Object;- renameFile: (source: string, target: string) => void;- onClose: () => void;+ open: boolean;+ selectedFilePath: string;+ classes: any;+ renameFile: (source: string, target: string) => void;+ onClose: () => void;}interface State {- inputError: boolean;- disableConfirmButton: boolean;- fileName: string;+ inputError: boolean;+ disableConfirmButton: boolean;+ fileName: string;}const styles = theme => ({- root: {- width: 550,- height: '100%',- marginBottom: 30,- background: theme.palette.background.paper- }+ root: {+ width: 550,+ height: '100%',+ marginBottom: 30,+ background: theme.palette.background.paper+ }});class RenameFileDialog extends React.Component<Props, State> {- state = {- inputError: false,- disableConfirmButton: true,- fileName: ''- };-- componentWillReceiveProps = (nextProps: any) => {- if (nextProps.open) {- const fileName = extractFileName(nextProps.selectedFilePath);- this.setState({ fileName }, () => {- this.fileName.focus();- if (fileName) {- const indexOfBracket = fileName.indexOf(AppConfig.beginTagContainer);- const indexOfDot = fileName.indexOf('.');- let endRange = fileName.length;- if (indexOfBracket > 0) {- endRange = indexOfBracket;- } else if (indexOfDot > 0) {- endRange = indexOfDot;- }- this.fileName.setSelectionRange(0, endRange);- }- return {- fileName- };- });- }- };-- fileName;-- handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {- const target = event.target;- const value = target.type === 'checkbox' ? target.checked : target.value;- const name = target.name;-- this.setState(- {- [name]: value- },- this.handleValidation- );- };-- handleValidation() {- if (this.state.fileName.length > 0) {- this.setState({ inputError: false, disableConfirmButton: false });- } else {- this.setState({ inputError: true, disableConfirmButton: true });- }- }-- onConfirm = () => {- if (!this.state.disableConfirmButton) {- const fileDirectory = extractContainingDirectoryPath(- this.props.selectedFilePath- );- const newFilePath =- fileDirectory + AppConfig.dirSeparator + this.state.fileName;- this.props.renameFile(this.props.selectedFilePath, newFilePath);- this.props.onClose();- this.setState({ inputError: false, disableConfirmButton: true });- } else {- this.handleValidation();- }- };-- renderTitle = () => (- <DialogTitle>{i18n.t('core:renameFileTitle')}</DialogTitle>- );-- renderContent = () => (- <DialogContent className={this.props.classes.root}>- <FormControl- data-tid="renameFileDialog"- fullWidth={true}- error={this.state.inputError}- >- <TextField- error={this.state.inputError}- margin="dense"- name="fileName"- autoFocus- inputRef={ref => {- this.fileName = ref;- }}- label={i18n.t('core:renameNewFileName')}- onChange={this.handleInputChange}- value={this.state.fileName}- data-tid="renameFileDialogInput"- fullWidth={true}- />- {this.state.inputError && (- <FormHelperText>Empty File Name</FormHelperText>- )}- </FormControl>- </DialogContent>- );-- renderActions = () => (- <DialogActions>- <Button- data-tid="closeRenameFileDialog"- onClick={this.props.onClose}- color="primary"- >- {i18n.t('core:cancel')}- </Button>- <Button- disabled={this.state.disableConfirmButton}- onClick={this.onConfirm}- data-tid="confirmRenameFileDialog"- color="primary"- >- {i18n.t('core:ok')}- </Button>- </DialogActions>- );-- render() {- const { onClose, open } = this.props;- return (- <Dialog- open={open}- TransitionComponent={DialogTransition}- keepMounted- onClose={onClose}- onBackdropClick={onClose}- // onKeyDown={((event) => onEnterKeyHandler(event, this.onConfirm))}- >- {this.renderTitle()}- {this.renderContent()}- {this.renderActions()}- </Dialog>- );- }+ state = {+ inputError: false,+ disableConfirmButton: true,+ fileName: ''+ };++ componentWillReceiveProps = (nextProps: any) => {+ if (nextProps.open) {+ const fileName = extractFileName(nextProps.selectedFilePath);+ this.setState({ fileName }, () => {+ this.fileName.focus();+ if (fileName) {+ const indexOfBracket = fileName.indexOf(AppConfig.beginTagContainer);+ const indexOfDot = fileName.indexOf('.');+ let endRange = fileName.length;+ if (indexOfBracket > 0) {+ endRange = indexOfBracket;+ } else if (indexOfDot > 0) {+ endRange = indexOfDot;+ }+ this.fileName.setSelectionRange(0, endRange);+ }+ return {+ fileName+ };+ });+ }+ };++ fileName;++ handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {+ const target = event.target;+ const value = target.type === 'checkbox' ? target.checked : target.value;+ const name = target.name;++ this.setState(+ // @ts-ignore+ {+ [name]: value+ },+ this.handleValidation+ );+ };++ handleValidation() {+ if (this.state.fileName.length > 0) {+ this.setState({ inputError: false, disableConfirmButton: false });+ } else {+ this.setState({ inputError: true, disableConfirmButton: true });+ }+ }++ onConfirm = () => {+ if (!this.state.disableConfirmButton) {+ const fileDirectory = extractContainingDirectoryPath(+ this.props.selectedFilePath+ );+ const newFilePath =+ fileDirectory + AppConfig.dirSeparator + this.state.fileName;+ this.props.renameFile(this.props.selectedFilePath, newFilePath);+ this.props.onClose();+ this.setState({ inputError: false, disableConfirmButton: true });+ } else {+ this.handleValidation();+ }+ };++ renderTitle = () => (+ <DialogTitle>{i18n.t('core:renameFileTitle')}</DialogTitle>+ );++ renderContent = () => (+ <DialogContent className={this.props.classes.root}>+ <FormControl+ data-tid="renameFileDialog"+ fullWidth={true}+ error={this.state.inputError}+ >+ <TextField+ error={this.state.inputError}+ margin="dense"+ name="fileName"+ autoFocus+ inputRef={ref => {+ this.fileName = ref;+ }}+ label={i18n.t('core:renameNewFileName')}+ onChange={this.handleInputChange}+ value={this.state.fileName}+ data-tid="renameFileDialogInput"+ fullWidth={true}+ />+ {this.state.inputError && (+ <FormHelperText>Empty File Name</FormHelperText>+ )}+ </FormControl>+ </DialogContent>+ );++ renderActions = () => (+ <DialogActions>+ <Button+ data-tid="closeRenameFileDialog"+ onClick={this.props.onClose}+ color="primary"+ >+ {i18n.t('core:cancel')}+ </Button>+ <Button+ disabled={this.state.disableConfirmButton}+ onClick={this.onConfirm}+ data-tid="confirmRenameFileDialog"+ color="primary"+ >+ {i18n.t('core:ok')}+ </Button>+ </DialogActions>+ );++ render() {+ const { onClose, open } = this.props;+ return (+ <Dialog+ open={open}+ TransitionComponent={DialogTransition}+ keepMounted+ onClose={onClose}+ onBackdropClick={onClose}+ // onKeyDown={((event) => onEnterKeyHandler(event, this.onConfirm))}+ >+ {this.renderTitle()}+ {this.renderContent()}+ {this.renderActions()}+ </Dialog>+ );+ }}function mapActionCreatorsToProps(dispatch) {- return bindActionCreators(- {- renameFile: AppActions.renameFile- },- dispatch- );+ return bindActionCreators(+ {+ renameFile: AppActions.renameFile+ },+ dispatch+ );}export default connect(- null,- mapActionCreatorsToProps+ null,+ mapActionCreatorsToProps)(withStyles(styles)(RenameFileDialog));diff --git a/app/components/dialogs/settings/SettingsFileTypes.tsx b/app/components/dialogs/settings/SettingsFileTypes.tsxindex 3e1c88bba..9420dcfb6 100644--- a/app/components/dialogs/settings/SettingsFileTypes.tsx+++ b/app/components/dialogs/settings/SettingsFileTypes.tsx@@ -33,7 +33,7 @@ import { sortBy } from '../../../utils/misc';import i18n from '../../../services/i18n';import TransparentBackground from '../../TransparentBackground';-const styles = theme => ({+const styles: any = (theme: any) => ({root: {background: theme.palette.background.paper},@@ -71,20 +71,21 @@ const styles = theme => ({}});-type Props = {- items: Array,- classes: Object,- updateItems: Function,- selectedItem: Object,- setSelectedItem: Function,- isValidationInProgress: boolean,- onRemoveItem: Function-};+interface Props {+ items: Array<any>;+ classes: any;+ updateItems: Function;+ selectedItem: any;+ setSelectedItem: Function;+ isValidationInProgress: boolean;+ onRemoveItem: Function;+}-type State = {- isColorPickerVisible: boolean,- availableExtensions: []-};+interface State {+ isColorPickerVisible: boolean;+ availableExtensions: Array<any>;+ isComponentActive: boolean;+}class SettingsFileTypes extends Component<Props, State> {state = {diff --git a/app/components/dialogs/settings/SettingsKeyBindings.tsx b/app/components/dialogs/settings/SettingsKeyBindings.tsxindex d4b28c772..be4c5ab5c 100644--- a/app/components/dialogs/settings/SettingsKeyBindings.tsx+++ b/app/components/dialogs/settings/SettingsKeyBindings.tsx@@ -27,91 +27,91 @@ import ListItemText from '@material-ui/core/ListItemText';import PlatformIO from '../../../services/platform-io';import i18n from '../../../services/i18n';import {- actions as SettingsActions,- getKeyBindings,- isGlobalKeyBindingEnabled+ actions as SettingsActions,+ getKeyBindings,+ isGlobalKeyBindingEnabled} from '../../../reducers/settings';import DefaultSettings from '../../../reducers/settings-default';import { isStr } from '../../../utils/misc';-const styles = theme => ({- root: {- background: theme.palette.background.paper- },- keyBinding: {- marginTop: 10,- marginBottom: 10- },- listItem: {- paddingLeft: 0,- paddingRight: 0- }+const styles: any = (theme: any) => ({+ root: {+ background: theme.palette.background.paper+ },+ keyBinding: {+ marginTop: 10,+ marginBottom: 10+ },+ listItem: {+ paddingLeft: 0,+ paddingRight: 0+ }});-type Props = {- classes: Object,- keyBindings: Array<Object>,- setKeyBinding: (kbName: string, kbCommand: string) => void,- setGlobalKeyBinding: (value: boolean) => void,- globalKeyBindingEnabled: boolean-};+interface Props {+ classes: any;+ keyBindings: Array<any>;+ setKeyBinding: (kbName: string, kbCommand: string) => void;+ setGlobalKeyBinding: (value: boolean) => void;+ globalKeyBindingEnabled: boolean;+}const SettingsKeyBindings = (props: Props) => {- const {- keyBindings,- classes,- setKeyBinding,- setGlobalKeyBinding,- globalKeyBindingEnabled- } = props;- return (- <form className={classes.root} noValidate autoComplete="off">- <ListItem className={classes.listItem}>- <ListItemText primary={i18n.t('core:enableGlobalKeyboardShortcuts')} />- <Switch- onClick={() => {- setGlobalKeyBinding(!globalKeyBindingEnabled);- PlatformIO.setGlobalShortcuts(!globalKeyBindingEnabled);- }}- checked={globalKeyBindingEnabled}- />- </ListItem>- {keyBindings.map(keyBinding => {- const defaultBinding = DefaultSettings.keyBindings.filter(- kb => kb.name === keyBinding.name- )[0];- return (- <TextField- className={classes.keyBinding}- key={keyBinding.name}- InputLabelProps={{ shrink: true }}- fullWidth- onBlur={event => setKeyBinding(keyBinding.name, event.target.value)}- label={i18n.t('core:' + keyBinding.name)}- placeholder={- 'suggested binding: ' +- (defaultBinding ? defaultBinding.command : '')- }- defaultValue={isStr(keyBinding.command) ? keyBinding.command : ''}- />- );- })}- </form>- );+ const {+ keyBindings,+ classes,+ setKeyBinding,+ setGlobalKeyBinding,+ globalKeyBindingEnabled+ } = props;+ return (+ <form className={classes.root} noValidate autoComplete="off">+ <ListItem className={classes.listItem}>+ <ListItemText primary={i18n.t('core:enableGlobalKeyboardShortcuts')} />+ <Switch+ onClick={() => {+ setGlobalKeyBinding(!globalKeyBindingEnabled);+ PlatformIO.setGlobalShortcuts(!globalKeyBindingEnabled);+ }}+ checked={globalKeyBindingEnabled}+ />+ </ListItem>+ {keyBindings.map(keyBinding => {+ const defaultBinding = DefaultSettings.keyBindings.filter(+ kb => kb.name === keyBinding.name+ )[0];+ return (+ <TextField+ className={classes.keyBinding}+ key={keyBinding.name}+ InputLabelProps={{ shrink: true }}+ fullWidth+ onBlur={event => setKeyBinding(keyBinding.name, event.target.value)}+ label={i18n.t('core:' + keyBinding.name)}+ placeholder={+ 'suggested binding: ' ++ (defaultBinding ? defaultBinding.command : '')+ }+ defaultValue={isStr(keyBinding.command) ? keyBinding.command : ''}+ />+ );+ })}+ </form>+ );};function mapStateToProps(state) {- return {- keyBindings: getKeyBindings(state),- globalKeyBindingEnabled: isGlobalKeyBindingEnabled(state)- };+ return {+ keyBindings: getKeyBindings(state),+ globalKeyBindingEnabled: isGlobalKeyBindingEnabled(state)+ };}function mapActionCreatorsToProps(dispatch) {- return bindActionCreators(SettingsActions, dispatch);+ return bindActionCreators(SettingsActions, dispatch);}export default connect(- mapStateToProps,- mapActionCreatorsToProps+ mapStateToProps,+ mapActionCreatorsToProps)(withStyles(styles)(SettingsKeyBindings));diff --git a/app/components/menus/TagMenu.tsx b/app/components/menus/TagMenu.tsxindex b500c12aa..d65f6fcd8 100644--- a/app/components/menus/TagMenu.tsx+++ b/app/components/menus/TagMenu.tsx@@ -36,131 +36,129 @@ import { getMaxSearchResults } from '../../reducers/settings';import { actions as AppActions } from '../../reducers/app';const isTagLibraryReadOnly =- window.ExtTagLibrary && window.ExtTagLibrary.length > 0;+ window.ExtTagLibrary && window.ExtTagLibrary.length > 0;type Props = {- anchorEl?: Object;- open?: boolean;- onClose: () => void;- selectedTag?: Tag;- selectedTagGroupEntry?: TagGroup;- deleteTag: (uuid: string, tagGroupUuid: string) => void;- searchLocationIndex: (searchQuery: SearchQuery) => void;- editTag: () => void;- openSearchPanel: () => void;- maxSearchResults: number;+ anchorEl?: Element;+ open?: boolean;+ onClose: () => void;+ selectedTag?: Tag;+ selectedTagGroupEntry?: TagGroup;+ deleteTag: (uuid: string, tagGroupUuid: string) => void;+ searchLocationIndex: (searchQuery: SearchQuery) => void;+ editTag: () => void;+ openSearchPanel: () => void;+ maxSearchResults: number;};const TagLibraryMenu = (props: Props) => {- const [isEditTagDialogOpened, setIsEditTagDialogOpened] = useState(false);- const [isDeleteTagDialogOpened, setIsDeleteTagDialogOpened] = useState(false);+ const [isEditTagDialogOpened, setIsEditTagDialogOpened] = useState(false);+ const [isDeleteTagDialogOpened, setIsDeleteTagDialogOpened] = useState(false);- function tagSelectedFiles() {- // TODO not implemented- props.onClose();- }+ function showFilesWithThisTag() {+ if (props.selectedTag) {+ props.openSearchPanel();+ props.searchLocationIndex({+ tagsAND: [props.selectedTag],+ maxSearchResults: props.maxSearchResults+ });+ }+ props.onClose();+ }- function showFilesWithThisTag() {- if (props.selectedTag) {- props.openSearchPanel();- props.searchLocationIndex({- tagsAND: [props.selectedTag],- maxSearchResults: props.maxSearchResults- });- }- props.onClose();- }+ function showEditTagDialog() {+ props.onClose();+ setIsEditTagDialogOpened(true);+ }- function showEditTagDialog() {- props.onClose();- setIsEditTagDialogOpened(true);- }+ function showDeleteTagDialog() {+ props.onClose();+ setIsDeleteTagDialogOpened(true);+ }- function showDeleteTagDialog() {- props.onClose();- setIsDeleteTagDialogOpened(true);- }+ function handleCloseDialogs() {+ setIsEditTagDialogOpened(false);+ setIsDeleteTagDialogOpened(false);+ }- function handleCloseDialogs() {- setIsEditTagDialogOpened(false);- setIsDeleteTagDialogOpened(false);- }+ function confirmDeleteTag() {+ if (props.selectedTag && props.selectedTagGroupEntry) {+ props.deleteTag(props.selectedTag.id, props.selectedTagGroupEntry.uuid);+ }+ }- function confirmDeleteTag() {- if (props.selectedTag && props.selectedTagGroupEntry) {- props.deleteTag(props.selectedTag.id, props.selectedTagGroupEntry.uuid);- }- }-- return (- <div style={{ overflowY: 'hidden !important' }}>- <Menu anchorEl={props.anchorEl} open={props.open} onClose={props.onClose}>- <MenuItem- data-tid="showFilesWithThisTag"- onClick={showFilesWithThisTag}- >- <ListItemIcon>- <ShowEntriesWithTagIcon />- </ListItemIcon>- <ListItemText primary={i18n.t('core:showFilesWithThisTag')} />- </MenuItem>- {!isTagLibraryReadOnly && (- <MenuItem data-tid="editTagDialog" onClick={showEditTagDialog}>- <ListItemIcon>- <Edit />- </ListItemIcon>- <ListItemText primary={i18n.t('core:editTag')} />- </MenuItem>- )}- {!isTagLibraryReadOnly && (- <MenuItem data-tid="deleteTagDialog" onClick={showDeleteTagDialog}>- <ListItemIcon>- <DeleteIcon />- </ListItemIcon>- <ListItemText primary={i18n.t('core:deleteTagFromTagGroup')} />- </MenuItem>- )}- </Menu>- <EditTagDialog- open={isEditTagDialogOpened}- onClose={handleCloseDialogs}- editTag={props.editTag}- selectedTagGroupEntry={props.selectedTagGroupEntry}- selectedTag={props.selectedTag}- />- <ConfirmDialog- open={isDeleteTagDialogOpened}- onClose={handleCloseDialogs}- title={i18n.t('core:deleteTagFromTagGroup')}- content={i18n.t('core:deleteTagFromTagGroupContentConfirm', {- tagName: props.selectedTag ? props.selectedTag.title : ''- })}- confirmCallback={result => {- if (result) {- confirmDeleteTag();- }- }}- cancelDialogTID={'cancelDeleteTagDialogTagMenu'}- confirmDialogTID={'confirmDeleteTagDialogTagMenu'}- />- </div>- );+ return (+ <div+ // @ts-ignore+ style={{ overflowY: 'hidden !important' }}+ >+ <Menu anchorEl={props.anchorEl} open={props.open} onClose={props.onClose}>+ <MenuItem+ data-tid="showFilesWithThisTag"+ onClick={showFilesWithThisTag}+ >+ <ListItemIcon>+ <ShowEntriesWithTagIcon />+ </ListItemIcon>+ <ListItemText primary={i18n.t('core:showFilesWithThisTag')} />+ </MenuItem>+ {!isTagLibraryReadOnly && (+ <MenuItem data-tid="editTagDialog" onClick={showEditTagDialog}>+ <ListItemIcon>+ <Edit />+ </ListItemIcon>+ <ListItemText primary={i18n.t('core:editTag')} />+ </MenuItem>+ )}+ {!isTagLibraryReadOnly && (+ <MenuItem data-tid="deleteTagDialog" onClick={showDeleteTagDialog}>+ <ListItemIcon>+ <DeleteIcon />+ </ListItemIcon>+ <ListItemText primary={i18n.t('core:deleteTagFromTagGroup')} />+ </MenuItem>+ )}+ </Menu>+ <EditTagDialog+ open={isEditTagDialogOpened}+ onClose={handleCloseDialogs}+ editTag={props.editTag}+ selectedTagGroupEntry={props.selectedTagGroupEntry}+ selectedTag={props.selectedTag}+ />+ <ConfirmDialog+ open={isDeleteTagDialogOpened}+ onClose={handleCloseDialogs}+ title={i18n.t('core:deleteTagFromTagGroup')}+ content={i18n.t('core:deleteTagFromTagGroupContentConfirm', {+ tagName: props.selectedTag ? props.selectedTag.title : ''+ })}+ confirmCallback={result => {+ if (result) {+ confirmDeleteTag();+ }+ }}+ cancelDialogTID={'cancelDeleteTagDialogTagMenu'}+ confirmDialogTID={'confirmDeleteTagDialogTagMenu'}+ />+ </div>+ );};function mapStateToProps(state) {- return {- maxSearchResults: getMaxSearchResults(state)- };+ return {+ maxSearchResults: getMaxSearchResults(state)+ };}function mapDispatchToProps(dispatch) {- return bindActionCreators(- {- openSearchPanel: AppActions.openSearchPanel,- searchLocationIndex: LocationIndexActions.searchLocationIndex- },- dispatch- );+ return bindActionCreators(+ {+ openSearchPanel: AppActions.openSearchPanel,+ searchLocationIndex: LocationIndexActions.searchLocationIndex+ },+ dispatch+ );}export default connect(mapStateToProps, mapDispatchToProps)(TagLibraryMenu);diff --git a/app/config.ts b/app/config.tsindex f7fc33bf7..65225db93 100644--- a/app/config.ts+++ b/app/config.ts@@ -19,7 +19,8 @@ const isCordovaiOS =/^file:\/{3}[^\/]/i.test(window.location.href) &&/ios|iphone|ipod|ipad/i.test(navigator.userAgent);const isCordovaAndroid = document.URL.indexOf('file:///android_asset') === 0;-const isIOS = navigator.userAgent.match(/(iPad|iPhone|iPod)/i);+const iOSMatcher = navigator.userAgent.match(/(iPad|iPhone|iPod)/i);+const isIOS = iOSMatcher && iOSMatcher.length > 0;const isAndroid = navigator.userAgent.toLowerCase().includes('android');export default {diff --git a/app/containers/App.tsx b/app/containers/App.tsxindex 2989130d9..c02482fe1 100644--- a/app/containers/App.tsx+++ b/app/containers/App.tsx@@ -18,12 +18,11 @@import React, { Component } from 'react';import { connect } from 'react-redux';-// import injectTapEventPlugin from 'react-tap-event-plugin';import { I18nextProvider } from 'react-i18next'; // as we build ourself via webpackimport { createMuiTheme, ThemeProvider } from '@material-ui/core/styles';import '../assets/fonts/roboto/index.css';import i18n from '../services/i18n';-import { getCurrentTheme, getKeyBindingObject } from '../reducers/settings';+import { getCurrentTheme } from '../reducers/settings';import AppOnBoarding from '../components/AppOnboarding';// Needed for onTouchTap http://stackoverflow.com/a/34015469/988941@@ -82,7 +81,8 @@ const darkTheme = createMuiTheme({class App extends Component {props: {- children: Object+ children: Object;+ currentTheme: string;};render() {diff --git a/app/containers/LoginPage.tsx b/app/containers/LoginPage.tsxindex e546f6178..f52ab3439 100644--- a/app/containers/LoginPage.tsx+++ b/app/containers/LoginPage.tsx@@ -17,7 +17,6 @@*/import React, { Component } from 'react';-import { bindActionCreators } from 'redux';import { connect } from 'react-redux';import { translate } from 'react-i18next';import Button from '@material-ui/core/Button';diff --git a/app/perspectives/grid-perspective/components/GridOptionsMenu.tsx b/app/perspectives/grid-perspective/components/GridOptionsMenu.tsxindex 824e5b349..bd3ce7084 100644--- a/app/perspectives/grid-perspective/components/GridOptionsMenu.tsx+++ b/app/perspectives/grid-perspective/components/GridOptionsMenu.tsx@@ -31,22 +31,22 @@ import RadioUncheckedIcon from '@material-ui/icons/RadioButtonUnchecked';import HelpIcon from '@material-ui/icons/Help';import i18n from '../../../services/i18n';-type Props = {- open: boolean,- onClose: () => void,- anchorEl: Object | null,- toggleShowDirectories: boolean,- toggleShowTags: boolean,- showDirectories: boolean,- showTags: boolean,- toggleThumbnailsMode: boolean,- thumbnailMode: string,- singleClickAction: string,- entrySize: string,- changeEntrySize: (entrySize: string) => void,- changeSingleClickAction: (actionType: string) => void,- openHelpWebPage: () => void-};+interface Props {+ open: boolean;+ onClose: () => void;+ anchorEl: Element;+ toggleShowDirectories: () => void;+ toggleShowTags: () => void;+ showDirectories: boolean;+ showTags: boolean;+ toggleThumbnailsMode: () => void;+ thumbnailMode: string;+ singleClickAction: string;+ entrySize: string;+ changeEntrySize: (entrySize: string) => void;+ changeSingleClickAction: (actionType: string) => void;+ openHelpWebPage: () => void;+}const GridOptionsMenu = (props: Props) => {const {diff --git a/app/perspectives/grid-perspective/components/MainContainer.tsx b/app/perspectives/grid-perspective/components/MainContainer.tsxindex b2186d6f9..bb1bc3356 100644--- a/app/perspectives/grid-perspective/components/MainContainer.tsx+++ b/app/perspectives/grid-perspective/components/MainContainer.tsx@@ -64,19 +64,19 @@ import GridOptionsMenu from './GridOptionsMenu';const settings = JSON.parse(localStorage.getItem('tsPerspectiveGrid')); // loading settingsinterface Props {- classes: Object;- theme: Object;+ classes: any;+ theme: any;desktopMode: boolean;currentDirectoryPath: string;currentDirectoryColor: string;lastSelectedEntryPath: string | null;- selectedEntries: Array<Object>;- supportedFileTypes: Array<Object>;+ selectedEntries: Array<any>;+ supportedFileTypes: Array<any>;isAppLoading: boolean;isReadOnlyMode: boolean;- openFile: (path: string, isFile?: boolean) => void;- getNextFile: () => void;- getPrevFile: () => void;+ openFile: (path: string, isFile: boolean) => void;+ getNextFile: () => any;+ getPrevFile: () => any;deleteFile: (path: string) => void;deleteDirectory: (path: string) => void;loadDirectoryContent: (path: string) => void;@@ -90,7 +90,6 @@ interface Props {addTags: () => void;removeTags: () => void;removeAllTags: () => void;- editTagForEntry: () => void;perspectiveCommand: any;directoryContent: Array<FileSystemEntry>;moveFiles: (files: Array<string>, destination: string) => void;@@ -100,23 +99,23 @@ interface Props {notificationType: string,autohide: boolean) => void;-};+}interface State {- fileContextMenuAnchorEl: Object | null;+ fileContextMenuAnchorEl: Element;fileContextMenuOpened: boolean;- dirContextMenuAnchorEl: Object | null;+ dirContextMenuAnchorEl: Element;dirContextMenuOpened: boolean;- tagContextMenuAnchorEl: Object | null;+ tagContextMenuAnchorEl: Element;tagContextMenuOpened: boolean;layoutType: string;singleClickAction: string;doubleClickAction: string;entrySize: string;thumbnailMode: string;- sortingContextMenuAnchorEl: Object | null;+ sortingContextMenuAnchorEl: Element;sortingContextMenuOpened: boolean | null;- optionsContextMenuAnchorEl: Object | null;+ optionsContextMenuAnchorEl: Element;optionsContextMenuOpened: boolean | null;sortBy: string;orderBy: null | boolean;@@ -130,7 +129,7 @@ interface State {isFileRenameDialogOpened: boolean;selectedEntryPath: string;selectedTag: Tag | null;-};+}class GridPerspective extends React.Component<Props, State> {constructor(props) {@@ -427,7 +426,7 @@ class GridPerspective extends React.Component<Props, State> {if (fsEntry.isFile) {this.props.setSelectedEntries([fsEntry]);this.setState(this.computeFileOperationsEnabled);- this.props.openFile(fsEntry.path);+ this.props.openFile(fsEntry.path, true);} else {console.log('Handle Grid cell db click, selected path : ', fsEntry.path);this.props.loadDirectoryContent(fsEntry.path);@@ -472,7 +471,11 @@ class GridPerspective extends React.Component<Props, State> {}};- handleTagMenu = (event: React.ChangeEvent<HTMLInputElement>, tag: Tag, entryPath: string) => {+ handleTagMenu = (+ event: React.ChangeEvent<HTMLInputElement>,+ tag: Tag,+ entryPath: string+ ) => {event.preventDefault();event.stopPropagation();@@ -604,7 +607,7 @@ class GridPerspective extends React.Component<Props, State> {selected = true;}- const cellContent = (+ const cellContent: any = (<TagDropContainer entryPath={fsEntry.path}><CellContentselected={selected}@@ -635,6 +638,7 @@ class GridPerspective extends React.Component<Props, State> {return (<div style={{ position: 'relative' }}><TargetMoveFileBox+ // @ts-ignoreaccepts={[DragItemTypes.FILE]}onDrop={this.handleFileMoveDrop}>@@ -709,7 +713,7 @@ class GridPerspective extends React.Component<Props, State> {fsEntry => fsEntry.isFile && fsEntry.path === lastSelectedEntryPath);if (isLastSelectedEntryFile) {- this.props.openFile(lastSelectedEntryPath);+ this.props.openFile(lastSelectedEntryPath, true);} else {this.props.loadDirectoryContent(lastSelectedEntryPath);}@@ -730,17 +734,7 @@ class GridPerspective extends React.Component<Props, State> {currentDirectoryColor,selectedEntries,loadParentDirectoryContent,- toggleSelectAllFiles,- allFilesSelected,- handleLayoutSwitch,- openAddRemoveTagsDialog,- fileOperationsEnabled,- openMoveCopyFilesDialog,- openDeleteFileDialog,- handleSortingMenu,- handleOptionsMenu,- theme,- desktopMode+ theme} = this.props;const { layoutType, entrySize, sortBy, orderBy } = this.state;const selectedFilePaths = selectedEntries@@ -771,7 +765,7 @@ class GridPerspective extends React.Component<Props, State> {layoutType={this.state.layoutType}isReadOnlyMode={this.props.isReadOnlyMode}selectedEntries={this.props.selectedEntries}- loadParentDirectoryContent={this.props.loadParentDirectoryContent}+ loadParentDirectoryContent={loadParentDirectoryContent}toggleSelectAllFiles={this.toggleSelectAllFiles}allFilesSelected={this.state.allFilesSelected}handleLayoutSwitch={this.handleLayoutSwitch}@@ -792,6 +786,7 @@ class GridPerspective extends React.Component<Props, State> {<divstyle={{height: '100%',+ // @ts-ignoreoverflowY: AppConfig.isFirefox ? 'auto' : 'overlay',backgroundColor: currentDirectoryColor || 'transparent'}}@@ -865,8 +860,8 @@ class GridPerspective extends React.Component<Props, State> {content={i18n.t('core:deleteConfirmationContent')}list={selectedFilePaths}confirmCallback={result => {- if (result && this.props.selectedEntries) {- this.props.selectedEntries.map(fsentry => {+ if (result && selectedEntries) {+ selectedEntries.map(fsentry => {if (fsentry.isFile) {this.props.deleteFile(fsentry.path);}@@ -899,8 +894,6 @@ class GridPerspective extends React.Component<Props, State> {directoryPath={this.state.selectedEntryPath}loadDirectoryContent={this.props.loadDirectoryContent}openDirectory={this.props.openDirectory}- showInFileManager={this.props.showInFileManager}- openFileNatively={this.props.openFileNatively}openFile={this.props.openFile}deleteDirectory={this.props.deleteDirectory}isReadOnlyMode={this.props.isReadOnlyMode}@@ -913,7 +906,6 @@ class GridPerspective extends React.Component<Props, State> {selectedTag={this.state.selectedTag}currentEntryPath={this.state.selectedEntryPath}removeTags={this.props.removeTags}- editTagForEntry={this.props.editTagForEntry}isReadOnlyMode={this.props.isReadOnlyMode}/><SortingMenu@@ -977,4 +969,5 @@ function mapStateToProps(state) {export default connect(mapStateToProps,mapActionCreatorsToProps+ // @ts-ignore)(withStyles(styles, { withTheme: true })(GridPerspective));diff --git a/app/perspectives/grid-perspective/components/MainToolbar.tsx b/app/perspectives/grid-perspective/components/MainToolbar.tsxindex 2d8fad858..f75f4aee0 100644--- a/app/perspectives/grid-perspective/components/MainToolbar.tsx+++ b/app/perspectives/grid-perspective/components/MainToolbar.tsx@@ -31,22 +31,22 @@ import CopyIcon from '@material-ui/icons/FileCopy';import DeleteIcon from '@material-ui/icons/Delete';import i18n from '../../../services/i18n';-type Props = {- classes: Object,- isReadOnlyMode: boolean,- selectedEntries: Array<Object>,- loadParentDirectoryContent: () => void,- toggleSelectAllFiles: boolean,- allFilesSelected: boolean,- handleLayoutSwitch: (event: Object) => void,- openAddRemoveTagsDialog: () => void,- fileOperationsEnabled: boolean,- openMoveCopyFilesDialog: () => void,- openDeleteFileDialog: () => void,- handleSortingMenu: (event: Object) => void,- handleOptionsMenu: (event: Object) => void,- layoutType: string-};+interface Props {+ classes: any;+ isReadOnlyMode: boolean;+ selectedEntries: Array<Object>;+ loadParentDirectoryContent: () => void;+ toggleSelectAllFiles: (event: any) => void;+ allFilesSelected: boolean;+ handleLayoutSwitch: (event: Object) => void;+ openAddRemoveTagsDialog: () => void;+ fileOperationsEnabled: boolean;+ openMoveCopyFilesDialog: () => void;+ openDeleteFileDialog: () => void;+ handleSortingMenu: (event: Object) => void;+ handleOptionsMenu: (event: Object) => void;+ layoutType: string;+}const MainToolbar = (props: Props) => {const {diff --git a/app/perspectives/grid-perspective/components/SortingMenu.tsx b/app/perspectives/grid-perspective/components/SortingMenu.tsxindex 3094ab9ae..90ac1b5d1 100644--- a/app/perspectives/grid-perspective/components/SortingMenu.tsx+++ b/app/perspectives/grid-perspective/components/SortingMenu.tsx@@ -25,14 +25,14 @@ import ArrowUpIcon from '@material-ui/icons/KeyboardArrowUp';import ArrowDownIcon from '@material-ui/icons/KeyboardArrowDown';import i18n from '../../../services/i18n';-type Props = {- open: boolean,- onClose: () => void,- anchorEl: Object | null,- handleSortBy: (sortType: string) => void,- sortBy: string,- orderBy: null | boolean-};+interface Props {+ open: boolean;+ onClose: () => void;+ anchorEl: Element;+ handleSortBy: (sortType: string) => void;+ sortBy: string;+ orderBy: null | boolean;+}const SortingMenu = (props: Props) => {const { open, onClose, sortBy, orderBy, handleSortBy, anchorEl } = props;diff --git a/app/perspectives/grid-perspective/components/styles.css.tsx b/app/perspectives/grid-perspective/components/styles.css.tsxindex f45cdf7de..97dec4d87 100644--- a/app/perspectives/grid-perspective/components/styles.css.tsx+++ b/app/perspectives/grid-perspective/components/styles.css.tsx@@ -17,7 +17,7 @@*/import AppConfig from '../../../config';-export default (theme: Object) => ({+export default (theme: any): any => ({gridContainer: {display: 'grid',gridGap: '2px 2px',diff --git a/app/reducers/app.ts b/app/reducers/app.tsindex 03f266a08..318d80b86 100644--- a/app/reducers/app.ts+++ b/app/reducers/app.ts@@ -178,7 +178,7 @@ export const initialState = {};// The state described here will not be persisted-export default (state: Object = initialState, action: Object) => {+export default (state: any = initialState, action: any) => {switch (action.type) {case types.DEVICE_ONLINE: {return { ...state, isOnline: true, error: null };@@ -549,7 +549,7 @@ export const actions = {}),showCreateDirectoryDialog: () => (dispatch: (actions: Object) => void,- getState: () => Object+ getState: () => any) => {const { app } = getState();if (!app.currentDirectoryPath) {@@ -566,7 +566,7 @@ export const actions = {},showCreateFileDialog: () => (dispatch: (actions: Object) => void,- getState: () => Object+ getState: () => any) => {const { app } = getState();if (!app.currentDirectoryPath) {@@ -611,7 +611,7 @@ export const actions = {closeAllVerticalPanels: () => ({ type: types.CLOSE_ALLVERTICAL_PANELS }),loadParentDirectoryContent: () => (dispatch: (actions: Object) => void,- getState: () => Object+ getState: () => any) => {const state = getState();const currentDirectoryPath = state.app.currentDirectoryPath;@@ -649,10 +649,10 @@ export const actions = {},loadDirectoryContent: (directoryPath: string) => (dispatch: (actions: Object) => void,- getState: () => Object+ getState: () => any) => {console.time('listDirectoryPromise');- const { settings } = getState();+ const { settings } = getState();window.walkCanceled = false;loadMetaDataPromise(directoryPath)@@ -677,7 +677,7 @@ export const actions = {}).catch(error => {console.timeEnd('listDirectoryPromise');- dispatch(actions.loadDirectoryFailure(error)); // Currently this is never called, due the promise alwasy resolvse+ dispatch(actions.loadDirectoryFailure(error)); // Currently this is never called, due the promise always resolve});},loadDirectorySuccess: (@@ -690,14 +690,14 @@ export const actions = {loadDirectorySuccessInt: (directoryPath: string,directoryContent: Array<Object>,- showIsLoading: boolean+ showIsLoading?: boolean) => ({type: types.LOAD_DIRECTORY_SUCCESS,directoryPath,directoryContent,showIsLoading}),- loadDirectoryFailure: (directoryPath: string, error: any) => (+ loadDirectoryFailure: (directoryPath: string, error?: any) => (dispatch: (actions: Object) => void) => {console.warn('Error loading directory: ' + error);@@ -738,7 +738,7 @@ export const actions = {}),deleteDirectory: (directoryPath: string) => (dispatch: (actions: Object) => void,- getState: () => Object+ getState: () => any) => {const { settings } = getState();PlatformIO.deleteDirectoryPromise(directoryPath, settings.useTrashCan)@@ -835,7 +835,7 @@ export const actions = {},createFile: () => (dispatch: (actions: Object) => void,- getState: () => Object+ getState: () => any) => {const { app } = getState();if (app.currentDirectoryPath) {@@ -886,7 +886,7 @@ export const actions = {fileName: string,content: string,fileType: 'md' | 'txt' | 'html'- ) => (dispatch: (actions: Object) => void, getState: () => Object) => {+ ) => (dispatch: (actions: Object) => void, getState: () => any) => {const fileNameAndExt = fileName + '.' + fileType;const filePath =normalizePath(targetPath) + AppConfig.dirSeparator + fileNameAndExt;@@ -935,7 +935,7 @@ export const actions = {}),openLocationById: (locationId: string) => (dispatch: (actions: Object) => void,- getState: () => Object+ getState: () => any) => {const locations: Array<Location> = getState().locations;locations.map(location => {@@ -947,7 +947,7 @@ export const actions = {},openLocation: (location: Location) => (dispatch: (actions: Object) => void,- getState: () => Object+ getState: () => any) => {if (Pro && Pro.Watcher) {Pro.Watcher.stopWatching();@@ -1017,7 +1017,7 @@ export const actions = {},closeLocation: (locationId: string) => (dispatch: (actions: Object) => void,- getState: () => Object+ getState: () => any) => {const locations: Array<Location> = getState().locations;const { currentLocationId } = getState().app;@@ -1041,8 +1041,8 @@ export const actions = {}),showNotification: (text: string,- notificationType?: string = 'default',- autohide?: boolean = true+ notificationType: string = 'default',+ autohide: boolean = true) => ({type: types.SET_NOTIFICATION,visible: true,@@ -1071,9 +1071,9 @@ export const actions = {}),openFile: (entryPath: string,- isFile?: boolean = true,+ isFile: boolean = true,editMode: boolean = false- ) => (dispatch: (actions: Object) => void, getState: () => Object) => {+ ) => (dispatch: (actions: Object) => void, getState: () => any) => {const supportedFileTypes: Array<Object> = getState().settings.supportedFileTypes;const entryForOpening: OpenedEntry = findExtensionsForEntry(@@ -1107,7 +1107,7 @@ export const actions = {}),getNextFile: (pivotFilePath?: string) => (dispatch: (actions: Object) => void,- getState: () => Object+ getState: () => any) => {const currentEntries = getState().app.currentDirectoryEntries.filter(entry => entry.isFile@@ -1138,7 +1138,7 @@ export const actions = {},getPrevFile: (pivotFilePath?: string) => (dispatch: (actions: Object) => void,- getState: () => Object+ getState: () => any) => {const currentEntries = getState().app.currentDirectoryEntries.filter(entry => entry.isFile@@ -1210,7 +1210,7 @@ export const actions = {dispatch(actions.reflectRenameEntryInt(path, newPath));dispatch(LocationIndexActions.reflectRenameEntry(path, newPath));},- reflectUpdateSidecarTagsInt: (path: string, tags: Array<Tags>) => ({+ reflectUpdateSidecarTagsInt: (path: string, tags: Array<Tag>) => ({type: types.REFLECT_UPDATE_SIDECARTAGS,path,tags@@ -1222,7 +1222,7 @@ export const actions = {}),reflectUpdateSidecarTags: (path: string,- tags: Array<Tags>,+ tags: Array<Tag>,updateIndex: boolean = true) => (dispatch: (actions: Object) => void) => {dispatch(actions.reflectUpdateSidecarTagsInt(path, tags));@@ -1238,7 +1238,7 @@ export const actions = {},deleteFile: (filePath: string) => (dispatch: (actions: Object) => void,- getState: () => Object+ getState: () => any) => {const { settings } = getState();PlatformIO.deleteFilePromise(filePath, settings.useTrashCan)@@ -1334,7 +1334,7 @@ export const actions = {},saveFile: () => () =>// dispatch: (actions: Object) => void,- // getState: () => Object+ // getState: () => any{actions.showNotification(i18n.t('core:notImplementedYet'),@@ -1448,7 +1448,7 @@ function findExtensionPathForId(extensionId: string): string {}function findExtensionsForEntry(- supportedFileTypes: Array<Object>,+ supportedFileTypes: Array<any>,entryPath: string,isFile: boolean = true): OpenedEntry {@@ -1569,11 +1569,11 @@ export function findAvailableExtensions() {}// Selectors-export const getDirectoryContent = (state: Object) =>+export const getDirectoryContent = (state: any) =>state.app.currentDirectoryEntries;-export const getDirectoryPath = (state: Object) =>+export const getDirectoryPath = (state: any) =>state.app.currentDirectoryPath;-export const getCurrentLocationPath = (state: Object) => {+export const getCurrentLocationPath = (state: any) => {let pathCurrentLocation;if (state.locations) {state.locations.map(location => {@@ -1588,59 +1588,59 @@ export const getCurrentLocationPath = (state: Object) => {}return pathCurrentLocation;};-export const isUpdateAvailable = (state: Object) => state.app.isUpdateAvailable;-export const isUpdateInProgress = (state: Object) =>+export const isUpdateAvailable = (state: any) => state.app.isUpdateAvailable;+export const isUpdateInProgress = (state: any) =>state.app.isUpdateInProgress;-export const isOnline = (state: Object) => state.app.isOnline;-export const getLastSelectedEntry = (state: Object) =>+export const isOnline = (state: any) => state.app.isOnline;+export const getLastSelectedEntry = (state: any) =>state.app.lastSelectedEntry;-export const getSelectedTag = (state: Object) => state.app.tag;-export const getSelectedEntries = (state: Object) => state.app.selectedEntries;-export const isFileOpened = (state: Object) => state.app.openedFiles.length > 0;-export const isGeneratingThumbs = (state: Object) =>+export const getSelectedTag = (state: any) => state.app.tag;+export const getSelectedEntries = (state: any) => state.app.selectedEntries;+export const isFileOpened = (state: any) => state.app.openedFiles.length > 0;+export const isGeneratingThumbs = (state: any) =>state.app.isGeneratingThumbs;-// export const isFileDragged = (state: Object) => state.app.isFileDragged;-export const isReadOnlyMode = (state: Object) => state.app.isReadOnlyMode;-export const isOnboardingDialogOpened = (state: Object) =>+// export const isFileDragged = (state: any) => state.app.isFileDragged;+export const isReadOnlyMode = (state: any) => state.app.isReadOnlyMode;+export const isOnboardingDialogOpened = (state: any) =>state.app.onboardingDialogOpened;-export const isEditTagDialogOpened = (state: Object) =>+export const isEditTagDialogOpened = (state: any) =>state.app.editTagDialogOpened;-export const isAboutDialogOpened = (state: Object) =>+export const isAboutDialogOpened = (state: any) =>state.app.aboutDialogOpened;-export const isKeysDialogOpened = (state: Object) => state.app.keysDialogOpened;-export const isLicenseDialogOpened = (state: Object) =>+export const isKeysDialogOpened = (state: any) => state.app.keysDialogOpened;+export const isLicenseDialogOpened = (state: any) =>state.app.licenseDialogOpened;-export const isThirdPartyLibsDialogOpened = (state: Object) =>+export const isThirdPartyLibsDialogOpened = (state: any) =>state.app.thirdPartyLibsDialogOpened;-export const isSettingsDialogOpened = (state: Object) =>+export const isSettingsDialogOpened = (state: any) =>state.app.settingsDialogOpened;-export const isCreateDirectoryOpened = (state: Object) =>+export const isCreateDirectoryOpened = (state: any) =>state.app.createDirectoryDialogOpened;-export const isCreateFileDialogOpened = (state: Object) =>+export const isCreateFileDialogOpened = (state: any) =>state.app.createFileDialogOpened;-export const isSelectDirectoryDialogOpened = (state: Object) =>+export const isSelectDirectoryDialogOpened = (state: any) =>state.app.selectDirectoryDialogOpened;-export const getOpenedFiles = (state: Object) => state.app.openedFiles;-export const getNotificationStatus = (state: Object) =>+export const getOpenedFiles = (state: any) => state.app.openedFiles;+export const getNotificationStatus = (state: any) =>state.app.notificationStatus;-export const getCurrentDirectoryColor = (state: Object) =>+export const getCurrentDirectoryColor = (state: any) =>state.app.currentDirectoryColor;-export const getSearchResults = (state: Object) =>+export const getSearchResults = (state: any) =>state.app.currentDirectoryEntries;-export const getSearchResultCount = (state: Object) =>+export const getSearchResultCount = (state: any) =>state.app.currentDirectoryEntries.length;-export const getCurrentLocationId = (state: Object) =>+export const getCurrentLocationId = (state: any) =>state.app.currentLocationId;-export const isEntryInFullWidth = (state: Object) =>+export const isEntryInFullWidth = (state: any) =>state.app.isEntryInFullWidth;-export const isLoading = (state: Object) => state.app.isLoading;-export const isLocationManagerPanelOpened = (state: Object) =>+export const isLoading = (state: any) => state.app.isLoading;+export const isLocationManagerPanelOpened = (state: any) =>state.app.locationManagerPanelOpened;-export const isTagLibraryPanelOpened = (state: Object) =>+export const isTagLibraryPanelOpened = (state: any) =>state.app.tagLibraryPanelOpened;-export const isSearchPanelOpened = (state: Object) =>+export const isSearchPanelOpened = (state: any) =>state.app.searchPanelOpened;-export const isPerspectivesPanelOpened = (state: Object) =>+export const isPerspectivesPanelOpened = (state: any) =>state.app.perspectivesPanelOpened;-export const isHelpFeedbackPanelOpened = (state: Object) =>+export const isHelpFeedbackPanelOpened = (state: any) =>state.app.helpFeedbackPanelOpened;diff --git a/app/reducers/io-actions.ts b/app/reducers/io-actions.tsindex fdc2607d0..cc0e40aa3 100644--- a/app/reducers/io-actions.ts+++ b/app/reducers/io-actions.ts@@ -37,7 +37,7 @@ const actions = {IPTCDescription: true,IPTCTags: true}- ) => (dispatch: (actions: Object) => void, getState: () => Object) => {+ ) => (dispatch: (actions: any) => void, getState: () => any) => {const { currentDirectoryEntries } = getState().app;if (!Pro || !Pro.ContentExtractor) {dispatch(AppActions.showNotification(i18n.t('core:needProVersion')));diff --git a/app/reducers/location-index.ts b/app/reducers/location-index.tsindex 0a60eb392..07cda878f 100644--- a/app/reducers/location-index.ts+++ b/app/reducers/location-index.ts@@ -53,7 +53,7 @@ export const initialState = {isIndexing: false};-export default (state: Object = initialState, action: Object) => {+export default (state: any = initialState, action: any) => {switch (action.type) {case types.INDEX_DIRECTORY_START: {return {@@ -233,7 +233,7 @@ export const actions = {cancelDirectoryIndexing: () => ({ type: types.INDEX_DIRECTORY_CANCEL }),createDirectoryIndex: (directoryPath: string, extractText: boolean) => (dispatch: (actions: Object) => void,- getState: () => Object+ getState: () => any) => {const state = getState();const currentLocation: Location = getLocation(@@ -263,7 +263,7 @@ export const actions = {},loadDirectoryIndex: (directoryPath: string) => (dispatch: (actions: Object) => void,- getState: () => Object+ getState: () => any) => {const state = getState();const currentLocation: Location = getLocation(@@ -302,7 +302,7 @@ export const actions = {}),searchLocationIndex: (searchQuery: SearchQuery) => (dispatch: (actions: Object) => void,- getState: () => Object+ getState: () => any) => {dispatch(AppActions.showNotification(i18n.t('core:searching'), 'default', false)@@ -365,6 +365,6 @@ export const actions = {};// Selectors-export const getIndexedEntriesCount = (state: Object) =>+export const getIndexedEntriesCount = (state: any) =>state.locationIndex.currentDirectoryIndex.length;-export const isIndexing = (state: Object) => state.locationIndex.isIndexing;+export const isIndexing = (state: any) => state.locationIndex.isIndexing;diff --git a/app/reducers/locations.ts b/app/reducers/locations.tsindex 8286fec61..f44d099cd 100644--- a/app/reducers/locations.ts+++ b/app/reducers/locations.ts@@ -21,187 +21,187 @@ import { immutablySwapItems } from '../utils/misc';import { actions as AppActions } from '../reducers/app';export const types = {- ADD_LOCATION: 'APP/ADD_LOCATION',- MOVE_UP_LOCATION: 'APP/MOVE_UP_LOCATION',- MOVE_DOWN_LOCATION: 'APP/MOVE_DOWN_LOCATION',- EDIT_LOCATION: 'APP/EDIT_LOCATION',- REMOVE_LOCATION: 'APP/REMOVE_LOCATION'+ ADD_LOCATION: 'APP/ADD_LOCATION',+ MOVE_UP_LOCATION: 'APP/MOVE_UP_LOCATION',+ MOVE_DOWN_LOCATION: 'APP/MOVE_DOWN_LOCATION',+ EDIT_LOCATION: 'APP/EDIT_LOCATION',+ REMOVE_LOCATION: 'APP/REMOVE_LOCATION'};export const locationType = {- TYPE_LOCAL: '0',- TYPE_CLOUD: '1'+ TYPE_LOCAL: '0',+ TYPE_CLOUD: '1'};export type Location = {- uuid: string,- name: string,- type: string,- accessKeyId?: string,- secretAccessKey?: string,- bucketName?: string,- region?: string,- paths: Array<string>,- perspective?: string, // id of the perspective- creationDate?: string,- isDefault: boolean,- isReadOnly?: boolean,- watchForChanges?: boolean,- persistIndex?: boolean,- fullTextIndex?: boolean+ uuid: string;+ name: string;+ type: string;+ accessKeyId?: string;+ secretAccessKey?: string;+ bucketName?: string;+ region?: string;+ paths: Array<string>;+ perspective?: string; // id of the perspective+ creationDate?: string;+ isDefault: boolean;+ isReadOnly?: boolean;+ watchForChanges?: boolean;+ persistIndex?: boolean;+ fullTextIndex?: boolean;};export const initialState = [];-export default (state: Array<Location> = initialState, action: Object) => {- switch (action.type) {- case types.ADD_LOCATION: {- if (action.location.isDefault) {- state.forEach(location => {- // eslint-disable-next-line no-param-reassign- location.isDefault = false;- });- }- return [- ...state,- {- ...action.location,- uuid: action.location.uuid || uuidv1(),- creationDate: new Date().toJSON()- }- ];- }- case types.EDIT_LOCATION: {- let indexForEditing = -1;- state.forEach((location, index) => {- if (location.uuid === action.location.uuid) {- indexForEditing = index;- }- if (action.location.isDefault) {- // eslint-disable-next-line no-param-reassign- location.isDefault = false;- }- });- if (indexForEditing >= 0) {- return [- ...state.slice(0, indexForEditing),- { ...state[indexForEditing], ...action.location },- ...state.slice(indexForEditing + 1)- ];- }- return state;- }- case types.MOVE_UP_LOCATION: {- let indexForUpdating = -1;- state.forEach((location, index) => {- if (location.uuid === action.uuid) {- indexForUpdating = index;- }- });- if (indexForUpdating > 0) {- const secondIndex = indexForUpdating - 1;- return immutablySwapItems(state, indexForUpdating, secondIndex);- }- return state;- }- case types.MOVE_DOWN_LOCATION: {- let indexForUpdating = -1;- state.forEach((location, index) => {- if (location.uuid === action.uuid) {- indexForUpdating = index;- }- });- if (indexForUpdating >= 0 && indexForUpdating < state.length - 1) {- const secondIndex = indexForUpdating + 1;- return immutablySwapItems(state, indexForUpdating, secondIndex);- }- return state;- }- case types.REMOVE_LOCATION: {- let indexForRemoving = -1;- state.forEach((location, index) => {- if (location.uuid === action.location.uuid) {- indexForRemoving = index;- }- });- if (indexForRemoving >= 0) {- return [- ...state.slice(0, indexForRemoving),- ...state.slice(indexForRemoving + 1)- ];- // return state.filter( (item, index) => index !== indexForRemoving);- }- return state;- }- default: {- return state;- }- }+export default (state: Array<Location> = initialState, action: any) => {+ switch (action.type) {+ case types.ADD_LOCATION: {+ if (action.location.isDefault) {+ state.forEach(location => {+ // eslint-disable-next-line no-param-reassign+ location.isDefault = false;+ });+ }+ return [+ ...state,+ {+ ...action.location,+ uuid: action.location.uuid || uuidv1(),+ creationDate: new Date().toJSON()+ }+ ];+ }+ case types.EDIT_LOCATION: {+ let indexForEditing = -1;+ state.forEach((location, index) => {+ if (location.uuid === action.location.uuid) {+ indexForEditing = index;+ }+ if (action.location.isDefault) {+ // eslint-disable-next-line no-param-reassign+ location.isDefault = false;+ }+ });+ if (indexForEditing >= 0) {+ return [+ ...state.slice(0, indexForEditing),+ { ...state[indexForEditing], ...action.location },+ ...state.slice(indexForEditing + 1)+ ];+ }+ return state;+ }+ case types.MOVE_UP_LOCATION: {+ let indexForUpdating = -1;+ state.forEach((location, index) => {+ if (location.uuid === action.uuid) {+ indexForUpdating = index;+ }+ });+ if (indexForUpdating > 0) {+ const secondIndex = indexForUpdating - 1;+ return immutablySwapItems(state, indexForUpdating, secondIndex);+ }+ return state;+ }+ case types.MOVE_DOWN_LOCATION: {+ let indexForUpdating = -1;+ state.forEach((location, index) => {+ if (location.uuid === action.uuid) {+ indexForUpdating = index;+ }+ });+ if (indexForUpdating >= 0 && indexForUpdating < state.length - 1) {+ const secondIndex = indexForUpdating + 1;+ return immutablySwapItems(state, indexForUpdating, secondIndex);+ }+ return state;+ }+ case types.REMOVE_LOCATION: {+ let indexForRemoving = -1;+ state.forEach((location, index) => {+ if (location.uuid === action.location.uuid) {+ indexForRemoving = index;+ }+ });+ if (indexForRemoving >= 0) {+ return [+ ...state.slice(0, indexForRemoving),+ ...state.slice(indexForRemoving + 1)+ ];+ // return state.filter( (item, index) => index !== indexForRemoving);+ }+ return state;+ }+ default: {+ return state;+ }+ }};export const actions = {- addLocation: (location: Location, openAfterCreate?: boolean = true) => (- dispatch: (actions: Object) => void- ) => {- dispatch(actions.createLocation(location));- if (openAfterCreate) {- dispatch(AppActions.openLocation(location));- }- },- createLocation: (location: Location) => ({- type: types.ADD_LOCATION,- location- }),- moveLocationUp: (uuid: string) => ({ type: types.MOVE_UP_LOCATION, uuid }),- moveLocationDown: (uuid: string) => ({- type: types.MOVE_DOWN_LOCATION,- uuid- }),- editLocation: (location: Location) => (- dispatch: (actions: Object) => void- ) => {- dispatch(actions.changeLocation(location));- dispatch(AppActions.openLocation(location));- dispatch(AppActions.setReadOnlyMode(location.isReadOnly || false));- },- changeLocation: (location: Location) => ({- type: types.EDIT_LOCATION,- location- }),- removeLocation: (location: Location) => (- dispatch: (actions: Object) => void- ) => {- dispatch(AppActions.closeLocation(location.uuid));- dispatch(actions.deleteLocation(location));- },- deleteLocation: (location: Location) => ({- type: types.REMOVE_LOCATION,- location- })+ addLocation: (location: Location, openAfterCreate: boolean = true) => (+ dispatch: (actions: Object) => void+ ) => {+ dispatch(actions.createLocation(location));+ if (openAfterCreate) {+ dispatch(AppActions.openLocation(location));+ }+ },+ createLocation: (location: Location) => ({+ type: types.ADD_LOCATION,+ location+ }),+ moveLocationUp: (uuid: string) => ({ type: types.MOVE_UP_LOCATION, uuid }),+ moveLocationDown: (uuid: string) => ({+ type: types.MOVE_DOWN_LOCATION,+ uuid+ }),+ editLocation: (location: Location) => (+ dispatch: (actions: Object) => void+ ) => {+ dispatch(actions.changeLocation(location));+ dispatch(AppActions.openLocation(location));+ dispatch(AppActions.setReadOnlyMode(location.isReadOnly || false));+ },+ changeLocation: (location: Location) => ({+ type: types.EDIT_LOCATION,+ location+ }),+ removeLocation: (location: Location) => (+ dispatch: (actions: Object) => void+ ) => {+ dispatch(AppActions.closeLocation(location.uuid));+ dispatch(actions.deleteLocation(location));+ },+ deleteLocation: (location: Location) => ({+ type: types.REMOVE_LOCATION,+ location+ })};// Selectors-export const getLocations = (state: Object): Array<Location> => state.locations;+export const getLocations = (state: any): Array<Location> => state.locations;export const getLocation = (- state: Object,- locationId: string+ state: any,+ locationId: string): Location | null => {- let foundLocation = null;- state.locations.map(location => {- if (location.uuid === locationId) {- foundLocation = location;- }- return true;- });- return foundLocation;+ let foundLocation = null;+ state.locations.map(location => {+ if (location.uuid === locationId) {+ foundLocation = location;+ }+ return true;+ });+ return foundLocation;};-export const getDefaultLocationId = (state: Object): ?string => {- let defaultLocationID;- state.locations.map(location => {- if (location.isDefault) {- defaultLocationID = location.uuid;- }- return true;- });- return defaultLocationID;+export const getDefaultLocationId = (state: any): string | undefined => {+ let defaultLocationID;+ state.locations.map(location => {+ if (location.isDefault) {+ defaultLocationID = location.uuid;+ }+ return true;+ });+ return defaultLocationID;};diff --git a/app/reducers/settings.ts b/app/reducers/settings.tsindex 97662bd5b..1eb850e20 100644--- a/app/reducers/settings.ts+++ b/app/reducers/settings.ts@@ -68,7 +68,7 @@ export const types = {SET_FIRST_RUN: 'SETTINGS/SET_FIRST_RUN'};-export default (state: Object = defaultSettings, action: any) => {+export default (state: any = defaultSettings, action: any) => {switch (action.type) {case types.UPGRADE_SETTINGS: {const mergedKeyBindings = defaultSettings.keyBindings.map(x =>@@ -418,15 +418,13 @@ export const actions = {}),checkForUpdate: () => (dispatch: (actions: Object) => void- // getState: () => Object+ // getState: () => any) => {// const { settings } = getState();getLastVersionPromise().then(lastVersion => {console.log('Last version on server: ' + lastVersion);- // $FlowFixMeconst newVersion = semver.coerce(lastVersion); // lastVersion '3.0.5' ;- // $FlowFixMeconst currentVersion = semver.coerce(versionMeta.version);// const lastPublishedVersion = semver.coerce(settings.lastPublishedVersion);if (semver.valid(newVersion) && semver.gt(newVersion, currentVersion)) {@@ -472,64 +470,63 @@ export function getLastVersionPromise(): Promise<string> {}// Selectors-export const getSettings = (state: Object) => state.settings;-export const getDesktopMode = (state: Object) => {+export const getSettings = (state: any) => state.settings;+export const getDesktopMode = (state: any) => {if (typeof window.ExtDisplayMode === 'undefined') {return state.settings.desktopMode;}return window.ExtDisplayMode !== 'mobile';};-export const getCheckForUpdateOnStartup = (state: Object) =>+export const getCheckForUpdateOnStartup = (state: any) =>state.settings.checkForUpdates;-export const getLastPublishedVersion = (state: Object) =>+export const getLastPublishedVersion = (state: any) =>state.settings.lastPublishedVersion;-export const getShowUnixHiddenEntries = (state: Object) =>+export const getShowUnixHiddenEntries = (state: any) =>state.settings.showUnixHiddenEntries;-export const getUseDefaultLocation = (state: Object) =>+export const getUseDefaultLocation = (state: any) =>state.settings.useDefaultLocation;-export const getColoredFileExtension = (state: Object) =>+export const getColoredFileExtension = (state: any) =>state.settings.coloredFileExtension;-export const getShowTagAreaOnStartup = (state: Object) =>+export const getShowTagAreaOnStartup = (state: any) =>state.settings.showTagAreaOnStartup;-export const getLoadsLocationMetaData = (state: Object) =>+export const getLoadsLocationMetaData = (state: any) =>state.settings.loadsLocationMetaData;-export const getSearchInSubfolders = (state: Object) =>+export const getSearchInSubfolders = (state: any) =>state.settings.searchInSubfolders;-export const getWatchCurrentDirectory = (state: Object) =>+export const getWatchCurrentDirectory = (state: any) =>state.settings.watchCurrentDirectory;-export const getCurrentLanguage = (state: Object) =>+export const getCurrentLanguage = (state: any) =>state.settings.interfaceLanguage;-export const getAppDataPath = (state: Object) => state.settings.appDataPath;-export const getSupportedLanguages = (state: Object) =>- state.settings.languages;-export const getCalculateTags = (state: Object) => state.settings.calculateTags;-export const getUseTrashCan = (state: Object) => state.settings.useTrashCan;-export const getPersistTagsInSidecarFile = (state: Object) =>+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) =>state.settings.persistTagsInSidecarFile;-export const getUseGenerateThumbnails = (state: Object) =>+export const getUseGenerateThumbnails = (state: any) =>state.settings.useGenerateThumbnails;-export const getUseTextExtraction = (state: Object) =>+export const getUseTextExtraction = (state: any) =>state.settings.useTextExtraction;-export const getKeyBindings = (state: Object) => state.settings.keyBindings;-export const getKeyBindingObject = (state: Object) =>+export const getKeyBindings = (state: any) => state.settings.keyBindings;+export const getKeyBindingObject = (state: any) =>generateKeyBindingObject(state.settings.keyBindings);-export const getSupportedFileTypes = (state: Object) =>+export const getSupportedFileTypes = (state: any) =>state.settings.supportedFileTypes;-export const getPerspectives = (state: Object) =>+export const getPerspectives = (state: any) =>state.settings.supportedPerspectives;-export const getTagColor = (state: Object) => state.settings.tagBackgroundColor;-export const getTagTextColor = (state: Object) => state.settings.tagTextColor;-export const getCurrentTheme = (state: Object) => state.settings.currentTheme;-export const isGlobalKeyBindingEnabled = (state: Object) =>+export const getTagColor = (state: any) => state.settings.tagBackgroundColor;+export const getTagTextColor = (state: any) => state.settings.tagTextColor;+export const getCurrentTheme = (state: any) => state.settings.currentTheme;+export const isGlobalKeyBindingEnabled = (state: any) =>state.settings.enableGlobalKeyboardShortcuts;-export const getLeftVerticalSplitSize = (state: Object) =>+export const getLeftVerticalSplitSize = (state: any) =>state.settings.leftVerticalSplitSize;-export const getMainVerticalSplitSize = (state: Object) =>+export const getMainVerticalSplitSize = (state: any) =>state.settings.mainVerticalSplitSize;-export const getTagDelimiter = (state: Object) => state.settings.tagDelimiter;-export const getMaxSearchResults = (state: Object) =>+export const getTagDelimiter = (state: any) => state.settings.tagDelimiter;+export const getMaxSearchResults = (state: any) =>state.settings.maxSearchResult;-export const isFirstRun = (state: Object) => {+export const isFirstRun = (state: any) => {if (typeof window.ExtIsFirstRun === 'undefined') {return state.settings.firstRun;}@@ -538,7 +535,7 @@ export const isFirstRun = (state: Object) => {function generateKeyBindingObject(keyBindings: Array<Object>) {const kbObject = {};- keyBindings.map(kb => {+ keyBindings.map((kb: any) => {kbObject[kb.name] = kb.command;return true;});diff --git a/app/reducers/tagging-actions.ts b/app/reducers/tagging-actions.tsindex 5ace8bf9f..536ddfb21 100644--- a/app/reducers/tagging-actions.ts+++ b/app/reducers/tagging-actions.ts@@ -19,11 +19,7 @@import uuidv1 from 'uuid';import i18n from '../services/i18n';import { actions as AppActions } from './app';-import {- actions as TagLibraryActions,- Tag,- TagGroup-} from './taglibrary';+import { actions as TagLibraryActions, Tag, TagGroup } from './taglibrary';import {extractFileExtension,extractFileName,@@ -40,16 +36,16 @@ import { formatDateTime4Tag, isPlusCode } from '../utils/misc';import AppConfig from '../config';import PlatformIO from '../services/platform-io';import { Pro } from '../pro';-import ocl from '../utils/openlocationcode';+// import openlocationcode from '../utils/openlocationcode';-export const defaultTagLocation = ocl.encode(51.48, 0); // default tag coordinate Greenwich+export const defaultTagLocation = ''; // (new openlocationcode()).encode(51.48, 0, undefined); // default tag coordinate Greenwichconst actions = {addTags: (paths: Array<string>,tags: Array<Tag>,- updateIndex?: boolean = true- ) => (dispatch: (actions: Object) => void, getState: () => Object) => {+ updateIndex: boolean = true+ ) => (dispatch: (actions: Object) => void, getState: () => any) => {const { settings, taglibrary } = getState();const processedTags = [];@@ -137,8 +133,8 @@ const actions = {addTagsToEntry: (path: string,tags: Array<Tag>,- updateIndex?: boolean = true- ) => async (dispatch: (actions: Object) => void, getState: () => Object) => {+ updateIndex: boolean = true+ ) => async (dispatch: (actions: Object) => void, getState: () => any) => {const { settings } = getState();const entryProperties = await PlatformIO.getPropertiesPromise(path);let fsEntryMeta;@@ -273,7 +269,7 @@ const actions = {*/editTagForEntry: (path: string, tag: Tag, newTagTitle: string) => async (dispatch: (actions: Object) => void,- getState: () => Object+ getState: () => any) => {const { settings, taglibrary } = getState();if (@@ -434,7 +430,7 @@ const actions = {},removeTagsFromEntry: (path: string, tags: Array<Tag>) => (dispatch: (actions: Object) => void,- getState: () => Object+ getState: () => any) => {const { settings } = getState();const tagTitlesForRemoving = [];@@ -517,7 +513,7 @@ const actions = {},removeAllTagsFromEntry: (path: string) => (dispatch: (actions: Object) => void,- getState: () => Object+ getState: () => any) => {const { settings } = getState();loadMetaDataPromise(path)@@ -636,7 +632,7 @@ const actions = {},collectTagsFromLocation: (tagGroup: TagGroup) => (dispatch: (actions: Object) => void,- getState: () => Object+ getState: () => any) => {const { locationIndex, settings } = getState();@@ -678,21 +674,6 @@ const actions = {}};-function handleSmartTag(smarttagFunction: string) {- switch (smarttagFunction) {- case 'today':- message = data.title ? data.title : '';- if (data.message) {- message = message + ': ' + data.message;- }- this.props.showNotification(message, NotificationTypes.default);- break;- default:- console.log('Not recognized messaging command: ' + msg);- break;- }-}-function generateTagValue(tag) {let tagTitle = tag.functionality;switch (tag.functionality) {diff --git a/app/reducers/taglibrary-default.ts b/app/reducers/taglibrary-default.tsindex 52e65d3c3..a275e7e5b 100644--- a/app/reducers/taglibrary-default.ts+++ b/app/reducers/taglibrary-default.ts@@ -170,4 +170,4 @@ export default [}]}-];+] as any;diff --git a/app/reducers/taglibrary.ts b/app/reducers/taglibrary.tsindex 24cbf4e2b..f721f1f07 100644--- a/app/reducers/taglibrary.ts+++ b/app/reducers/taglibrary.ts@@ -24,555 +24,557 @@ import defaultTagLibrary from './taglibrary-default';import AppConfig from '../config';export const types = {- CREATE_TAGGROUP: 'CREATE_TAGGROUP',- IMPORT_TAGGROUP: 'IMPORT_TAGGROUP',- IMPORT_OLD_TAGGROUP: 'IMPORT_OLD_TAGGROUP',- ADD_TAGGROUP: 'ADD_TAGGROUP',- MERGE_TAGGROUP: 'MERGE_TAGGROUP',- REMOVE_TAGGROUP: 'REMOVE_TAGGROUP',- UPDATE_TAGGROUP: 'UPDATE_TAGGROUP',- TOGGLE_TAGGROUP: 'TOGGLE_TAGGROUP',- ADD_TAG: 'ADD_TAG',- REMOVE_TAG: 'REMOVE_TAG',- UPDATE_TAG: 'UPDATE_TAG',- SORT_TAG_GROUP_UP: 'SORT_TAG_GROUP_UP',- MOVE_TAG_GROUP_UP: 'MOVE_TAG_GROUP_UP',- MOVE_TAG_GROUP_DOWN: 'MOVE_TAG_GROUP_DOWN',- EDIT_TAG_COLOR: 'EDIT_TAG_COLOR',- MOVE_TAG: 'MOVE_TAG'+ CREATE_TAGGROUP: 'CREATE_TAGGROUP',+ IMPORT_TAGGROUP: 'IMPORT_TAGGROUP',+ IMPORT_OLD_TAGGROUP: 'IMPORT_OLD_TAGGROUP',+ ADD_TAGGROUP: 'ADD_TAGGROUP',+ MERGE_TAGGROUP: 'MERGE_TAGGROUP',+ REMOVE_TAGGROUP: 'REMOVE_TAGGROUP',+ UPDATE_TAGGROUP: 'UPDATE_TAGGROUP',+ TOGGLE_TAGGROUP: 'TOGGLE_TAGGROUP',+ ADD_TAG: 'ADD_TAG',+ REMOVE_TAG: 'REMOVE_TAG',+ UPDATE_TAG: 'UPDATE_TAG',+ SORT_TAG_GROUP_UP: 'SORT_TAG_GROUP_UP',+ MOVE_TAG_GROUP_UP: 'MOVE_TAG_GROUP_UP',+ MOVE_TAG_GROUP_DOWN: 'MOVE_TAG_GROUP_DOWN',+ EDIT_TAG_COLOR: 'EDIT_TAG_COLOR',+ MOVE_TAG: 'MOVE_TAG'};export type Uuid = string;export interface Tag {- title: string;- type: 'plain' | 'sidecar' | 'smart'; // smart should be eventually removed from this list, functionality should be enough- id?: Uuid;- icon?: string;- description?: string;- style?: string;- path?: string; // needed for geo tagging should be removed- functionality?: string;- keyBinding?: string;- color?: string;- textcolor?: string;+ title?: string;+ type?: 'plain' | 'sidecar' | 'smart'; // smart should be eventually removed from this list, functionality should be enough+ id?: Uuid;+ icon?: string;+ description?: string;+ style?: string;+ path?: string; // needed for geo tagging should be removed+ modified_date?: string;+ functionality?: string;+ keyBinding?: string;+ color?: string;+ textcolor?: string;}export interface TagGroup {- uuid: Uuid;- title: string;- expanded: boolean;- description?: string;- categoryId?: string;- readOnly?: boolean;- color?: string;- textcolor?: string;- children?: Array<Tag>;+ uuid: Uuid;+ title: string;+ expanded: boolean;+ description?: string;+ categoryId?: string;+ readOnly?: boolean;+ color?: string;+ textcolor?: string;+ children?: Array<Tag>;}-export default (state: Array<TagGroup> = defaultTagLibrary, action: Object) => {- switch (action.type) {- case types.CREATE_TAGGROUP: {- return [- ...state,- {- uuid: uuidv1(),- title: action.entry.title,- expanded: action.entry.expanded,- color: action.entry.color,- textcolor: action.entry.textcolor,- children: [],- created_date: new Date(),- modified_date: new Date()- }- ];- }- case types.ADD_TAGGROUP: {- let indexForEditing = -1;- state.forEach((tagGroup, index) => {- if (tagGroup.uuid === action.entry.uuid) {- indexForEditing = index;- }- });- if (indexForEditing >= 0) {- return [- ...state.slice(0, indexForEditing),- {- uuid: action.entry.uuid,- title: action.entry.title,- expanded: action.entry.expanded,- children: [- ...state[indexForEditing].children,- action.entry.children[0]- ],- created_date: new Date(),- modified_date: new Date()- },- ...state.slice(indexForEditing + 1)- ];- }- return state;- }- case types.MERGE_TAGGROUP: {- const indexForEditing = state.findIndex(- obj => obj.uuid === action.entry.uuid- );- if (indexForEditing >= 0) {- const tags = [- ...state[indexForEditing].children,- ...action.entry.children- ];- tags.splice(0, tags.length - AppConfig.maxCollectedTag);- return [- ...state.slice(0, indexForEditing),- {- uuid: action.entry.uuid,- title: action.entry.title,- expanded: action.entry.expanded,- children: tags,- created_date: action.entry.created_date,- modified_date: new Date()- },- ...state.slice(indexForEditing + 1)- ];- }- return [- ...state,- {- uuid: action.entry.uuid || uuidv1(),- title: action.entry.title,- expanded: action.entry.expanded,- color: action.entry.color,- textcolor: action.entry.textcolor,- children: action.entry.children,- created_date: new Date(),- modified_date: new Date()- }- ];- }- case types.UPDATE_TAGGROUP: {- let indexForEditing = -1;- state.forEach((tagGroup, index) => {- if (tagGroup.uuid === action.entry.uuid) {- indexForEditing = index;- }- });+export default (state: Array<TagGroup> = defaultTagLibrary, action: any) => {+ switch (action.type) {+ case types.CREATE_TAGGROUP: {+ return [+ ...state,+ {+ uuid: uuidv1(),+ title: action.entry.title,+ expanded: action.entry.expanded,+ color: action.entry.color,+ textcolor: action.entry.textcolor,+ children: [],+ created_date: new Date(),+ modified_date: new Date()+ }+ ];+ }+ case types.ADD_TAGGROUP: {+ let indexForEditing = -1;+ state.forEach((tagGroup, index) => {+ if (tagGroup.uuid === action.entry.uuid) {+ indexForEditing = index;+ }+ });+ if (indexForEditing >= 0) {+ return [+ ...state.slice(0, indexForEditing),+ {+ uuid: action.entry.uuid,+ title: action.entry.title,+ expanded: action.entry.expanded,+ children: [+ ...state[indexForEditing].children,+ action.entry.children[0]+ ],+ created_date: new Date(),+ modified_date: new Date()+ },+ ...state.slice(indexForEditing + 1)+ ];+ }+ return state;+ }+ case types.MERGE_TAGGROUP: {+ const indexForEditing = state.findIndex(+ obj => obj.uuid === action.entry.uuid+ );+ if (indexForEditing >= 0) {+ const tags = [+ ...state[indexForEditing].children,+ ...action.entry.children+ ];+ tags.splice(0, tags.length - AppConfig.maxCollectedTag);+ return [+ ...state.slice(0, indexForEditing),+ {+ uuid: action.entry.uuid,+ title: action.entry.title,+ expanded: action.entry.expanded,+ children: tags,+ created_date: action.entry.created_date,+ modified_date: new Date()+ },+ ...state.slice(indexForEditing + 1)+ ];+ }+ return [+ ...state,+ {+ uuid: action.entry.uuid || uuidv1(),+ title: action.entry.title,+ expanded: action.entry.expanded,+ color: action.entry.color,+ textcolor: action.entry.textcolor,+ children: action.entry.children,+ created_date: new Date(),+ modified_date: new Date()+ }+ ];+ }+ case types.UPDATE_TAGGROUP: {+ let indexForEditing = -1;+ state.forEach((tagGroup, index) => {+ if (tagGroup.uuid === action.entry.uuid) {+ indexForEditing = index;+ }+ });- if (indexForEditing >= 0) {- const modifiedEntry = extend(- { created_date: new Date() },- action.entry,- { modified_date: new Date() }- );- return [- ...state.slice(0, indexForEditing),- modifiedEntry,- ...state.slice(indexForEditing + 1)- ];- }- return state;- }- case types.REMOVE_TAGGROUP: {- let indexForRemoving = -1;- state.forEach((tagGroup, index) => {- if (tagGroup.uuid === action.uuid) {- indexForRemoving = index;- }- });- if (indexForRemoving >= 0) {- return [- ...state.slice(0, indexForRemoving),- ...state.slice(indexForRemoving + 1)- ];- }- return state;- }- case types.ADD_TAG: {- let indexForEditing = -1;- state.forEach((tagGroup, index) => {- if (tagGroup.uuid === action.uuid) {- indexForEditing = index;- }- });+ if (indexForEditing >= 0) {+ const modifiedEntry = extend(+ { created_date: new Date() },+ action.entry,+ { modified_date: new Date() }+ );+ return [+ ...state.slice(0, indexForEditing),+ modifiedEntry,+ ...state.slice(indexForEditing + 1)+ ];+ }+ return state;+ }+ case types.REMOVE_TAGGROUP: {+ let indexForRemoving = -1;+ state.forEach((tagGroup, index) => {+ if (tagGroup.uuid === action.uuid) {+ indexForRemoving = index;+ }+ });+ if (indexForRemoving >= 0) {+ return [+ ...state.slice(0, indexForRemoving),+ ...state.slice(indexForRemoving + 1)+ ];+ }+ return state;+ }+ case types.ADD_TAG: {+ let indexForEditing = -1;+ state.forEach((tagGroup, index) => {+ if (tagGroup.uuid === action.uuid) {+ indexForEditing = index;+ }+ });- if (indexForEditing >= 0) {- let tags = action.tag- .split(' ')- .join(',')- .split(','); // handle spaces around commas- tags = [...new Set(tags)]; // remove duplicates- tags = tags.filter(tag => tag.length > 0); // zero length tags+ if (indexForEditing >= 0) {+ let tags = action.tag+ .split(' ')+ .join(',')+ .split(','); // handle spaces around commas+ tags = new Set(tags); // remove duplicates+ tags = tags.filter(tag => tag.length > 0); // zero length tags- const taggroupTags = state[indexForEditing].children;- taggroupTags.forEach(tag => {- // filter out duplicated tags- tags = tags.filter(e => e !== tag.title);- });- return [- ...state.slice(0, indexForEditing),- {- ...state[indexForEditing],- children: taggroupTags.concat(- tags.map(tagTitle => ({- id: uuidv1(),- type:- taggroupTags.length > 0 ? taggroupTags[0].type : 'sidecar',- title: tagTitle.trim(),- functionality: '',- description: '',- icon: '',- color: state[indexForEditing].color- ? state[indexForEditing].color- : '', // default color- textcolor: state[indexForEditing].textcolor- ? state[indexForEditing].textcolor- : '', // default color- style: taggroupTags.length > 0 ? taggroupTags[0].style : '',- created_date: new Date(),- modified_date: new Date()- }))- )- },- ...state.slice(indexForEditing + 1)- ];- }- return state;- }- case types.UPDATE_TAG: {- let tagIndexForUpdating = -1;- let indexForUpdating = -1;- state.forEach((tagGroup, index) => {- if (tagGroup.uuid === action.uuid) {- indexForUpdating = index;- }- tagGroup.children.forEach((tag, tagIndex) => {- if (tag.id === action.entry.id) {- tagIndexForUpdating = tagIndex;- }- });- });- if (tagIndexForUpdating >= 0) {- const modifiedEntry = extend(- { created_date: new Date() },- action.entry,- { modified_date: new Date() }- );- return [- ...state.slice(0, indexForUpdating),- {- ...state[indexForUpdating],- children: [- ...state[indexForUpdating].children.slice(0, tagIndexForUpdating),- modifiedEntry,- ...state[indexForUpdating].children.slice(tagIndexForUpdating + 1)- ]- },- ...state.slice(indexForUpdating + 1)- ];- }- return state;- }- case types.REMOVE_TAG: {- let tagIndexForRemoving = -1;- let indexForEditing = -1;- state.forEach((tagGroup, index) => {- if (tagGroup.uuid === action.uuid) {- indexForEditing = index;- }- tagGroup.children.forEach((tag, tagIndex) => {- if (tag.id === action.tagID) {- tagIndexForRemoving = tagIndex;- }- });- });- if (tagIndexForRemoving >= 0) {- return [- ...state.slice(0, indexForEditing),- {- ...state[indexForEditing],- children: [- ...state[indexForEditing].children.slice(0, tagIndexForRemoving),- ...state[indexForEditing].children.slice(tagIndexForRemoving + 1)- ]- },- ...state.slice(indexForEditing + 1)- ];- }- return state;- }- case types.TOGGLE_TAGGROUP: {- let indexForUpdating = -1;- state.forEach((tagGroup, index) => {- if (tagGroup.uuid === action.uuid) {- indexForUpdating = index;- }- });- if (indexForUpdating >= 0) {- return [- ...state.slice(0, indexForUpdating),- {- ...state[indexForUpdating],- expanded: !action.expanded- },- ...state.slice(indexForUpdating + 1)- ];- }- return state;- }- case types.MOVE_TAG_GROUP_DOWN: {- let indexForUpdating = -1;- state.forEach((tagGroup, index) => {- if (tagGroup.uuid === action.uuid) {- indexForUpdating = index;- }- });- if (indexForUpdating >= 0 && indexForUpdating < state.length - 1) {- const secondIndex = indexForUpdating + 1;- return immutablySwapItems(state, indexForUpdating, secondIndex);- }- return state;- }- case types.MOVE_TAG_GROUP_UP: {- let indexForUpdating = -1;- state.forEach((tagGroup, index) => {- if (tagGroup.uuid === action.uuid) {- indexForUpdating = index;- }- });- if (indexForUpdating > 0) {- const secondIndex = indexForUpdating - 1;- return immutablySwapItems(state, indexForUpdating, secondIndex);- }- return state;- }- case types.SORT_TAG_GROUP_UP: {- let indexForUpdating = -1;- state.forEach((tagGroup, index) => {- if (tagGroup.uuid === action.uuid) {- indexForUpdating = index;- }- });- if (indexForUpdating >= 0) {- return [- ...state.slice(0, indexForUpdating),- {- ...state[indexForUpdating],- children: state[indexForUpdating].children.sort((a, b) =>- a.title > b.title ? 1 : a.title < b.title ? -1 : 0- )- },- ...state.slice(indexForUpdating + 1)- ];- }- return state;- }- case types.MOVE_TAG: {- let tagIndexForRemoving = -1;- let indexFromGroup = -1;- let indexToGroup = -1;- state.forEach((tagGroup, index) => {- if (tagGroup.uuid === action.fromTagGroupId) {- indexFromGroup = index;- }- if (tagGroup.uuid === action.toTagGroupId) {- indexToGroup = index;- }- });- if (indexFromGroup >= 0 && state[indexFromGroup].children) {- state[indexFromGroup].children.forEach((tag, tagIndex) => {- if (tag.id === action.tagID) {- tagIndexForRemoving = tagIndex;- }- return true;- });- }- if (indexToGroup >= 0 && indexToGroup >= 0 && tagIndexForRemoving >= 0) {- const newTagLibrary = [...state];- const tag = { ...state[indexFromGroup].children[tagIndexForRemoving] };- const found = newTagLibrary[indexToGroup].children.find(- t => t.title === tag.title- );- if (!found) {- newTagLibrary[indexToGroup].children.push(tag);- newTagLibrary[indexFromGroup].children = [- ...newTagLibrary[indexFromGroup].children.slice(- 0,- tagIndexForRemoving- ),- ...newTagLibrary[indexFromGroup].children.slice(- tagIndexForRemoving + 1- )- ];- return newTagLibrary;- }- console.warn(- 'Tag with this title alread exists in the target tag group'- );- }- return state;- }- case types.IMPORT_TAGGROUP: {- const arr = [...state];- console.log(arr);- if (action.entry[0].key) {- action.entry.forEach((tagGroup, index) => {- // migration of old tag groups 2.9 or less in the new version 3.0-present- if (tagGroup.key === state.uuid || tagGroup.key !== state.uuid) {- tagGroup = {- title: tagGroup.title,- uuid: tagGroup.key,- expanded: true,- children: tagGroup.children- };- const tagsArr = [];- tagGroup.children.forEach(tag => {- if (!tag.id) {- tag = {- id: uuidv1(),- type: tag.type,- title: tag.title,- functionality: tag.title,- color: tag.color,- textcolor: tag.textcolor,- description: tag.description,- icon: tag.icon,- style: tag.style- };- tagsArr.push(tag);- }- tagGroup.children = tagsArr;- arr.push(tagGroup);- });- }- });- } else {- action.entry.forEach(tagGroup => {- const index = state.findIndex(obj => obj.uuid === tagGroup.uuid);- if (index > -1) {- tagGroup.children.forEach(tag => {- const stateTag = state[index].children.find(- obj => obj.id === tag.id- );- if (stateTag === undefined) {- arr[index].children.push(tag);- }- });- } else {- arr.push(tagGroup);- }- });- }+ const taggroupTags = state[indexForEditing].children;+ taggroupTags.forEach(tag => {+ // filter out duplicated tags+ tags = tags.filter(e => e !== tag.title);+ });+ return [+ ...state.slice(0, indexForEditing),+ {+ ...state[indexForEditing],+ children: taggroupTags.concat(+ tags.map(tagTitle => ({+ id: uuidv1(),+ type:+ taggroupTags.length > 0 ? taggroupTags[0].type : 'sidecar',+ title: tagTitle.trim(),+ functionality: '',+ description: '',+ icon: '',+ color: state[indexForEditing].color+ ? state[indexForEditing].color+ : '', // default color+ textcolor: state[indexForEditing].textcolor+ ? state[indexForEditing].textcolor+ : '', // default color+ style: taggroupTags.length > 0 ? taggroupTags[0].style : '',+ created_date: new Date(),+ modified_date: new Date()+ }))+ )+ },+ ...state.slice(indexForEditing + 1)+ ];+ }+ return state;+ }+ case types.UPDATE_TAG: {+ let tagIndexForUpdating = -1;+ let indexForUpdating = -1;+ state.forEach((tagGroup, index) => {+ if (tagGroup.uuid === action.uuid) {+ indexForUpdating = index;+ }+ tagGroup.children.forEach((tag, tagIndex) => {+ if (tag.id === action.entry.id) {+ tagIndexForUpdating = tagIndex;+ }+ });+ });+ if (tagIndexForUpdating >= 0) {+ const modifiedEntry = extend(+ { created_date: new Date() },+ action.entry,+ { modified_date: new Date() }+ );+ return [+ ...state.slice(0, indexForUpdating),+ {+ ...state[indexForUpdating],+ children: [+ ...state[indexForUpdating].children.slice(0, tagIndexForUpdating),+ modifiedEntry,+ ...state[indexForUpdating].children.slice(tagIndexForUpdating + 1)+ ]+ },+ ...state.slice(indexForUpdating + 1)+ ];+ }+ return state;+ }+ case types.REMOVE_TAG: {+ let tagIndexForRemoving = -1;+ let indexForEditing = -1;+ state.forEach((tagGroup, index) => {+ if (tagGroup.uuid === action.uuid) {+ indexForEditing = index;+ }+ tagGroup.children.forEach((tag, tagIndex) => {+ if (tag.id === action.tagID) {+ tagIndexForRemoving = tagIndex;+ }+ });+ });+ if (tagIndexForRemoving >= 0) {+ return [+ ...state.slice(0, indexForEditing),+ {+ ...state[indexForEditing],+ children: [+ ...state[indexForEditing].children.slice(0, tagIndexForRemoving),+ ...state[indexForEditing].children.slice(tagIndexForRemoving + 1)+ ]+ },+ ...state.slice(indexForEditing + 1)+ ];+ }+ return state;+ }+ case types.TOGGLE_TAGGROUP: {+ let indexForUpdating = -1;+ state.forEach((tagGroup, index) => {+ if (tagGroup.uuid === action.uuid) {+ indexForUpdating = index;+ }+ });+ if (indexForUpdating >= 0) {+ return [+ ...state.slice(0, indexForUpdating),+ {+ ...state[indexForUpdating],+ expanded: !action.expanded+ },+ ...state.slice(indexForUpdating + 1)+ ];+ }+ return state;+ }+ case types.MOVE_TAG_GROUP_DOWN: {+ let indexForUpdating = -1;+ state.forEach((tagGroup, index) => {+ if (tagGroup.uuid === action.uuid) {+ indexForUpdating = index;+ }+ });+ if (indexForUpdating >= 0 && indexForUpdating < state.length - 1) {+ const secondIndex = indexForUpdating + 1;+ return immutablySwapItems(state, indexForUpdating, secondIndex);+ }+ return state;+ }+ case types.MOVE_TAG_GROUP_UP: {+ let indexForUpdating = -1;+ state.forEach((tagGroup, index) => {+ if (tagGroup.uuid === action.uuid) {+ indexForUpdating = index;+ }+ });+ if (indexForUpdating > 0) {+ const secondIndex = indexForUpdating - 1;+ return immutablySwapItems(state, indexForUpdating, secondIndex);+ }+ return state;+ }+ case types.SORT_TAG_GROUP_UP: {+ let indexForUpdating = -1;+ state.forEach((tagGroup, index) => {+ if (tagGroup.uuid === action.uuid) {+ indexForUpdating = index;+ }+ });+ if (indexForUpdating >= 0) {+ return [+ ...state.slice(0, indexForUpdating),+ {+ ...state[indexForUpdating],+ children: state[indexForUpdating].children.sort((a, b) =>+ a.title > b.title ? 1 : a.title < b.title ? -1 : 0+ )+ },+ ...state.slice(indexForUpdating + 1)+ ];+ }+ return state;+ }+ case types.MOVE_TAG: {+ let tagIndexForRemoving = -1;+ let indexFromGroup = -1;+ let indexToGroup = -1;+ state.forEach((tagGroup, index) => {+ if (tagGroup.uuid === action.fromTagGroupId) {+ indexFromGroup = index;+ }+ if (tagGroup.uuid === action.toTagGroupId) {+ indexToGroup = index;+ }+ });+ if (indexFromGroup >= 0 && state[indexFromGroup].children) {+ state[indexFromGroup].children.forEach((tag, tagIndex) => {+ if (tag.id === action.tagID) {+ tagIndexForRemoving = tagIndex;+ }+ return true;+ });+ }+ if (indexToGroup >= 0 && indexToGroup >= 0 && tagIndexForRemoving >= 0) {+ const newTagLibrary = [...state];+ const tag = { ...state[indexFromGroup].children[tagIndexForRemoving] };+ const found = newTagLibrary[indexToGroup].children.find(+ t => t.title === tag.title+ );+ if (!found) {+ newTagLibrary[indexToGroup].children.push(tag);+ newTagLibrary[indexFromGroup].children = [+ ...newTagLibrary[indexFromGroup].children.slice(+ 0,+ tagIndexForRemoving+ ),+ ...newTagLibrary[indexFromGroup].children.slice(+ tagIndexForRemoving + 1+ )+ ];+ return newTagLibrary;+ }+ console.warn(+ 'Tag with this title already exists in the target tag group'+ );+ }+ return state;+ }+ case types.IMPORT_TAGGROUP: {+ const arr = [...state];+ console.log(arr);+ if (action.entry[0].key) {+ action.entry.forEach((tagGroup, index) => {+ // migration of old tag groups 2.9 or less in the new version 3.0-present+ // @ts-ignore+ if (tagGroup.key === state.uuid || tagGroup.key !== state.uuid) {+ tagGroup = {+ title: tagGroup.title,+ uuid: tagGroup.key,+ expanded: true,+ children: tagGroup.children+ };+ const tagsArr = [];+ tagGroup.children.forEach(tag => {+ if (!tag.id) {+ tag = {+ id: uuidv1(),+ type: tag.type,+ title: tag.title,+ functionality: tag.title,+ color: tag.color,+ textcolor: tag.textcolor,+ description: tag.description,+ icon: tag.icon,+ style: tag.style+ };+ tagsArr.push(tag);+ }+ tagGroup.children = tagsArr;+ arr.push(tagGroup);+ });+ }+ });+ } else {+ action.entry.forEach(tagGroup => {+ const index = state.findIndex(obj => obj.uuid === tagGroup.uuid);+ if (index > -1) {+ tagGroup.children.forEach(tag => {+ const stateTag = state[index].children.find(+ obj => obj.id === tag.id+ );+ if (stateTag === undefined) {+ arr[index].children.push(tag);+ }+ });+ } else {+ arr.push(tagGroup);+ }+ });+ }- return arr;- }- default: {- return state;- }- }+ return arr;+ }+ default: {+ return state;+ }+ }};export const actions = {- createTagGroup: (entry: TagGroup) => ({ type: types.CREATE_TAGGROUP, entry }),- editTagGroup: (entry: TagGroup) => ({ type: types.UPDATE_TAGGROUP, entry }),- removeTagGroup: (parentTagGroupUuid: Uuid) => ({- type: types.REMOVE_TAGGROUP,- uuid: parentTagGroupUuid- }),- toggleTagGroup: (expanded: boolean, parentTagGroupUuid: Uuid) => ({- type: types.TOGGLE_TAGGROUP,- expanded,- uuid: parentTagGroupUuid- }),- addTagGroup: (entry: TagGroup) => ({ type: types.ADD_TAGGROUP, entry }),- mergeTagGroup: (entry: TagGroup) => ({ type: types.MERGE_TAGGROUP, entry }),- addTag: (tag: string, parentTagGroupUuid: Uuid) => {- console.log('INSIDE ADD TAG');- console.log(tag, parentTagGroupUuid);- return { type: types.ADD_TAG, tag, uuid: parentTagGroupUuid };- },- editTag: (entry: Tag, parentTagGroupUuid: Uuid) => ({- type: types.UPDATE_TAG,- entry,- uuid: parentTagGroupUuid- }),- deleteTag: (tagID: string, parentTagGroupUuid: Uuid) => ({- type: types.REMOVE_TAG,- tagID,- uuid: parentTagGroupUuid- }),- moveTagGroupUp: (parentTagGroupUuid: Uuid) => ({- type: types.MOVE_TAG_GROUP_UP,- uuid: parentTagGroupUuid- }),- moveTagGroupDown: (parentTagGroupUuid: Uuid) => ({- type: types.MOVE_TAG_GROUP_DOWN,- uuid: parentTagGroupUuid- }),- sortTagGroup: (parentTagGroupUuid: Uuid) => ({- type: types.SORT_TAG_GROUP_UP,- uuid: parentTagGroupUuid- }),- moveTag: (tagID: string, fromTagGroupUuid: Uuid, toTagGroupUuid: Uuid) => ({- type: types.MOVE_TAG,- tagID,- fromTagGroupId: fromTagGroupUuid,- toTagGroupId: toTagGroupUuid- }),- importTagGroups: entry => ({ type: types.IMPORT_TAGGROUP, entry }),- exportTagGroups: (entry: Array<Object>) => (- dispatch: (actions: Object) => void,- getState: () => Object- ) => {- const { settings } = getState();- const tagLibrary = entry;- const jsonFormat =- '{ "appName": "' +- versionMeta.name +- '", "appVersion": "' +- versionMeta.version +- '", "settingsVersion": ' +- settings.settingsVersion +- ', "tagGroups": ';- const getAllTags = [];- tagLibrary.forEach(value => {- getAllTags.push(value);- });+ createTagGroup: (entry: TagGroup) => ({ type: types.CREATE_TAGGROUP, entry }),+ editTagGroup: (entry: TagGroup) => ({ type: types.UPDATE_TAGGROUP, entry }),+ removeTagGroup: (parentTagGroupUuid: Uuid) => ({+ type: types.REMOVE_TAGGROUP,+ uuid: parentTagGroupUuid+ }),+ toggleTagGroup: (expanded: boolean, parentTagGroupUuid: Uuid) => ({+ type: types.TOGGLE_TAGGROUP,+ expanded,+ uuid: parentTagGroupUuid+ }),+ addTagGroup: (entry: TagGroup) => ({ type: types.ADD_TAGGROUP, entry }),+ mergeTagGroup: (entry: TagGroup) => ({ type: types.MERGE_TAGGROUP, entry }),+ addTag: (tag: string, parentTagGroupUuid: Uuid) => {+ console.log('INSIDE ADD TAG');+ console.log(tag, parentTagGroupUuid);+ return { type: types.ADD_TAG, tag, uuid: parentTagGroupUuid };+ },+ editTag: (entry: Tag, parentTagGroupUuid: Uuid) => ({+ type: types.UPDATE_TAG,+ entry,+ uuid: parentTagGroupUuid+ }),+ deleteTag: (tagID: string, parentTagGroupUuid: Uuid) => ({+ type: types.REMOVE_TAG,+ tagID,+ uuid: parentTagGroupUuid+ }),+ moveTagGroupUp: (parentTagGroupUuid: Uuid) => ({+ type: types.MOVE_TAG_GROUP_UP,+ uuid: parentTagGroupUuid+ }),+ moveTagGroupDown: (parentTagGroupUuid: Uuid) => ({+ type: types.MOVE_TAG_GROUP_DOWN,+ uuid: parentTagGroupUuid+ }),+ sortTagGroup: (parentTagGroupUuid: Uuid) => ({+ type: types.SORT_TAG_GROUP_UP,+ uuid: parentTagGroupUuid+ }),+ moveTag: (tagID: string, fromTagGroupUuid: Uuid, toTagGroupUuid: Uuid) => ({+ type: types.MOVE_TAG,+ tagID,+ fromTagGroupId: fromTagGroupUuid,+ toTagGroupId: toTagGroupUuid+ }),+ importTagGroups: entry => ({ type: types.IMPORT_TAGGROUP, entry }),+ exportTagGroups: (entry: Array<Object>) => (+ dispatch: (actions: Object) => void,+ getState: () => any+ ) => {+ const { settings } = getState();+ const tagLibrary = entry;+ const jsonFormat =+ '{ "appName": "' ++ versionMeta.name ++ '", "appVersion": "' ++ versionMeta.version ++ '", "settingsVersion": ' ++ settings.settingsVersion ++ ', "tagGroups": ';+ const getAllTags = [];+ tagLibrary.forEach(value => {+ getAllTags.push(value);+ });- const blob = new Blob([jsonFormat + JSON.stringify(getAllTags) + '}'], {- type: 'application/json'- });- const dateTimeTag = formatDateTime4Tag(new Date(), true);- saveAsTextFile(blob, 'tag-library [tagspaces ' + dateTimeTag + '].json');- console.log('Tag library exported...');- }+ const blob = new Blob([jsonFormat + JSON.stringify(getAllTags) + '}'], {+ type: 'application/json'+ });+ const dateTimeTag = formatDateTime4Tag(new Date(), true);+ saveAsTextFile(blob, 'tag-library [tagspaces ' + dateTimeTag + '].json');+ console.log('Tag library exported...');+ }};// Selectors-export const getTagGroups = (state: Object) => state.taglibrary;-export const getAllTags = (state: Object) => {- const allTags: Array<Tag> = [];- state.taglibrary.forEach(tagGroup => {- tagGroup.children.forEach(tag => {- allTags.push(tag);- });- });- return allTags.sort((a, b) =>- a.title > b.title ? 1 : a.title < b.title ? -1 : 0- );+export const getTagGroups = (state: any) => state.taglibrary;+export const getAllTags = (state: any) => {+ const allTags: Array<Tag> = [];+ state.taglibrary.forEach(tagGroup => {+ tagGroup.children.forEach(tag => {+ allTags.push(tag);+ });+ });+ return allTags.sort((a, b) =>+ a.title > b.title ? 1 : a.title < b.title ? -1 : 0+ );};-export const getTagColors = (state: Object, tagTitle: string) => {- const tagColors = {- textcolor: state.settings.tagTextColor,- color: state.settings.tagBackgroundColor- };- state.taglibrary.forEach(tagGroup => {- tagGroup.children.forEach((tag: Tag) => {- if (tag.title === tagTitle) {- tagColors.textcolor = tag.textcolor;- tagColors.color = tag.color;- }- });- });- return tagColors;+export const getTagColors = (state: any, tagTitle: string) => {+ const tagColors = {+ textcolor: state.settings.tagTextColor,+ color: state.settings.tagBackgroundColor+ };+ state.taglibrary.forEach(tagGroup => {+ tagGroup.children.forEach((tag: Tag) => {+ if (tag.title === tagTitle) {+ tagColors.textcolor = tag.textcolor;+ tagColors.color = tag.color;+ }+ });+ });+ return tagColors;};diff --git a/app/services/cordova-io.ts b/app/services/cordova-io.tsindex 4b12800a7..4e9e59269 100644--- a/app/services/cordova-io.ts+++ b/app/services/cordova-io.ts@@ -31,6 +31,8 @@ const appSettingTagsFile = 'settingsTags.json';// let anotatedTree;// let pendingCallbacks = 0;+declare let cordova;+declare let navigator;export default class CordovaIO {constructor() {// Redefining the back button@@ -109,7 +111,7 @@ export default class CordovaIO {// Register ios file open handlerhandleOpenURL = (url: string) => {- const fileName = url.substring(url.lastIndexOf('/') + 1, url.length);+ // const fileName = url.substring(url.lastIndexOf('/') + 1, url.length);/* showConfirmDialog('File copied', 'File ' + fileName + ' is copied in inbox folder. Would you like to open it ?', () => {FileOpener.openFile(url);}); */@@ -197,7 +199,7 @@ export default class CordovaIO {window.resolveLocalFileSystemURL(dataFolderPath,- fs => {+ (fs: any) => {fs.getFile(fileName, { create: true }, fileCallback, fail);},error => {@@ -295,7 +297,7 @@ export default class CordovaIO {fileEntry.file(file => {const reader = new FileReader();- reader.onloadend = evt => {+ reader.onloadend = (evt: any) => {let content = null;if (evt.target.result.length > 0) {content = evt.target.result;@@ -325,22 +327,22 @@ export default class CordovaIO {loadSettings = () => this.loadedSettings;- saveSettingsTags = (tagGroups: Object) => {- // TODO use js objects- const jsonFormat =- '{ "appName": "' +- Config.DefaultSettings.appName +- '", "appVersion": "' +- Config.DefaultSettings.appVersion +- '", "appBuild": "' +- Config.DefaultSettings.appBuild +- '", "settingsVersion": ' +- Config.DefaultSettings.settingsVersion +- ', "tagGroups": ' +- tagGroups +- ' }';- this.saveSettingsFile(appSettingTagsFile, jsonFormat);- };+ // saveSettingsTags = (tagGroups: Object) => {+ // // TODO use js objects+ // const jsonFormat =+ // '{ "appName": "' ++ // Config.DefaultSettings.appName ++ // '", "appVersion": "' ++ // Config.DefaultSettings.appVersion ++ // '", "appBuild": "' ++ // Config.DefaultSettings.appBuild ++ // '", "settingsVersion": ' ++ // Config.DefaultSettings.settingsVersion ++ // ', "tagGroups": ' ++ // tagGroups ++ // ' }';+ // this.saveSettingsFile(appSettingTagsFile, jsonFormat);+ // };loadSettingsTags = () => this.loadedSettingsTags;@@ -377,7 +379,7 @@ export default class CordovaIO {handleStartParameters = () => {if (this.urlFromIntent !== undefined && this.urlFromIntent.length > 0) {console.log('Intent URL: ' + this.urlFromIntent);- const filePath = decodeURIComponent(this.urlFromIntent);+ // const filePath = decodeURIComponent(this.urlFromIntent);// TODO FileOpener.openFileOnStartup(filePath);}};@@ -389,8 +391,8 @@ export default class CordovaIO {console.warn('Creating directory tree is not supported in Cordova yet.');};- listMetaDirectoryPromise = async (path: string): Promise<Array<Object>> => {- const promise = new Promise(resolve => {+ listMetaDirectoryPromise = async (path: string): Promise<Array<any>> => {+ const promise: Promise<Array<any>> = new Promise(resolve => {const entries = [];const metaDirPath =cleanTrailingDirSeparator(path) +@@ -407,7 +409,7 @@ export default class CordovaIO {if (entryPath.toLowerCase() === metaDirPath.toLowerCase()) {console.log('Skipping current folder');} else {- const ee = {};+ const ee: any = {};ee.name = entry.name;ee.path = decodeURI(entryPath);ee.isFile = true;@@ -446,7 +448,7 @@ export default class CordovaIO {reader.readEntries(entries => {entries.forEach(entry => {- const eentry = {};+ const eentry: any = {};eentry.name = entry.name;eentry.path = entry.fullPath;eentry.tags = [];@@ -469,29 +471,31 @@ export default class CordovaIO {if (!lite) {if (entry.isDirectory) {// Read tsm.json from subfolders- const metaDirAvailable = metaContent.find(- obj => obj.name === AppConfig.metaFolder+ const metaDirAvailable: any = metaContent.find(+ (obj: any) => obj.name === AppConfig.metaFolder);- if (metaDirAvailable) {+ if (metaDirAvailable && metaDirAvailable.path) {metaPromises.push(this.getEntryMeta(eentry, metaDirAvailable.path));}} else {- const metaFileAvailable = metaContent.find(- obj => obj.name === entry.name + AppConfig.metaFileExt+ const metaFileAvailable: any = metaContent.find(+ (obj: any) =>+ obj.name === entry.name + AppConfig.metaFileExt);- if (metaFileAvailable) {+ if (metaFileAvailable && metaFileAvailable.path) {metaPromises.push(this.getEntryMeta(eentry, metaFileAvailable.path));}// Finding if thumbnail available- const metaThumbAvailable = metaContent.find(- obj => obj.name === entry.name + AppConfig.thumbFileExt+ const metaThumbAvailable: any = metaContent.find(+ (obj: any) =>+ obj.name === entry.name + AppConfig.thumbFileExt);- if (metaThumbAvailable) {+ if (metaThumbAvailable && metaThumbAvailable.path) {eentry.thumbPath = metaThumbAvailable.path;}}@@ -628,7 +632,7 @@ export default class CordovaIO {new Promise((resolve, reject) => {const entryPath = this.normalizePath(path);// getFileSystemPromise(dir).then(function(fileSystem) {- const fileProperties: object = {};+ const fileProperties: any = {};this.fsRoot.getFile(entryPath,{@@ -690,7 +694,7 @@ export default class CordovaIO {resolvePath?: string): Promise<any> => {// TODO refactor- const getFilePromise = (filePath, resolvePath) => {+ const getFilePromise = (filePath, resolvePath): Promise<any> => {const getFile = (fullPath, result, fail) => {const filePath = this.normalizePath(fullPath);@@ -815,7 +819,7 @@ export default class CordovaIO {});} else {- const errMsg = $.i18n.t('ns.common:fileExists', { fileName: filePath });+ const errMsg = 'File already exists: ' + filePath; // i18n.t('ns.common:fileExists', { fileName: filePath });// showAlertDialog(errMsg);reject(errMsg);}@@ -1012,7 +1016,10 @@ export default class CordovaIO {/*** Rename a directory*/- renameDirectoryPromise = (dirPath: string, newDirName: string): Promise<any> =>+ renameDirectoryPromise = (+ dirPath: string,+ newDirName: string+ ): Promise<any> =>new Promise((resolve, reject) => {let newDirPath =extractParentDirectoryPath(dirPath) +diff --git a/app/services/electron-io.ts b/app/services/electron-io.tsindex 4f649a9b4..eacc4f02b 100644--- a/app/services/electron-io.ts+++ b/app/services/electron-io.ts@@ -29,21 +29,21 @@ import PlatformIO from './platform-io';import TrayIcon from '../assets/icons/trayIcon.png';// import TrayIconWin from '../assets/icons/trayIcon.ico';import TrayIcon2x from '../assets/icons/[email protected]';-import TrayIcon3x from '../assets/icons/[email protected]';+// import TrayIcon3x from '../assets/icons/[email protected]';import { Pro } from '../pro';export default class ElectronIO {- electron: Object;- win: Object;- app: Object;- ipcRenderer: Object;- remote: Object;- workerWindow: Object;- pathUtils: Object;- fs: Object;- fsWatcher: Object;- webFrame: Object;- tsTray: Object;+ electron: any;+ win: any;+ app: any;+ ipcRenderer: any;+ remote: any;+ workerWindow: any;+ pathUtils: any;+ fs: any;+ fsWatcher: any;+ webFrame: any;+ tsTray: any;constructor() {if (window.require) {@@ -94,7 +94,8 @@ export default class ElectronIO {// } elseif (process.platform === 'win32') {- nImage = nativeImage.createFromDataURL(TrayIcon2x);+ nImage = nativeImage.createFromDataURL(TrayIcon2x);+ // @ts-ignore} else if (process.platform === 'darwin') {nImage = nativeImage.createFromDataURL(TrayIcon);// nImage.addRepresentation({ scaleFactor: 2.0, dataURL: TrayIcon2x });@@ -188,7 +189,7 @@ export default class ElectronIO {console.log('Creating directory index for: ' + directoryPath);const generateDirectoryTree = (dirPath: string) => {try {- const tree = {};+ const tree: any = {};const dstats = this.fs.lstatSync(dirPath);tree.name = this.pathUtils.basename(dirPath);tree.isFile = false;@@ -619,7 +620,7 @@ export default class ElectronIO {loadTextFilePromise = (filePath: string,- isPreview?: boolean = false+ isPreview: boolean = false): Promise<string> =>new Promise((resolve, reject) => {if (isPreview) {@@ -660,7 +661,7 @@ export default class ElectronIO {if (fileURL.indexOf('file://') === -1) {fileURL = 'file://' + fileURL;}- const xhr = new XMLHttpRequest();+ const xhr: any = new XMLHttpRequest();xhr.open('GET', fileURL, true);xhr.responseType = type || 'arraybuffer';xhr.onerror = reject;@@ -743,7 +744,7 @@ export default class ElectronIO {deleteFilePromise = (path: string,- useTrash?: boolean = true+ useTrash: boolean = true): Promise<any> => {if (useTrash) {return new Promise((resolve, reject) => {@@ -765,7 +766,7 @@ export default class ElectronIO {deleteDirectoryPromise = (path: string,- useTrash?: boolean = true+ useTrash: boolean = true): Promise<any> => {if (useTrash) {return new Promise((resolve, reject) => {diff --git a/app/services/search.ts b/app/services/search.tsindex e035a6577..14bf521dd 100644--- a/app/services/search.ts+++ b/app/services/search.ts@@ -24,47 +24,47 @@ import { Pro } from '../pro';// export type FileTypeGroups = 'images' | 'notes' | 'documents' | 'audio' | 'video' | 'archives';export const FileTypeGroups = {- any: [''],- images: [- 'jpg',- 'jpeg',- 'png',- 'gif',- 'bmp',- 'tif',- 'tiff',- 'ico',- 'webp',- 'psd'- ],- notes: ['md', 'mdown', 'txt', 'html'],- documents: ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'odt', 'ods'],- audio: ['ogg', 'mp3', 'wav', 'wave'],- video: ['ogv', 'mp4', 'webm', 'm4v', 'mkv', 'avi'],- archives: ['zip', 'rar', 'gz', 'tgz', 'arc', '7z'],- bookmarks: ['url', 'lnk', 'sym'],- ebooks: ['epub', 'mobi', 'azw', 'prc', 'azw1', 'azw3', 'azw4', 'azw8', 'azk'],- folders: ['folders'],- files: ['files'],- untagged: ['untagged']+ any: [''],+ images: [+ 'jpg',+ 'jpeg',+ 'png',+ 'gif',+ 'bmp',+ 'tif',+ 'tiff',+ 'ico',+ 'webp',+ 'psd'+ ],+ notes: ['md', 'mdown', 'txt', 'html'],+ documents: ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'odt', 'ods'],+ audio: ['ogg', 'mp3', 'wav', 'wave'],+ video: ['ogv', 'mp4', 'webm', 'm4v', 'mkv', 'avi'],+ archives: ['zip', 'rar', 'gz', 'tgz', 'arc', '7z'],+ bookmarks: ['url', 'lnk', 'sym'],+ ebooks: ['epub', 'mobi', 'azw', 'prc', 'azw1', 'azw3', 'azw4', 'azw8', 'azk'],+ folders: ['folders'],+ files: ['files'],+ untagged: ['untagged']};export type SearchQuery = {- textQuery?: string;- fileTypes?: Array<string>;- tagsAND?: Array<Tag>;- tagsOR?: Array<Tag>;- tagsNOT?: Array<Tag>;- lastModified: string;- fileSize: string;- searchBoxing: 'location' | 'folder';- currentDirectory: string;- tagTimePeriodFrom?: number | null;- tagTimePeriodTo?: number | null;- tagPlaceLat?: number | null;- tagPlaceLong?: number | null;- tagPlaceRadius?: number | null;- maxSearchResults?: number;+ textQuery?: string;+ fileTypes?: Array<string>;+ tagsAND?: Array<Tag>;+ tagsOR?: Array<Tag>;+ tagsNOT?: Array<Tag>;+ lastModified?: string;+ fileSize?: string;+ searchBoxing?: 'location' | 'folder';+ currentDirectory?: string;+ tagTimePeriodFrom?: number | null;+ tagTimePeriodTo?: number | null;+ tagPlaceLat?: number | null;+ tagPlaceLong?: number | null;+ tagPlaceRadius?: number | null;+ maxSearchResults?: number;};// id, name, isFile, tags, extension, size, lmdt, path@@ -101,35 +101,35 @@ export type SearchQuery = {*/const fuseOptions = {- shouldSort: true,- threshold: 0.3,- location: 0,- distance: 100,- tokenize: true,- maxPatternLength: 32,- minMatchCharLength: 1,- keys: [- {- name: 'name',- weight: 0.4- },- {- name: 'description',- weight: 0.4- },- {- name: 'textContent',- weight: 0.4- },- {- name: 'tags',- weight: 0.3- },- {- name: 'path', // TODO ignore .ts folder, should not be in the index- weight: 0.1- }- ]+ shouldSort: true,+ threshold: 0.3,+ location: 0,+ distance: 100,+ tokenize: true,+ maxPatternLength: 32,+ minMatchCharLength: 1,+ keys: [+ {+ name: 'name',+ weight: 0.4+ },+ {+ name: 'description',+ weight: 0.4+ },+ {+ name: 'textContent',+ weight: 0.4+ },+ {+ name: 'tags',+ weight: 0.3+ },+ {+ name: 'path', // TODO ignore .ts folder, should not be in the index+ weight: 0.1+ }+ ]};// Constructs the string for the JMESPath search query. We first filter for all ORTags, then continuously pipe the result in to the@@ -137,169 +137,169 @@ const fuseOptions = {// The final string for the tag search should look like this:// index[? tags[? title=='ORTag1' || title=='ORTag2']] | [? tags[? title=='ANDTag1']] | [? tags[? title=='ANDTag2']] | [?!(tags[? title=='NOTTag1'])] | [?!(tags[? title=='NOTTag2'])] | extensionFilterfunction constructjmespathQuery(searchQuery: SearchQuery): string {- let jmespathQuery = '';- const ANDtagsExist = searchQuery.tagsAND && searchQuery.tagsAND.length >= 1;- const ORtagsExist = searchQuery.tagsOR && searchQuery.tagsOR.length >= 1;- const NOTtagsExist = searchQuery.tagsNOT && searchQuery.tagsNOT.length >= 1;- if (ANDtagsExist || ORtagsExist || NOTtagsExist) {- jmespathQuery = '[?';+ let jmespathQuery = '';+ const ANDtagsExist = searchQuery.tagsAND && searchQuery.tagsAND.length >= 1;+ const ORtagsExist = searchQuery.tagsOR && searchQuery.tagsOR.length >= 1;+ const NOTtagsExist = searchQuery.tagsNOT && searchQuery.tagsNOT.length >= 1;+ if (ANDtagsExist || ORtagsExist || NOTtagsExist) {+ jmespathQuery = '[?';- if (ORtagsExist) {- jmespathQuery += ' tags[? ';- searchQuery.tagsOR.forEach(tag => {- const cleanedTagTitle = tag.title.trim().toLowerCase();- if (cleanedTagTitle.length > 0) {- jmespathQuery += "title=='" + cleanedTagTitle + "' || ";- }- return true;- });- }+ if (ORtagsExist) {+ jmespathQuery += ' tags[? ';+ searchQuery.tagsOR.forEach(tag => {+ const cleanedTagTitle = tag.title.trim().toLowerCase();+ if (cleanedTagTitle.length > 0) {+ jmespathQuery += "title=='" + cleanedTagTitle + "' || ";+ }+ return true;+ });+ }- if (ANDtagsExist) {- if (jmespathQuery.endsWith(' || ')) {- jmespathQuery =- jmespathQuery.substring(0, jmespathQuery.length - 4) +- ']] | [? tags[? ';- } else {- jmespathQuery += ' tags[? ';- }- searchQuery.tagsAND.forEach(tag => {- const cleanedTagTitle = tag.title.trim().toLowerCase();- if (cleanedTagTitle.length > 0) {- jmespathQuery += "title=='" + cleanedTagTitle + "']] | [? tags[? ";- }- });- }+ if (ANDtagsExist) {+ if (jmespathQuery.endsWith(' || ')) {+ jmespathQuery =+ jmespathQuery.substring(0, jmespathQuery.length - 4) ++ ']] | [? tags[? ';+ } else {+ jmespathQuery += ' tags[? ';+ }+ searchQuery.tagsAND.forEach(tag => {+ const cleanedTagTitle = tag.title.trim().toLowerCase();+ if (cleanedTagTitle.length > 0) {+ jmespathQuery += "title=='" + cleanedTagTitle + "']] | [? tags[? ";+ }+ });+ }- if (NOTtagsExist) {- if (jmespathQuery.endsWith(' || ')) {- jmespathQuery =- jmespathQuery.substring(0, jmespathQuery.length - 4) +- ']] | [?!(tags[? ';- } else if (jmespathQuery.endsWith('[? tags[? ')) {- jmespathQuery =- jmespathQuery.substring(0, jmespathQuery.length - 10) + '[?!(tags[? ';- } else {- jmespathQuery += '!(tags[? ';- }- searchQuery.tagsNOT.forEach(tag => {- const cleanedTagTitle = tag.title.trim().toLowerCase();- if (cleanedTagTitle.length > 0) {- jmespathQuery += "title=='" + cleanedTagTitle + "'])] | [?!(tags[? ";- }- return true;- });- }+ if (NOTtagsExist) {+ if (jmespathQuery.endsWith(' || ')) {+ jmespathQuery =+ jmespathQuery.substring(0, jmespathQuery.length - 4) ++ ']] | [?!(tags[? ';+ } else if (jmespathQuery.endsWith('[? tags[? ')) {+ jmespathQuery =+ jmespathQuery.substring(0, jmespathQuery.length - 10) + '[?!(tags[? ';+ } else {+ jmespathQuery += '!(tags[? ';+ }+ searchQuery.tagsNOT.forEach(tag => {+ const cleanedTagTitle = tag.title.trim().toLowerCase();+ if (cleanedTagTitle.length > 0) {+ jmespathQuery += "title=='" + cleanedTagTitle + "'])] | [?!(tags[? ";+ }+ return true;+ });+ }- if (jmespathQuery.endsWith(' || ')) {- jmespathQuery =- jmespathQuery.substring(0, jmespathQuery.length - 4) + ']]';- } else if (jmespathQuery.endsWith(' | [? tags[? ')) {- jmespathQuery = jmespathQuery.substring(0, jmespathQuery.length - 13);- } else if (jmespathQuery.endsWith(' | [?!(tags[? ')) {- jmespathQuery = jmespathQuery.substring(0, jmespathQuery.length - 14);- }- }+ if (jmespathQuery.endsWith(' || ')) {+ jmespathQuery =+ jmespathQuery.substring(0, jmespathQuery.length - 4) + ']]';+ } else if (jmespathQuery.endsWith(' | [? tags[? ')) {+ jmespathQuery = jmespathQuery.substring(0, jmespathQuery.length - 13);+ } else if (jmespathQuery.endsWith(' | [?!(tags[? ')) {+ jmespathQuery = jmespathQuery.substring(0, jmespathQuery.length - 14);+ }+ }- const extensionQuery = Pro- ? Pro.Search.constructFileTypeQuery(searchQuery)- : '';- if (extensionQuery.length > 0) {- jmespathQuery =- jmespathQuery.length > 0- ? jmespathQuery + ' | ' + extensionQuery- : extensionQuery;- }+ const extensionQuery = Pro+ ? Pro.Search.constructFileTypeQuery(searchQuery)+ : '';+ if (extensionQuery.length > 0) {+ jmespathQuery =+ jmespathQuery.length > 0+ ? jmespathQuery + ' | ' + extensionQuery+ : extensionQuery;+ }- if (jmespathQuery.length > 0) {- return 'index' + jmespathQuery;- }- return jmespathQuery;+ if (jmespathQuery.length > 0) {+ return 'index' + jmespathQuery;+ }+ return jmespathQuery;}function prepareIndex(index: Array<Object>) {- console.time('PreparingIndex');- let resultIndex = [];- if (Pro && Pro.Search && Pro.Search.prepareIndex) {- resultIndex = Pro.Search.prepareIndex(index);- } else {- resultIndex = index.map(entry => {- const tags = [...entry.tags];- if (tags && tags.length) {- tags.map(tag => {- tag.title = tag.title.toLowerCase();- return tag;- });- }- return {- ...entry,- tags- };- });- }- console.timeEnd('PreparingIndex');- return resultIndex;+ console.time('PreparingIndex');+ let resultIndex = [];+ if (Pro && Pro.Search && Pro.Search.prepareIndex) {+ resultIndex = Pro.Search.prepareIndex(index);+ } else {+ resultIndex = index.map((entry: any) => {+ const tags = [...entry.tags];+ if (tags && tags.length) {+ tags.map(tag => {+ tag.title = tag.title.toLowerCase();+ return tag;+ });+ }+ return {+ ...entry,+ tags+ };+ });+ }+ console.timeEnd('PreparingIndex');+ return resultIndex;}export default class Search {- static searchLocationIndex = (- locationContent: Array<Object>,- searchQuery: SearchQuery- ): Promise<Array<Object> | []> =>- new Promise(resolve => {- console.time('searchtime');- const jmespathQuery = constructjmespathQuery(searchQuery);- let results = prepareIndex(locationContent);- let searched = false;+ static searchLocationIndex = (+ locationContent: Array<Object>,+ searchQuery: SearchQuery+ ): Promise<Array<Object> | []> =>+ new Promise(resolve => {+ console.time('searchtime');+ const jmespathQuery = constructjmespathQuery(searchQuery);+ let results = prepareIndex(locationContent);+ let searched = false;- // Limiting the search to current folder only (with sub-folders)- if (searchQuery.searchBoxing === 'folder') {- results = results.filter(entry =>- entry.path.startsWith(searchQuery.currentDirectory)- );- }+ // Limiting the search to current folder only (with sub-folders)+ if (searchQuery.searchBoxing === 'folder') {+ results = results.filter(entry =>+ entry.path.startsWith(searchQuery.currentDirectory)+ );+ }- if (jmespathQuery) {- const resultCount = results.length;- console.log('jmespath query: ' + jmespathQuery);- console.time('jmespath');- results = jmespath.search({ index: results }, jmespathQuery);- console.timeEnd('jmespath');- console.log('jmespath results: ' + results.length);- searched = searched || results.length < resultCount;- }+ if (jmespathQuery) {+ const resultCount = results.length;+ console.log('jmespath query: ' + jmespathQuery);+ console.time('jmespath');+ results = jmespath.search({ index: results }, jmespathQuery);+ console.timeEnd('jmespath');+ console.log('jmespath results: ' + results.length);+ searched = searched || results.length < resultCount;+ }- if (Pro && Pro.Search.filterIndex) {- const resultCount = results.length;- results = Pro.Search.filterIndex(results, searchQuery);- searched = searched || results.length < resultCount;- }+ if (Pro && Pro.Search.filterIndex) {+ const resultCount = results.length;+ results = Pro.Search.filterIndex(results, searchQuery);+ searched = searched || results.length < resultCount;+ }- if (searchQuery.textQuery && searchQuery.textQuery.length > 1) {- const resultCount = results.length;- console.log('fuse query: ' + searchQuery.textQuery);- console.time('fuse');- const fuse = new Fuse(results, fuseOptions);- results = fuse.search(searchQuery.textQuery);- console.timeEnd('fuse');- searched = searched || results.length < resultCount;- }+ if (searchQuery.textQuery && searchQuery.textQuery.length > 1) {+ const resultCount = results.length;+ console.log('fuse query: ' + searchQuery.textQuery);+ console.time('fuse');+ const fuse = new Fuse(results, fuseOptions);+ results = fuse.search(searchQuery.textQuery);+ console.timeEnd('fuse');+ searched = searched || results.length < resultCount;+ }- if (searched) {- console.log('Results found: ' + results.length);- if (- searchQuery.maxSearchResults &&- results.length >= searchQuery.maxSearchResults- ) {- results = results.slice(0, searchQuery.maxSearchResults);- }- console.log('Results send: ' + results.length);- console.timeEnd('searchtime');- resolve(results);- return true;- }- results = [];- console.timeEnd('searchtime');- resolve(results);- });+ if (searched) {+ console.log('Results found: ' + results.length);+ if (+ searchQuery.maxSearchResults &&+ results.length >= searchQuery.maxSearchResults+ ) {+ results = results.slice(0, searchQuery.maxSearchResults);+ }+ console.log('Results send: ' + results.length);+ console.timeEnd('searchtime');+ resolve(results);+ return true;+ }+ results = [];+ console.timeEnd('searchtime');+ resolve(results);+ });}diff --git a/app/services/thumbsgenerator.ts b/app/services/thumbsgenerator.tsindex 98ae74b7f..82af16fed 100644--- a/app/services/thumbsgenerator.ts+++ b/app/services/thumbsgenerator.ts@@ -18,11 +18,11 @@import EXIF from 'exif-js';import {- extractFileExtension,- extractContainingDirectoryPath,- extractFileName,- normalizePath,- getMetaDirectoryPath+ extractFileExtension,+ extractContainingDirectoryPath,+ extractFileName,+ normalizePath,+ getMetaDirectoryPath} from '../utils/paths';import { base64ToArrayBuffer } from '../utils/misc';import AppConfig from '../config';@@ -34,261 +34,261 @@ const bgColor = AppConfig.thumbBgColor;const supportedImgs = ['jpg', 'jpeg', 'png', 'gif', 'svg', 'webp', 'bmp'];const supportedContainers = [- 'zip',- 'epub',- 'docx',- 'pptx',- 'pptm',- 'potx',- 'potm',- 'ppxs',- 'ppsm',- 'sldx',- 'sldm',- 'dotx',- 'dotm',- 'xlsx',- 'xlsm',- 'xlst',- 'odp',- 'odg',- 'ods',- 'odt'+ 'zip',+ 'epub',+ 'docx',+ 'pptx',+ 'pptm',+ 'potx',+ 'potm',+ 'ppxs',+ 'ppsm',+ 'sldx',+ 'sldm',+ 'dotx',+ 'dotm',+ 'xlsx',+ 'xlsm',+ 'xlst',+ 'odp',+ 'odg',+ 'ods',+ 'odt'];const supportedText = [- 'txt',- 'md',- 'coffee',- 'c',- 'cpp',- 'css',- 'groovy',- 'haxe',- 'xml',- 'java',- 'js',- 'json',- 'less',- 'markdown',- 'mdown',- 'php',- 'pl',- 'py',- 'rb',- 'ini',- 'sh',- 'sql',- 'mhtml'+ 'txt',+ 'md',+ 'coffee',+ 'c',+ 'cpp',+ 'css',+ 'groovy',+ 'haxe',+ 'xml',+ 'java',+ 'js',+ 'json',+ 'less',+ 'markdown',+ 'mdown',+ 'php',+ 'pl',+ 'py',+ 'rb',+ 'ini',+ 'sh',+ 'sql',+ 'mhtml'];const supportedVideos = ['ogv', 'mp4', 'webm', 'm4v', 'mkv'];const maxFileSize = 30 * 1024 * 1024;function saveThumbnailPromise(filePath, dataURL) {- return new Promise((resolve, reject) => {- if (!dataURL || dataURL.length < 7) {- // data:,- return reject('Invalid dataURL');- }- const baseString = dataURL.split(',').pop();- const content = base64ToArrayBuffer(baseString);- PlatformIO.saveBinaryFilePromise(filePath, content, true)- .then(() => resolve(filePath))- .catch(error => {- console.warn(- 'Saving thumbnail for ' +- filePath +- ' failed with ' +- JSON.stringify(error)- );- return reject('Saving tmb failed for: ' + filePath);- });- });+ return new Promise((resolve, reject) => {+ if (!dataURL || dataURL.length < 7) {+ // data:,+ return reject('Invalid dataURL');+ }+ const baseString = dataURL.split(',').pop();+ const content = base64ToArrayBuffer(baseString);+ PlatformIO.saveBinaryFilePromise(filePath, content, true)+ .then(() => resolve(filePath))+ .catch(error => {+ console.warn(+ 'Saving thumbnail for ' ++ filePath ++ ' failed with ' ++ JSON.stringify(error)+ );+ return reject('Saving tmb failed for: ' + filePath);+ });+ });}function getThumbFileLocation(filePath: string) {- const containingFolder = extractContainingDirectoryPath(filePath);- const metaFolder = getMetaDirectoryPath(containingFolder);- return (- metaFolder +- AppConfig.dirSeparator +- extractFileName(filePath) +- AppConfig.thumbFileExt- );+ const containingFolder = extractContainingDirectoryPath(filePath);+ const metaFolder = getMetaDirectoryPath(containingFolder);+ return (+ metaFolder ++ AppConfig.dirSeparator ++ extractFileName(filePath) ++ AppConfig.thumbFileExt+ );}export function getThumbnailURLPromise(- filePath: string-): Promise<{ filePath: string }> {- return new Promise(resolve => {- PlatformIO.getPropertiesPromise(filePath)- .then(origStats => {- const thumbFilePath = getThumbFileLocation(filePath);- PlatformIO.getPropertiesPromise(thumbFilePath)- .then(stats => {- if (stats) {- // Thumbnail exists- if (origStats.lmdt > stats.lmdt) {- // Checking if is up to date- createThumbnailPromise(filePath, origStats.size, thumbFilePath)- .then(tmbPath => resolve({ filePath, tmbPath }))- .catch(err => {- console.warn('Thumb generation failed ' + err);- resolve({ filePath, tmbPath: thumbFilePath });- });- } else {- // Tmb up to date- resolve({ filePath });- }- } else {- // Thumbnail does not exists- createThumbnailPromise(filePath, origStats.size, thumbFilePath)- .then(tmbPath => resolve({ filePath, tmbPath }))- .catch(err => {- console.warn('Thumb generation failed ' + err);- resolve({ filePath });- });- }- return true;- })- .catch(err => {- console.warn('Error getting tmb properties ' + err);- resolve({ filePath });- });- return true;- })- .catch(err => {- console.warn('Error getting file properties ' + err);- resolve({ filePath });- });- });+ filePath: string+): Promise<{ filePath: string; tmbPath?: string }> {+ return new Promise(resolve => {+ PlatformIO.getPropertiesPromise(filePath)+ .then(origStats => {+ const thumbFilePath = getThumbFileLocation(filePath);+ PlatformIO.getPropertiesPromise(thumbFilePath)+ .then(stats => {+ if (stats) {+ // Thumbnail exists+ if (origStats.lmdt > stats.lmdt) {+ // Checking if is up to date+ createThumbnailPromise(filePath, origStats.size, thumbFilePath)+ .then(tmbPath => resolve({ filePath, tmbPath }))+ .catch(err => {+ console.warn('Thumb generation failed ' + err);+ resolve({ filePath, tmbPath: thumbFilePath });+ });+ } else {+ // Tmb up to date+ resolve({ filePath });+ }+ } else {+ // Thumbnail does not exists+ createThumbnailPromise(filePath, origStats.size, thumbFilePath)+ .then(tmbPath => resolve({ filePath, tmbPath }))+ .catch(err => {+ console.warn('Thumb generation failed ' + err);+ resolve({ filePath });+ });+ }+ return true;+ })+ .catch(err => {+ console.warn('Error getting tmb properties ' + err);+ resolve({ filePath });+ });+ return true;+ })+ .catch(err => {+ console.warn('Error getting file properties ' + err);+ resolve({ filePath });+ });+ });}export function replaceThumbnailURLPromise(- filePath: string,- thumbFilePath: string+ filePath: string,+ thumbFilePath: string): Promise<any> {- return new Promise(resolve => {- PlatformIO.getPropertiesPromise(filePath)- .then(origStats => {- createThumbnailPromise(filePath, origStats.size, thumbFilePath)- .then(tmbPath => resolve({ filePath, tmbPath }))- .catch(err => {- console.warn('Thumb generation failed ' + err);- resolve({ filePath, tmbPath: thumbFilePath });- });- return true;- })- .catch(err => {- console.warn('Error getting file properties ' + err);- resolve({ filePath });- });- });+ return new Promise(resolve => {+ PlatformIO.getPropertiesPromise(filePath)+ .then(origStats => {+ createThumbnailPromise(filePath, origStats.size, thumbFilePath)+ .then(tmbPath => resolve({ filePath, tmbPath }))+ .catch(err => {+ console.warn('Thumb generation failed ' + err);+ resolve({ filePath, tmbPath: thumbFilePath });+ });+ return true;+ })+ .catch(err => {+ console.warn('Error getting file properties ' + err);+ resolve({ filePath });+ });+ });}export function createThumbnailPromise(- filePath: string,- fileSize: number,- thumbFilePath: string+ filePath: string,+ fileSize: number,+ thumbFilePath: string): Promise<any> {- return new Promise(async resolve => {- const metaDirectory = extractContainingDirectoryPath(thumbFilePath);- const fileDirectory = extractContainingDirectoryPath(filePath);- const normalizedFileDirectory = normalizePath(fileDirectory);- if (normalizedFileDirectory.endsWith(AppConfig.metaFolder)) {- resolve(); // prevent creating thumbs in meta/.ts folder- return true;- }- const stats = await PlatformIO.getPropertiesPromise(metaDirectory);- if (!stats || stats.isFile) {- await PlatformIO.createDirectoryPromise(metaDirectory);- }+ return new Promise(async resolve => {+ const metaDirectory = extractContainingDirectoryPath(thumbFilePath);+ const fileDirectory = extractContainingDirectoryPath(filePath);+ const normalizedFileDirectory = normalizePath(fileDirectory);+ if (normalizedFileDirectory.endsWith(AppConfig.metaFolder)) {+ resolve(); // prevent creating thumbs in meta/.ts folder+ return true;+ }+ const stats = await PlatformIO.getPropertiesPromise(metaDirectory);+ if (!stats || stats.isFile) {+ await PlatformIO.createDirectoryPromise(metaDirectory);+ }- generateThumbnailPromise(filePath, fileSize)- .then(dataURL => {- if (dataURL && dataURL.length) {- saveThumbnailPromise(thumbFilePath, dataURL)- .then(() => resolve(thumbFilePath))- .catch(err => {- console.warn('Thumb saving failed ' + err + ' for ' + filePath);- resolve();- });- return true;- }- resolve();- return true;- })- .catch(err => {- console.warn('Thumb generation failed ' + err + ' for ' + filePath);- resolve();- });- return true;- });+ generateThumbnailPromise(filePath, fileSize)+ .then(dataURL => {+ if (dataURL && dataURL.length) {+ saveThumbnailPromise(thumbFilePath, dataURL)+ .then(() => resolve(thumbFilePath))+ .catch(err => {+ console.warn('Thumb saving failed ' + err + ' for ' + filePath);+ resolve();+ });+ return true;+ }+ resolve();+ return true;+ })+ .catch(err => {+ console.warn('Thumb generation failed ' + err + ' for ' + filePath);+ resolve();+ });+ return true;+ });}export function generateThumbnailPromise(fileURL: string, fileSize: number) {- const ext = extractFileExtension(fileURL).toLowerCase();+ const ext = extractFileExtension(fileURL).toLowerCase();- if (supportedImgs.indexOf(ext) >= 0) {- if (fileSize && fileSize < maxFileSize) {- return generateImageThumbnail(fileURL);- }- } else if (Pro && ext === 'pdf') {- return Pro.ThumbsGenerator.generatePDFThumbnail(fileURL, maxSize);- } else if (Pro && ext === 'html') {- return Pro.ThumbsGenerator.generateHtmlThumbnail(fileURL, maxSize);- } else if (Pro && ext === 'url') {- return Pro.ThumbsGenerator.generateUrlThumbnail(fileURL, maxSize);- } else if (Pro && ext === 'tiff') {- return Pro.ThumbsGenerator.generateTiffThumbnail(fileURL, maxSize);- } else if (Pro && ext === 'mp3') {- if (fileSize && fileSize < maxFileSize) {- // return Pro.ThumbsGenerator.generateMp3Thumbnail(fileURL, maxSize);- }- } else if (Pro && supportedText.indexOf(ext) >= 0) {- return Pro.ThumbsGenerator.generateTextThumbnail(fileURL, maxSize);- } else if (Pro && supportedContainers.indexOf(ext) >= 0) {- if (fileSize && fileSize < maxFileSize) {- return Pro.ThumbsGenerator.generateZipContainerImageThumbnail(- fileURL,- maxSize,- supportedImgs- );- }- } else if (supportedVideos.indexOf(ext) >= 0) {- if (Pro) {- return Pro.ThumbsGenerator.generateVideoThumbnail(fileURL, maxSize);- }- return generateVideoThumbnail(fileURL);- }- return generateDefaultThumbnail();+ if (supportedImgs.indexOf(ext) >= 0) {+ if (fileSize && fileSize < maxFileSize) {+ return generateImageThumbnail(fileURL);+ }+ } else if (Pro && ext === 'pdf') {+ return Pro.ThumbsGenerator.generatePDFThumbnail(fileURL, maxSize);+ } else if (Pro && ext === 'html') {+ return Pro.ThumbsGenerator.generateHtmlThumbnail(fileURL, maxSize);+ } else if (Pro && ext === 'url') {+ return Pro.ThumbsGenerator.generateUrlThumbnail(fileURL, maxSize);+ } else if (Pro && ext === 'tiff') {+ return Pro.ThumbsGenerator.generateTiffThumbnail(fileURL, maxSize);+ } else if (Pro && ext === 'mp3') {+ if (fileSize && fileSize < maxFileSize) {+ // return Pro.ThumbsGenerator.generateMp3Thumbnail(fileURL, maxSize);+ }+ } else if (Pro && supportedText.indexOf(ext) >= 0) {+ return Pro.ThumbsGenerator.generateTextThumbnail(fileURL, maxSize);+ } else if (Pro && supportedContainers.indexOf(ext) >= 0) {+ if (fileSize && fileSize < maxFileSize) {+ return Pro.ThumbsGenerator.generateZipContainerImageThumbnail(+ fileURL,+ maxSize,+ supportedImgs+ );+ }+ } else if (supportedVideos.indexOf(ext) >= 0) {+ if (Pro) {+ return Pro.ThumbsGenerator.generateVideoThumbnail(fileURL, maxSize);+ }+ return generateVideoThumbnail(fileURL);+ }+ return generateDefaultThumbnail();}function generateDefaultThumbnail() {- return Promise.resolve('');+ return Promise.resolve('');}function generateImageThumbnail(fileURL): Promise<string> {- return new Promise(resolve => {- let canvas: HTMLCanvasElement = document.createElement('canvas');- const ctx = canvas.getContext('2d');- let img: HTMLImageElement = new Image();+ return new Promise(resolve => {+ let canvas: HTMLCanvasElement = document.createElement('canvas');+ const ctx = canvas.getContext('2d');+ let img: HTMLImageElement = new Image();- const errorHandler = err => {- console.warn(- 'Error while generating thumbnail for: ' +- fileURL +- ' - ' +- JSON.stringify(err)- );- resolve('');- };+ const errorHandler = err => {+ console.warn(+ 'Error while generating thumbnail for: ' ++ fileURL ++ ' - ' ++ JSON.stringify(err)+ );+ resolve('');+ };- img.crossOrigin = 'anonymous';- img.onload = () => {- EXIF.getData(img, function() {- // TODO Use EXIF only for jpegs- const orientation = EXIF.getTag(this, 'Orientation');- /*+ img.crossOrigin = 'anonymous';+ img.onload = () => {+ EXIF.getData(img as any, function() {+ // TODO Use EXIF only for jpegs+ const orientation = EXIF.getTag(this, 'Orientation');+ /*1 - 0 degrees – the correct orientation, no adjustment is required.2 - 0 degrees, mirrored – image has been flipped back-to-front.3 - 180 degrees – image is upside down.@@ -298,92 +298,92 @@ function generateImageThumbnail(fileURL): Promise<string> {7 - 270 degrees – image is on its far side.8 - 270 degrees, mirrored – image is on its far side and flipped back-to-front.*/- let angleInRadians;- switch (orientation) {- case 8:- angleInRadians = 270 * (Math.PI / 180);- break;- case 3:- angleInRadians = 180 * (Math.PI / 180);- break;- case 6:- angleInRadians = 90 * (Math.PI / 180);- break;- case 1:- // ctx.rotate(0);- break;- default:- // ctx.rotate(0);- }- if (img.width >= img.height) {- canvas.width = maxSize;- canvas.height = (maxSize * img.height) / img.width;- } else {- canvas.height = maxSize;- canvas.width = (maxSize * img.width) / img.height;- }- const width = canvas.width;- const height = canvas.height;- const x = canvas.width / 2;- const y = canvas.height / 2;+ let angleInRadians;+ switch (orientation) {+ case 8:+ angleInRadians = 270 * (Math.PI / 180);+ break;+ case 3:+ angleInRadians = 180 * (Math.PI / 180);+ break;+ case 6:+ angleInRadians = 90 * (Math.PI / 180);+ break;+ case 1:+ // ctx.rotate(0);+ break;+ default:+ // ctx.rotate(0);+ }+ if (img.width >= img.height) {+ canvas.width = maxSize;+ canvas.height = (maxSize * img.height) / img.width;+ } else {+ canvas.height = maxSize;+ canvas.width = (maxSize * img.width) / img.height;+ }+ const width = canvas.width;+ const height = canvas.height;+ const x = canvas.width / 2;+ const y = canvas.height / 2;- ctx.translate(x, y);- ctx.rotate(angleInRadians);- ctx.fillStyle = bgColor;- ctx.fillRect(-width / 2, -height / 2, width, height);- ctx.drawImage(img, -width / 2, -height / 2, width, height);- ctx.rotate(-angleInRadians);- ctx.translate(-x, -y);- const dataurl = canvas.toDataURL(AppConfig.thumbType);- resolve(dataurl);- img = null;- canvas = null;- });- };- img.src = fileURL;- img.onerror = errorHandler;- });+ ctx.translate(x, y);+ ctx.rotate(angleInRadians);+ ctx.fillStyle = bgColor;+ ctx.fillRect(-width / 2, -height / 2, width, height);+ ctx.drawImage(img, -width / 2, -height / 2, width, height);+ ctx.rotate(-angleInRadians);+ ctx.translate(-x, -y);+ const dataurl = canvas.toDataURL(AppConfig.thumbType);+ resolve(dataurl);+ img = null;+ canvas = null;+ });+ };+ img.src = fileURL;+ img.onerror = errorHandler;+ });}function generateVideoThumbnail(fileURL): Promise<string> {- return new Promise(resolve => {- let canvas: HTMLCanvasElement = document.createElement('canvas');- const ctx = canvas.getContext('2d');- let img: HTMLImageElement = new Image();- let video: HTMLVideoElement = document.createElement('video');- const captureTime = 1.5; // time in seconds at which to capture the image from the video+ return new Promise(resolve => {+ let canvas: HTMLCanvasElement = document.createElement('canvas');+ const ctx = canvas.getContext('2d');+ let img: HTMLImageElement = new Image();+ let video: HTMLVideoElement = document.createElement('video');+ const captureTime = 1.5; // time in seconds at which to capture the image from the video- const errorHandler = err => {- console.warn(- 'Error while generating thumbnail for: ' +- fileURL +- ' - ' +- JSON.stringify(err)- );- resolve('');- };+ const errorHandler = err => {+ console.warn(+ 'Error while generating thumbnail for: ' ++ fileURL ++ ' - ' ++ JSON.stringify(err)+ );+ resolve('');+ };- video.onloadedmetadata = () => {- video.currentTime = Math.min(Math.max(0, captureTime), video.duration);- if (video.videoWidth >= video.videoHeight) {- canvas.width = maxSize;- canvas.height = (maxSize * video.videoHeight) / video.videoWidth;- } else {- canvas.height = maxSize;- canvas.width = (maxSize * video.videoWidth) / video.videoHeight;- }- };+ video.onloadedmetadata = () => {+ video.currentTime = Math.min(Math.max(0, captureTime), video.duration);+ if (video.videoWidth >= video.videoHeight) {+ canvas.width = maxSize;+ canvas.height = (maxSize * video.videoHeight) / video.videoWidth;+ } else {+ canvas.height = maxSize;+ canvas.width = (maxSize * video.videoWidth) / video.videoHeight;+ }+ };- video.onseeked = () => {- ctx.drawImage(video, 0, 0, canvas.width, canvas.height);- const dataurl = canvas.toDataURL(AppConfig.thumbType);- img.onerror = errorHandler;- resolve(dataurl);- img = null;- canvas = null;- video = null;- };- video.onerror = errorHandler;- video.src = fileURL;- });+ video.onseeked = () => {+ ctx.drawImage(video, 0, 0, canvas.width, canvas.height);+ const dataurl = canvas.toDataURL(AppConfig.thumbType);+ img.onerror = errorHandler;+ resolve(dataurl);+ img = null;+ canvas = null;+ video = null;+ };+ video.onerror = errorHandler;+ video.src = fileURL;+ });}diff --git a/app/services/utils-io.ts b/app/services/utils-io.tsindex c3318ee32..fb03531bf 100644--- a/app/services/utils-io.ts+++ b/app/services/utils-io.ts@@ -21,504 +21,507 @@ import uuidv1 from 'uuid';import PlatformIO from './platform-io';import AppConfig from '../config';import {- extractTagsAsObjects,- extractFileExtension,- cleanTrailingDirSeparator,- getMetaDirectoryPath,- getMetaFileLocationForFile,- getMetaFileLocationForDir,- extractContainingDirectoryPath+ extractTagsAsObjects,+ extractFileExtension,+ cleanTrailingDirSeparator,+ getMetaDirectoryPath,+ getMetaFileLocationForFile,+ getMetaFileLocationForDir,+ extractContainingDirectoryPath} from '../utils/paths';// import { formatDateTime4Tag } from '../utils/misc';import versionMeta from '../version.json';import { Tag } from '../reducers/taglibrary';export interface FileSystemEntry {- uuid: string;- name: string;- isFile: boolean;- extension: string;- thumbPath?: string;- color?: string;- textContent?: string;- description: string;- tags: Array<Tag>;- size: number;- lmdt: number;- path: string;- meta?: FileSystemEntryMeta;+ uuid?: string;+ name: string;+ isFile: boolean;+ extension: string;+ thumbPath?: string;+ color?: string;+ textContent?: string;+ description?: string;+ tags?: Array<Tag>;+ size: number;+ lmdt: number;+ path: string;+ meta?: FileSystemEntryMeta;}export interface FileSystemEntryMeta {- description: string;- tags: Array<Tag>;- color?: string;- appVersionCreated: string;- appName: string;- appVersionUpdated: string;- lastUpdated: string;+ description: string;+ tags: Array<Tag>;+ color?: string;+ appVersionCreated: string;+ appName: string;+ appVersionUpdated: string;+ lastUpdated: string;}export function enhanceEntry(entry: any): FileSystemEntry {- let fileNameTags = [];- if (entry.isFile) {- fileNameTags = extractTagsAsObjects(entry.name);- }- let sidecarDescription = '';- let sidecarColor = '';- let uuid;- let sidecarTags = [];- if (entry.meta) {- sidecarDescription = entry.meta.description || '';- sidecarColor = entry.meta.color || '';- sidecarTags = entry.meta.tags || [];- sidecarTags.map(tag => {- tag.type = 'sidecar';- return true;- });- uuid = entry.meta.uuid || undefined;- }- const enhancedEntry = {- uuid: uuid || uuidv1(),- name: entry.name,- isFile: entry.isFile,- extension: entry.isFile ? extractFileExtension(entry.name) : '',- thumbPath: entry.thumbPath,- description: sidecarDescription,- color: sidecarColor,- textContent: entry.textContent,- tags: [...sidecarTags, ...fileNameTags],- size: entry.size,- lmdt: entry.lmdt,- path: entry.path- };- // console.log('Enhancing ' + entry.path); console.log(enhancedEntry);- return enhancedEntry;+ let fileNameTags = [];+ if (entry.isFile) {+ fileNameTags = extractTagsAsObjects(entry.name);+ }+ let sidecarDescription = '';+ let sidecarColor = '';+ let uuid;+ let sidecarTags = [];+ if (entry.meta) {+ sidecarDescription = entry.meta.description || '';+ sidecarColor = entry.meta.color || '';+ sidecarTags = entry.meta.tags || [];+ sidecarTags.map(tag => {+ tag.type = 'sidecar';+ return true;+ });+ uuid = entry.meta.uuid || undefined;+ }+ const enhancedEntry = {+ uuid: uuid || uuidv1(),+ name: entry.name,+ isFile: entry.isFile,+ extension: entry.isFile ? extractFileExtension(entry.name) : '',+ thumbPath: entry.thumbPath,+ description: sidecarDescription,+ color: sidecarColor,+ textContent: entry.textContent,+ tags: [...sidecarTags, ...fileNameTags],+ size: entry.size,+ lmdt: entry.lmdt,+ path: entry.path+ };+ // console.log('Enhancing ' + entry.path); console.log(enhancedEntry);+ return enhancedEntry;}export function createDirectoryIndex(- directoryPath: string,- extractText: boolean = false+ directoryPath: string,+ extractText: boolean = false): Promise<Array<Object>> {- const dirPath = cleanTrailingDirSeparator(directoryPath);- if (PlatformIO.isWorkerAvailable() && !PlatformIO.haveObjectStoreSupport()) {- // Start indexing in worker if not in the object store mode- return PlatformIO.createDirectoryIndexInWorker(dirPath, extractText);- }+ const dirPath = cleanTrailingDirSeparator(directoryPath);+ if (PlatformIO.isWorkerAvailable() && !PlatformIO.haveObjectStoreSupport()) {+ // Start indexing in worker if not in the object store mode+ return PlatformIO.createDirectoryIndexInWorker(dirPath, extractText);+ }- return new Promise((resolve, reject) => {- setTimeout(() => {- const directoryIndex = [];- let counter = 0;- console.time('createDirectoryIndex');- walkDirectory(- dirPath,- {- recursive: true,- skipMetaFolder: true,- skipDotHiddenFolder: true,- extractText- },- fileEntry => {- counter += 1;- if (counter > AppConfig.indexerLimit) {- console.warn('Walk canceled by ' + AppConfig.indexerLimit);- window.walkCanceled = true;- }- directoryIndex.push(enhanceEntry(fileEntry));- },- directoryEntry => {- if (directoryEntry.name !== AppConfig.metaFolder) {- counter += 1;- directoryIndex.push(enhanceEntry(directoryEntry));- }- }- )- .then(() => {- // entries - can be used for further processing- window.walkCanceled = false;- console.log(- 'Directory index created ' +- dirPath +- ' containing ' +- directoryIndex.length- );- console.timeEnd('createDirectoryIndex');- resolve(directoryIndex);- return true;- })- .catch(err => {- window.walkCanceled = false;- console.timeEnd('createDirectoryIndex');- console.warn('Error creating index: ' + err);- reject(err);- });- }, 2000);- });+ return new Promise((resolve, reject) => {+ setTimeout(() => {+ const directoryIndex = [];+ let counter = 0;+ console.time('createDirectoryIndex');+ walkDirectory(+ dirPath,+ {+ recursive: true,+ skipMetaFolder: true,+ skipDotHiddenFolder: true,+ extractText+ },+ fileEntry => {+ counter += 1;+ if (counter > AppConfig.indexerLimit) {+ console.warn('Walk canceled by ' + AppConfig.indexerLimit);+ window.walkCanceled = true;+ }+ directoryIndex.push(enhanceEntry(fileEntry));+ },+ directoryEntry => {+ if (directoryEntry.name !== AppConfig.metaFolder) {+ counter += 1;+ directoryIndex.push(enhanceEntry(directoryEntry));+ }+ }+ )+ .then(() => {+ // entries - can be used for further processing+ window.walkCanceled = false;+ console.log(+ 'Directory index created ' ++ dirPath ++ ' containing ' ++ directoryIndex.length+ );+ console.timeEnd('createDirectoryIndex');+ resolve(directoryIndex);+ return true;+ })+ .catch(err => {+ window.walkCanceled = false;+ console.timeEnd('createDirectoryIndex');+ console.warn('Error creating index: ' + err);+ reject(err);+ });+ }, 2000);+ });}export function walkDirectory(- path: string,- options: Object = {},- fileCallback: any,- dirCallback: any+ path: string,+ options: Object = {},+ fileCallback: any,+ dirCallback: any) {- const mergedOptions = {- recursive: false,- skipMetaFolder: true,- skipDotHiddenFolder: false,- loadMetaDate: true,- extractText: false,- ...options- };- return PlatformIO.listDirectoryPromise(path, false, mergedOptions.extractText)- .then(entries => {- if (window.walkCanceled) {- return false;- }- return Promise.all(- entries.map(entry => {- if (window.walkCanceled) {- return false;- }+ const mergedOptions = {+ recursive: false,+ skipMetaFolder: true,+ skipDotHiddenFolder: false,+ loadMetaDate: true,+ extractText: false,+ ...options+ };+ return (+ PlatformIO.listDirectoryPromise(path, false, mergedOptions.extractText)+ // @ts-ignore+ .then(entries => {+ if (window.walkCanceled) {+ return false;+ }+ return Promise.all(+ entries.map(entry => {+ if (window.walkCanceled) {+ return false;+ }- if (entry.isFile) {- if (fileCallback) {- fileCallback(entry);- }- return entry;- }+ if (entry.isFile) {+ if (fileCallback) {+ fileCallback(entry);+ }+ return entry;+ }- if (dirCallback) {- dirCallback(entry);- }+ if (dirCallback) {+ dirCallback(entry);+ }- if (mergedOptions.recursive) {- if (- mergedOptions.skipDotHiddenFolder &&- entry.name.startsWith('.')- ) {- return entry;- }- if (- mergedOptions.skipMetaFolder &&- entry.name === AppConfig.metaFolder- ) {- return entry;- }- return walkDirectory(- entry.path,- mergedOptions,- fileCallback,- dirCallback- );- }- return entry;- })- );- })- .catch(err => {- console.warn('Error walking directory ' + err);- return err;- });+ if (mergedOptions.recursive) {+ if (+ mergedOptions.skipDotHiddenFolder &&+ entry.name.startsWith('.')+ ) {+ return entry;+ }+ if (+ mergedOptions.skipMetaFolder &&+ entry.name === AppConfig.metaFolder+ ) {+ return entry;+ }+ return walkDirectory(+ entry.path,+ mergedOptions,+ fileCallback,+ dirCallback+ );+ }+ return entry;+ })+ );+ })+ .catch(err => {+ console.warn('Error walking directory ' + err);+ return err;+ })+ );}export async function getAllPropertiesPromise(- entryPath: string+ entryPath: string): Promise<FileSystemEntry> {- const entryProps = await PlatformIO.getPropertiesPromise(entryPath);- let metaFilePath;- if (entryProps.isFile) {- metaFilePath = getMetaFileLocationForFile(entryPath);- } else {- metaFilePath = getMetaFileLocationForDir(entryPath);- }- const metaFileProps = await PlatformIO.getPropertiesPromise(metaFilePath);- if (metaFileProps.isFile) {- entryProps.meta = await loadJSONFile(metaFilePath);- }- return enhanceEntry(entryProps);+ const entryProps = await PlatformIO.getPropertiesPromise(entryPath);+ let metaFilePath;+ if (entryProps.isFile) {+ metaFilePath = getMetaFileLocationForFile(entryPath);+ } else {+ metaFilePath = getMetaFileLocationForDir(entryPath);+ }+ const metaFileProps = await PlatformIO.getPropertiesPromise(metaFilePath);+ if (metaFileProps.isFile) {+ entryProps.meta = await loadJSONFile(metaFilePath);+ }+ return enhanceEntry(entryProps);}-export async function loadJSONFile(filePath: string): any {- let jsonObject;- let jsonContent = await PlatformIO.loadTextFilePromise(filePath);- const UTF8_BOM = '\ufeff';- if (jsonContent.indexOf(UTF8_BOM) === 0) {- jsonContent = jsonContent.substring(1, jsonContent.length);- }- try {- jsonObject = JSON.parse(jsonContent);- } catch (err) {- console.warn('Error parsing meta json file for ' + filePath + ' - ' + err);- }- return jsonObject;+export async function loadJSONFile(filePath: string) {+ let jsonObject;+ let jsonContent = await PlatformIO.loadTextFilePromise(filePath);+ const UTF8_BOM = '\ufeff';+ if (jsonContent.indexOf(UTF8_BOM) === 0) {+ jsonContent = jsonContent.substring(1, jsonContent.length);+ }+ try {+ jsonObject = JSON.parse(jsonContent);+ } catch (err) {+ console.warn('Error parsing meta json file for ' + filePath + ' - ' + err);+ }+ return jsonObject;}export function saveAsTextFile(blob: any, filename: string) {- saveAs(blob, filename);+ saveAs(blob, filename);}export function openLinkExternally(uri: string) {- const decodedURI = decodeURIComponent(uri);- if (- decodedURI.startsWith('http://') ||- decodedURI.startsWith('https://') ||- decodedURI.startsWith('file://')- ) {- PlatformIO.openFile(decodedURI);- } else {- console.log('Not supported URL format: ' + decodedURI);- }+ const decodedURI = decodeURIComponent(uri);+ if (+ decodedURI.startsWith('http://') ||+ decodedURI.startsWith('https://') ||+ decodedURI.startsWith('file://')+ ) {+ PlatformIO.openFile(decodedURI);+ } else {+ console.log('Not supported URL format: ' + decodedURI);+ }}export function deleteFilesPromise(filePathList: Array<string>) {- const fileDeletionPromises = [];- filePathList.forEach(filePath => {- fileDeletionPromises.push(PlatformIO.deleteFilePromise(filePath));- });- return Promise.all(fileDeletionPromises);+ const fileDeletionPromises = [];+ filePathList.forEach(filePath => {+ fileDeletionPromises.push(PlatformIO.deleteFilePromise(filePath));+ });+ return Promise.all(fileDeletionPromises);}export function renameFilesPromise(renameJobs: Array<Array<string>>) {- const fileRenamePromises = [];- renameJobs.forEach(renameJob => {- fileRenamePromises.push(- PlatformIO.renameFilePromise(renameJob[0], renameJob[1])- );- });- return Promise.all(fileRenamePromises);+ const fileRenamePromises = [];+ renameJobs.forEach(renameJob => {+ fileRenamePromises.push(+ PlatformIO.renameFilePromise(renameJob[0], renameJob[1])+ );+ });+ return Promise.all(fileRenamePromises);}export function copyFilesPromise(copyJobs: Array<Array<string>>) {- const ioJobPromises = [];- copyJobs.forEach(copyJob => {- ioJobPromises.push(PlatformIO.copyFilePromise(copyJob[0], copyJob[1]));- });- return Promise.all(ioJobPromises);+ const ioJobPromises = [];+ copyJobs.forEach(copyJob => {+ ioJobPromises.push(PlatformIO.copyFilePromise(copyJob[0], copyJob[1]));+ });+ return Promise.all(ioJobPromises);}export async function loadSubFolders(- path: string,- loadHidden: boolean = false+ path: string,+ loadHidden: boolean = false) {- const folderContent = await PlatformIO.listDirectoryPromise(path, true);- const subfolders = [];- let i = 0;- let isHidden = false;- folderContent.map(entry => {- if (!entry.isFile) {- isHidden = entry.name.startsWith('.');- if (isHidden) {- if (loadHidden) {- subfolders.push({- key: '0-' + (i += 1),- isLeaf: false,- name: entry.name,- isFile: entry.isFile,- lmdt: entry.lmdt,- meta: entry.meta,- path: entry.path,- tags: entry.tags- });- } else {- // do nothing- }- } else {- subfolders.push({- key: '0-' + (i += 1),- isLeaf: false,- name: entry.name,- isFile: entry.isFile,- lmdt: entry.lmdt,- meta: entry.meta,- path: entry.path,- tags: entry.tags- });- }- }- return true;- });- return subfolders;+ const folderContent = await PlatformIO.listDirectoryPromise(path, true);+ const subfolders = [];+ let i = 0;+ let isHidden = false;+ folderContent.map(entry => {+ if (!entry.isFile) {+ isHidden = entry.name.startsWith('.');+ if (isHidden) {+ if (loadHidden) {+ subfolders.push({+ key: '0-' + (i += 1),+ isLeaf: false,+ name: entry.name,+ isFile: entry.isFile,+ lmdt: entry.lmdt,+ meta: entry.meta,+ path: entry.path,+ tags: entry.tags+ });+ } else {+ // do nothing+ }+ } else {+ subfolders.push({+ key: '0-' + (i += 1),+ isLeaf: false,+ name: entry.name,+ isFile: entry.isFile,+ lmdt: entry.lmdt,+ meta: entry.meta,+ path: entry.path,+ tags: entry.tags+ });+ }+ }+ return true;+ });+ return subfolders;}export function generateFileName(- fileName: string,- tags: Array<string>,- tagDelimiter: string+ fileName: string,+ tags: Array<string>,+ tagDelimiter: string) {- let tagsString = '';- const prefixTagContainer = AppConfig.prefixTagContainer;- // Creating the string will all the tags by more that 0 tags- if (tags && tags.length > 0) {- tagsString = AppConfig.beginTagContainer;- for (let i = 0; i < tags.length; i += 1) {- if (i === tags.length - 1) {- tagsString += tags[i].trim();- } else {- tagsString += tags[i].trim() + tagDelimiter;- }- }- tagsString = tagsString.trim() + AppConfig.endTagContainer;- }- // console.log('The tags string: ' + tagsString);- const fileExt = extractFileExtension(fileName);- // console.log('Filename: ' + fileName + ' file extension: ' + fileExt);- // Assembling the new filename with the tags- let newFileName = '';- const beginTagContainer = fileName.indexOf(AppConfig.beginTagContainer);- const endTagContainer = fileName.indexOf(AppConfig.endTagContainer);- const lastDotPosition = fileName.lastIndexOf('.');- if (- beginTagContainer < 0 ||- endTagContainer < 0 ||- beginTagContainer >= endTagContainer- ) {- // Filename does not contains tags.- if (lastDotPosition < 0) {- // File does not have an extension- newFileName = fileName.trim() + tagsString;- } else {- // File has an extension- newFileName =- fileName.substring(0, lastDotPosition).trim() +- prefixTagContainer +- tagsString +- '.' +- fileExt;- }- } else {- // File does not have an extension- newFileName =- fileName.substring(0, beginTagContainer).trim() +- prefixTagContainer +- tagsString +- fileName.substring(endTagContainer + 1, fileName.length).trim();- }- if (newFileName.length < 1) {- throw new Error('Generated filename is invalid');- }- // Removing double prefix- newFileName = newFileName- .split(prefixTagContainer + '' + prefixTagContainer)- .join(prefixTagContainer);- return newFileName;+ let tagsString = '';+ const prefixTagContainer = AppConfig.prefixTagContainer;+ // Creating the string will all the tags by more that 0 tags+ if (tags && tags.length > 0) {+ tagsString = AppConfig.beginTagContainer;+ for (let i = 0; i < tags.length; i += 1) {+ if (i === tags.length - 1) {+ tagsString += tags[i].trim();+ } else {+ tagsString += tags[i].trim() + tagDelimiter;+ }+ }+ tagsString = tagsString.trim() + AppConfig.endTagContainer;+ }+ // console.log('The tags string: ' + tagsString);+ const fileExt = extractFileExtension(fileName);+ // console.log('Filename: ' + fileName + ' file extension: ' + fileExt);+ // Assembling the new filename with the tags+ let newFileName = '';+ const beginTagContainer = fileName.indexOf(AppConfig.beginTagContainer);+ const endTagContainer = fileName.indexOf(AppConfig.endTagContainer);+ const lastDotPosition = fileName.lastIndexOf('.');+ if (+ beginTagContainer < 0 ||+ endTagContainer < 0 ||+ beginTagContainer >= endTagContainer+ ) {+ // Filename does not contains tags.+ if (lastDotPosition < 0) {+ // File does not have an extension+ newFileName = fileName.trim() + tagsString;+ } else {+ // File has an extension+ newFileName =+ fileName.substring(0, lastDotPosition).trim() ++ prefixTagContainer ++ tagsString ++ '.' ++ fileExt;+ }+ } else {+ // File does not have an extension+ newFileName =+ fileName.substring(0, beginTagContainer).trim() ++ prefixTagContainer ++ tagsString ++ fileName.substring(endTagContainer + 1, fileName.length).trim();+ }+ if (newFileName.length < 1) {+ throw new Error('Generated filename is invalid');+ }+ // Removing double prefix+ newFileName = newFileName+ .split(prefixTagContainer + '' + prefixTagContainer)+ .join(prefixTagContainer);+ return newFileName;}export async function loadMetaDataPromise(- path: string+ path: string): Promise<FileSystemEntryMeta> {- const entryProperties = await PlatformIO.getPropertiesPromise(path);- let metaDataObject;- if (entryProperties.isFile) {- const metaFilePath = getMetaFileLocationForFile(path);- const metaData = await loadJSONFile(metaFilePath);- metaDataObject = {- description: metaData.description || '',- color: metaData.color || '',- tags: metaData.tags || [],- appVersionCreated: metaData.appVersionCreated || '',- appName: metaData.appName || '',- appVersionUpdated: metaData.appVersionUpdated || '',- lastUpdated: metaData.lastUpdated || ''- };- } else {- const metaFilePath = getMetaFileLocationForDir(path);- const metaData = await loadJSONFile(metaFilePath);- metaDataObject = {- description: metaData.description || '',- color: metaData.color || '',- tags: metaData.tags || [],- appVersionCreated: metaData.appVersionCreated || '',- appName: metaData.appName || '',- appVersionUpdated: metaData.appVersionUpdated || '',- lastUpdated: metaData.lastUpdated || ''- };- }- return metaDataObject;+ const entryProperties = await PlatformIO.getPropertiesPromise(path);+ let metaDataObject;+ if (entryProperties.isFile) {+ const metaFilePath = getMetaFileLocationForFile(path);+ const metaData = await loadJSONFile(metaFilePath);+ metaDataObject = {+ description: metaData.description || '',+ color: metaData.color || '',+ tags: metaData.tags || [],+ appVersionCreated: metaData.appVersionCreated || '',+ appName: metaData.appName || '',+ appVersionUpdated: metaData.appVersionUpdated || '',+ lastUpdated: metaData.lastUpdated || ''+ };+ } else {+ const metaFilePath = getMetaFileLocationForDir(path);+ const metaData = await loadJSONFile(metaFilePath);+ metaDataObject = {+ description: metaData.description || '',+ color: metaData.color || '',+ tags: metaData.tags || [],+ appVersionCreated: metaData.appVersionCreated || '',+ appName: metaData.appName || '',+ appVersionUpdated: metaData.appVersionUpdated || '',+ lastUpdated: metaData.lastUpdated || ''+ };+ }+ return metaDataObject;}export async function saveMetaDataPromise(- path: string,- metaData: Object+ path: string,+ metaData: Object): Promise<any> {- const entryProperties = await PlatformIO.getPropertiesPromise(path);- let metaFilePath;- let newFsEntryMeta;+ const entryProperties = await PlatformIO.getPropertiesPromise(path);+ let metaFilePath;+ let newFsEntryMeta;- if (entryProperties.isFile) {- metaFilePath = getMetaFileLocationForFile(path);- // check and create meta folder if not exist- await PlatformIO.createDirectoryPromise(- extractContainingDirectoryPath(metaFilePath)- );+ if (entryProperties.isFile) {+ metaFilePath = getMetaFileLocationForFile(path);+ // check and create meta folder if not exist+ await PlatformIO.createDirectoryPromise(+ extractContainingDirectoryPath(metaFilePath)+ );- newFsEntryMeta = {- ...metaData,- appName: versionMeta.name,- appVersionUpdated: versionMeta.version,- lastUpdated: new Date().toJSON()- };- } else {- // check and create meta folder if not exist- // todo not need to check if folder exist first createDirectoryPromise() recursively will skip creation of existing folders https://nodejs.org/api/fs.html#fs_fs_mkdir_path_options_callback- const metaDirectoryPath = getMetaDirectoryPath(path);- const metaDirectoryProperties = await PlatformIO.getPropertiesPromise(- metaDirectoryPath- );- if (!metaDirectoryProperties) {- await PlatformIO.createDirectoryPromise(metaDirectoryPath);- }+ newFsEntryMeta = {+ ...metaData,+ appName: versionMeta.name,+ appVersionUpdated: versionMeta.version,+ lastUpdated: new Date().toJSON()+ };+ } else {+ // check and create meta folder if not exist+ // todo not need to check if folder exist first createDirectoryPromise() recursively will skip creation of existing folders https://nodejs.org/api/fs.html#fs_fs_mkdir_path_options_callback+ const metaDirectoryPath = getMetaDirectoryPath(path);+ const metaDirectoryProperties = await PlatformIO.getPropertiesPromise(+ metaDirectoryPath+ );+ if (!metaDirectoryProperties) {+ await PlatformIO.createDirectoryPromise(metaDirectoryPath);+ }- metaFilePath = getMetaFileLocationForDir(path);- newFsEntryMeta = {- ...metaData,- appName: versionMeta.name,- appVersionUpdated: versionMeta.version,- lastUpdated: new Date().toJSON()- };- }- const content = JSON.stringify(newFsEntryMeta);- return PlatformIO.saveTextFilePromise(metaFilePath, content, true);+ metaFilePath = getMetaFileLocationForDir(path);+ newFsEntryMeta = {+ ...metaData,+ appName: versionMeta.name,+ appVersionUpdated: versionMeta.version,+ lastUpdated: new Date().toJSON()+ };+ }+ const content = JSON.stringify(newFsEntryMeta);+ return PlatformIO.saveTextFilePromise(metaFilePath, content, true);}export function findColorForFileEntry(- fileExtension: string,- isFile: boolean,- supportedFileTypes: Array<Object>+ fileExtension: string,+ isFile: boolean,+ supportedFileTypes: Array<any>): string {- if (!isFile) {- return AppConfig.defaultFolderColor;- }- let color = AppConfig.defaultFileColor;- supportedFileTypes.map(fileType => {- if (fileType.type.toLowerCase() === fileExtension.toLowerCase()) {- if (fileType.color) {- color = fileType.color;- }- }- return true;- });- return color;+ if (!isFile) {+ return AppConfig.defaultFolderColor;+ }+ let color = AppConfig.defaultFileColor;+ supportedFileTypes.map(fileType => {+ if (fileType.type.toLowerCase() === fileExtension.toLowerCase()) {+ if (fileType.color) {+ color = fileType.color;+ }+ }+ return true;+ });+ return color;}export function loadFileContentPromise(- fullPath: string,- type: string+ fullPath: string,+ type: string): Promise<any> {- return new Promise((resolve, reject) => {- const xhr = new XMLHttpRequest();- xhr.open('GET', fullPath, true);- xhr.responseType = type || 'arraybuffer';- xhr.onerror = reject;- xhr.onload = () => {- const response = xhr.response || xhr.responseText;- if (response) {- resolve(response);- } else {- reject('loadFileContentPromise error');- }- };- xhr.send();- });+ return new Promise((resolve, reject) => {+ const xhr: any = new XMLHttpRequest();+ xhr.open('GET', fullPath, true);+ xhr.responseType = type || 'arraybuffer';+ xhr.onerror = reject;+ xhr.onload = () => {+ const response = xhr.response || xhr.responseText;+ if (response) {+ resolve(response);+ } else {+ reject('loadFileContentPromise error');+ }+ };+ xhr.send();+ });}diff --git a/app/services/webdav-io.ts b/app/services/webdav-io.tsindex ba6fdd3ac..98595284b 100644--- a/app/services/webdav-io.ts+++ b/app/services/webdav-io.ts@@ -18,273 +18,272 @@import nl from 'js-webdav-client';import {- extractParentDirectoryPath,- normalizePath,- getMetaFileLocationForDir+ extractParentDirectoryPath,+ normalizePath,+ getMetaFileLocationForDir} from '../utils/paths';import AppConfig from '../config';+import { FileSystemEntry } from './utils-io';export default class WebDAVIO {- davClient: any;-- constructor() {- console.log('Loading web.js..' + nl);- // exact copy of getAjax with timeout added- nl.sara.webdav.Client.prototype.getAjax = (- method,- url,- callback,- headers- ) => {- const /** @type XMLHttpRequest */ ajax =- typeof Components !== 'undefined' &&- typeof Components.classes !== 'undefined'- ? Components.classes[- '@mozilla.org/xmlextras/xmlhttprequest;1'- ].createInstance(Components.interfaces.nsIXMLHttpRequest)- : new XMLHttpRequest();- if (this._username !== null) {- ajax.open(method, url, true, this._username, this._password);- } else {- ajax.open(method, url, true);- }- ajax.onreadystatechange = () => {- nl.sara.webdav.Client.ajaxHandler(ajax, callback);- };-- ajax.ontimeout = () => {- ajax.readyState = 4;- ajax.ajax.status = -1;- nl.sara.webdav.Client.ajaxHandler(ajax, callback);- };-- if (headers === undefined) {- headers = {};- }- for (const header in this._headers) {- if (headers[header] === undefined) {- ajax.setRequestHeader(header, this._headers[header]);- }- }- for (const header in headers) {- ajax.setRequestHeader(header, headers[header]);- }- return ajax;- };-- console.log('Connecting webdav...');- let useHTTPS = false;- if (location.href.indexOf('https') === 0) {- useHTTPS = true;- }- this.davClient = new nl.sara.webdav.Client(- location.hostname,- useHTTPS,- location.port- );- }-- isWorkerAvailable = (): boolean => false;-- getDevicePaths = (): Object => {- const paths = {- Home: '/files/'- };- return paths;- };-- getAppDataPath = (): string =>- // TODO- 'SOMEPATH_FIX_ME';-- getUserHomePath = (): string => '/';-- getNameForPath = (entrypath: string, separator = '/') => {- let path = entrypath;- if (path.lastIndexOf(separator) === path.length - 1) {- path = path.substring(0, path.lastIndexOf(separator));- }- const encodedName = path.substring(- path.lastIndexOf(separator) + 1,- path.length- );- return decodeURI(encodedName);- };-- isDirectory = (path: string): boolean =>- // TODO find a better solution- path.lastIndexOf('/') === path.length - 1;-- checkStatusCode = (code: number): boolean => {- const status = parseInt(code / 100);- if (status === 2) {- return true;- }- return false;- };-- // TODO- handleStartParameters = (): void => {- /* let filePath = getURLParameter('open');+ davClient: any;+ _username: string;+ _password: string;+ _headers: any;++ constructor() {+ console.log('Loading web.js..' + nl);+ // exact copy of getAjax with timeout added+ nl.sara.webdav.Client.prototype.getAjax = (+ method,+ url,+ callback,+ headers+ ) => {+ const ajax: any = new XMLHttpRequest();+ if (this._username !== null) {+ ajax.open(method, url, true, this._username, this._password);+ } else {+ ajax.open(method, url, true);+ }+ ajax.onreadystatechange = () => {+ nl.sara.webdav.Client.ajaxHandler(ajax, callback);+ };++ ajax.ontimeout = () => {+ ajax.readyState = 4;+ ajax.ajax.status = -1;+ nl.sara.webdav.Client.ajaxHandler(ajax, callback);+ };++ if (headers === undefined) {+ headers = {};+ }+ for (const header in this._headers) {+ if (headers[header] === undefined) {+ ajax.setRequestHeader(header, this._headers[header]);+ }+ }+ for (const header in headers) {+ ajax.setRequestHeader(header, headers[header]);+ }+ return ajax;+ };++ console.log('Connecting webdav...');+ let useHTTPS = false;+ if (location.href.indexOf('https') === 0) {+ useHTTPS = true;+ }+ this.davClient = new nl.sara.webdav.Client(+ location.hostname,+ useHTTPS,+ // @ts-ignore+ location.port+ );+ }++ isWorkerAvailable = (): boolean => false;++ getDevicePaths = (): Object => {+ const paths = {+ Home: '/files/'+ };+ return paths;+ };++ getAppDataPath = (): string =>+ // TODO+ 'SOMEPATH_FIX_ME';++ getUserHomePath = (): string => '/';++ getNameForPath = (entrypath: string, separator = '/') => {+ let path = entrypath;+ if (path.lastIndexOf(separator) === path.length - 1) {+ path = path.substring(0, path.lastIndexOf(separator));+ }+ const encodedName = path.substring(+ path.lastIndexOf(separator) + 1,+ path.length+ );+ return decodeURI(encodedName);+ };++ isDirectory = (path: string): boolean =>+ // TODO find a better solution+ path.lastIndexOf('/') === path.length - 1;++ checkStatusCode = (code: number): boolean => {+ const status = parseInt('' + code / 100);+ if (status === 2) {+ return true;+ }+ return false;+ };++ // TODO+ handleStartParameters = (): void => {+ /* let filePath = getURLParameter('open');if (filePath && filePath.length > 0) {filePath = decodeURIComponent(filePath);console.log('Opening file in browser: ' + filePath);FileOpener.openFileOnStartup(filePath);} */- };-- /**- * Creates recursively a tree structure for a given directory path- * @param {string} dirPath - the full path of the directory for which the tree will be generated- */- createDirectoryTree = (dirPath: string) => {- console.log('Creating directory index for: ' + dirPath);- const directoyTree = [];- return directoyTree;- };-- listMetaDirectoryPromise = async (path: string): Promise<Array<any>> => {- const promise = new Promise(resolve => {- const entries = [];- const metaDirPath =- normalizePath(path) +- AppConfig.dirSeparator +- AppConfig.metaFolder +- AppConfig.dirSeparator;- const davSuccess = (status, data) => {- const dirList = data._responses;- for (const dir in dirList) {- const entryPath = dirList[dir].href;- if (entryPath.toLowerCase() === metaDirPath.toLowerCase()) {- console.log('Skipping current folder');- } else {- const fileName = this.getNameForPath(entryPath);-- const entry = {};- entry.name = fileName;- entry.path = decodeURI(entryPath);- entry.isFile = true;- entries.push(entry);- }- }- return resolve(entries);- };-- this.davClient.propfind(- metaDirPath,- davSuccess,- 1 // 1 , davClient.INFINITY- );- return resolve(entries);- });- const result = await promise; // this.listDirectoryPromise(normalizePath(path) + AppConfig.dirSeparator + AppConfig.metaFolder + AppConfig.dirSeparator, true);- return result;- };-- /**- * Creates a list with containing the files and the sub directories of a given directory- */- listDirectoryPromise = (- directoryPath: string,- lite: boolean = false- ): Promise<Array<Object>> =>- new Promise(async (resolve, reject) => {- let enhancedEntries;- let dirPath = directoryPath.split('//').join('/');-- const metaContent = !lite- ? await this.listMetaDirectoryPromise(directoryPath)- : [];-- // let containsMetaFolder = false;- const davSuccess = (status, data) => {- console.log('Dirlist Status: ' + status);- if (!this.checkStatusCode(status)) {- console.warn('Listing directory ' + dirPath + ' failed ' + status);- reject('Listing directory ' + dirPath + ' failed ' + status);- }- const dirList = data._responses;- let fileName;- let isDir;- let filesize;- let lmdt;- let path;- let eentry;-- enhancedEntries = [];- const metaPromises = [];- for (const entry in dirList) {- // if (Object.prototype.hasOwnProperty.call(dirList, entry)) {- path = dirList[entry].href;- if (dirPath.toLowerCase() === path.toLowerCase()) {- console.log('Skipping current folder');- } else {- isDir = false;- filesize = undefined;- lmdt = undefined;- // console.log(dirList[entry]._namespaces['DAV:']);- if (this.isFile(dirList[entry]._namespaces['DAV:'])) {- filesize =- dirList[entry]._namespaces['DAV:'].getcontentlength._xmlvalue[0]- .data;- lmdt =- data._responses[entry]._namespaces['DAV:'].getlastmodified- ._xmlvalue[0].data;- } else {- isDir = true;- // const metaFilePath = getMetaFileLocationForFile(path, '/');- }- fileName = this.getNameForPath(path);-- eentry = {};- eentry.name = fileName;- eentry.path = decodeURI(path);- eentry.tags = [];- eentry.thumbPath = isDir- ? eentry.path +- AppConfig.metaFolder +- '/' +- AppConfig.folderThumbFile- : '';- // eentry.meta = {};- eentry.isFile = !isDir;- eentry.size = filesize;- eentry.lmdt = Date.parse(lmdt);- // const x = getMetaFileLocationForFile(eentry.path);-- if (!lite) {- if (isDir) {- // Read tsm.json from subfolders- const pathMetaFile = getMetaFileLocationForDir(eentry.path);- metaPromises.push(this.getEntryMeta(eentry, pathMetaFile));- } else {- const metaFileAvailable = metaContent.find(- obj => obj.name === fileName + AppConfig.metaFileExt- );- if (metaFileAvailable) {- metaPromises.push(- this.getEntryMeta(eentry, metaFileAvailable.path)- );- }-- // Finding if file thumbnail available- const metaThumbAvailable = metaContent.find(- obj => obj.name === fileName + AppConfig.thumbFileExt- );- if (metaThumbAvailable) {- eentry.thumbPath = metaThumbAvailable.path;- }- }- }-- enhancedEntries.push(eentry);- // }- }- }-- Promise.all(metaPromises)- .then(entriesMeta => {- /* entriesMeta.forEach((entryMeta) => {+ };++ /**+ * Creates recursively a tree structure for a given directory path+ * @param {string} dirPath - the full path of the directory for which the tree will be generated+ */+ createDirectoryTree = (dirPath: string) => {+ console.log('Creating directory index for: ' + dirPath);+ const directoyTree = [];+ return directoyTree;+ };++ listMetaDirectoryPromise = async (path: string): Promise<Array<any>> => {+ const promise: Promise<Array<any>> = new Promise(resolve => {+ const entries = [];+ const metaDirPath =+ normalizePath(path) ++ AppConfig.dirSeparator ++ AppConfig.metaFolder ++ AppConfig.dirSeparator;+ const davSuccess = (status, data) => {+ const dirList = data._responses;+ for (const dir in dirList) {+ const entryPath = dirList[dir].href;+ if (entryPath.toLowerCase() === metaDirPath.toLowerCase()) {+ console.log('Skipping current folder');+ } else {+ const fileName = this.getNameForPath(entryPath);++ const entry: any = {};+ entry.name = fileName;+ entry.path = decodeURI(entryPath);+ entry.isFile = true;+ entries.push(entry);+ }+ }+ return resolve(entries);+ };++ this.davClient.propfind(+ metaDirPath,+ davSuccess,+ 1 // 1 , davClient.INFINITY+ );+ return resolve(entries);+ });+ const result = await promise; // this.listDirectoryPromise(normalizePath(path) + AppConfig.dirSeparator + AppConfig.metaFolder + AppConfig.dirSeparator, true);+ return result;+ };++ /**+ * Creates a list with containing the files and the sub directories of a given directory+ */+ listDirectoryPromise = (+ directoryPath: string,+ lite: boolean = false+ ): Promise<Array<Object>> =>+ new Promise(async (resolve, reject) => {+ let enhancedEntries;+ let dirPath = directoryPath.split('//').join('/');++ const metaContent = !lite+ ? await this.listMetaDirectoryPromise(directoryPath)+ : [];++ // let containsMetaFolder = false;+ const davSuccess = (status, data) => {+ console.log('Dirlist Status: ' + status);+ if (!this.checkStatusCode(status)) {+ console.warn('Listing directory ' + dirPath + ' failed ' + status);+ reject('Listing directory ' + dirPath + ' failed ' + status);+ }+ const dirList = data._responses;+ let fileName;+ let isDir;+ let filesize;+ let lmdt;+ let path;+ let eentry;++ enhancedEntries = [];+ const metaPromises = [];+ for (const entry in dirList) {+ // if (Object.prototype.hasOwnProperty.call(dirList, entry)) {+ path = dirList[entry].href;+ if (dirPath.toLowerCase() === path.toLowerCase()) {+ console.log('Skipping current folder');+ } else {+ isDir = false;+ filesize = undefined;+ lmdt = undefined;+ // console.log(dirList[entry]._namespaces['DAV:']);+ if (this.isFile(dirList[entry]._namespaces['DAV:'])) {+ filesize =+ dirList[entry]._namespaces['DAV:'].getcontentlength._xmlvalue[0]+ .data;+ lmdt =+ data._responses[entry]._namespaces['DAV:'].getlastmodified+ ._xmlvalue[0].data;+ } else {+ isDir = true;+ // const metaFilePath = getMetaFileLocationForFile(path, '/');+ }+ fileName = this.getNameForPath(path);++ eentry = {};+ eentry.name = fileName;+ eentry.path = decodeURI(path);+ eentry.tags = [];+ eentry.thumbPath = isDir+ ? eentry.path ++ AppConfig.metaFolder ++ '/' ++ AppConfig.folderThumbFile+ : '';+ // eentry.meta = {};+ eentry.isFile = !isDir;+ eentry.size = filesize;+ eentry.lmdt = Date.parse(lmdt);+ // const x = getMetaFileLocationForFile(eentry.path);++ if (!lite) {+ if (isDir) {+ // Read tsm.json from subfolders+ const pathMetaFile = getMetaFileLocationForDir(eentry.path);+ metaPromises.push(this.getEntryMeta(eentry, pathMetaFile));+ } else {+ const metaFileAvailable = metaContent.find(+ obj => obj.name === fileName + AppConfig.metaFileExt+ );+ if (metaFileAvailable) {+ metaPromises.push(+ this.getEntryMeta(eentry, metaFileAvailable.path)+ );+ }++ // Finding if file thumbnail available+ const metaThumbAvailable = metaContent.find(+ obj => obj.name === fileName + AppConfig.thumbFileExt+ );+ if (metaThumbAvailable) {+ eentry.thumbPath = metaThumbAvailable.path;+ }+ }+ }++ enhancedEntries.push(eentry);+ // }+ }+ }++ Promise.all(metaPromises)+ .then(entriesMeta => {+ /* entriesMeta.forEach((entryMeta) => {enhancedEntries.some((enhancedEntry) => {if (enhancedEntry.path === entryMeta.path) {// eslint-disable-next-line no-param-reassign@@ -294,430 +293,435 @@ export default class WebDAVIO {return false;});}); */- resolve(enhancedEntries);- return true;- })- .catch(() => {- resolve(enhancedEntries);- });- };- if (dirPath.substring(dirPath.length - 1) !== '/') {- dirPath += '/';- }- dirPath = encodeURI(dirPath);-- this.davClient.propfind(- dirPath,- davSuccess,- 1 // 1 , davClient.INFINITY- );- });-- isFile = (dav: Object): boolean =>- !(- typeof dav.getcontentlength === 'undefined' ||- dav.getcontentlength._xmlvalue.length === 0 ||- (dav.resourcetype._xmlvalue.length === 1 &&- dav.resourcetype._xmlvalue[0].localName === 'collection')- );-- getEntryMeta = (eentry: Object, metaPath: string): Promise<Object> => {- return new Promise(resolve => {- if (eentry.isFile) {- this.loadTextFilePromise(metaPath)- .then(result => {- // eslint-disable-next-line no-param-reassign- eentry.meta = JSON.parse(result.trim());- return resolve(eentry);- // resolve({- // ...eentry,- // meta: JSON.parse(result.trim())- // });- })- .catch(err => {- console.log(- 'No meta file for folder found: ' + eentry.path + ' - ' + err- );- resolve(eentry);- });- } else if (!eentry.path.endsWith(AppConfig.metaFolder + '/')) {- // Skip the /.ts folder- this.loadTextFilePromise(metaPath)- .then(result => {- // eslint-disable-next-line no-param-reassign- eentry.meta = JSON.parse(result.trim());- return resolve(eentry);- // resolve({- // ...eentry,- // meta: JSON.parse(result.trim())- // });- })- .catch(err => {- console.log(- 'No meta file for folder found: ' + eentry.path + ' - ' + err- );- resolve(eentry);- });- }- resolve(eentry);- });- };-- /**- * Finds out the properties of a file or directory such last modification date or file size- */- getPropertiesPromise = (filePath: string): Promise<Object> =>- new Promise((resolve, reject) => {- this.davClient.propfind(- encodeURI(filePath),- (status, data) => {- console.log(- 'Properties Status / Content: ' +- status +- ' / ' +- JSON.stringify(data._responses)- );- const fileProperties = {};- if (this.checkStatusCode(status)) {- for (const entry in data._responses) {- fileProperties.path = filePath;- fileProperties.name = this.getNameForPath(filePath);- const isFile = this.isFile(- data._responses[entry]._namespaces['DAV:']- );- fileProperties.isFile = isFile;- if (isFile) {- fileProperties.size =- data._responses[entry]._namespaces[- 'DAV:'- ].getcontentlength._xmlvalue[0].data;- fileProperties.lmdt = Date.parse(- data._responses[entry]._namespaces['DAV:'].getlastmodified- ._xmlvalue[0].data- );- }- }- resolve(fileProperties);- } else {- resolve(false);- // reject('getFileProperties ' + filePath + ' failed ' + status);- }- },- 1- );- });-- /**- * Load the content of a text file- */- loadTextFilePromise = (filePath: string) =>- this.getFileContentPromise(filePath, 'text');-- /**- * Gets the content of file, useful for binary files- */- getFileContentPromise = (filePath: string, type): Promise<Object> => {- console.log('getFileContent file: ' + filePath);- return new Promise((resolve, reject) => {- const ajax = this.davClient.getAjax('GET', encodeURI(filePath));- ajax.onreadystatechange = null;- ajax.responseType = type || 'arraybuffer';- ajax.onerror = reject;-- ajax.onload = () => {- const response = ajax.response || ajax.responseText;- if (this.checkStatusCode(ajax.status)) {- resolve(response);- } else {- reject('getFileContentPromise ajax error');- }- };- ajax.send();- });- };-- /**- * Persists a given content(binary supported) to a specified filepath- */- saveFilePromise = (- filePath: string,- content: string,- overWrite: boolean,- mode: string- ): Promise<Object> =>- new Promise((resolve, reject) => {- let isNewFile = false;- this.davClient.propfind(- encodeURI(filePath),- (status, data) => {- console.log(- 'Check file exists: Status / Content: ' + status + ' / ' + data- );- if (parseInt(status) === 404) {- isNewFile = true;- }- if (isNewFile || overWrite === true || mode === 'text') {- this.davClient.put(- encodeURI(filePath),- (status, data, headers) => {- console.log(- 'Creating File Status/Content/Headers: ' +- status +- ' / ' +- data +- ' / ' +- headers- );- if (this.checkStatusCode(status)) {- resolve(isNewFile);- } else {- reject('saveFilePromise: ' + filePath + ' failed ' + status);- }- },- content,- 'application/octet-stream'- );- } else {- reject('File Already Exists.');- }- },- 1- );- });-- /**- * Persists a given text content to a specified filepath- */- saveTextFilePromise(- filePath: string,- content: string,- overWrite: boolean- ): Promise<Object> {- console.log('Saving text file: ' + filePath);- return this.saveFilePromise(filePath, content, overWrite, 'text');- }-- /**- * Persists a given binary content to a specified filepath- */- saveBinaryFilePromise(- filePath: string,- content: string,- overWrite: boolean- ): Promise<Object> {- console.log('Saving binary file: ' + filePath);- return this.saveFilePromise(filePath, content, overWrite);- }-- /**- * Creates a directory- */- createDirectoryPromise = (dirPath: string): Promise<Object> => {- console.log('Creating directory: ' + dirPath);- return new Promise((resolve, reject) => {- this.davClient.mkcol(encodeURI(dirPath), (status, data, headers) => {- console.log(- 'Directory Creation Status/Content/Headers: ' +- status +- ' / ' +- data +- ' / ' +- headers- );- if (this.checkStatusCode(status)) {- resolve(dirPath);- } else {- reject('createDirectory ' + dirPath + ' failed ' + status);- }- });- });- };-- /**- * Copies a given file to a specified location- */- copyFilePromise = (- filePath: string,- newFilePath: string- ): Promise<Object> => {- console.log('Copying file: ' + filePath + ' to ' + newFilePath);- return new Promise((resolve, reject) => {- if (filePath.toLowerCase() === newFilePath.toLowerCase()) {- reject('Copying file failed, files have the same path');- } else {- this.davClient.copy(- encodeURI(filePath),- (status, data, headers) => {- console.log(- 'Copy File Status/Content/Headers: ' +- status +- ' / ' +- data +- ' / ' +- headers- );- if (this.checkStatusCode(status)) {- resolve(filePath, newFilePath);- } else {- reject('copyFile ' + filePath + ' failed ' + status);- }- },- encodeURI(newFilePath),- this.davClient.FAIL_ON_OVERWRITE- );- }- });- };-- /**- * Renames a given file- */- renameFilePromise = (- filePath: string,- newFilePath: string- ): Promise<Object> => {- console.log('Renaming file: ' + filePath + ' to ' + newFilePath);- return new Promise((resolve, reject) => {- if (filePath === newFilePath) {- reject('Renaming file failed, files have the same path');- } else {- this.davClient.move(- encodeURI(filePath),- (status, data, headers) => {- console.log(- 'Rename File Status/Content/Headers: ' +- status +- ' / ' +- data +- ' / ' +- headers- );- if (this.checkStatusCode(status)) {- resolve([filePath, newFilePath]);- } else {- reject('rename: ' + filePath + ' failed ' + status);- }- },- encodeURI(newFilePath),- this.davClient.FAIL_ON_OVERWRITE- );- }- });- };-- /**- * Rename a directory- */- renameDirectoryPromise = (- dirPath: string,- newDirectoryPath: string- ): Promise<Object> => {- const newDirPath =- extractParentDirectoryPath(dirPath) + '/' + newDirectoryPath;- console.log('Renaming directory: ' + dirPath + ' to ' + newDirPath);- return new Promise((resolve, reject) => {- if (dirPath === newDirPath) {- reject('Renaming directory failed, directories have the same path');- } else {- this.davClient.move(- encodeURI(dirPath),- (status, data, headers) => {- console.log(- 'Rename Directory Status/Content/Headers: ' +- status +- ' / ' +- data +- ' / ' +- headers- );- if (this.checkStatusCode(status)) {- resolve(newDirPath);- } else {- reject('rename: ' + dirPath + ' failed ' + status);- }- },- encodeURI(newDirPath),- this.davClient.FAIL_ON_OVERWRITE- );- }- });- };-- /**- * Delete a specified file- */- deleteFilePromise = (path: string): Promise<Object> =>- this.deleteDirectoryPromise(path);-- /**- * Delete a specified directory, the directory should be empty, if the trash can functionality is not enabled- */- deleteDirectoryPromise = (path: string): Promise<Object> =>- new Promise((resolve, reject) => {- this.davClient.remove(encodeURI(path), (status, data, headers) => {- console.log(- 'Directory/File Deletion Status/Content/Headers: ' +- status +- ' / ' +- data +- ' / ' +- headers- );- if (this.checkStatusCode(status)) {- resolve(path);- } else {- reject('delete ' + path + ' failed ' + status);- }- });- });-- /**- * Choosing directory- */- selectDirectoryDialog = () => {- console.log('Selecting directory is not implemented in the web version');- };-- /**- * Choosing file- */- selectFileDialog = () => {- console.log('Selecting file not relevant for the web version');- };-- /**- * Opens directory in new tab / window- */- openDirectory = (dirPath: string) => {- console.log(- 'Opening directory ' + dirPath + ' not possible for the web version.'- );- };-- /**- * Opens directory in new tab / window, selecting the file- */- showInFileManager = (filePath: string) => {- console.log(- 'Showing item ' + filePath + ' not possible for the web version.'- );- };-- /**- * Open the file url in a new tab / window- */- openFile = (filePath: string): void => {- window.open(filePath, '_blank');- };-- openUrl = (url: string): void => {- window.open(url, '_blank');- };-- /**- * Places the application window on top of the other windows- */- focusWindow = (): void => {- window.focus();- };+ resolve(enhancedEntries);+ return true;+ })+ .catch(() => {+ resolve(enhancedEntries);+ });+ };+ if (dirPath.substring(dirPath.length - 1) !== '/') {+ dirPath += '/';+ }+ dirPath = encodeURI(dirPath);++ this.davClient.propfind(+ dirPath,+ davSuccess,+ 1 // 1 , davClient.INFINITY+ );+ });++ isFile = (dav: any): boolean =>+ !(+ typeof dav.getcontentlength === 'undefined' ||+ dav.getcontentlength._xmlvalue.length === 0 ||+ (dav.resourcetype._xmlvalue.length === 1 &&+ dav.resourcetype._xmlvalue[0].localName === 'collection')+ );++ getEntryMeta = (+ eentry: FileSystemEntry,+ metaPath: string+ ): Promise<Object> => {+ return new Promise(resolve => {+ if (eentry.isFile) {+ this.loadTextFilePromise(metaPath)+ .then(result => {+ // eslint-disable-next-line no-param-reassign+ eentry.meta = JSON.parse(result.trim());+ return resolve(eentry);+ // resolve({+ // ...eentry,+ // meta: JSON.parse(result.trim())+ // });+ })+ .catch(err => {+ console.log(+ 'No meta file for folder found: ' + eentry.path + ' - ' + err+ );+ resolve(eentry);+ });+ } else if (!eentry.path.endsWith(AppConfig.metaFolder + '/')) {+ // Skip the /.ts folder+ this.loadTextFilePromise(metaPath)+ .then(result => {+ // eslint-disable-next-line no-param-reassign+ eentry.meta = JSON.parse(result.trim());+ return resolve(eentry);+ // resolve({+ // ...eentry,+ // meta: JSON.parse(result.trim())+ // });+ })+ .catch(err => {+ console.log(+ 'No meta file for folder found: ' + eentry.path + ' - ' + err+ );+ resolve(eentry);+ });+ }+ resolve(eentry);+ });+ };++ /**+ * Finds out the properties of a file or directory such last modification date or file size+ */+ getPropertiesPromise = (filePath: string): Promise<Object> =>+ new Promise((resolve, reject) => {+ this.davClient.propfind(+ encodeURI(filePath),+ (status, data) => {+ console.log(+ 'Properties Status / Content: ' ++ status ++ ' / ' ++ JSON.stringify(data._responses)+ );+ const fileProperties: any = {};+ if (this.checkStatusCode(status)) {+ for (const entry in data._responses) {+ fileProperties.path = filePath;+ fileProperties.name = this.getNameForPath(filePath);+ const isFile = this.isFile(+ data._responses[entry]._namespaces['DAV:']+ );+ fileProperties.isFile = isFile;+ if (isFile) {+ fileProperties.size =+ data._responses[entry]._namespaces[+ 'DAV:'+ ].getcontentlength._xmlvalue[0].data;+ fileProperties.lmdt = Date.parse(+ data._responses[entry]._namespaces['DAV:'].getlastmodified+ ._xmlvalue[0].data+ );+ }+ }+ resolve(fileProperties);+ } else {+ resolve(false);+ // reject('getFileProperties ' + filePath + ' failed ' + status);+ }+ },+ 1+ );+ });++ /**+ * Load the content of a text file+ */+ loadTextFilePromise = (filePath: string): Promise<string> =>+ this.getFileContentPromise(filePath, 'text');++ /**+ * Gets the content of file, useful for binary files+ */+ getFileContentPromise = (filePath: string, type): Promise<any> => {+ console.log('getFileContent file: ' + filePath);+ return new Promise((resolve, reject) => {+ const ajax = this.davClient.getAjax('GET', encodeURI(filePath));+ ajax.onreadystatechange = null;+ ajax.responseType = type || 'arraybuffer';+ ajax.onerror = reject;++ ajax.onload = () => {+ const response = ajax.response || ajax.responseText;+ if (this.checkStatusCode(ajax.status)) {+ resolve(response);+ } else {+ reject('getFileContentPromise ajax error');+ }+ };+ ajax.send();+ });+ };++ /**+ * Persists a given content(binary supported) to a specified filepath+ */+ saveFilePromise = (+ filePath: string,+ content: string,+ overWrite: boolean,+ mode?: string+ ): Promise<Object> =>+ new Promise((resolve, reject) => {+ let isNewFile = false;+ this.davClient.propfind(+ encodeURI(filePath),+ (status, data) => {+ console.log(+ 'Check file exists: Status / Content: ' + status + ' / ' + data+ );+ if (parseInt(status) === 404) {+ isNewFile = true;+ }+ if (isNewFile || overWrite === true || mode === 'text') {+ this.davClient.put(+ encodeURI(filePath),+ (status, data, headers) => {+ console.log(+ 'Creating File Status/Content/Headers: ' ++ status ++ ' / ' ++ data ++ ' / ' ++ headers+ );+ if (this.checkStatusCode(status)) {+ resolve(isNewFile);+ } else {+ reject('saveFilePromise: ' + filePath + ' failed ' + status);+ }+ },+ content,+ 'application/octet-stream'+ );+ } else {+ reject('File Already Exists.');+ }+ },+ 1+ );+ });++ /**+ * Persists a given text content to a specified filepath+ */+ saveTextFilePromise(+ filePath: string,+ content: string,+ overWrite: boolean+ ): Promise<Object> {+ console.log('Saving text file: ' + filePath);+ return this.saveFilePromise(filePath, content, overWrite, 'text');+ }++ /**+ * Persists a given binary content to a specified filepath+ */+ saveBinaryFilePromise(+ filePath: string,+ content: string,+ overWrite: boolean+ ): Promise<Object> {+ console.log('Saving binary file: ' + filePath);+ return this.saveFilePromise(filePath, content, overWrite);+ }++ /**+ * Creates a directory+ */+ createDirectoryPromise = (dirPath: string): Promise<Object> => {+ console.log('Creating directory: ' + dirPath);+ return new Promise((resolve, reject) => {+ this.davClient.mkcol(encodeURI(dirPath), (status, data, headers) => {+ console.log(+ 'Directory Creation Status/Content/Headers: ' ++ status ++ ' / ' ++ data ++ ' / ' ++ headers+ );+ if (this.checkStatusCode(status)) {+ resolve(dirPath);+ } else {+ reject('createDirectory ' + dirPath + ' failed ' + status);+ }+ });+ });+ };++ /**+ * Copies a given file to a specified location+ */+ copyFilePromise = (+ filePath: string,+ newFilePath: string+ ): Promise<Object> => {+ console.log('Copying file: ' + filePath + ' to ' + newFilePath);+ return new Promise(+ (resolve: (filePath: string, newFilePath: string) => void, reject) => {+ if (filePath.toLowerCase() === newFilePath.toLowerCase()) {+ reject('Copying file failed, files have the same path');+ } else {+ this.davClient.copy(+ encodeURI(filePath),+ (status, data, headers) => {+ console.log(+ 'Copy File Status/Content/Headers: ' ++ status ++ ' / ' ++ data ++ ' / ' ++ headers+ );+ if (this.checkStatusCode(status)) {+ resolve(filePath, newFilePath);+ } else {+ reject('copyFile ' + filePath + ' failed ' + status);+ }+ },+ encodeURI(newFilePath),+ this.davClient.FAIL_ON_OVERWRITE+ );+ }+ }+ );+ };++ /**+ * Renames a given file+ */+ renameFilePromise = (+ filePath: string,+ newFilePath: string+ ): Promise<Object> => {+ console.log('Renaming file: ' + filePath + ' to ' + newFilePath);+ return new Promise((resolve, reject) => {+ if (filePath === newFilePath) {+ reject('Renaming file failed, files have the same path');+ } else {+ this.davClient.move(+ encodeURI(filePath),+ (status, data, headers) => {+ console.log(+ 'Rename File Status/Content/Headers: ' ++ status ++ ' / ' ++ data ++ ' / ' ++ headers+ );+ if (this.checkStatusCode(status)) {+ resolve([filePath, newFilePath]);+ } else {+ reject('rename: ' + filePath + ' failed ' + status);+ }+ },+ encodeURI(newFilePath),+ this.davClient.FAIL_ON_OVERWRITE+ );+ }+ });+ };++ /**+ * Rename a directory+ */+ renameDirectoryPromise = (+ dirPath: string,+ newDirectoryPath: string+ ): Promise<Object> => {+ const newDirPath =+ extractParentDirectoryPath(dirPath) + '/' + newDirectoryPath;+ console.log('Renaming directory: ' + dirPath + ' to ' + newDirPath);+ return new Promise((resolve, reject) => {+ if (dirPath === newDirPath) {+ reject('Renaming directory failed, directories have the same path');+ } else {+ this.davClient.move(+ encodeURI(dirPath),+ (status, data, headers) => {+ console.log(+ 'Rename Directory Status/Content/Headers: ' ++ status ++ ' / ' ++ data ++ ' / ' ++ headers+ );+ if (this.checkStatusCode(status)) {+ resolve(newDirPath);+ } else {+ reject('rename: ' + dirPath + ' failed ' + status);+ }+ },+ encodeURI(newDirPath),+ this.davClient.FAIL_ON_OVERWRITE+ );+ }+ });+ };++ /**+ * Delete a specified file+ */+ deleteFilePromise = (path: string): Promise<Object> =>+ this.deleteDirectoryPromise(path);++ /**+ * Delete a specified directory, the directory should be empty, if the trash can functionality is not enabled+ */+ deleteDirectoryPromise = (path: string): Promise<Object> =>+ new Promise((resolve, reject) => {+ this.davClient.remove(encodeURI(path), (status, data, headers) => {+ console.log(+ 'Directory/File Deletion Status/Content/Headers: ' ++ status ++ ' / ' ++ data ++ ' / ' ++ headers+ );+ if (this.checkStatusCode(status)) {+ resolve(path);+ } else {+ reject('delete ' + path + ' failed ' + status);+ }+ });+ });++ /**+ * Choosing directory+ */+ selectDirectoryDialog = () => {+ console.log('Selecting directory is not implemented in the web version');+ };++ /**+ * Choosing file+ */+ selectFileDialog = () => {+ console.log('Selecting file not relevant for the web version');+ };++ /**+ * Opens directory in new tab / window+ */+ openDirectory = (dirPath: string) => {+ console.log(+ 'Opening directory ' + dirPath + ' not possible for the web version.'+ );+ };++ /**+ * Opens directory in new tab / window, selecting the file+ */+ showInFileManager = (filePath: string) => {+ console.log(+ 'Showing item ' + filePath + ' not possible for the web version.'+ );+ };++ /**+ * Open the file url in a new tab / window+ */+ openFile = (filePath: string): void => {+ window.open(filePath, '_blank');+ };++ openUrl = (url: string): void => {+ window.open(url, '_blank');+ };++ /**+ * Places the application window on top of the other windows+ */+ focusWindow = (): void => {+ window.focus();+ };}diff --git a/app/utils/misc.ts b/app/utils/misc.tsindex 421c4ed97..842ef7aae 100644--- a/app/utils/misc.ts+++ b/app/utils/misc.ts@@ -1,3 +1,4 @@+// @ts-nocheck/*** TagSpaces - universal file and folder organizer* Copyright (C) 2017-present TagSpaces UG (haftungsbeschraenkt)@@ -267,7 +268,7 @@ export function formatDateTime(date: string, includeTime: boolean) {/** Convert a date in the following format 20191204 or 20191204~124532 */export function formatDateTime4Tag(- date: string,+ date: string | Date,includeTime: boolean,includeMS?: boolean): string {diff --git a/app/utils/paths.ts b/app/utils/paths.tsindex 58577b0bd..690768466 100644--- a/app/utils/paths.ts+++ b/app/utils/paths.ts@@ -218,7 +218,7 @@ export function extractContainingDirectoryName(filePath: string) {);}-export function extractTitle(entryPath: string, isDirectory?: boolean = false) {+export function extractTitle(entryPath: string, isDirectory: boolean = false) {let title;if (isDirectory) {title = extractDirectoryName(entryPath);