Skip to content

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

removing unneeded library, applying prettier

Ilian Sapundshiev03c783451970
diff --git a/app/components/dialogs/ColorPickerDialog.tsx b/app/components/dialogs/ColorPickerDialog.tsx
index eec1341da..7fc7e276b 100644
--- a/app/components/dialogs/ColorPickerDialog.tsx
+++ b/app/components/dialogs/ColorPickerDialog.tsx
@@ -27,105 +27,105 @@ import { SketchPicker } from 'react-color';
import i18n from '-/services/i18n';
const presetColors = [
- '#ffffff',
- '#000000',
- '#ac725e',
- '#d06b64',
- '#f83a22',
- '#fa573c',
- '#ff7537',
- '#ffad46',
- '#42d692',
- '#008000',
- '#7bd148',
- '#fad165',
- '#FFCC24',
- '#92e1c0',
- '#9fe1e7',
- '#9fc6e7',
- '#4986e7',
- '#9a9cff',
- '#b99aff',
- '#c2c2c2',
- '#cabdbf',
- '#cca6ac',
- '#f691b2',
- '#cd74e6',
- '#a47ae2'
+ '#ffffff',
+ '#000000',
+ '#ac725e',
+ '#d06b64',
+ '#f83a22',
+ '#fa573c',
+ '#ff7537',
+ '#ffad46',
+ '#42d692',
+ '#008000',
+ '#7bd148',
+ '#fad165',
+ '#FFCC24',
+ '#92e1c0',
+ '#9fe1e7',
+ '#9fc6e7',
+ '#4986e7',
+ '#9a9cff',
+ '#b99aff',
+ '#c2c2c2',
+ '#cabdbf',
+ '#cca6ac',
+ '#f691b2',
+ '#cd74e6',
+ '#a47ae2'
];
interface Props {
- classes: any;
- open: boolean;
- color: string;
- setColor: (color: string) => void;
- presetColors?: Array<string>;
- onClose: () => void;
+ classes: any;
+ open: boolean;
+ color: string;
+ setColor: (color: string) => void;
+ presetColors?: Array<string>;
+ onClose: () => void;
}
const styles = {
- noBorder: {
- padding: '0 !important',
- boxShadow: 'none !important',
- backgroundColor: 'transparent !important'
- }
+ noBorder: {
+ padding: '0 !important',
+ boxShadow: 'none !important',
+ backgroundColor: 'transparent !important'
+ }
};
const ColorPickerDialog = (props: Props) => {
- const [color, setColor] = useState(undefined);
- const [colorHex, setColorHex] = useState(undefined);
- const { open = false, onClose } = props;
+ const [color, setColor] = useState(undefined);
+ const [colorHex, setColorHex] = useState(undefined);
+ const { open = false, onClose } = props;
- function onConfirm() {
- if (color && colorHex) {
- const hexAlphaColor = colorHex + Math.round(color.a * 255).toString(16);
- props.setColor(hexAlphaColor);
- }
- props.onClose();
- }
+ function onConfirm() {
+ if (color && colorHex) {
+ const hexAlphaColor = colorHex + Math.round(color.a * 255).toString(16);
+ props.setColor(hexAlphaColor);
+ }
+ props.onClose();
+ }
- function handleChangeComplete(newColor: any) {
- setColor(newColor.rgb);
- setColorHex(newColor.hex);
- }
+ function handleChangeComplete(newColor: any) {
+ setColor(newColor.rgb);
+ setColorHex(newColor.hex);
+ }
- return (
- <Dialog open={open} onClose={onClose} keepMounted scroll="paper">
- <DialogTitle data-tid="colorPickerDialogTitle">
- {i18n.t('core:colorPickerDialogTitle')}
- </DialogTitle>
- <DialogContent
- style={{
- marginLeft: 'auto',
- marginRight: 'auto'
- }}
- >
- <SketchPicker
- className={props.classes.noBorder}
- name="color"
- presetColors={props.presetColors ? props.presetColors : presetColors}
- color={color || props.color}
- onChangeComplete={handleChangeComplete}
- />
- </DialogContent>
- <DialogActions>
- <Button
- data-tid="colorPickerCloseDialog"
- onClick={props.onClose}
- color="primary"
- >
- {i18n.t('core:cancel')}
- </Button>
- <Button
- onClick={onConfirm}
- data-tid="colorPickerConfirm"
- color="primary"
- >
- {i18n.t('core:ok')}
- </Button>
- </DialogActions>
- </Dialog>
- );
+ return (
+ <Dialog open={open} onClose={onClose} keepMounted scroll="paper">
+ <DialogTitle data-tid="colorPickerDialogTitle">
+ {i18n.t('core:colorPickerDialogTitle')}
+ </DialogTitle>
+ <DialogContent
+ style={{
+ marginLeft: 'auto',
+ marginRight: 'auto'
+ }}
+ >
+ <SketchPicker
+ className={props.classes.noBorder}
+ name="color"
+ presetColors={props.presetColors ? props.presetColors : presetColors}
+ color={color || props.color}
+ onChangeComplete={handleChangeComplete}
+ />
+ </DialogContent>
+ <DialogActions>
+ <Button
+ data-tid="colorPickerCloseDialog"
+ onClick={props.onClose}
+ color="primary"
+ >
+ {i18n.t('core:cancel')}
+ </Button>
+ <Button
+ onClick={onConfirm}
+ data-tid="colorPickerConfirm"
+ color="primary"
+ >
+ {i18n.t('core:ok')}
+ </Button>
+ </DialogActions>
+ </Dialog>
+ );
};
export default withStyles(styles)(ColorPickerDialog);
diff --git a/app/components/dialogs/Dialogs.css.tsx b/app/components/dialogs/Dialogs.css.tsx
index 80acd16ee..eb2cee96f 100644
--- a/app/components/dialogs/Dialogs.css.tsx
+++ b/app/components/dialogs/Dialogs.css.tsx
@@ -17,11 +17,11 @@
*/
export default (theme: any) => ({
- panel: {
- height: '100%',
- maxHeight: '100%',
- padding: 5,
- overflowY: 'hidden',
- backgroundColor: theme.palette.background.default
- }
+ panel: {
+ height: '100%',
+ maxHeight: '100%',
+ padding: 5,
+ overflowY: 'hidden',
+ backgroundColor: theme.palette.background.default
+ }
});
diff --git a/app/components/dialogs/EditEntryTagDialog.tsx b/app/components/dialogs/EditEntryTagDialog.tsx
index 3b78790ea..77b0e0daf 100644
--- a/app/components/dialogs/EditEntryTagDialog.tsx
+++ b/app/components/dialogs/EditEntryTagDialog.tsx
@@ -34,185 +34,183 @@ import { isPlusCode } from '-/utils/misc';
import { Tag } from '-/reducers/taglibrary';
import { Pro } from '-/pro';
import { getSelectedTag } from '-/reducers/app';
-import TaggingActions, {
- defaultTagLocation
-} from '-/reducers/tagging-actions';
+import TaggingActions, { defaultTagLocation } from '-/reducers/tagging-actions';
import { isDateTimeTag } from '-/utils/dates';
const styles = () => ({
- root: {
- minWidth: 400,
- height: '100%',
- marginBottom: 30
- }
+ root: {
+ minWidth: 400,
+ height: '100%',
+ marginBottom: 30
+ }
});
interface Props {
- classes: any;
- open: boolean;
- fullScreen: boolean;
- onClose: () => void;
- editTagForEntry: (path: string, tag: Tag, title: string) => void;
- currentEntryPath: string;
- selectedTag: Tag;
+ classes: any;
+ open: boolean;
+ fullScreen: boolean;
+ onClose: () => void;
+ editTagForEntry: (path: string, tag: Tag, title: string) => void;
+ currentEntryPath: string;
+ selectedTag: Tag;
}
const GeoTagEditor = Pro && Pro.UI ? Pro.UI.GeoTagEditor : React.Fragment;
const DateTagEditor = Pro && Pro.UI ? Pro.UI.DateTagEditor : React.Fragment;
const EditEntryTagDialog = (props: Props) => {
- const [disableConfirmButton, setDisableConfirmButton] = useState(true);
- const [errorTag, setErrorTag] = useState(false);
- const [title, setTitle] = useState(
- props.selectedTag && props.selectedTag.title
- );
- const { onClose, open, fullScreen } = props;
-
- useEffect(() => {
- handleValidation();
- });
-
- function handleValidation() {
- const tagCheck = RegExp(/^[^\#\/\\ \[\]]{1,}$/);
- if (title && tagCheck.test(title)) {
- setErrorTag(false);
- setDisableConfirmButton(false);
- } else {
- setErrorTag(true);
- setDisableConfirmButton(true);
- }
- }
-
- function onConfirm() {
- if (!disableConfirmButton) {
- props.editTagForEntry(props.currentEntryPath, props.selectedTag, title);
- setErrorTag(false);
- setDisableConfirmButton(true);
- props.onClose();
- }
- }
-
- function renderTitle() {
- return <DialogTitle>{i18n.t('core:tagProperties')}</DialogTitle>;
- }
-
- function renderContent() {
- const showGeoEditor = GeoTagEditor && isPlusCode(title);
- let showDatePeriodEditor = false;
- if (title.indexOf('-') > -1) {
- const a = title.split('-');
- if (a.length === 2) {
- for (let i = 0; i < a.length; i += 1) {
- if (isDateTimeTag(a[i])) {
- showDatePeriodEditor = true;
- } else {
- showDatePeriodEditor = false;
- break;
- }
- }
- }
- } else showDatePeriodEditor = isDateTimeTag(title);
- showDatePeriodEditor = DateTagEditor && showDatePeriodEditor;
-
- return (
- <DialogContent
- data-tid="editEntryTagDialog"
- className={props.classes.root}
- >
- <FormControl fullWidth={true} error={errorTag}>
- <TextField
- fullWidth={true}
- error={errorTag}
- margin="dense"
- name="title"
- autoFocus
- label={i18n.t('core:editTag')}
- onChange={event => {
- const target = event.target;
- setTitle(target.value);
- }}
- value={title}
- data-tid="editTagEntryDialog_input"
- />
- {errorTag && (
- <FormHelperText>{i18n.t('core:tagTitleHelper')}</FormHelperText>
- )}
- </FormControl>
- {showGeoEditor && (
- <GeoTagEditor
- key={title}
- geoTag={title}
- onChange={setTitle}
- zoom={title === defaultTagLocation ? 2 : undefined}
- />
- )}
- {showDatePeriodEditor && (
- <DateTagEditor
- key={title}
- datePeriodTag={title}
- onChange={setTitle}
- />
- )}
- </DialogContent>
- );
- }
-
- function renderActions() {
- return (
- <DialogActions>
- <Button
- data-tid="closeEditTagEntryDialog"
- onClick={props.onClose}
- color="primary"
- >
- {i18n.t('core:cancel')}
- </Button>
- <Button
- disabled={disableConfirmButton}
- onClick={onConfirm}
- data-tid="confirmEditTagEntryDialog"
- color="primary"
- >
- {i18n.t('core:ok')}
- </Button>
- </DialogActions>
- );
- }
-
- return (
- <Dialog
- open={open}
- fullScreen={fullScreen}
- onClose={onClose}
- // onEnterKey={(event) => onEnterKeyHandler(event, onConfirm)}
- >
- {renderTitle()}
- {renderContent()}
- {renderActions()}
- </Dialog>
- );
+ const [disableConfirmButton, setDisableConfirmButton] = useState(true);
+ const [errorTag, setErrorTag] = useState(false);
+ const [title, setTitle] = useState(
+ props.selectedTag && props.selectedTag.title
+ );
+ const { onClose, open, fullScreen } = props;
+
+ useEffect(() => {
+ handleValidation();
+ });
+
+ function handleValidation() {
+ const tagCheck = RegExp(/^[^\#\/\\ \[\]]{1,}$/);
+ if (title && tagCheck.test(title)) {
+ setErrorTag(false);
+ setDisableConfirmButton(false);
+ } else {
+ setErrorTag(true);
+ setDisableConfirmButton(true);
+ }
+ }
+
+ function onConfirm() {
+ if (!disableConfirmButton) {
+ props.editTagForEntry(props.currentEntryPath, props.selectedTag, title);
+ setErrorTag(false);
+ setDisableConfirmButton(true);
+ props.onClose();
+ }
+ }
+
+ function renderTitle() {
+ return <DialogTitle>{i18n.t('core:tagProperties')}</DialogTitle>;
+ }
+
+ function renderContent() {
+ const showGeoEditor = GeoTagEditor && isPlusCode(title);
+ let showDatePeriodEditor = false;
+ if (title.indexOf('-') > -1) {
+ const a = title.split('-');
+ if (a.length === 2) {
+ for (let i = 0; i < a.length; i += 1) {
+ if (isDateTimeTag(a[i])) {
+ showDatePeriodEditor = true;
+ } else {
+ showDatePeriodEditor = false;
+ break;
+ }
+ }
+ }
+ } else showDatePeriodEditor = isDateTimeTag(title);
+ showDatePeriodEditor = DateTagEditor && showDatePeriodEditor;
+
+ return (
+ <DialogContent
+ data-tid="editEntryTagDialog"
+ className={props.classes.root}
+ >
+ <FormControl fullWidth={true} error={errorTag}>
+ <TextField
+ fullWidth={true}
+ error={errorTag}
+ margin="dense"
+ name="title"
+ autoFocus
+ label={i18n.t('core:editTag')}
+ onChange={event => {
+ const target = event.target;
+ setTitle(target.value);
+ }}
+ value={title}
+ data-tid="editTagEntryDialog_input"
+ />
+ {errorTag && (
+ <FormHelperText>{i18n.t('core:tagTitleHelper')}</FormHelperText>
+ )}
+ </FormControl>
+ {showGeoEditor && (
+ <GeoTagEditor
+ key={title}
+ geoTag={title}
+ onChange={setTitle}
+ zoom={title === defaultTagLocation ? 2 : undefined}
+ />
+ )}
+ {showDatePeriodEditor && (
+ <DateTagEditor
+ key={title}
+ datePeriodTag={title}
+ onChange={setTitle}
+ />
+ )}
+ </DialogContent>
+ );
+ }
+
+ function renderActions() {
+ return (
+ <DialogActions>
+ <Button
+ data-tid="closeEditTagEntryDialog"
+ onClick={props.onClose}
+ color="primary"
+ >
+ {i18n.t('core:cancel')}
+ </Button>
+ <Button
+ disabled={disableConfirmButton}
+ onClick={onConfirm}
+ data-tid="confirmEditTagEntryDialog"
+ color="primary"
+ >
+ {i18n.t('core:ok')}
+ </Button>
+ </DialogActions>
+ );
+ }
+
+ return (
+ <Dialog
+ open={open}
+ fullScreen={fullScreen}
+ onClose={onClose}
+ // onEnterKey={(event) => onEnterKeyHandler(event, onConfirm)}
+ >
+ {renderTitle()}
+ {renderContent()}
+ {renderActions()}
+ </Dialog>
+ );
};
function mapStateToProps(state) {
- return {
- selectedTag: getSelectedTag(state),
- currentEntryPath: getSelectedTag(state)
- ? getSelectedTag(state).path
- : undefined
- };
+ return {
+ selectedTag: getSelectedTag(state),
+ currentEntryPath: getSelectedTag(state)
+ ? getSelectedTag(state).path
+ : undefined
+ };
}
function mapDispatchToProps(dispatch) {
- return bindActionCreators(
- {
- editTagForEntry: TaggingActions.editTagForEntry
- },
- dispatch
- );
+ return bindActionCreators(
+ {
+ editTagForEntry: TaggingActions.editTagForEntry
+ },
+ dispatch
+ );
}
export default withMobileDialog()(
- withStyles(styles)(
- connect(mapStateToProps, mapDispatchToProps)(EditEntryTagDialog)
- )
+ withStyles(styles)(
+ connect(mapStateToProps, mapDispatchToProps)(EditEntryTagDialog)
+ )
);
diff --git a/app/components/dialogs/GenericDialog.tsx b/app/components/dialogs/GenericDialog.tsx
index 727387f67..f6b1db28f 100644
--- a/app/components/dialogs/GenericDialog.tsx
+++ b/app/components/dialogs/GenericDialog.tsx
@@ -21,73 +21,73 @@ import Dialog from '@material-ui/core/Dialog';
import Slide from '@material-ui/core/Slide';
export function DialogTransition(props: any) {
- return <Slide direction="down" {...props} />;
+ return <Slide direction="down" {...props} />;
}
interface Props {
- open: boolean;
- fullScreen?: boolean;
- onClose: () => void;
- onBackdropClick?: () => void;
- onEnterKey?: () => void;
- renderTitle?: () => Object;
- renderContent: () => Object;
- renderActions?: () => Object;
+ 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.tsx
index 830fe0ae1..7aaab4dee 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'
+ }
});
interface Props {
- open: boolean;
- classes: any;
- fullScreen: boolean;
- keyBindings: Array<any>;
- onClose: () => void;
+ 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/RenameDirectoryDialog.tsx b/app/components/dialogs/RenameDirectoryDialog.tsx
index 8ba7215d1..752008004 100644
--- a/app/components/dialogs/RenameDirectoryDialog.tsx
+++ b/app/components/dialogs/RenameDirectoryDialog.tsx
@@ -32,117 +32,117 @@ import { extractDirectoryName } from '-/utils/paths';
import { actions as AppActions } from '-/reducers/app';
interface Props {
- open: boolean;
- selectedDirectoryPath: string;
- onClose: () => void;
- renameDirectory: (directoryPath: string, newDirectoryName: string) => void;
+ open: boolean;
+ selectedDirectoryPath: string;
+ onClose: () => void;
+ renameDirectory: (directoryPath: string, newDirectoryName: string) => void;
}
interface State {
- inputError: boolean;
- disableConfirmButton: boolean;
- name: string;
+ inputError: boolean;
+ disableConfirmButton: boolean;
+ name: string;
}
class RenameDirectoryDialog extends React.Component<Props, State> {
- state = {
- inputError: false,
- disableConfirmButton: true,
- name: this.props.selectedDirectoryPath
- ? extractDirectoryName(this.props.selectedDirectoryPath)
- : ''
- };
+ state = {
+ inputError: false,
+ disableConfirmButton: true,
+ name: this.props.selectedDirectoryPath
+ ? extractDirectoryName(this.props.selectedDirectoryPath)
+ : ''
+ };
- handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {
- this.setState(
- {
- name: event.target.value
- },
- this.handleValidation
- );
- };
+ handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {
+ this.setState(
+ {
+ name: event.target.value
+ },
+ this.handleValidation
+ );
+ };
- handleValidation() {
- // const nameRegex = this.state.name.match('^[A-Z][-a-zA-Z]+$');
- if (this.state.name.length > 0) {
- this.setState({
- inputError: false,
- disableConfirmButton: false
- });
- } else {
- this.setState({
- inputError: true,
- disableConfirmButton: true
- });
- }
- }
+ handleValidation() {
+ // const nameRegex = this.state.name.match('^[A-Z][-a-zA-Z]+$');
+ if (this.state.name.length > 0) {
+ this.setState({
+ inputError: false,
+ disableConfirmButton: false
+ });
+ } else {
+ this.setState({
+ inputError: true,
+ disableConfirmButton: true
+ });
+ }
+ }
- onConfirm = () => {
- if (!this.state.disableConfirmButton) {
- this.props.renameDirectory(
- this.props.selectedDirectoryPath,
- this.state.name
- );
- this.setState({
- inputError: false,
- disableConfirmButton: true
- });
- this.props.onClose();
- }
- };
+ onConfirm = () => {
+ if (!this.state.disableConfirmButton) {
+ this.props.renameDirectory(
+ this.props.selectedDirectoryPath,
+ this.state.name
+ );
+ this.setState({
+ inputError: false,
+ disableConfirmButton: true
+ });
+ this.props.onClose();
+ }
+ };
- render() {
- const { open, onClose } = this.props;
+ render() {
+ const { open, onClose } = this.props;
- return (
- <Dialog open={open} onClose={onClose} keepMounted scroll="paper">
- <DialogTitle>{i18n.t('core:renameDirectory')}</DialogTitle>
- <DialogContent>
- <FormControl fullWidth={true} error={this.state.inputError}>
- <TextField
- fullWidth={true}
- autoFocus
- required
- error={this.state.inputError}
- margin="dense"
- name="name"
- label={i18n.t('core:renameDirectoryTitleName')}
- onChange={this.handleInputChange}
- value={this.state.name}
- data-tid="renameDirectoryDialogInput"
- />
- <FormHelperText>{i18n.t('core:directoryNameHelp')}</FormHelperText>
- </FormControl>
- </DialogContent>
- <DialogActions>
- <Button
- data-tid="closeRenameDirectoryDialog"
- onClick={this.props.onClose}
- color="primary"
- >
- {i18n.t('core:cancel')}
- </Button>
- <Button
- disabled={this.state.disableConfirmButton}
- onClick={this.onConfirm}
- data-tid="confirmRenameDirectory"
- color="primary"
- >
- {i18n.t('core:ok')}
- </Button>
- </DialogActions>
- </Dialog>
- );
- }
+ return (
+ <Dialog open={open} onClose={onClose} keepMounted scroll="paper">
+ <DialogTitle>{i18n.t('core:renameDirectory')}</DialogTitle>
+ <DialogContent>
+ <FormControl fullWidth={true} error={this.state.inputError}>
+ <TextField
+ fullWidth={true}
+ autoFocus
+ required
+ error={this.state.inputError}
+ margin="dense"
+ name="name"
+ label={i18n.t('core:renameDirectoryTitleName')}
+ onChange={this.handleInputChange}
+ value={this.state.name}
+ data-tid="renameDirectoryDialogInput"
+ />
+ <FormHelperText>{i18n.t('core:directoryNameHelp')}</FormHelperText>
+ </FormControl>
+ </DialogContent>
+ <DialogActions>
+ <Button
+ data-tid="closeRenameDirectoryDialog"
+ onClick={this.props.onClose}
+ color="primary"
+ >
+ {i18n.t('core:cancel')}
+ </Button>
+ <Button
+ disabled={this.state.disableConfirmButton}
+ onClick={this.onConfirm}
+ data-tid="confirmRenameDirectory"
+ color="primary"
+ >
+ {i18n.t('core:ok')}
+ </Button>
+ </DialogActions>
+ </Dialog>
+ );
+ }
}
function mapActionCreatorsToProps(dispatch) {
- return bindActionCreators(
- {
- renameDirectory: AppActions.renameDirectory
- },
- dispatch
- );
+ return bindActionCreators(
+ {
+ renameDirectory: AppActions.renameDirectory
+ },
+ dispatch
+ );
}
export default connect(null, mapActionCreatorsToProps)(RenameDirectoryDialog);
diff --git a/app/components/dialogs/RenameFileDialog.tsx b/app/components/dialogs/RenameFileDialog.tsx
index a6999364e..147f4e279 100644
--- a/app/components/dialogs/RenameFileDialog.tsx
+++ b/app/components/dialogs/RenameFileDialog.tsx
@@ -31,10 +31,7 @@ import FormHelperText from '@material-ui/core/FormHelperText';
import { DialogTransition } from './GenericDialog';
import AppConfig from '-/config';
import i18n from '-/services/i18n';
-import {
- extractFileName,
- extractContainingDirectoryPath
-} from '-/utils/paths';
+import { extractFileName, extractContainingDirectoryPath } from '-/utils/paths';
import { actions as AppActions } from '-/reducers/app';
interface Props {
diff --git a/app/components/dialogs/settings/SettingsKeyBindings.tsx b/app/components/dialogs/settings/SettingsKeyBindings.tsx
index 88bb73689..af7316279 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: any = (theme: any) => ({
- root: {
- background: theme.palette.background.paper
- },
- keyBinding: {
- marginTop: 10,
- marginBottom: 10
- },
- listItem: {
- paddingLeft: 0,
- paddingRight: 0
- }
+ root: {
+ background: theme.palette.background.paper
+ },
+ keyBinding: {
+ marginTop: 10,
+ marginBottom: 10
+ },
+ listItem: {
+ paddingLeft: 0,
+ paddingRight: 0
+ }
});
interface Props {
- classes: any;
- keyBindings: Array<any>;
- setKeyBinding: (kbName: string, kbCommand: string) => void;
- setGlobalKeyBinding: (value: boolean) => void;
- globalKeyBindingEnabled: boolean;
+ 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/LocationMenu.tsx b/app/components/menus/LocationMenu.tsx
index a9a4ce1e2..649513b42 100644
--- a/app/components/menus/LocationMenu.tsx
+++ b/app/components/menus/LocationMenu.tsx
@@ -31,10 +31,7 @@ import Button from '@material-ui/core/Button';
import ArrowDropDownIcon from '@material-ui/icons/ArrowDropDown';
import i18n from '-/services/i18n';
import { getLocations, Location, locationType } from '-/reducers/locations';
-import {
- actions as AppActions,
- getCurrentLocationId
-} from '-/reducers/app';
+import { actions as AppActions, getCurrentLocationId } from '-/reducers/app';
interface Props {
currentLocationId: string | null;
diff --git a/app/perspectives/grid-perspective/components/CellContent.tsx b/app/perspectives/grid-perspective/components/CellContent.tsx
index 26c36d273..e105bce0b 100644
--- a/app/perspectives/grid-perspective/components/CellContent.tsx
+++ b/app/perspectives/grid-perspective/components/CellContent.tsx
@@ -28,10 +28,7 @@ import FolderIcon from '@material-ui/icons/FolderOpen';
import TagIcon from '@material-ui/icons/LocalOffer';
import { formatFileSize, formatDateTime } from '-/utils/misc';
import { extractTitle } from '-/utils/paths';
-import {
- FileSystemEntry,
- findColorForFileEntry
-} from '-/services/utils-io';
+import { FileSystemEntry, findColorForFileEntry } from '-/services/utils-io';
import TagContainerDnd from '-/components/TagContainerDnd';
import TagContainer from '-/components/TagContainer';
import i18n from '-/services/i18n';
diff --git a/app/reducers/app.ts b/app/reducers/app.ts
index 318d80b86..a20c3d4f2 100644
--- a/app/reducers/app.ts
+++ b/app/reducers/app.ts
@@ -99,19 +99,19 @@ export const NotificationTypes = {
};
export type OpenedEntry = {
- path: string,
- url?: string,
- viewingExtensionPath: string,
- viewingExtensionId: string,
- editingExtensionPath?: string,
- editingExtensionId?: string,
- isFile?: boolean,
- color?: string,
- editMode?: boolean,
- changed?: boolean,
- shouldReload?: boolean,
- focused?: boolean, // TODO make it mandatory once support for multiple files is added
- tags?: Array<Tag>
+ path: string;
+ url?: string;
+ viewingExtensionPath: string;
+ viewingExtensionId: string;
+ editingExtensionPath?: string;
+ editingExtensionId?: string;
+ isFile?: boolean;
+ color?: string;
+ editMode?: boolean;
+ changed?: boolean;
+ shouldReload?: boolean;
+ focused?: boolean; // TODO make it mandatory once support for multiple files is added
+ tags?: Array<Tag>;
};
let showLocations = true;
@@ -652,7 +652,7 @@ export const actions = {
getState: () => any
) => {
console.time('listDirectoryPromise');
- const { settings } = getState();
+ const { settings } = getState();
window.walkCanceled = false;
loadMetaDataPromise(directoryPath)
@@ -1571,8 +1571,7 @@ export function findAvailableExtensions() {
// Selectors
export const getDirectoryContent = (state: any) =>
state.app.currentDirectoryEntries;
-export const getDirectoryPath = (state: any) =>
- state.app.currentDirectoryPath;
+export const getDirectoryPath = (state: any) => state.app.currentDirectoryPath;
export const getCurrentLocationPath = (state: any) => {
let pathCurrentLocation;
if (state.locations) {
@@ -1589,24 +1588,20 @@ export const getCurrentLocationPath = (state: any) => {
return pathCurrentLocation;
};
export const isUpdateAvailable = (state: any) => state.app.isUpdateAvailable;
-export const isUpdateInProgress = (state: any) =>
- state.app.isUpdateInProgress;
+export const isUpdateInProgress = (state: any) => state.app.isUpdateInProgress;
export const isOnline = (state: any) => state.app.isOnline;
-export const getLastSelectedEntry = (state: any) =>
- state.app.lastSelectedEntry;
+export const getLastSelectedEntry = (state: any) => state.app.lastSelectedEntry;
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 isGeneratingThumbs = (state: any) => state.app.isGeneratingThumbs;
// 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: any) =>
state.app.editTagDialogOpened;
-export const isAboutDialogOpened = (state: any) =>
- state.app.aboutDialogOpened;
+export const isAboutDialogOpened = (state: any) => state.app.aboutDialogOpened;
export const isKeysDialogOpened = (state: any) => state.app.keysDialogOpened;
export const isLicenseDialogOpened = (state: any) =>
state.app.licenseDialogOpened;
@@ -1629,17 +1624,14 @@ export const getSearchResults = (state: any) =>
state.app.currentDirectoryEntries;
export const getSearchResultCount = (state: any) =>
state.app.currentDirectoryEntries.length;
-export const getCurrentLocationId = (state: any) =>
- state.app.currentLocationId;
-export const isEntryInFullWidth = (state: any) =>
- state.app.isEntryInFullWidth;
+export const getCurrentLocationId = (state: any) => state.app.currentLocationId;
+export const isEntryInFullWidth = (state: any) => state.app.isEntryInFullWidth;
export const isLoading = (state: any) => state.app.isLoading;
export const isLocationManagerPanelOpened = (state: any) =>
state.app.locationManagerPanelOpened;
export const isTagLibraryPanelOpened = (state: any) =>
state.app.tagLibraryPanelOpened;
-export const isSearchPanelOpened = (state: any) =>
- state.app.searchPanelOpened;
+export const isSearchPanelOpened = (state: any) => state.app.searchPanelOpened;
export const isPerspectivesPanelOpened = (state: any) =>
state.app.perspectivesPanelOpened;
export const isHelpFeedbackPanelOpened = (state: any) =>
diff --git a/app/reducers/location-index.ts b/app/reducers/location-index.ts
index 07cda878f..9974918ff 100644
--- a/app/reducers/location-index.ts
+++ b/app/reducers/location-index.ts
@@ -20,10 +20,10 @@ import { Location, getLocation, locationType } from './locations';
import { createDirectoryIndex } from '../services/utils-io';
import { Pro } from '../pro';
import {
- extractFileExtension,
- extractFileName,
- extractTagsAsObjects
- // getThumbFileLocationForFile
+ extractFileExtension,
+ extractFileName,
+ extractTagsAsObjects
+ // getThumbFileLocationForFile
} from '../utils/paths';
import { SearchQuery } from '../services/search';
import Search from '../services/search';
@@ -34,105 +34,105 @@ import i18n from '../services/i18n';
import { Tag } from './taglibrary';
export const types = {
- INDEX_DIRECTORY: 'INDEX_DIRECTORY',
- INDEX_DIRECTORY_CLEAR: 'INDEX_DIRECTORY_CLEAR',
- INDEX_DIRECTORY_START: 'INDEX_DIRECTORY_START',
- INDEX_DIRECTORY_CANCEL: 'INDEX_DIRECTORY_CANCEL',
- INDEX_DIRECTORY_SUCCESS: 'INDEX_DIRECTORY_SUCCESS',
- INDEX_DIRECTORY_FAILURE: 'INDEX_DIRECTORY_FAILURE',
- INDEX_DIRECTORY_SEARCH: 'INDEX_DIRECTORY_SEARCH',
- REFLECT_DELETE_ENTRY: 'INDEX/REFLECT_DELETE_ENTRY',
- REFLECT_CREATE_ENTRY: 'INDEX/REFLECT_CREATE_ENTRY',
- REFLECT_RENAME_ENTRY: 'INDEX/REFLECT_RENAME_ENTRY',
- REFLECT_UPDATE_SIDECARTAGS: 'INDEX/REFLECT_UPDATE_SIDECARTAGS',
- REFLECT_UPDATE_SIDECARMETA: 'INDEX/REFLECT_UPDATE_SIDECARMETA'
+ INDEX_DIRECTORY: 'INDEX_DIRECTORY',
+ INDEX_DIRECTORY_CLEAR: 'INDEX_DIRECTORY_CLEAR',
+ INDEX_DIRECTORY_START: 'INDEX_DIRECTORY_START',
+ INDEX_DIRECTORY_CANCEL: 'INDEX_DIRECTORY_CANCEL',
+ INDEX_DIRECTORY_SUCCESS: 'INDEX_DIRECTORY_SUCCESS',
+ INDEX_DIRECTORY_FAILURE: 'INDEX_DIRECTORY_FAILURE',
+ INDEX_DIRECTORY_SEARCH: 'INDEX_DIRECTORY_SEARCH',
+ REFLECT_DELETE_ENTRY: 'INDEX/REFLECT_DELETE_ENTRY',
+ REFLECT_CREATE_ENTRY: 'INDEX/REFLECT_CREATE_ENTRY',
+ REFLECT_RENAME_ENTRY: 'INDEX/REFLECT_RENAME_ENTRY',
+ REFLECT_UPDATE_SIDECARTAGS: 'INDEX/REFLECT_UPDATE_SIDECARTAGS',
+ REFLECT_UPDATE_SIDECARMETA: 'INDEX/REFLECT_UPDATE_SIDECARMETA'
};
export const initialState = {
- currentDirectoryIndex: [],
- isIndexing: false
+ currentDirectoryIndex: [],
+ isIndexing: false
};
export default (state: any = initialState, action: any) => {
- switch (action.type) {
- case types.INDEX_DIRECTORY_START: {
- return {
- ...state,
- currentDirectoryIndex: [],
- isIndexing: true
- };
- }
- case types.INDEX_DIRECTORY_CLEAR: {
- return {
- ...state,
- currentDirectoryIndex: [],
- isIndexing: false
- };
- }
- case types.INDEX_DIRECTORY_CANCEL: {
- window.walkCanceled = true;
- return { ...state, isIndexing: false };
- }
- case types.INDEX_DIRECTORY_SUCCESS: {
- return {
- ...state,
- currentDirectoryIndex: action.directoryIndex,
- isIndexing: false
- };
- }
- case types.INDEX_DIRECTORY_FAILURE: {
- return {
- ...state,
- lastError: action.error,
- currentDirectoryIndex: [],
- isIndexing: false
- };
- }
- case types.REFLECT_DELETE_ENTRY: {
- const newDirectoryIndex = state.currentDirectoryIndex.filter(
- entry => !entry.path.startsWith(action.path)
- );
- if (state.currentDirectoryIndex.length > newDirectoryIndex.length) {
- return {
- ...state,
- currentDirectoryIndex: newDirectoryIndex
- };
- }
- return state;
- }
- case types.REFLECT_CREATE_ENTRY: {
- const entryIndex = state.currentDirectoryIndex.findIndex(
- entry => entry.path === action.newEntry.path
- );
- if (entryIndex) {
- return state;
- }
- return {
- ...state,
- currentDirectoryIndex: [action.newEntry, ...state.currentDirectoryIndex]
- };
- }
- case types.REFLECT_RENAME_ENTRY: {
- return {
- ...state,
- currentDirectoryIndex: state.currentDirectoryIndex.map(entry => {
- if (entry.path !== action.path) {
- return entry;
- }
- return {
- ...entry,
- path: action.newPath,
- // thumbPath: getThumbFileLocationForFile(action.newPath), // disabled due performance concerns
- name: extractFileName(action.newPath),
- extension: extractFileExtension(action.newPath),
- tags: [
- ...entry.tags.filter(tag => tag.type === 'sidecar'), // add only sidecar tags
- ...extractTagsAsObjects(action.newPath) // , getTagDelimiter(state))
- ]
- };
- })
- };
- /* const indexForRenamingInIndex = state.currentDirectoryIndex.findIndex((entry) => entry.path === action.path);
+ switch (action.type) {
+ case types.INDEX_DIRECTORY_START: {
+ return {
+ ...state,
+ currentDirectoryIndex: [],
+ isIndexing: true
+ };
+ }
+ case types.INDEX_DIRECTORY_CLEAR: {
+ return {
+ ...state,
+ currentDirectoryIndex: [],
+ isIndexing: false
+ };
+ }
+ case types.INDEX_DIRECTORY_CANCEL: {
+ window.walkCanceled = true;
+ return { ...state, isIndexing: false };
+ }
+ case types.INDEX_DIRECTORY_SUCCESS: {
+ return {
+ ...state,
+ currentDirectoryIndex: action.directoryIndex,
+ isIndexing: false
+ };
+ }
+ case types.INDEX_DIRECTORY_FAILURE: {
+ return {
+ ...state,
+ lastError: action.error,
+ currentDirectoryIndex: [],
+ isIndexing: false
+ };
+ }
+ case types.REFLECT_DELETE_ENTRY: {
+ const newDirectoryIndex = state.currentDirectoryIndex.filter(
+ entry => !entry.path.startsWith(action.path)
+ );
+ if (state.currentDirectoryIndex.length > newDirectoryIndex.length) {
+ return {
+ ...state,
+ currentDirectoryIndex: newDirectoryIndex
+ };
+ }
+ return state;
+ }
+ case types.REFLECT_CREATE_ENTRY: {
+ const entryIndex = state.currentDirectoryIndex.findIndex(
+ entry => entry.path === action.newEntry.path
+ );
+ if (entryIndex) {
+ return state;
+ }
+ return {
+ ...state,
+ currentDirectoryIndex: [action.newEntry, ...state.currentDirectoryIndex]
+ };
+ }
+ case types.REFLECT_RENAME_ENTRY: {
+ return {
+ ...state,
+ currentDirectoryIndex: state.currentDirectoryIndex.map(entry => {
+ if (entry.path !== action.path) {
+ return entry;
+ }
+ return {
+ ...entry,
+ path: action.newPath,
+ // thumbPath: getThumbFileLocationForFile(action.newPath), // disabled due performance concerns
+ name: extractFileName(action.newPath),
+ extension: extractFileExtension(action.newPath),
+ tags: [
+ ...entry.tags.filter(tag => tag.type === 'sidecar'), // add only sidecar tags
+ ...extractTagsAsObjects(action.newPath) // , getTagDelimiter(state))
+ ]
+ };
+ })
+ };
+ /* const indexForRenamingInIndex = state.currentDirectoryIndex.findIndex((entry) => entry.path === action.path);
if (indexForRenamingInIndex >= 0) {
const updateEntry = {
...state.currentDirectoryIndex[indexForRenamingInIndex],
@@ -155,24 +155,24 @@ export default (state: any = initialState, action: any) => {
};
}
return state; */
- }
- case types.REFLECT_UPDATE_SIDECARTAGS: {
- return {
- ...state,
- currentDirectoryIndex: state.currentDirectoryIndex.map(entry => {
- if (entry.path !== action.path) {
- return entry;
- }
- return {
- ...entry,
- tags: [
- ...entry.tags.filter(tag => tag.type === 'plain'),
- ...action.tags
- ]
- };
- })
- };
- /* const indexForUpdatingInIndex = state.currentDirectoryIndex.findIndex((entry) => entry.path === action.path);
+ }
+ case types.REFLECT_UPDATE_SIDECARTAGS: {
+ return {
+ ...state,
+ currentDirectoryIndex: state.currentDirectoryIndex.map(entry => {
+ if (entry.path !== action.path) {
+ return entry;
+ }
+ return {
+ ...entry,
+ tags: [
+ ...entry.tags.filter(tag => tag.type === 'plain'),
+ ...action.tags
+ ]
+ };
+ })
+ };
+ /* const indexForUpdatingInIndex = state.currentDirectoryIndex.findIndex((entry) => entry.path === action.path);
if (indexForUpdatingInIndex >= 0) {
const updateEntry = {
...state.currentDirectoryIndex[indexForUpdatingInIndex],
@@ -191,21 +191,21 @@ export default (state: any = initialState, action: any) => {
};
}
return state; */
- }
- case types.REFLECT_UPDATE_SIDECARMETA: {
- return {
- ...state,
- currentDirectoryIndex: state.currentDirectoryIndex.map(entry => {
- if (entry.path !== action.path) {
- return entry;
- }
- return {
- ...entry,
- ...action.entryMeta
- };
- })
- };
- /* const indexForUpdatingInIndex = state.currentDirectoryIndex.findIndex((entry) => entry.path === action.path);
+ }
+ case types.REFLECT_UPDATE_SIDECARMETA: {
+ return {
+ ...state,
+ currentDirectoryIndex: state.currentDirectoryIndex.map(entry => {
+ if (entry.path !== action.path) {
+ return entry;
+ }
+ return {
+ ...entry,
+ ...action.entryMeta
+ };
+ })
+ };
+ /* const indexForUpdatingInIndex = state.currentDirectoryIndex.findIndex((entry) => entry.path === action.path);
if (indexForUpdatingInIndex >= 0) {
const updateEntry = {
...state.currentDirectoryIndex[indexForUpdatingInIndex],
@@ -221,150 +221,150 @@ export default (state: any = initialState, action: any) => {
};
}
return state; */
- }
- default: {
- return state;
- }
- }
+ }
+ default: {
+ return state;
+ }
+ }
};
export const actions = {
- startDirectoryIndexing: () => ({ type: types.INDEX_DIRECTORY_START }),
- cancelDirectoryIndexing: () => ({ type: types.INDEX_DIRECTORY_CANCEL }),
- createDirectoryIndex: (directoryPath: string, extractText: boolean) => (
- dispatch: (actions: Object) => void,
- getState: () => any
- ) => {
- const state = getState();
- const currentLocation: Location = getLocation(
- state,
- state.app.currentLocationId
- );
- dispatch(actions.startDirectoryIndexing());
- createDirectoryIndex(directoryPath, extractText)
- .then(directoryIndex => {
- dispatch(actions.indexDirectorySuccess(directoryIndex));
- if (Pro && Pro.Indexer) {
- // && (currentLocation.persistIndex || PlatformIO.haveObjectStoreSupport())) { // always persist on s3 stores
- Pro.Indexer.persistIndex(
- directoryPath,
- directoryIndex,
- currentLocation.type === locationType.TYPE_CLOUD
- ? '/'
- : AppConfig.dirSeparator
- );
- }
- return true;
- })
- .catch(err => {
- dispatch(actions.indexDirectoryFailure(err));
- // dispatch(actions.startDirectoryIndexing());
- });
- },
- loadDirectoryIndex: (directoryPath: string) => (
- dispatch: (actions: Object) => void,
- getState: () => any
- ) => {
- const state = getState();
- const currentLocation: Location = getLocation(
- state,
- state.app.currentLocationId
- );
- dispatch(actions.startDirectoryIndexing());
- dispatch(
- AppActions.showNotification(i18n.t('core:loadingIndex'), 'default', true)
- );
- if (Pro && Pro.Indexer.loadIndex) {
- Pro.Indexer.loadIndex(
- directoryPath,
- currentLocation.type === locationType.TYPE_CLOUD
- ? '/'
- : AppConfig.dirSeparator
- )
- .then(directoryIndex => {
- dispatch(actions.indexDirectorySuccess(directoryIndex));
- return true;
- })
- .catch(err => {
- dispatch(actions.indexDirectoryFailure(err));
- dispatch(
- AppActions.showNotification(
- i18n.t('core:loadingIndexFailed'),
- 'warning',
- true
- )
- );
- });
- }
- },
- clearDirectoryIndex: () => ({
- type: types.INDEX_DIRECTORY_CLEAR
- }),
- searchLocationIndex: (searchQuery: SearchQuery) => (
- dispatch: (actions: Object) => void,
- getState: () => any
- ) => {
- dispatch(
- AppActions.showNotification(i18n.t('core:searching'), 'default', false)
- );
- setTimeout(() => {
- // Workaround used to show the start search notification
- Search.searchLocationIndex(
- getState().locationIndex.currentDirectoryIndex,
- searchQuery
- )
- .then(searchResults => {
- dispatch(AppActions.updateSearchResults(searchResults));
- dispatch(AppActions.hideNotifications());
- return true;
- })
- .catch(() => {
- dispatch(AppActions.updateSearchResults([]));
- dispatch(AppActions.hideNotifications());
- dispatch(
- AppActions.showNotification(
- i18n.t('core:searchingFailed'),
- 'warning',
- true
- )
- );
- });
- }, 50);
- },
- indexDirectorySuccess: (directoryIndex: Array<Object>) => ({
- type: types.INDEX_DIRECTORY_SUCCESS,
- directoryIndex
- }),
- indexDirectoryFailure: (error: string) => ({
- type: types.INDEX_DIRECTORY_FAILURE,
- error
- }),
- reflectDeleteEntry: (path: string) => ({
- type: types.REFLECT_DELETE_ENTRY,
- path
- }),
- reflectCreateEntry: (newEntry: Object) => ({
- type: types.REFLECT_CREATE_ENTRY,
- newEntry
- }),
- reflectRenameEntry: (path: string, newPath: string) => ({
- type: types.REFLECT_RENAME_ENTRY,
- path,
- newPath
- }),
- reflectUpdateSidecarTags: (path: string, tags: Array<Tag>) => ({
- type: types.REFLECT_UPDATE_SIDECARTAGS,
- path,
- tags
- }),
- reflectUpdateSidecarMeta: (path: string, entryMeta: Object) => ({
- type: types.REFLECT_UPDATE_SIDECARMETA,
- path,
- entryMeta
- })
+ startDirectoryIndexing: () => ({ type: types.INDEX_DIRECTORY_START }),
+ cancelDirectoryIndexing: () => ({ type: types.INDEX_DIRECTORY_CANCEL }),
+ createDirectoryIndex: (directoryPath: string, extractText: boolean) => (
+ dispatch: (actions: Object) => void,
+ getState: () => any
+ ) => {
+ const state = getState();
+ const currentLocation: Location = getLocation(
+ state,
+ state.app.currentLocationId
+ );
+ dispatch(actions.startDirectoryIndexing());
+ createDirectoryIndex(directoryPath, extractText)
+ .then(directoryIndex => {
+ dispatch(actions.indexDirectorySuccess(directoryIndex));
+ if (Pro && Pro.Indexer) {
+ // && (currentLocation.persistIndex || PlatformIO.haveObjectStoreSupport())) { // always persist on s3 stores
+ Pro.Indexer.persistIndex(
+ directoryPath,
+ directoryIndex,
+ currentLocation.type === locationType.TYPE_CLOUD
+ ? '/'
+ : AppConfig.dirSeparator
+ );
+ }
+ return true;
+ })
+ .catch(err => {
+ dispatch(actions.indexDirectoryFailure(err));
+ // dispatch(actions.startDirectoryIndexing());
+ });
+ },
+ loadDirectoryIndex: (directoryPath: string) => (
+ dispatch: (actions: Object) => void,
+ getState: () => any
+ ) => {
+ const state = getState();
+ const currentLocation: Location = getLocation(
+ state,
+ state.app.currentLocationId
+ );
+ dispatch(actions.startDirectoryIndexing());
+ dispatch(
+ AppActions.showNotification(i18n.t('core:loadingIndex'), 'default', true)
+ );
+ if (Pro && Pro.Indexer.loadIndex) {
+ Pro.Indexer.loadIndex(
+ directoryPath,
+ currentLocation.type === locationType.TYPE_CLOUD
+ ? '/'
+ : AppConfig.dirSeparator
+ )
+ .then(directoryIndex => {
+ dispatch(actions.indexDirectorySuccess(directoryIndex));
+ return true;
+ })
+ .catch(err => {
+ dispatch(actions.indexDirectoryFailure(err));
+ dispatch(
+ AppActions.showNotification(
+ i18n.t('core:loadingIndexFailed'),
+ 'warning',
+ true
+ )
+ );
+ });
+ }
+ },
+ clearDirectoryIndex: () => ({
+ type: types.INDEX_DIRECTORY_CLEAR
+ }),
+ searchLocationIndex: (searchQuery: SearchQuery) => (
+ dispatch: (actions: Object) => void,
+ getState: () => any
+ ) => {
+ dispatch(
+ AppActions.showNotification(i18n.t('core:searching'), 'default', false)
+ );
+ setTimeout(() => {
+ // Workaround used to show the start search notification
+ Search.searchLocationIndex(
+ getState().locationIndex.currentDirectoryIndex,
+ searchQuery
+ )
+ .then(searchResults => {
+ dispatch(AppActions.updateSearchResults(searchResults));
+ dispatch(AppActions.hideNotifications());
+ return true;
+ })
+ .catch(() => {
+ dispatch(AppActions.updateSearchResults([]));
+ dispatch(AppActions.hideNotifications());
+ dispatch(
+ AppActions.showNotification(
+ i18n.t('core:searchingFailed'),
+ 'warning',
+ true
+ )
+ );
+ });
+ }, 50);
+ },
+ indexDirectorySuccess: (directoryIndex: Array<Object>) => ({
+ type: types.INDEX_DIRECTORY_SUCCESS,
+ directoryIndex
+ }),
+ indexDirectoryFailure: (error: string) => ({
+ type: types.INDEX_DIRECTORY_FAILURE,
+ error
+ }),
+ reflectDeleteEntry: (path: string) => ({
+ type: types.REFLECT_DELETE_ENTRY,
+ path
+ }),
+ reflectCreateEntry: (newEntry: Object) => ({
+ type: types.REFLECT_CREATE_ENTRY,
+ newEntry
+ }),
+ reflectRenameEntry: (path: string, newPath: string) => ({
+ type: types.REFLECT_RENAME_ENTRY,
+ path,
+ newPath
+ }),
+ reflectUpdateSidecarTags: (path: string, tags: Array<Tag>) => ({
+ type: types.REFLECT_UPDATE_SIDECARTAGS,
+ path,
+ tags
+ }),
+ reflectUpdateSidecarMeta: (path: string, entryMeta: Object) => ({
+ type: types.REFLECT_UPDATE_SIDECARMETA,
+ path,
+ entryMeta
+ })
};
// Selectors
export const getIndexedEntriesCount = (state: any) =>
- state.locationIndex.currentDirectoryIndex.length;
+ state.locationIndex.currentDirectoryIndex.length;
export const isIndexing = (state: any) => state.locationIndex.isIndexing;
diff --git a/app/reducers/locations.ts b/app/reducers/locations.ts
index f44d099cd..bc0d3fc13 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: 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;
- }
- }
+ 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: any): Array<Location> => state.locations;
export const getLocation = (
- state: any,
- 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: any): string | undefined => {
- let defaultLocationID;
- state.locations.map(location => {
- if (location.isDefault) {
- defaultLocationID = location.uuid;
- }
- return true;
- });
- return defaultLocationID;
+ let defaultLocationID;
+ state.locations.map(location => {
+ if (location.isDefault) {
+ defaultLocationID = location.uuid;
+ }
+ return true;
+ });
+ return defaultLocationID;
};
diff --git a/app/services/electron-io.ts b/app/services/electron-io.ts
index eacc4f02b..4d3ad0e58 100644
--- a/app/services/electron-io.ts
+++ b/app/services/electron-io.ts
@@ -94,8 +94,8 @@ export default class ElectronIO {
// } else
if (process.platform === 'win32') {
- nImage = nativeImage.createFromDataURL(TrayIcon2x);
- // @ts-ignore
+ nImage = nativeImage.createFromDataURL(TrayIcon2x);
+ // @ts-ignore
} else if (process.platform === 'darwin') {
nImage = nativeImage.createFromDataURL(TrayIcon);
// nImage.addRepresentation({ scaleFactor: 2.0, dataURL: TrayIcon2x });
diff --git a/app/services/electron-menus.ts b/app/services/electron-menus.ts
index dea4f81a5..cdba90541 100644
--- a/app/services/electron-menus.ts
+++ b/app/services/electron-menus.ts
@@ -23,69 +23,69 @@ import AppConfig from '../config';
let ipcRenderer;
if (AppConfig.isElectron && window.require) {
- const electron = window.require('electron');
- ipcRenderer = electron.ipcRenderer;
+ const electron = window.require('electron');
+ ipcRenderer = electron.ipcRenderer;
}
export default function buildDesktopMenu(mainPageProps: any) {
- if (!AppConfig.isElectron) {
- return;
- }
+ if (!AppConfig.isElectron) {
+ return;
+ }
- ipcRenderer.on('file', (event, arg) => {
- // console.log('Global events: ' + arg);
- switch (arg) {
- case 'new-text-file':
- mainPageProps.toggleCreateFileDialog();
- break;
- case 'audio':
- // console.log('showAudioRecordingDialog');
- break;
- case 'next-file': {
- const path = mainPageProps.getNextFile();
- mainPageProps.openFile(path);
- mainPageProps.setLastSelectedEntry(path);
- break;
- }
- case 'previous-file': {
- const path = mainPageProps.getPrevFile();
- mainPageProps.openFile(path);
- mainPageProps.setLastSelectedEntry(path);
- break;
- }
- default:
- return false;
- }
- });
+ ipcRenderer.on('file', (event, arg) => {
+ // console.log('Global events: ' + arg);
+ switch (arg) {
+ case 'new-text-file':
+ mainPageProps.toggleCreateFileDialog();
+ break;
+ case 'audio':
+ // console.log('showAudioRecordingDialog');
+ break;
+ case 'next-file': {
+ const path = mainPageProps.getNextFile();
+ mainPageProps.openFile(path);
+ mainPageProps.setLastSelectedEntry(path);
+ break;
+ }
+ case 'previous-file': {
+ const path = mainPageProps.getPrevFile();
+ mainPageProps.openFile(path);
+ mainPageProps.setLastSelectedEntry(path);
+ break;
+ }
+ default:
+ return false;
+ }
+ });
- ipcRenderer.on('play-pause', (event, arg) => {
- // Create the event.
- const audioEvent = new CustomEvent('toggle-resume', { detail: '' });
- window.dispatchEvent(audioEvent);
- });
+ ipcRenderer.on('play-pause', (event, arg) => {
+ // Create the event.
+ const audioEvent = new CustomEvent('toggle-resume', { detail: '' });
+ window.dispatchEvent(audioEvent);
+ });
- const templateDefault = [
- {
- label: i18n.t('core:file'),
- submenu: [
- /* {
+ const templateDefault = [
+ {
+ label: i18n.t('core:file'),
+ submenu: [
+ /* {
label: i18n.t('core:openNewInstance'),
accelerator: '',
click: () => {
// ipcRenderer.send('new-win', 'newWin');
}
}, */
- /* {
+ /* {
type: 'separator'
}, */
- {
- label: i18n.t('core:newFileNote'),
- // accelerator: 'CommandOrControl+Alt+N',
- click: () => {
- mainPageProps.toggleCreateFileDialog();
- }
- },
- /* {
+ {
+ label: i18n.t('core:newFileNote'),
+ // accelerator: 'CommandOrControl+Alt+N',
+ click: () => {
+ mainPageProps.toggleCreateFileDialog();
+ }
+ },
+ /* {
label: i18n.t('core:createMarkdown'),
accelerator: '',
// click: createMDFile
@@ -96,20 +96,20 @@ export default function buildDesktopMenu(mainPageProps: any) {
// click: createHTMLFile
},
*/
- {
- type: 'separator'
- },
- {
- label: i18n.t('core:createDirectory'),
- accelerator: '',
- click: () => {
- mainPageProps.showCreateDirectoryDialog();
- }
- },
- {
- type: 'separator'
- },
- /* {
+ {
+ type: 'separator'
+ },
+ {
+ label: i18n.t('core:createDirectory'),
+ accelerator: '',
+ click: () => {
+ mainPageProps.showCreateDirectoryDialog();
+ }
+ },
+ {
+ type: 'separator'
+ },
+ /* {
label: i18n.t('core:saveFile'),
accelerator: mainPageProps.keyBindings.saveDocument,
click: () => {
@@ -119,236 +119,236 @@ export default function buildDesktopMenu(mainPageProps: any) {
{
type: 'separator'
}, */
- /* {
+ /* {
label: i18n.t('core:closeWin'),
accelerator: '',
click: (item, focusedWindow) => {
focusedWindow.destroy();
}
}, */
- {
- label: i18n.t('core:exitApp'),
- accelerator: 'CmdOrCtrl+Q',
- click: PlatformIO.quitApp
- }
- ]
- },
- {
- label: i18n.t('core:edit'),
- submenu: [
- {
- label: i18n.t('core:undo'),
- accelerator: 'CmdOrCtrl+Z',
- role: 'undo'
- },
- {
- label: i18n.t('core:redo'),
- accelerator: 'Shift+CmdOrCtrl+Z',
- role: 'redo'
- },
- {
- type: 'separator'
- },
- {
- label: i18n.t('core:cut'),
- accelerator: 'CmdOrCtrl+X',
- role: 'cut'
- },
- {
- label: i18n.t('core:copy'),
- accelerator: 'CmdOrCtrl+C',
- role: 'copy'
- },
- {
- label: i18n.t('core:paste'),
- accelerator: 'CmdOrCtrl+V',
- role: 'paste'
- },
- {
- label: i18n.t('core:selectAll'),
- accelerator: 'CmdOrCtrl+A',
- role: 'selectall'
- }
- ]
- },
- {
- label: i18n.t('core:view'),
- submenu: [
- {
- label: i18n.t('core:showLocationManager'),
- accelerator: mainPageProps.keyBindings.showLocationManager,
- click: () => {
- mainPageProps.openLocationManagerPanel();
- }
- },
- {
- label: i18n.t('core:showTagLibrary'),
- accelerator: mainPageProps.keyBindings.showTagLibrary,
- click: () => {
- mainPageProps.openTagLibraryPanel();
- }
- },
- {
- label: i18n.t('core:showSearch'),
- accelerator: mainPageProps.keyBindings.showSearch,
- click: () => {
- mainPageProps.openSearchPanel();
- }
- },
- {
- label: i18n.t('core:showDevTools'),
- accelerator: mainPageProps.keyBindings.openDevTools,
- click: (item, focusedWindow) => {
- focusedWindow.toggleDevTools();
- }
- },
- {
- label: i18n.t('core:reloadApplication'),
- accelerator: mainPageProps.keyBindings.reloadApplication,
- click: (item, focusedWindow) => {
- // ipcRenderer.send('relaunch-app', 'relaunch');
- focusedWindow.webContents.reload();
- }
- },
- {
- type: 'separator'
- },
- {
- label: i18n.t('core:zoomReset'),
- accelerator: 'CmdOrCtrl+0',
- click: () => {
- mainPageProps.setZoomResetApp();
- }
- },
- {
- label: i18n.t('core:zoomIn'),
- accelerator: 'CmdOrCtrl+Plus',
- click: () => {
- mainPageProps.setZoomInApp();
- }
- },
- {
- label: i18n.t('core:zoomOut'),
- accelerator: 'CmdOrCtrl+-',
- click: () => {
- mainPageProps.setZoomOutApp();
- }
- },
- {
- label: i18n.t('core:toggleFullScreen'),
- accelerator: mainPageProps.keyBindings.toggleFullScreen,
- click: (item, focusedWindow) => {
- focusedWindow.setFullScreen(!focusedWindow.isFullScreen());
- }
- },
- {
- type: 'separator'
- },
- {
- label: i18n.t('core:settings'),
- click: () => {
- mainPageProps.toggleSettingsDialog();
- }
- }
- ]
- },
- {
- label: '&' + i18n.t('core:help'),
- submenu: [
- {
- label: '&' + i18n.t('core:documentation'),
- accelerator: mainPageProps.keyBindings.showHelp,
- click: () => {
- // mainPageProps.openURLExternally(AppConfig.documentationLinks.general);
- mainPageProps.openHelpFeedbackPanel();
- }
- },
- {
- label: '&' + i18n.t('core:shortcutKeys'),
- click: () => {
- mainPageProps.toggleKeysDialog();
- }
- },
- {
- label: 'Welcome Wizzard',
- click: () => {
- mainPageProps.toggleOnboardingDialog();
- }
- },
- {
- label: '&' + i18n.t('core:whatsNew'),
- click: () => {
- mainPageProps.openURLExternally(AppConfig.links.changelogURL);
- }
- },
- {
- type: 'separator'
- },
- {
- label: '&' + i18n.t('core:likeUsOnFacebook'),
- click: () => {
- mainPageProps.openURLExternally(AppConfig.links.facebook);
- }
- },
- {
- label: '&' + i18n.t('core:followOnTwitter'),
- click: () => {
- mainPageProps.openURLExternally(AppConfig.links.twitter);
- }
- },
- {
- type: 'separator'
- },
- {
- label: '&' + i18n.t('core:suggestNewFeatures'),
- click: () => {
- mainPageProps.openURLExternally(AppConfig.links.suggestFeature);
- }
- },
- {
- label: '&' + i18n.t('core:reportIssues'),
- click: () => {
- mainPageProps.openURLExternally(AppConfig.links.reportIssue);
- }
- },
- {
- type: 'separator'
- },
- {
- label: i18n.t('core:webClipperChrome'),
- click: () => {
- mainPageProps.openURLExternally(AppConfig.links.webClipperChrome);
- }
- },
- {
- label: i18n.t('core:webClipperFirefox'),
- click: () => {
- mainPageProps.openURLExternally(AppConfig.links.webClipperFirefox);
- }
- },
- {
- type: 'separator'
- },
- {
- label: '&' + i18n.t('core:license'),
- click: () => {
- mainPageProps.toggleLicenseDialog();
- }
- },
- {
- label: '&' + i18n.t('core:thirdPartyLibs'),
- click: () => {
- mainPageProps.toggleThirdPartyLibsDialog();
- }
- },
- {
- label: '&' + i18n.t('core:aboutTagSpaces'),
- click: () => {
- mainPageProps.toggleAboutDialog();
- }
- }
- ]
- }
- ];
- PlatformIO.initMainMenu(templateDefault);
+ {
+ label: i18n.t('core:exitApp'),
+ accelerator: 'CmdOrCtrl+Q',
+ click: PlatformIO.quitApp
+ }
+ ]
+ },
+ {
+ label: i18n.t('core:edit'),
+ submenu: [
+ {
+ label: i18n.t('core:undo'),
+ accelerator: 'CmdOrCtrl+Z',
+ role: 'undo'
+ },
+ {
+ label: i18n.t('core:redo'),
+ accelerator: 'Shift+CmdOrCtrl+Z',
+ role: 'redo'
+ },
+ {
+ type: 'separator'
+ },
+ {
+ label: i18n.t('core:cut'),
+ accelerator: 'CmdOrCtrl+X',
+ role: 'cut'
+ },
+ {
+ label: i18n.t('core:copy'),
+ accelerator: 'CmdOrCtrl+C',
+ role: 'copy'
+ },
+ {
+ label: i18n.t('core:paste'),
+ accelerator: 'CmdOrCtrl+V',
+ role: 'paste'
+ },
+ {
+ label: i18n.t('core:selectAll'),
+ accelerator: 'CmdOrCtrl+A',
+ role: 'selectall'
+ }
+ ]
+ },
+ {
+ label: i18n.t('core:view'),
+ submenu: [
+ {
+ label: i18n.t('core:showLocationManager'),
+ accelerator: mainPageProps.keyBindings.showLocationManager,
+ click: () => {
+ mainPageProps.openLocationManagerPanel();
+ }
+ },
+ {
+ label: i18n.t('core:showTagLibrary'),
+ accelerator: mainPageProps.keyBindings.showTagLibrary,
+ click: () => {
+ mainPageProps.openTagLibraryPanel();
+ }
+ },
+ {
+ label: i18n.t('core:showSearch'),
+ accelerator: mainPageProps.keyBindings.showSearch,
+ click: () => {
+ mainPageProps.openSearchPanel();
+ }
+ },
+ {
+ label: i18n.t('core:showDevTools'),
+ accelerator: mainPageProps.keyBindings.openDevTools,
+ click: (item, focusedWindow) => {
+ focusedWindow.toggleDevTools();
+ }
+ },
+ {
+ label: i18n.t('core:reloadApplication'),
+ accelerator: mainPageProps.keyBindings.reloadApplication,
+ click: (item, focusedWindow) => {
+ // ipcRenderer.send('relaunch-app', 'relaunch');
+ focusedWindow.webContents.reload();
+ }
+ },
+ {
+ type: 'separator'
+ },
+ {
+ label: i18n.t('core:zoomReset'),
+ accelerator: 'CmdOrCtrl+0',
+ click: () => {
+ mainPageProps.setZoomResetApp();
+ }
+ },
+ {
+ label: i18n.t('core:zoomIn'),
+ accelerator: 'CmdOrCtrl+Plus',
+ click: () => {
+ mainPageProps.setZoomInApp();
+ }
+ },
+ {
+ label: i18n.t('core:zoomOut'),
+ accelerator: 'CmdOrCtrl+-',
+ click: () => {
+ mainPageProps.setZoomOutApp();
+ }
+ },
+ {
+ label: i18n.t('core:toggleFullScreen'),
+ accelerator: mainPageProps.keyBindings.toggleFullScreen,
+ click: (item, focusedWindow) => {
+ focusedWindow.setFullScreen(!focusedWindow.isFullScreen());
+ }
+ },
+ {
+ type: 'separator'
+ },
+ {
+ label: i18n.t('core:settings'),
+ click: () => {
+ mainPageProps.toggleSettingsDialog();
+ }
+ }
+ ]
+ },
+ {
+ label: '&' + i18n.t('core:help'),
+ submenu: [
+ {
+ label: '&' + i18n.t('core:documentation'),
+ accelerator: mainPageProps.keyBindings.showHelp,
+ click: () => {
+ // mainPageProps.openURLExternally(AppConfig.documentationLinks.general);
+ mainPageProps.openHelpFeedbackPanel();
+ }
+ },
+ {
+ label: '&' + i18n.t('core:shortcutKeys'),
+ click: () => {
+ mainPageProps.toggleKeysDialog();
+ }
+ },
+ {
+ label: 'Welcome Wizzard',
+ click: () => {
+ mainPageProps.toggleOnboardingDialog();
+ }
+ },
+ {
+ label: '&' + i18n.t('core:whatsNew'),
+ click: () => {
+ mainPageProps.openURLExternally(AppConfig.links.changelogURL);
+ }
+ },
+ {
+ type: 'separator'
+ },
+ {
+ label: '&' + i18n.t('core:likeUsOnFacebook'),
+ click: () => {
+ mainPageProps.openURLExternally(AppConfig.links.facebook);
+ }
+ },
+ {
+ label: '&' + i18n.t('core:followOnTwitter'),
+ click: () => {
+ mainPageProps.openURLExternally(AppConfig.links.twitter);
+ }
+ },
+ {
+ type: 'separator'
+ },
+ {
+ label: '&' + i18n.t('core:suggestNewFeatures'),
+ click: () => {
+ mainPageProps.openURLExternally(AppConfig.links.suggestFeature);
+ }
+ },
+ {
+ label: '&' + i18n.t('core:reportIssues'),
+ click: () => {
+ mainPageProps.openURLExternally(AppConfig.links.reportIssue);
+ }
+ },
+ {
+ type: 'separator'
+ },
+ {
+ label: i18n.t('core:webClipperChrome'),
+ click: () => {
+ mainPageProps.openURLExternally(AppConfig.links.webClipperChrome);
+ }
+ },
+ {
+ label: i18n.t('core:webClipperFirefox'),
+ click: () => {
+ mainPageProps.openURLExternally(AppConfig.links.webClipperFirefox);
+ }
+ },
+ {
+ type: 'separator'
+ },
+ {
+ label: '&' + i18n.t('core:license'),
+ click: () => {
+ mainPageProps.toggleLicenseDialog();
+ }
+ },
+ {
+ label: '&' + i18n.t('core:thirdPartyLibs'),
+ click: () => {
+ mainPageProps.toggleThirdPartyLibsDialog();
+ }
+ },
+ {
+ label: '&' + i18n.t('core:aboutTagSpaces'),
+ click: () => {
+ mainPageProps.toggleAboutDialog();
+ }
+ }
+ ]
+ }
+ ];
+ PlatformIO.initMainMenu(templateDefault);
}
diff --git a/app/services/electron-tray-menu.ts b/app/services/electron-tray-menu.ts
index e4cae9d6e..fe4e852a6 100644
--- a/app/services/electron-tray-menu.ts
+++ b/app/services/electron-tray-menu.ts
@@ -22,66 +22,66 @@ import i18n from './i18n';
import AppConfig from '../config';
export default function buildTrayIconMenu(mainPageProps: any) {
- if (!AppConfig.isElectron) {
- return;
- }
+ if (!AppConfig.isElectron) {
+ return;
+ }
- const cKey = AppConfig.isMacLike ? ' - Cmd' : ' - Ctrl';
+ const cKey = AppConfig.isMacLike ? ' - Cmd' : ' - Ctrl';
- function openNextFile() {
- const path = mainPageProps.getNextFile();
- mainPageProps.openFile(path);
- mainPageProps.setLastSelectedEntry(path);
- }
+ function openNextFile() {
+ const path = mainPageProps.getNextFile();
+ mainPageProps.openFile(path);
+ mainPageProps.setLastSelectedEntry(path);
+ }
- function openPrevFile() {
- const path = mainPageProps.getPrevFile();
- mainPageProps.openFile(path);
- mainPageProps.setLastSelectedEntry(path);
- }
+ function openPrevFile() {
+ const path = mainPageProps.getPrevFile();
+ mainPageProps.openFile(path);
+ mainPageProps.setLastSelectedEntry(path);
+ }
- function playResumePlayback() {
- const audioEvent = new CustomEvent('toggle-resume', { detail: '' });
- window.dispatchEvent(audioEvent);
- }
+ function playResumePlayback() {
+ const audioEvent = new CustomEvent('toggle-resume', { detail: '' });
+ window.dispatchEvent(audioEvent);
+ }
- const trayMenuTemplate = [
- {
- label: i18n.t('core:showTagSpaces') + cKey + '+Shift+W',
- click: PlatformIO.showMainWindow
- },
- {
- type: 'separator'
- },
- {
- label: i18n.t('core:newFileNote') + cKey + '+Shift+N',
- click: mainPageProps.toggleCreateFileDialog
- },
- {
- type: 'separator'
- },
- {
- label: i18n.t('core:openNextFileTooltip') + cKey + '+Shift+D',
- click: openNextFile
- },
- {
- label: i18n.t('core:openPrevFileTooltip') + cKey + '+Shift+A',
- click: openPrevFile
- },
- {
- type: 'separator'
- },
- {
- label: i18n.t('core:pauseResumePlayback') + cKey + '+Shift+P',
- click: playResumePlayback
- },
- {
- type: 'separator'
- },
- {
- label: i18n.t('core:quitTagSpaces') + cKey + '+Q',
- click: PlatformIO.quitApp
- }
- ];
- PlatformIO.initTrayMenu(trayMenuTemplate);
+ const trayMenuTemplate = [
+ {
+ label: i18n.t('core:showTagSpaces') + cKey + '+Shift+W',
+ click: PlatformIO.showMainWindow
+ },
+ {
+ type: 'separator'
+ },
+ {
+ label: i18n.t('core:newFileNote') + cKey + '+Shift+N',
+ click: mainPageProps.toggleCreateFileDialog
+ },
+ {
+ type: 'separator'
+ },
+ {
+ label: i18n.t('core:openNextFileTooltip') + cKey + '+Shift+D',
+ click: openNextFile
+ },
+ {
+ label: i18n.t('core:openPrevFileTooltip') + cKey + '+Shift+A',
+ click: openPrevFile
+ },
+ {
+ type: 'separator'
+ },
+ {
+ label: i18n.t('core:pauseResumePlayback') + cKey + '+Shift+P',
+ click: playResumePlayback
+ },
+ {
+ type: 'separator'
+ },
+ {
+ label: i18n.t('core:quitTagSpaces') + cKey + '+Q',
+ click: PlatformIO.quitApp
+ }
+ ];
+ PlatformIO.initTrayMenu(trayMenuTemplate);
}
diff --git a/app/services/onlineListener.ts b/app/services/onlineListener.ts
index b814ac76e..d74c8c64f 100644
--- a/app/services/onlineListener.ts
+++ b/app/services/onlineListener.ts
@@ -19,15 +19,15 @@
import { actions as CommonActions } from '../reducers/app';
export default (dispatch: any) => {
- window.addEventListener('online', updateOnlineStatus);
- window.addEventListener('offline', updateOnlineStatus);
+ window.addEventListener('online', updateOnlineStatus);
+ window.addEventListener('offline', updateOnlineStatus);
- function updateOnlineStatus(event) {
- console.log('Online status: ' + event.type);
- if (navigator.onLine) {
- dispatch(CommonActions.goOnline());
- } else {
- dispatch(CommonActions.goOffline());
- }
- }
+ function updateOnlineStatus(event) {
+ console.log('Online status: ' + event.type);
+ if (navigator.onLine) {
+ dispatch(CommonActions.goOnline());
+ } else {
+ dispatch(CommonActions.goOffline());
+ }
+ }
};
diff --git a/app/services/thumbsgenerator.ts b/app/services/thumbsgenerator.ts
index 82af16fed..4452b55ef 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
+ 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 });
- });
- });
+ 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 as any, 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/utils/dates.ts b/app/utils/dates.ts
index 2b9b916af..3cb6b54e1 100644
--- a/app/utils/dates.ts
+++ b/app/utils/dates.ts
@@ -129,7 +129,7 @@ export const msInDay = 1000 * 60 * 60 * 24;
/** Extract the time period from string e.g. 201902 -> fromDate: 2019-01-01 00:00:00, toDate; 2019-01-31 23:59:59 */
export function extractTimePeriod(
value: string
-): { fromDateTime: Date | null, toDateTime: Date | null } {
+): { fromDateTime: Date | null; toDateTime: Date | null } {
let fromDateTime = null;
let toDateTime = null;
if (value.length && !/(^|\s)([0123456789])(\s|$)/.test(value.substr(0, 1))) {
diff --git a/app/utils/openlocationcode.js b/app/utils/openlocationcode.js
deleted file mode 100644
index 6d6f0507c..000000000
--- a/app/utils/openlocationcode.js
+++ /dev/null
@@ -1,802 +0,0 @@
-// Copyright 2014 Google Inc. All rights reserved.
-//
-// Licensed under the Apache License, Version 2.0 (the 'License');
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an 'AS IS' BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-/**
- * Convert locations to and from short codes.
- *
- * Open Location Codes are short, 10-11 character codes that can be used instead
- * of street addresses. The codes can be generated and decoded offline, and use
- * a reduced character set that minimises the chance of codes including words.
- *
- * Codes are able to be shortened relative to a nearby location. This means that
- * in many cases, only four to seven characters of the code are needed.
- * To recover the original code, the same location is not required, as long as
- * a nearby location is provided.
- *
- * Codes represent rectangular areas rather than points, and the longer the
- * code, the smaller the area. A 10 character code represents a 13.5x13.5
- * meter area (at the equator. An 11 character code represents approximately
- * a 2.8x3.5 meter area.
- *
- * Two encoding algorithms are used. The first 10 characters are pairs of
- * characters, one for latitude and one for longitude, using base 20. Each pair
- * reduces the area of the code by a factor of 400. Only even code lengths are
- * sensible, since an odd-numbered length would have sides in a ratio of 20:1.
- *
- * At position 11, the algorithm changes so that each character selects one
- * position from a 4x5 grid. This allows single-character refinements.
- *
- * Examples:
- *
- * Encode a location, default accuracy:
- * var code = OpenLocationCode.encode(47.365590, 8.524997);
- *
- * Encode a location using one stage of additional refinement:
- * var code = OpenLocationCode.encode(47.365590, 8.524997, 11);
- *
- * Decode a full code:
- * var coord = OpenLocationCode.decode(code);
- * var msg = 'Center is ' + coord.latitudeCenter + ',' + coord.longitudeCenter;
- *
- * Attempt to trim the first characters from a code:
- * var shortCode = OpenLocationCode.shorten('8FVC9G8F+6X', 47.5, 8.5);
- *
- * Recover the full code from a short code:
- * var code = OpenLocationCode.recoverNearest('9G8F+6X', 47.4, 8.6);
- * var code = OpenLocationCode.recoverNearest('8F+6X', 47.4, 8.6);
- */
-(function(root, factory) {
- /* global define, module */
- if (typeof module === 'object' && module.exports) {
- // Node. Does not work with strict CommonJS, but
- // only CommonJS-like environments that support module.exports,
- // like Node.
- module.exports = factory();
- } else {
- // Browser globals
- root.OpenLocationCode = factory();
- }
-})(this, function() {
- var OpenLocationCode = {};
-
- /**
- * Provides a normal precision code, approximately 14x14 meters.
- * @const {number}
- */
- OpenLocationCode.CODE_PRECISION_NORMAL = 10;
-
- /**
- * Provides an extra precision code, approximately 2x3 meters.
- * @const {number}
- */
- OpenLocationCode.CODE_PRECISION_EXTRA = 11;
-
- // A separator used to break the code into two parts to aid memorability.
- var SEPARATOR_ = '+';
-
- // The number of characters to place before the separator.
- var SEPARATOR_POSITION_ = 8;
-
- // The character used to pad codes.
- var PADDING_CHARACTER_ = '0';
-
- // The character set used to encode the values.
- var CODE_ALPHABET_ = '23456789CFGHJMPQRVWX';
-
- // The base to use to convert numbers to/from.
- var ENCODING_BASE_ = CODE_ALPHABET_.length;
-
- // The maximum value for latitude in degrees.
- var LATITUDE_MAX_ = 90;
-
- // The maximum value for longitude in degrees.
- var LONGITUDE_MAX_ = 180;
-
- // The max number of digits to process in a plus code.
- var MAX_DIGIT_COUNT = 15;
-
- // Maximum code length using lat/lng pair encoding. The area of such a
- // code is approximately 13x13 meters (at the equator), and should be suitable
- // for identifying buildings. This excludes prefix and separator characters.
- var PAIR_CODE_LENGTH_ = 10;
-
- // The resolution values in degrees for each position in the lat/lng pair
- // encoding. These give the place value of each position, and therefore the
- // dimensions of the resulting area.
- var PAIR_RESOLUTIONS_ = [20.0, 1.0, 0.05, 0.0025, 0.000125];
-
- // Number of columns in the grid refinement method.
- var GRID_COLUMNS_ = 4;
-
- // Number of rows in the grid refinement method.
- var GRID_ROWS_ = 5;
-
- // Size of the initial grid in degrees.
- var GRID_SIZE_DEGREES_ = 0.000125;
-
- // Minimum length of a code that can be shortened.
- var MIN_TRIMMABLE_CODE_LEN_ = 6;
-
- /**
- Returns the OLC alphabet.
- */
- var getAlphabet = (OpenLocationCode.getAlphabet = function() {
- return CODE_ALPHABET_;
- });
-
- /**
- * Determines if a code is valid.
- *
- * To be valid, all characters must be from the Open Location Code character
- * set with at most one separator. The separator can be in any even-numbered
- * position up to the eighth digit.
- *
- * @param {string} code The string to check.
- * @return {boolean} True if the string is a valid code.
- */
- var isValid = (OpenLocationCode.isValid = function(code) {
- if (!code || typeof code !== 'string') {
- return false;
- }
- // The separator is required.
- if (code.indexOf(SEPARATOR_) == -1) {
- return false;
- }
- if (code.indexOf(SEPARATOR_) != code.lastIndexOf(SEPARATOR_)) {
- return false;
- }
- // Is it the only character?
- if (code.length == 1) {
- return false;
- }
- // Is it in an illegal position?
- if (
- code.indexOf(SEPARATOR_) > SEPARATOR_POSITION_ ||
- code.indexOf(SEPARATOR_) % 2 == 1
- ) {
- return false;
- }
- // We can have an even number of padding characters before the separator,
- // but then it must be the final character.
- if (code.indexOf(PADDING_CHARACTER_) > -1) {
- // Not allowed to start with them!
- if (code.indexOf(PADDING_CHARACTER_) == 0) {
- return false;
- }
- // There can only be one group and it must have even length.
- var padMatch = code.match(
- new RegExp('(' + PADDING_CHARACTER_ + '+)', 'g')
- );
- if (
- padMatch.length > 1 ||
- padMatch[0].length % 2 == 1 ||
- padMatch[0].length > SEPARATOR_POSITION_ - 2
- ) {
- return false;
- }
- // If the code is long enough to end with a separator, make sure it does.
- if (code.charAt(code.length - 1) != SEPARATOR_) {
- return false;
- }
- }
- // If there are characters after the separator, make sure there isn't just
- // one of them (not legal).
- if (code.length - code.indexOf(SEPARATOR_) - 1 == 1) {
- return false;
- }
-
- // Strip the separator and any padding characters.
- code = code
- .replace(new RegExp('\\' + SEPARATOR_ + '+'), '')
- .replace(new RegExp(PADDING_CHARACTER_ + '+'), '');
- // Check the code contains only valid characters.
- for (var i = 0, len = code.length; i < len; i++) {
- var character = code.charAt(i).toUpperCase();
- if (character != SEPARATOR_ && CODE_ALPHABET_.indexOf(character) == -1) {
- return false;
- }
- }
- return true;
- });
-
- /**
- * Determines if a code is a valid short code.
- *
- * @param {string} code The string to check.
- * @return {boolean} True if the string can be produced by removing four or
- * more characters from the start of a valid code.
- */
- var isShort = (OpenLocationCode.isShort = function(code) {
- // Check it's valid.
- if (!isValid(code)) {
- return false;
- }
- // If there are less characters than expected before the SEPARATOR.
- if (
- code.indexOf(SEPARATOR_) >= 0 &&
- code.indexOf(SEPARATOR_) < SEPARATOR_POSITION_
- ) {
- return true;
- }
- return false;
- });
-
- /**
- * Determines if a code is a valid full Open Location Code.
- *
- * @param {string} code The string to check.
- * @return {boolean} True if the code represents a valid latitude and
- * longitude combination.
- */
- var isFull = (OpenLocationCode.isFull = function(code) {
- if (!isValid(code)) {
- return false;
- }
- // If it's short, it's not full.
- if (isShort(code)) {
- return false;
- }
-
- // Work out what the first latitude character indicates for latitude.
- var firstLatValue =
- CODE_ALPHABET_.indexOf(code.charAt(0).toUpperCase()) * ENCODING_BASE_;
- if (firstLatValue >= LATITUDE_MAX_ * 2) {
- // The code would decode to a latitude of >= 90 degrees.
- return false;
- }
- if (code.length > 1) {
- // Work out what the first longitude character indicates for longitude.
- var firstLngValue =
- CODE_ALPHABET_.indexOf(code.charAt(1).toUpperCase()) * ENCODING_BASE_;
- if (firstLngValue >= LONGITUDE_MAX_ * 2) {
- // The code would decode to a longitude of >= 180 degrees.
- return false;
- }
- }
- return true;
- });
-
- /**
- * Encode a location into an Open Location Code.
- *
- * @param {number} latitude The latitude in signed decimal degrees. It will
- * be clipped to the range -90 to 90.
- * @param {number} longitude The longitude in signed decimal degrees. Will be
- * normalised to the range -180 to 180.
- * @param {?number} codeLength The length of the code to generate. If
- * omitted, the value OpenLocationCode.CODE_PRECISION_NORMAL will be used.
- * For a more precise result, OpenLocationCode.CODE_PRECISION_EXTRA is
- * recommended.
- * @return {string} The code.
- * @throws {Exception} if any of the input values are not numbers.
- */
- var encode = (OpenLocationCode.encode = function(
- latitude,
- longitude,
- codeLength
- ) {
- latitude = Number(latitude);
- longitude = Number(longitude);
- if (typeof codeLength == 'undefined') {
- codeLength = OpenLocationCode.CODE_PRECISION_NORMAL;
- } else {
- codeLength = Math.min(MAX_DIGIT_COUNT, Number(codeLength));
- }
- if (isNaN(latitude) || isNaN(longitude) || isNaN(codeLength)) {
- throw 'ValueError: Parameters are not numbers';
- }
- if (
- codeLength < 2 ||
- (codeLength < PAIR_CODE_LENGTH_ && codeLength % 2 == 1)
- ) {
- throw 'IllegalArgumentException: Invalid Open Location Code length';
- }
- // Ensure that latitude and longitude are valid.
- latitude = clipLatitude(latitude);
- longitude = normalizeLongitude(longitude);
- // Latitude 90 needs to be adjusted to be just less, so the returned code
- // can also be decoded.
- if (latitude == 90) {
- latitude = latitude - computeLatitudePrecision(codeLength);
- }
- var code = encodePairs(
- latitude,
- longitude,
- Math.min(codeLength, PAIR_CODE_LENGTH_)
- );
- // If the requested length indicates we want grid refined codes.
- if (codeLength > PAIR_CODE_LENGTH_) {
- code += encodeGrid(latitude, longitude, codeLength - PAIR_CODE_LENGTH_);
- }
- return code;
- });
-
- /**
- * Decodes an Open Location Code into its location coordinates.
- *
- * Returns a CodeArea object that includes the coordinates of the bounding
- * box - the lower left, center and upper right.
- *
- * @param {string} code The code to decode.
- * @return {OpenLocationCode.CodeArea} An object with the coordinates of the
- * area of the code.
- * @throws {Exception} If the code is not valid.
- */
- var decode = (OpenLocationCode.decode = function(code) {
- if (!isFull(code)) {
- throw 'IllegalArgumentException: ' +
- 'Passed Open Location Code is not a valid full code: ' +
- code;
- }
- // Strip out separator character (we've already established the code is
- // valid so the maximum is one), padding characters and convert to upper
- // case.
- code = code.replace(SEPARATOR_, '');
- code = code.replace(new RegExp(PADDING_CHARACTER_ + '+'), '');
- code = code.toUpperCase();
- // Decode the lat/lng pair component.
- var codeArea = decodePairs(code.substring(0, PAIR_CODE_LENGTH_));
- // If there is a grid refinement component, decode that.
- if (code.length <= PAIR_CODE_LENGTH_) {
- return codeArea;
- }
- var gridArea = decodeGrid(
- code.substring(PAIR_CODE_LENGTH_, MAX_DIGIT_COUNT)
- );
- return CodeArea(
- codeArea.latitudeLo + gridArea.latitudeLo,
- codeArea.longitudeLo + gridArea.longitudeLo,
- codeArea.latitudeLo + gridArea.latitudeHi,
- codeArea.longitudeLo + gridArea.longitudeHi,
- codeArea.codeLength + gridArea.codeLength
- );
- });
-
- /**
- * Recover the nearest matching code to a specified location.
- *
- * Given a valid short Open Location Code this recovers the nearest matching
- * full code to the specified location.
- *
- * @param {string} shortCode A valid short code.
- * @param {number} referenceLatitude The latitude to use for the reference
- * location.
- * @param {number} referenceLongitude The longitude to use for the reference
- * location.
- * @return {string} The nearest matching full code to the reference location.
- * @throws {Exception} if the short code is not valid, or the reference
- * position values are not numbers.
- */
- var recoverNearest = (OpenLocationCode.recoverNearest = function(
- shortCode,
- referenceLatitude,
- referenceLongitude
- ) {
- if (!isShort(shortCode)) {
- if (isFull(shortCode)) {
- return shortCode;
- } else {
- throw 'ValueError: Passed short code is not valid: ' + shortCode;
- }
- }
- referenceLatitude = Number(referenceLatitude);
- referenceLongitude = Number(referenceLongitude);
- if (isNaN(referenceLatitude) || isNaN(referenceLongitude)) {
- throw 'ValueError: Reference position are not numbers';
- }
- // Ensure that latitude and longitude are valid.
- referenceLatitude = clipLatitude(referenceLatitude);
- referenceLongitude = normalizeLongitude(referenceLongitude);
-
- // Clean up the passed code.
- shortCode = shortCode.toUpperCase();
- // Compute the number of digits we need to recover.
- var paddingLength = SEPARATOR_POSITION_ - shortCode.indexOf(SEPARATOR_);
- // The resolution (height and width) of the padded area in degrees.
- var resolution = Math.pow(20, 2 - paddingLength / 2);
- // Distance from the center to an edge (in degrees).
- var halfResolution = resolution / 2.0;
-
- // Use the reference location to pad the supplied short code and decode it.
- var codeArea = decode(
- encode(referenceLatitude, referenceLongitude).substr(0, paddingLength) +
- shortCode
- );
- // How many degrees latitude is the code from the reference? If it is more
- // than half the resolution, we need to move it north or south but keep it
- // within -90 to 90 degrees.
- if (
- referenceLatitude + halfResolution < codeArea.latitudeCenter &&
- codeArea.latitudeCenter - resolution >= -LATITUDE_MAX_
- ) {
- // If the proposed code is more than half a cell north of the reference location,
- // it's too far, and the best match will be one cell south.
- codeArea.latitudeCenter -= resolution;
- } else if (
- referenceLatitude - halfResolution > codeArea.latitudeCenter &&
- codeArea.latitudeCenter + resolution <= LATITUDE_MAX_
- ) {
- // If the proposed code is more than half a cell south of the reference location,
- // it's too far, and the best match will be one cell north.
- codeArea.latitudeCenter += resolution;
- }
-
- // How many degrees longitude is the code from the reference?
- if (referenceLongitude + halfResolution < codeArea.longitudeCenter) {
- codeArea.longitudeCenter -= resolution;
- } else if (referenceLongitude - halfResolution > codeArea.longitudeCenter) {
- codeArea.longitudeCenter += resolution;
- }
-
- return encode(
- codeArea.latitudeCenter,
- codeArea.longitudeCenter,
- codeArea.codeLength
- );
- });
-
- /**
- * Remove characters from the start of an OLC code.
- *
- * This uses a reference location to determine how many initial characters
- * can be removed from the OLC code. The number of characters that can be
- * removed depends on the distance between the code center and the reference
- * location.
- *
- * @param {string} code The full code to shorten.
- * @param {number} latitude The latitude to use for the reference location.
- * @param {number} longitude The longitude to use for the reference location.
- * @return {string} The code, shortened as much as possible that it is still
- * the closest matching code to the reference location.
- * @throws {Exception} if the passed code is not a valid full code or the
- * reference location values are not numbers.
- */
- var shorten = (OpenLocationCode.shorten = function(
- code,
- latitude,
- longitude
- ) {
- if (!isFull(code)) {
- throw 'ValueError: Passed code is not valid and full: ' + code;
- }
- if (code.indexOf(PADDING_CHARACTER_) != -1) {
- throw 'ValueError: Cannot shorten padded codes: ' + code;
- }
- var code = code.toUpperCase();
- var codeArea = decode(code);
- if (codeArea.codeLength < MIN_TRIMMABLE_CODE_LEN_) {
- throw 'ValueError: Code length must be at least ' +
- MIN_TRIMMABLE_CODE_LEN_;
- }
- // Ensure that latitude and longitude are valid.
- latitude = Number(latitude);
- longitude = Number(longitude);
- if (isNaN(latitude) || isNaN(longitude)) {
- throw 'ValueError: Reference position are not numbers';
- }
- latitude = clipLatitude(latitude);
- longitude = normalizeLongitude(longitude);
- // How close are the latitude and longitude to the code center.
- var range = Math.max(
- Math.abs(codeArea.latitudeCenter - latitude),
- Math.abs(codeArea.longitudeCenter - longitude)
- );
- for (var i = PAIR_RESOLUTIONS_.length - 2; i >= 1; i--) {
- // Check if we're close enough to shorten. The range must be less than 1/2
- // the resolution to shorten at all, and we want to allow some safety, so
- // use 0.3 instead of 0.5 as a multiplier.
- if (range < PAIR_RESOLUTIONS_[i] * 0.3) {
- // Trim it.
- return code.substring((i + 1) * 2);
- }
- }
- return code;
- });
-
- /**
- * Clip a latitude into the range -90 to 90.
- *
- * @param {number} latitude
- * @return {number} The latitude value clipped to be in the range.
- */
- var clipLatitude = function(latitude) {
- return Math.min(90, Math.max(-90, latitude));
- };
-
- /**
- * Compute the latitude precision value for a given code length.
- * Lengths <= 10 have the same precision for latitude and longitude, but
- * lengths > 10 have different precisions due to the grid method having
- * fewer columns than rows.
- * @param {number} codeLength
- * @return {number} The latitude precision in degrees.
- */
- var computeLatitudePrecision = function(codeLength) {
- if (codeLength <= 10) {
- return Math.pow(20, Math.floor(codeLength / -2 + 2));
- }
- return Math.pow(20, -3) / Math.pow(GRID_ROWS_, codeLength - 10);
- };
-
- /**
- * Normalize a longitude into the range -180 to 180, not including 180.
- *
- * @param {number} longitude
- * @return {number} Normalized into the range -180 to 180.
- */
- var normalizeLongitude = function(longitude) {
- while (longitude < -180) {
- longitude = longitude + 360;
- }
- while (longitude >= 180) {
- longitude = longitude - 360;
- }
- return longitude;
- };
-
- /**
- * Encode a location into a sequence of OLC lat/lng pairs.
- *
- * This uses pairs of characters (longitude and latitude in that order) to
- * represent each step in a 20x20 grid. Each code, therefore, has 1/400th
- * the area of the previous code.
- *
- * This algorithm is used up to 10 digits.
- *
- * @param {number} latitude The location to encode.
- * @param {number} longitude The location to encode.
- * @param {number} codeLength Requested code length.
- * @return {string} The up to 10-digit OLC code for the location.
- */
- var encodePairs = function(latitude, longitude, codeLength) {
- var code = '';
- // Adjust latitude and longitude so they fall into positive ranges.
- var adjustedLatitude = latitude + LATITUDE_MAX_;
- var adjustedLongitude = longitude + LONGITUDE_MAX_;
- // Count digits - can't use string length because it may include a separator
- // character.
- var digitCount = 0;
- while (digitCount < codeLength) {
- // Provides the value of digits in this place in decimal degrees.
- var placeValue = PAIR_RESOLUTIONS_[Math.floor(digitCount / 2)];
- // Do the latitude - gets the digit for this place and subtracts that for
- // the next digit.
- var digitValue = Math.floor(adjustedLatitude / placeValue);
- adjustedLatitude -= digitValue * placeValue;
- code += CODE_ALPHABET_.charAt(digitValue);
- digitCount += 1;
- // And do the longitude - gets the digit for this place and subtracts that
- // for the next digit.
- digitValue = Math.floor(adjustedLongitude / placeValue);
- adjustedLongitude -= digitValue * placeValue;
- code += CODE_ALPHABET_.charAt(digitValue);
- digitCount += 1;
- // Should we add a separator here?
- if (digitCount == SEPARATOR_POSITION_ && digitCount < codeLength) {
- code += SEPARATOR_;
- }
- }
- if (code.length < SEPARATOR_POSITION_) {
- code =
- code +
- Array(SEPARATOR_POSITION_ - code.length + 1).join(PADDING_CHARACTER_);
- }
- if (code.length == SEPARATOR_POSITION_) {
- code = code + SEPARATOR_;
- }
- return code;
- };
-
- /**
- * Encode a location using the grid refinement method into an OLC string.
- *
- * The grid refinement method divides the area into a grid of 4x5, and uses a
- * single character to refine the area. This allows default accuracy OLC codes
- * to be refined with just a single character.
- *
- * This algorithm is used for codes longer than 10 digits.
- *
- * @param {number} latitude The location to encode.
- * @param {number} longitude The location to encode.
- * @param {number} codeLength Requested code length.
- * @return {string} The OLC code digits from the 11th digit on.
- */
- var encodeGrid = function(latitude, longitude, codeLength) {
- var code = '';
- var latPlaceValue = GRID_SIZE_DEGREES_;
- var lngPlaceValue = GRID_SIZE_DEGREES_;
- // Adjust latitude and longitude so they fall into positive ranges and
- // get the offset for the required places.
- latitude += LATITUDE_MAX_;
- longitude += LONGITUDE_MAX_;
- // To avoid problems with floating point, get rid of the degrees.
- latitude = latitude % 1.0;
- longitude = longitude % 1.0;
- var adjustedLatitude = latitude % latPlaceValue;
- var adjustedLongitude = longitude % lngPlaceValue;
- for (var i = 0; i < codeLength; i++) {
- // Work out the row and column.
- var row = Math.floor(adjustedLatitude / (latPlaceValue / GRID_ROWS_));
- var col = Math.floor(adjustedLongitude / (lngPlaceValue / GRID_COLUMNS_));
- latPlaceValue /= GRID_ROWS_;
- lngPlaceValue /= GRID_COLUMNS_;
- adjustedLatitude -= row * latPlaceValue;
- adjustedLongitude -= col * lngPlaceValue;
- code += CODE_ALPHABET_.charAt(row * GRID_COLUMNS_ + col);
- }
- return code;
- };
-
- /**
- * Decode an OLC code made up of lat/lng pairs.
- *
- * This decodes an OLC code made up of alternating latitude and longitude
- * characters, encoded using base 20.
- *
- * @param {string} code The code to decode, assumed to be a valid full code,
- * but with the separator removed.
- * @return {OpenLocationCode.CodeArea} The code area object.
- */
- var decodePairs = function(code) {
- // Get the latitude and longitude values. These will need correcting from
- // positive ranges.
- var latitude = decodePairsSequence(code, 0);
- var longitude = decodePairsSequence(code, 1);
- // Correct the values and set them into the CodeArea object.
- return new CodeArea(
- latitude[0] - LATITUDE_MAX_,
- longitude[0] - LONGITUDE_MAX_,
- latitude[1] - LATITUDE_MAX_,
- longitude[1] - LONGITUDE_MAX_,
- code.length
- );
- };
-
- /**
- * Decode either a latitude or longitude sequence.
- *
- * This decodes the latitude or longitude sequence of a lat/lng pair encoding.
- * Starting at the character at position offset, every second character is
- * decoded and the value returned.
- *
- * @param {string} code A valid full OLC code, with the separator removed.
- * @param {string} offset The character to start from.
- * @return {[number]} An array of two numbers, representing the lower and
- * upper range in decimal degrees. These are in positive ranges and will
- * need to be corrected appropriately.
- */
- var decodePairsSequence = function(code, offset) {
- var i = 0;
- var value = 0;
- while (i * 2 + offset < code.length) {
- value +=
- CODE_ALPHABET_.indexOf(code.charAt(i * 2 + offset)) *
- PAIR_RESOLUTIONS_[i];
- i += 1;
- }
- return [value, value + PAIR_RESOLUTIONS_[i - 1]];
- };
-
- /**
- * Decode the grid refinement portion of an OLC code.
- *
- * @param {string} code The grid refinement section of a code.
- * @return {OpenLocationCode.CodeArea} The area of the code.
- */
- var decodeGrid = function(code) {
- var latitudeLo = 0.0;
- var longitudeLo = 0.0;
- var latPlaceValue = GRID_SIZE_DEGREES_;
- var lngPlaceValue = GRID_SIZE_DEGREES_;
- var i = 0;
- while (i < code.length) {
- var codeIndex = CODE_ALPHABET_.indexOf(code.charAt(i));
- var row = Math.floor(codeIndex / GRID_COLUMNS_);
- var col = codeIndex % GRID_COLUMNS_;
-
- latPlaceValue /= GRID_ROWS_;
- lngPlaceValue /= GRID_COLUMNS_;
-
- latitudeLo += row * latPlaceValue;
- longitudeLo += col * lngPlaceValue;
- i += 1;
- }
- return CodeArea(
- latitudeLo,
- longitudeLo,
- latitudeLo + latPlaceValue,
- longitudeLo + lngPlaceValue,
- code.length
- );
- };
-
- /**
- * Coordinates of a decoded Open Location Code.
- *
- * The coordinates include the latitude and longitude of the lower left and
- * upper right corners and the center of the bounding box for the area the
- * code represents.
- *
- * @constructor
- */
- var CodeArea = (OpenLocationCode.CodeArea = function(
- latitudeLo,
- longitudeLo,
- latitudeHi,
- longitudeHi,
- codeLength
- ) {
- return new OpenLocationCode.CodeArea.fn.init(
- latitudeLo,
- longitudeLo,
- latitudeHi,
- longitudeHi,
- codeLength
- );
- });
- CodeArea.fn = CodeArea.prototype = {
- init: function(
- latitudeLo,
- longitudeLo,
- latitudeHi,
- longitudeHi,
- codeLength
- ) {
- /**
- * The latitude of the SW corner.
- * @type {number}
- */
- this.latitudeLo = latitudeLo;
- /**
- * The longitude of the SW corner in degrees.
- * @type {number}
- */
- this.longitudeLo = longitudeLo;
- /**
- * The latitude of the NE corner in degrees.
- * @type {number}
- */
- this.latitudeHi = latitudeHi;
- /**
- * The longitude of the NE corner in degrees.
- * @type {number}
- */
- this.longitudeHi = longitudeHi;
- /**
- * The number of digits in the code.
- * @type {number}
- */
- this.codeLength = codeLength;
- /**
- * The latitude of the center in degrees.
- * @type {number}
- */
- this.latitudeCenter = Math.min(
- latitudeLo + (latitudeHi - latitudeLo) / 2,
- LATITUDE_MAX_
- );
- /**
- * The longitude of the center in degrees.
- * @type {number}
- */
- this.longitudeCenter = Math.min(
- longitudeLo + (longitudeHi - longitudeLo) / 2,
- LONGITUDE_MAX_
- );
- }
- };
- CodeArea.fn.init.prototype = CodeArea.fn;
-
- return OpenLocationCode;
-});
diff --git a/app/utils/paths.ts b/app/utils/paths.ts
index 690768466..e01d09ec2 100644
--- a/app/utils/paths.ts
+++ b/app/utils/paths.ts
@@ -20,111 +20,111 @@ import AppConfig from '../config';
import { Tag } from '../reducers/taglibrary';
export function baseName(dirPath: string) {
- const fileName = dirPath.substring(
- dirPath.lastIndexOf(AppConfig.dirSeparator) + 1,
- dirPath.length
- );
- return fileName || dirPath;
+ const fileName = dirPath.substring(
+ dirPath.lastIndexOf(AppConfig.dirSeparator) + 1,
+ dirPath.length
+ );
+ return fileName || dirPath;
}
export function extractFileExtension(filePath: string) {
- const lastindexDirSeparator = filePath.lastIndexOf(AppConfig.dirSeparator);
- const lastIndexEndTagContainer = filePath.lastIndexOf(
- AppConfig.endTagContainer
- );
- const lastindexDot = filePath.lastIndexOf('.');
- if (lastindexDot < 0) {
- return '';
- } else if (lastindexDot < lastindexDirSeparator) {
- // case: "../remote.php/webdav/somefilename"
- return '';
- } else if (lastindexDot < lastIndexEndTagContainer) {
- // case: "[20120125 89.4kg 19.5% 60.5% 39.8% 2.6kg]"
- return '';
- }
- let extension = filePath
- .substring(lastindexDot + 1, filePath.length)
- .toLowerCase()
- .trim();
- const lastindexQuestionMark = extension.lastIndexOf('?');
- if (lastindexQuestionMark > 0) {
- // Removing everything after ? in URLs .png?queryParam1=2342
- extension = extension.substring(0, lastindexQuestionMark);
- }
- return extension;
+ const lastindexDirSeparator = filePath.lastIndexOf(AppConfig.dirSeparator);
+ const lastIndexEndTagContainer = filePath.lastIndexOf(
+ AppConfig.endTagContainer
+ );
+ const lastindexDot = filePath.lastIndexOf('.');
+ if (lastindexDot < 0) {
+ return '';
+ } else if (lastindexDot < lastindexDirSeparator) {
+ // case: "../remote.php/webdav/somefilename"
+ return '';
+ } else if (lastindexDot < lastIndexEndTagContainer) {
+ // case: "[20120125 89.4kg 19.5% 60.5% 39.8% 2.6kg]"
+ return '';
+ }
+ let extension = filePath
+ .substring(lastindexDot + 1, filePath.length)
+ .toLowerCase()
+ .trim();
+ const lastindexQuestionMark = extension.lastIndexOf('?');
+ if (lastindexQuestionMark > 0) {
+ // Removing everything after ? in URLs .png?queryParam1=2342
+ extension = extension.substring(0, lastindexQuestionMark);
+ }
+ return extension;
- /* alternative implementation
+ /* alternative implementation
const ext = fileURL.split('.').pop();
return (ext === fileURL) ? '' : ext; */
}
export function getMetaDirectoryPath(
- directoryPath: string,
- dirSeparator: string = AppConfig.dirSeparator
+ directoryPath: string,
+ dirSeparator: string = AppConfig.dirSeparator
) {
- return normalizePath(directoryPath) + dirSeparator + AppConfig.metaFolder;
+ return normalizePath(directoryPath) + dirSeparator + AppConfig.metaFolder;
}
export function getMetaFileLocationForFile(
- entryPath: string,
- dirSeparator: string = AppConfig.dirSeparator
+ entryPath: string,
+ dirSeparator: string = AppConfig.dirSeparator
) {
- const containingFolder = extractContainingDirectoryPath(
- entryPath,
- dirSeparator
- );
- const metaFolder = getMetaDirectoryPath(containingFolder, dirSeparator);
- return (
- metaFolder +
- dirSeparator +
- extractFileName(entryPath, dirSeparator) +
- AppConfig.metaFileExt
- );
+ const containingFolder = extractContainingDirectoryPath(
+ entryPath,
+ dirSeparator
+ );
+ const metaFolder = getMetaDirectoryPath(containingFolder, dirSeparator);
+ return (
+ metaFolder +
+ dirSeparator +
+ extractFileName(entryPath, dirSeparator) +
+ AppConfig.metaFileExt
+ );
}
export function getThumbFileLocationForFile(
- entryPath: string,
- dirSeparator: string = AppConfig.dirSeparator
+ entryPath: string,
+ dirSeparator: string = AppConfig.dirSeparator
) {
- const containingFolder = extractContainingDirectoryPath(
- entryPath,
- dirSeparator
- );
- const metaFolder = getMetaDirectoryPath(containingFolder, dirSeparator);
- return (
- metaFolder +
- dirSeparator +
- extractFileName(entryPath, dirSeparator) +
- AppConfig.thumbFileExt
- );
+ const containingFolder = extractContainingDirectoryPath(
+ entryPath,
+ dirSeparator
+ );
+ const metaFolder = getMetaDirectoryPath(containingFolder, dirSeparator);
+ return (
+ metaFolder +
+ dirSeparator +
+ extractFileName(entryPath, dirSeparator) +
+ AppConfig.thumbFileExt
+ );
}
export function getMetaFileLocationForDir(entryPath: string) {
- const metaFolder = getMetaDirectoryPath(entryPath);
- return metaFolder + AppConfig.dirSeparator + AppConfig.metaFolderFile;
+ const metaFolder = getMetaDirectoryPath(entryPath);
+ return metaFolder + AppConfig.dirSeparator + AppConfig.metaFolderFile;
}
export function extractFileName(
- filePath: string,
- dirSeparator: string = AppConfig.dirSeparator
+ filePath: string,
+ dirSeparator: string = AppConfig.dirSeparator
): string {
- return filePath.substring(
- filePath.lastIndexOf(dirSeparator) + 1,
- filePath.length
- );
+ return filePath.substring(
+ filePath.lastIndexOf(dirSeparator) + 1,
+ filePath.length
+ );
}
export function cleanTrailingDirSeparator(dirPath: string): string {
- if (dirPath) {
- if (dirPath.lastIndexOf('\\') === dirPath.length - 1) {
- return dirPath.substring(0, dirPath.length - 1);
- } else if (dirPath.lastIndexOf('/') === dirPath.length - 1) {
- return dirPath.substring(0, dirPath.length - 1);
- }
- return dirPath;
- }
- // console.log('Directory Path ' + dirPath + ' undefined');
- return '';
+ if (dirPath) {
+ if (dirPath.lastIndexOf('\\') === dirPath.length - 1) {
+ return dirPath.substring(0, dirPath.length - 1);
+ } else if (dirPath.lastIndexOf('/') === dirPath.length - 1) {
+ return dirPath.substring(0, dirPath.length - 1);
+ }
+ return dirPath;
+ }
+ // console.log('Directory Path ' + dirPath + ' undefined');
+ return '';
}
/**
@@ -133,176 +133,176 @@ export function cleanTrailingDirSeparator(dirPath: string): string {
* @returns {string} -> root/subFolder
*/
export function normalizePath(path: string): string {
- return cleanTrailingDirSeparator(path.replace(/\/\//g, '/'));
+ return cleanTrailingDirSeparator(path.replace(/\/\//g, '/'));
}
export function extractFileNameWithoutExt(filePath: string): string {
- const fileName = extractFileName(filePath);
- const indexOfDot = fileName.lastIndexOf('.');
- const lastIndexBeginTagContainer = fileName.lastIndexOf(
- AppConfig.beginTagContainer
- );
- const lastIndexEndTagContainer = fileName.lastIndexOf(
- AppConfig.endTagContainer
- );
- if (
- lastIndexBeginTagContainer === 0 &&
- lastIndexEndTagContainer + 1 === fileName.length
- ) {
- // case: "[tag1 tag.2]"
- return '';
- } else if (indexOfDot > 0) {
- // case: regular
- return fileName.substring(0, indexOfDot);
- } else if (indexOfDot === 0) {
- // case ".txt"
- return '';
- }
- return fileName;
+ const fileName = extractFileName(filePath);
+ const indexOfDot = fileName.lastIndexOf('.');
+ const lastIndexBeginTagContainer = fileName.lastIndexOf(
+ AppConfig.beginTagContainer
+ );
+ const lastIndexEndTagContainer = fileName.lastIndexOf(
+ AppConfig.endTagContainer
+ );
+ if (
+ lastIndexBeginTagContainer === 0 &&
+ lastIndexEndTagContainer + 1 === fileName.length
+ ) {
+ // case: "[tag1 tag.2]"
+ return '';
+ } else if (indexOfDot > 0) {
+ // case: regular
+ return fileName.substring(0, indexOfDot);
+ } else if (indexOfDot === 0) {
+ // case ".txt"
+ return '';
+ }
+ return fileName;
}
export function extractContainingDirectoryPath(
- filePath: string,
- dirSeparator: string = AppConfig.dirSeparator
+ filePath: string,
+ dirSeparator: string = AppConfig.dirSeparator
) {
- return filePath.substring(0, filePath.lastIndexOf(dirSeparator));
+ return filePath.substring(0, filePath.lastIndexOf(dirSeparator));
}
export function extractParentDirectoryPath(
- dirPath: string,
- dirSeparator: string = AppConfig.dirSeparator
+ dirPath: string,
+ dirSeparator: string = AppConfig.dirSeparator
) {
- if (!dirPath) return;
- let path = dirPath;
- if (path.endsWith(dirSeparator)) {
- path = path.substring(0, path.lastIndexOf(dirSeparator));
- }
- return path.substring(0, path.lastIndexOf(dirSeparator));
+ if (!dirPath) return;
+ let path = dirPath;
+ if (path.endsWith(dirSeparator)) {
+ path = path.substring(0, path.lastIndexOf(dirSeparator));
+ }
+ return path.substring(0, path.lastIndexOf(dirSeparator));
}
export function extractDirectoryName(
- dirPath: string,
- dirSeparator: string = AppConfig.dirSeparator
+ dirPath: string,
+ dirSeparator: string = AppConfig.dirSeparator
): string {
- if (!dirPath) return '';
- let directoryName;
- if (dirPath.endsWith(dirSeparator)) {
- directoryName = dirPath.substring(0, dirPath.lastIndexOf(dirSeparator));
- }
- directoryName = dirPath.substring(
- dirPath.lastIndexOf(dirSeparator) + 1,
- dirPath.length
- );
- return directoryName;
+ if (!dirPath) return '';
+ let directoryName;
+ if (dirPath.endsWith(dirSeparator)) {
+ directoryName = dirPath.substring(0, dirPath.lastIndexOf(dirSeparator));
+ }
+ directoryName = dirPath.substring(
+ dirPath.lastIndexOf(dirSeparator) + 1,
+ dirPath.length
+ );
+ return directoryName;
}
export function extractShortDirectoryName(
- dirPath: string,
- dirSeparator: string = AppConfig.dirSeparator
+ dirPath: string,
+ dirSeparator: string = AppConfig.dirSeparator
) {
- let shortDirName: string = extractDirectoryName(dirPath, dirSeparator);
- if (shortDirName.length > 20) {
- shortDirName = shortDirName.substr(0, 20) + '...';
- }
- return shortDirName;
+ let shortDirName: string = extractDirectoryName(dirPath, dirSeparator);
+ if (shortDirName.length > 20) {
+ shortDirName = shortDirName.substr(0, 20) + '...';
+ }
+ return shortDirName;
}
export function extractContainingDirectoryName(filePath: string) {
- const tmpStr = filePath.substring(
- 0,
- filePath.lastIndexOf(AppConfig.dirSeparator)
- );
- return tmpStr.substring(
- tmpStr.lastIndexOf(AppConfig.dirSeparator) + 1,
- tmpStr.length
- );
+ const tmpStr = filePath.substring(
+ 0,
+ filePath.lastIndexOf(AppConfig.dirSeparator)
+ );
+ return tmpStr.substring(
+ tmpStr.lastIndexOf(AppConfig.dirSeparator) + 1,
+ tmpStr.length
+ );
}
export function extractTitle(entryPath: string, isDirectory: boolean = false) {
- let title;
- if (isDirectory) {
- title = extractDirectoryName(entryPath);
- return title;
- }
- title = extractFileNameWithoutExt(entryPath);
+ let title;
+ if (isDirectory) {
+ title = extractDirectoryName(entryPath);
+ return title;
+ }
+ title = extractFileNameWithoutExt(entryPath);
- const beginTagContainer = title.indexOf(AppConfig.beginTagContainer);
- const endTagContainer = title.lastIndexOf(AppConfig.endTagContainer);
- /* cases like "", "t", "["
+ const beginTagContainer = title.indexOf(AppConfig.beginTagContainer);
+ const endTagContainer = title.lastIndexOf(AppConfig.endTagContainer);
+ /* cases like "", "t", "["
if( fileName.length <= 1) {
// cases like "asd ] asd ["
else if (beginTagContainer > endTagContainer) {
// case: [ not found in the filename
else if ( beginTagContainer < 0 )
else if ( endTagContainer < 0 ) */
- if (beginTagContainer >= 0 && beginTagContainer < endTagContainer) {
- if (beginTagContainer === 0 && endTagContainer === title.trim().length) {
- // case: "[tag1, tag2]"
- return '';
- } else if (endTagContainer === title.trim().length) {
- // case: "asd[tag1, tag2]"
- return title.slice(0, beginTagContainer);
- }
- // case: "title1 [tag1 tag2] title2"
- return (
- title.slice(0, beginTagContainer) +
- title.slice(endTagContainer + 1, title.length)
- );
- }
- try {
- title = decodeURIComponent(title);
- } catch (e) {
- console.warn('Decoding URI failed on: ' + title + ' with ' + e);
- }
- return title;
+ if (beginTagContainer >= 0 && beginTagContainer < endTagContainer) {
+ if (beginTagContainer === 0 && endTagContainer === title.trim().length) {
+ // case: "[tag1, tag2]"
+ return '';
+ } else if (endTagContainer === title.trim().length) {
+ // case: "asd[tag1, tag2]"
+ return title.slice(0, beginTagContainer);
+ }
+ // case: "title1 [tag1 tag2] title2"
+ return (
+ title.slice(0, beginTagContainer) +
+ title.slice(endTagContainer + 1, title.length)
+ );
+ }
+ try {
+ title = decodeURIComponent(title);
+ } catch (e) {
+ console.warn('Decoding URI failed on: ' + title + ' with ' + e);
+ }
+ return title;
}
export function extractTagsAsObjects(
- filePath: string,
- tagDelimiter?: string
+ filePath: string,
+ tagDelimiter?: string
): Array<Tag> {
- const tagsInFileName = extractTags(filePath, tagDelimiter);
- const tagArray = [];
- tagsInFileName.map(tag => {
- tagArray.push({
- title: '' + tag,
- type: 'plain'
- });
- return true;
- });
- return tagArray;
+ const tagsInFileName = extractTags(filePath, tagDelimiter);
+ const tagArray = [];
+ tagsInFileName.map(tag => {
+ tagArray.push({
+ title: '' + tag,
+ type: 'plain'
+ });
+ return true;
+ });
+ return tagArray;
}
export function extractTags(filePath: string, tagDelimiter?: string) {
- if (tagDelimiter === undefined) {
- // TODO get tagDelimiter from settings reducer only
- // eslint-disable-next-line no-param-reassign
- tagDelimiter = AppConfig.tagDelimiter;
- }
- // console.log('Extracting tags from: ' + filePath);
- const fileName = extractFileName(filePath);
- // WithoutExt
- let tags = [];
- const beginTagContainer = fileName.indexOf(AppConfig.beginTagContainer);
- const endTagContainer = fileName.indexOf(AppConfig.endTagContainer);
- if (
- beginTagContainer < 0 ||
- endTagContainer < 0 ||
- beginTagContainer >= endTagContainer
- ) {
- // console.log('Filename does not contains tags. Aborting extraction.');
- return tags;
- }
- const cleanedTags = [];
- const tagContainer = fileName
- .slice(beginTagContainer + 1, endTagContainer)
- .trim();
- tags = tagContainer.split(tagDelimiter);
- for (let i = 0; i < tags.length; i += 1) {
- // Min tag length set to 1 character
- if (tags[i].trim().length > 0) {
- cleanedTags.push(tags[i]);
- }
- }
- return cleanedTags;
+ if (tagDelimiter === undefined) {
+ // TODO get tagDelimiter from settings reducer only
+ // eslint-disable-next-line no-param-reassign
+ tagDelimiter = AppConfig.tagDelimiter;
+ }
+ // console.log('Extracting tags from: ' + filePath);
+ const fileName = extractFileName(filePath);
+ // WithoutExt
+ let tags = [];
+ const beginTagContainer = fileName.indexOf(AppConfig.beginTagContainer);
+ const endTagContainer = fileName.indexOf(AppConfig.endTagContainer);
+ if (
+ beginTagContainer < 0 ||
+ endTagContainer < 0 ||
+ beginTagContainer >= endTagContainer
+ ) {
+ // console.log('Filename does not contains tags. Aborting extraction.');
+ return tags;
+ }
+ const cleanedTags = [];
+ const tagContainer = fileName
+ .slice(beginTagContainer + 1, endTagContainer)
+ .trim();
+ tags = tagContainer.split(tagDelimiter);
+ for (let i = 0; i < tags.length; i += 1) {
+ // Min tag length set to 1 character
+ if (tags[i].trim().length > 0) {
+ cleanedTags.push(tags[i]);
+ }
+ }
+ return cleanedTags;
}
diff --git a/package.json b/package.json
index d51c293ae..c84edd98d 100644
--- a/package.json
+++ b/package.json
@@ -21,6 +21,8 @@
"postlint-fix": "prettier --ignore-path .eslintignore --single-quote --write '**/*.{*{js,jsx,json},babelrc,eslintrc,prettierrc,stylelintrc}'",
"postlint-styles-fix": "prettier --ignore-path .eslintignore --single-quote --write '**/*.{css,scss}'",
"precommit": "lint-staged",
+ "prettier-check": "prettier --check '**/*.{js,json,ts,tsx,yml}'",
+ "prettier-format": "prettier --write '**/*.{js,jsx,json,ts,tsx,yml}'",
"prestart-bak": "yarn build",
"bs": "yarn build && yarn start",
"start": "cross-env NODE_ENV=production electron ./app/",
@@ -92,7 +94,7 @@
],
"husky": {
"hooks": {
- "pre-commit": "yarn prettier-check"
+ "pre-commit": "yarn prettier-check && yarn type-check"
}
},
"jest": {