TagSpaces is an offline, open source, document manager with tagging support
Improve-search-usability (#1929)
Stanimir4943f10e30a7
diff --git a/app/components/SearchAutocomplete.tsx b/app/components/SearchAutocomplete.tsxindex c23332315..edd35e6a6 100644--- a/app/components/SearchAutocomplete.tsx+++ b/app/components/SearchAutocomplete.tsx@@ -27,6 +27,8 @@ import Button from '@mui/material/Button';import Tooltip from '-/components/Tooltip';import IconButton from '@mui/material/IconButton';import ClearSearchIcon from '@mui/icons-material/Close';+import AdvancedSearchIcon from '@mui/icons-material/TuneOutlined';+import DropDownIcon from '@mui/icons-material/ArrowDropDownOutlined';import {actions as AppActions,getDirectoryPath,@@ -34,7 +36,6 @@ import {} from '../reducers/app';import {actions as LocationIndexActions,- getIndexedEntriesCount,isIndexing,getSearchQuery} from '../reducers/location-index';@@ -86,7 +87,6 @@ interface Props {setSearchQuery: (searchQuery: TS.SearchQuery) => void;openLink: (url: string, options?: any) => void;currentDirectory: string;- indexedEntriesCount: number;maxSearchResults: number;indexing: boolean;showUnixHiddenEntries: boolean;@@ -104,8 +104,9 @@ interface Props {searches: Array<TS.SearchQuery>;switchLocationTypeByID: (locationId: string) => Promise<string | null>;// editedEntryPaths: Array<TS.EditedEntryPath>;- getTextQuery: () => string;+ textQuery: string;setTextQuery: (value: string) => void;+ setAnchorSearch: (el: HTMLButtonElement) => void;}const useStyles = makeStyles(theme => ({@@ -253,13 +254,13 @@ function SearchAutocomplete(props: Props) {if (props.searchQuery.textQuery) {props.setTextQuery(props.searchQuery.textQuery);emptySearch = false;- } else if (props.getTextQuery()) {+ } else if (props.textQuery) {emptySearch = false;}const searchQuery = {...props.searchQuery,- textQuery: props.getTextQuery()+ textQuery: props.textQuery};/*if (mainSearchField.current) {@@ -419,7 +420,7 @@ function SearchAutocomplete(props: Props) {}} else if (event.key === 'Backspace' || event.keyCode === 8) {if (- props.getTextQuery().length === 0 &&+ props.textQuery.length === 0 &&actionValues.current.length > 0) {actionValues.current = actionValues.current.slice(0, -1);@@ -601,7 +602,7 @@ function SearchAutocomplete(props: Props) {// don't execute search on search filterreturn;}- let query = props.getTextQuery();+ let query = props.textQuery;if (query.startsWith('ts:?ts') ||query.startsWith(AppConfig.tsProtocol + '?ts')@@ -1414,19 +1415,33 @@ function SearchAutocomplete(props: Props) {</IconButton></Tooltip>)}*/- <Tooltip title={i18n.t('clearSearch') + ' (ESC)'}>- <IconButton- id="clearSearchID"- onClick={() => {- clearSearch();- // props.openCurrentDirectory();- }}- size="small"- edge="end"- >- <ClearSearchIcon />- </IconButton>- </Tooltip>+ <>+ <Tooltip title={i18n.t('core:advancedSearch')}>+ <IconButton+ id="advancedButton"+ data-tid="advancedSearch"+ onClick={(event: React.MouseEvent<HTMLButtonElement>) => {+ props.setAnchorSearch(event.currentTarget);+ }}+ >+ <AdvancedSearchIcon />+ <DropDownIcon />+ </IconButton>+ </Tooltip>+ <Tooltip title={i18n.t('clearSearch') + ' (ESC)'}>+ <IconButton+ id="clearSearchID"+ onClick={() => {+ clearSearch();+ // props.openCurrentDirectory();+ }}+ size="small"+ edge="end"+ >+ <ClearSearchIcon />+ </IconButton>+ </Tooltip>+ </>);function haveEmptyAction(): boolean {@@ -1473,7 +1488,7 @@ function SearchAutocomplete(props: Props) {v.fullName ? v.fullName : v.label)}onChange={handleChange}- inputValue={props.getTextQuery()}+ inputValue={props.textQuery}onInputChange={handleInputChange}open={isOpen.current}/*onOpen={handleOpen}@@ -1673,7 +1688,6 @@ function mapStateToProps(state) {searchQuery: getSearchQuery(state),isDesktop: isDesktopMode(state),currentDirectory: getDirectoryPath(state),- indexedEntriesCount: getIndexedEntriesCount(state),maxSearchResults: getMaxSearchResults(state),showUnixHiddenEntries: getShowUnixHiddenEntries(state),language: getCurrentLanguage(state),@@ -1714,8 +1728,7 @@ function mapDispatchToProps(dispatch) {nextProp.language === prevProp.language &&nextProp.indexing === prevProp.indexing &&nextProp.searchQuery === prevProp.searchQuery &&- nextProp.currentDirectory === prevProp.currentDirectory &&- nextProp.indexedEntriesCount === prevProp.indexedEntriesCount;*/+ nextProp.currentDirectory === prevProp.currentDirectory && */// @ts-ignoreexport default connect(diff --git a/app/components/SearchBox.tsx b/app/components/SearchBox.tsxindex 3d5d62459..0860635e1 100644--- a/app/components/SearchBox.tsx+++ b/app/components/SearchBox.tsx@@ -20,8 +20,6 @@ import React, { useState, useRef } from 'react';import Tooltip from '-/components/Tooltip';import IconButton from '@mui/material/IconButton';import i18n from '-/services/i18n';-import AdvancedSearchIcon from '@mui/icons-material/TuneOutlined';-import DropDownIcon from '@mui/icons-material/ArrowDropDownOutlined';import Popover from '@mui/material/Popover';import SearchPopover from '-/components/SearchPopover';import SearchAutocomplete from '-/components/SearchAutocomplete';@@ -35,15 +33,7 @@ function SearchBox(props: Props) {const [anchorSearch, setAnchorSearch] = useState<HTMLButtonElement | null>(null);- const textQuery = useRef<string>(props.textQuery || '');-- function getTextQuery() {- return textQuery.current;- }-- function setTextQuery(value) {- textQuery.current = value;- }+ const [textQuery, setTextQuery] = useState<string>(props.textQuery || '');// const searchInlineRef = React.useRef<HTMLDivElement | null>(null);/* useEffect(() => {@@ -56,13 +46,14 @@ function SearchBox(props: Props) {<><SearchAutocompleteopen={props.open}- getTextQuery={getTextQuery}+ textQuery={textQuery}setTextQuery={setTextQuery}+ setAnchorSearch={setAnchorSearch}/>{/*<SearchInline open={props.open} />*/}{props.open && (<>- <Tooltip title={i18n.t('core:advancedSearch')}>+ {/*<Tooltip title={i18n.t('core:advancedSearch')}><IconButtonid="advancedButton"data-tid="advancedSearch"@@ -73,7 +64,7 @@ function SearchBox(props: Props) {<AdvancedSearchIcon /><DropDownIcon /></IconButton>- </Tooltip>+ </Tooltip>*/}<Popoveropen={Boolean(anchorSearch)}anchorEl={anchorSearch}@@ -95,7 +86,7 @@ function SearchBox(props: Props) {><SearchPopoveronClose={() => setAnchorSearch(null)}- getTextQuery={getTextQuery}+ textQuery={textQuery}setTextQuery={setTextQuery}/></Popover>diff --git a/app/components/SearchInline.css.tsx b/app/components/SearchInline.css.tsxindex ce4fca520..7b633386c 100644--- a/app/components/SearchInline.css.tsx+++ b/app/components/SearchInline.css.tsx@@ -48,8 +48,8 @@ export const styles = (theme: any) => {paddingLeft: 10,paddingRight: 10,marginTop: 0,- height: 'calc(100% - 50px)',- maxHeight: 'calc(100% - 50px)',+ height: 'calc(100% - 80px)',+ maxHeight: 'calc(100% - 80px)',overflowX: 'hidden',// @ts-ignoreoverflowY: AppConfig.isFirefox ? 'auto' : 'overlay'diff --git a/app/components/SearchInline.tsx b/app/components/SearchInline.tsxdeleted file mode 100644index afd1d12b9..000000000--- a/app/components/SearchInline.tsx+++ /dev/null@@ -1,588 +0,0 @@-/*-/!**- * TagSpaces - universal file and folder organizer- * Copyright (C) 2017-present TagSpaces UG (haftungsbeschraenkt)- *- * This program is free software: you can redistribute it and/or modify- * it under the terms of the GNU Affero General Public License (version 3) as- * published by the Free Software Foundation.- *- * This program is distributed in the hope that it will be useful,- * but WITHOUT ANY WARRANTY; without even the implied warranty of- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the- * GNU Affero General Public License for more details.- *- * You should have received a copy of the GNU Affero General Public License- * along with this program. If not, see <https://www.gnu.org/licenses/>.- *- *!/--import React, { useEffect, useRef, useState } from 'react';-import { bindActionCreators } from 'redux';-import { connect } from 'react-redux';-import makeStyles from '@mui/styles/makeStyles';-import ClearSearchIcon from '@mui/icons-material/Close';-import HelpOutlineIcon from '@mui/icons-material/HelpOutline';-import ExpandMoreIcon from '@mui/icons-material/ExpandMore';-import Button from '@mui/material/Button';-import Tooltip from '-/components/Tooltip';-import IconButton from '@mui/material/IconButton';-import InputAdornment from '@mui/material/InputAdornment';-import Typography from '@mui/material/Typography';-import {- escapeRegExp,- parseTextQuery,- removeAllTagsFromSearchQuery-} from '@tagspaces/tagspaces-common/misc';-import { actions as AppActions, getDirectoryPath } from '../reducers/app';-import {- actions as LocationIndexActions,- getIndexedEntriesCount,- isIndexing,- getSearchQuery-} from '../reducers/location-index';-import {- isDesktopMode,- getMaxSearchResults,- getShowUnixHiddenEntries,- getCurrentLanguage-} from '-/reducers/settings';-import i18n from '-/services/i18n';-import { FileTypeGroups } from '-/services/search';-import { TS } from '-/tagspaces.namespace';-import { Pro } from '../pro';-import useFirstRender from '-/utils/useFirstRender';-import MainSearchField from '-/components/MainSearchField';-import SavedSearchesMenu from '-/components/menus/SavedSearchesMenu';-import AppConfig from '-/AppConfig';--// type PropsClasses = Record<keyof StyleProps, string>;--interface Props {- style?: any;- watchForChanges: () => void;- searchLocationIndex: (searchQuery: TS.SearchQuery) => void;- createLocationsIndexes: () => void;- searchAllLocations: (searchQuery: TS.SearchQuery) => void;- // loadDirectoryContent: (path: string, generateThumbnails: boolean, loadDirMeta?: boolean) => void;- openURLExternally: (url: string) => void;- searchQuery: TS.SearchQuery; // () => any;- // openCurrentDirectory: () => void;- setSearchQuery: (searchQuery: TS.SearchQuery) => void;- openLink: (url: string, options?: any) => void;- currentDirectory: string;- indexedEntriesCount: number;- maxSearchResults: number;- indexing: boolean;- showUnixHiddenEntries: boolean;- isDesktop: boolean;- open: boolean;-}--const useStyles = makeStyles(theme => ({- customWidth: {- maxWidth: 550- },- noMaxWidth: {- maxWidth: 'none'- }-}));--function SearchInline(props: Props) {- // const [, forceUpdate] = useReducer(x => x + 1, 0);- const [- openSavedSearches,- setOpenSavedSearches- ] = useState<null | HTMLElement>(null);- const textQuery = useRef<string>(props.searchQuery.textQuery || '');- const textQueryMask = useRef<string>('');- const fileTypes = useRef<Array<string>>(- props.searchQuery.fileTypes- ? props.searchQuery.fileTypes- : FileTypeGroups.any- );-- // const searchBoxing = useRef<'location' | 'folder' | 'global'>(- // props.searchQuery.searchBoxing ? props.searchQuery.searchBoxing : 'location'- // );- const [searchBoxing, setSearchBoxing] = useState(- props.searchQuery.searchBoxing || 'location'- );-- const searchType = useRef<'fuzzy' | 'semistrict' | 'strict'>(- props.searchQuery.searchType ? props.searchQuery.searchType : 'fuzzy'- );- const lastModified = useRef<string>(- props.searchQuery.lastModified ? props.searchQuery.lastModified : ''- );- const tagTimePeriod = useRef<string>('');- const tagTimePeriodHelper = useRef<string>(' ');- const tagTimePeriodFrom = useRef<number | null>(- props.searchQuery.tagTimePeriodFrom- ? props.searchQuery.tagTimePeriodFrom- : null- );- const tagTimePeriodTo = useRef<number | null>(- props.searchQuery.tagTimePeriodTo ? props.searchQuery.tagTimePeriodTo : null- );- const [tagPlaceLat, setTagPlaceLat] = useState<number | null>(null);- const [tagPlaceLong, setTagPlaceLong] = useState<number | null>(null);- // const [tagPlaceRadius, setTagPlaceRadius] = useState<number>(0);- const forceIndexing = useRef<boolean>(- props.searchQuery.forceIndexing ? props.searchQuery.forceIndexing : false- );- const fileSize = useRef<string>(- props.searchQuery.fileSize ? props.searchQuery.fileSize : ''- );-- const mainSearchField = useRef<HTMLInputElement>(null);-- const firstRender = useFirstRender();-- useEffect(() => {- /!*if (!firstRender) {- if (Object.keys(props.searchQuery).length > 0) {- props.setSearchQuery({});- }- }*!/- if (!firstRender && !props.open) {- if (Object.keys(props.searchQuery).length > 0) {- clearSearch();- }- }- }, [props.currentDirectory]);-- let searchBoxingName = i18n.t('location');- if (searchBoxing === 'global') {- searchBoxingName = i18n.t('globalSearch');- } else if (searchBoxing === 'folder') {- searchBoxingName = i18n.t('folder');- }-- useEffect(() => {- if (Object.keys(props.searchQuery).length > 0) {- let emptySearch = true;- textQueryMask.current = '';-- if (props.searchQuery.tagsAND && props.searchQuery.tagsAND.length > 0) {- props.searchQuery.tagsAND.forEach(tag => {- textQueryMask.current += ' +' + tag.title;- });- emptySearch = false;- }- if (props.searchQuery.tagsOR && props.searchQuery.tagsOR.length > 0) {- props.searchQuery.tagsOR.forEach(tag => {- textQueryMask.current += ' |' + tag.title;- });- emptySearch = false;- }- if (props.searchQuery.tagsNOT && props.searchQuery.tagsNOT.length > 0) {- props.searchQuery.tagsNOT.forEach(tag => {- textQueryMask.current += ' -' + tag.title;- });- emptySearch = false;- }- let txtQuery = textQuery.current.trim() || props.searchQuery.textQuery;- txtQuery = removeAllTagsFromSearchQuery(txtQuery);- if (txtQuery) {- emptySearch = false;- }- /!* if (textQueryMask.current) {- txtQuery = textQuery.current.replace(textQueryMask.current, '').trim();- } else if (textQuery.current) {- txtQuery = textQuery.current; // props.searchQuery.textQuery;- } else {- txtQuery = '';- } *!/- const searchQuery = {- ...props.searchQuery,- textQuery: txtQuery- };- /!* if (textQuery.current) {- txtQuery = textQuery.current.replace(tagsMask, '');- } else {- txtQuery = props.searchQuery.textQuery || '';- }- *!/- textQuery.current = txtQuery + ' ' + textQueryMask.current.trim();- if (mainSearchField.current) {- mainSearchField.current.value =- txtQuery +- (textQueryMask.current ? ' ' + textQueryMask.current.trim() : '');- }- if (props.searchQuery.searchBoxing) {- setSearchBoxing(props.searchQuery.searchBoxing);- // searchBoxing.current = props.searchQuery.searchBoxing;- emptySearch = false;- }- if (props.searchQuery.fileTypes) {- fileTypes.current = props.searchQuery.fileTypes;- emptySearch = false;- }- if (props.searchQuery.searchType) {- searchType.current = props.searchQuery.searchType;- emptySearch = false;- }- if (props.searchQuery.lastModified) {- lastModified.current = props.searchQuery.lastModified;- emptySearch = false;- }- if (props.searchQuery.tagTimePeriodFrom) {- tagTimePeriodFrom.current = props.searchQuery.tagTimePeriodFrom;- emptySearch = false;- }- if (props.searchQuery.tagTimePeriodTo) {- tagTimePeriodTo.current = props.searchQuery.tagTimePeriodTo;- emptySearch = false;- }- if (props.searchQuery.forceIndexing) {- forceIndexing.current = props.searchQuery.forceIndexing;- }- if (props.searchQuery.fileSize) {- fileSize.current = props.searchQuery.fileSize;- emptySearch = false;- }- if (!emptySearch) {- if (searchBoxing === 'global') {- props.searchAllLocations(searchQuery);- } else {- props.searchLocationIndex(searchQuery);- }- }- }- }, [props.searchQuery]);-- const toggleSearchBoxing = () => {- if (searchBoxing === 'location') {- setSearchBoxing('folder');- } else if (searchBoxing === 'folder' && Pro) {- setSearchBoxing('global');- } else {- setSearchBoxing('location');- }- };-- const clickSearchButton = () => {- executeSearch();- };-- const startSearch = event => {- if (event.key === 'Enter' || event.keyCode === 13) {- executeSearch();- } else if (event.key === 'Escape' || event.keyCode === 27) {- clearSearch();- // props.openCurrentDirectory();- }- };-- const clearSearch = () => {- textQuery.current = '';- setSearchBoxing('location');- searchType.current = 'fuzzy';- fileTypes.current = FileTypeGroups.any;- lastModified.current = '';- tagTimePeriod.current = '';- tagTimePeriodHelper.current = ' ';- tagTimePeriodFrom.current = null;- tagTimePeriodTo.current = null;- setTagPlaceLat(null);- setTagPlaceLong(null);- // setTagPlaceRadius(0);- forceIndexing.current = false;- fileSize.current = '';- props.setSearchQuery({});- // props.setSearchResults([]);- props.watchForChanges();- // props.openCurrentDirectory();- };-- const removeTagsFromQuery = (- tags: Array<TS.Tag>,- query: string,- identifier: string- ) => {- if (tags) {- let newQuery = query- .trim()- .replace(- new RegExp(escapeRegExp(identifier) + '\\s+', 'g'),- identifier- );- tags.forEach(tag => {- newQuery = newQuery.replace(identifier + tag.title, '');- });-- return newQuery.trim();- }-- return query;- };-- const handleOpenSavedSearches = (- event: React.MouseEvent<HTMLButtonElement>- ) => {- setOpenSavedSearches(event.currentTarget);- };-- const classes = useStyles();-- function HelpTooltip(hClasses) {- return (- <Tooltip- classes={{ tooltip: hClasses.customWidth }}- title={- <span style={{ fontSize: 14 }}>- The search query consists of a tag part and a search term. This term- is optional and can be a single word. The tag part can have one or- more tags preceded by the following symbols:- <ul>- <li>- + will add only entries having this tag in the search results- (logical AND)- </li>- <li>- | will include all entries having this tag in the search results- (logical OR)- </li>- <li>- - will exclude entries having this tags from the search results- </li>- </ul>- Example queries:- <ul>- <li>- "italy +beach -sunset" - will find all files and folders having- italy in their name and the tag beach but not sunset- </li>- <li>- "|beach |sunset" - will find all files and folder having the- tags beach or sunset- </li>- </ul>- </span>- }- >- <IconButton size="small" edge="end">- <HelpOutlineIcon style={{ color: 'lightgray' }} />- </IconButton>- </Tooltip>- );- }-- const executeSearch = () => {- let query = textQuery.current;- if (- query.startsWith('ts:?ts') ||- query.startsWith(AppConfig.tsProtocol + '?ts')- ) {- props.openLink(query, { fullWidth: false });- clearSearch();- return;- }- const tagsAND = parseTextQuery(textQuery.current, '+');- query = removeTagsFromQuery(tagsAND, query, '+');- const tagsOR = parseTextQuery(textQuery.current, '|');- query = removeTagsFromQuery(tagsOR, query, '|');- const tagsNOT = parseTextQuery(textQuery.current, '-');- query = removeTagsFromQuery(tagsNOT, query, '-');- const searchQuery: TS.SearchQuery = {- textQuery: query,- tagsAND,- tagsOR,- tagsNOT,- searchBoxing,- searchType: searchType.current,- fileTypes: fileTypes.current,- lastModified: lastModified.current,- fileSize: fileSize.current,- tagTimePeriodFrom: tagTimePeriodFrom.current,- tagTimePeriodTo: tagTimePeriodTo.current,- tagPlaceLat,- tagPlaceLong,- // tagPlaceRadius,- maxSearchResults: props.maxSearchResults,- currentDirectory: props.currentDirectory,- forceIndexing: forceIndexing.current,- showUnixHiddenEntries: props.showUnixHiddenEntries- };- console.log('Search object: ' + JSON.stringify(searchQuery));- props.setSearchQuery(searchQuery);- };-- const { indexing, isDesktop, open } = props;-- if (!open) {- return null;- }- return (- <>- <div- style={{- width: '100%',- whiteSpace: 'nowrap',- display: 'flex',- alignItems: 'center'- }}- >- <MainSearchField- fullWidth- id="textQuery"- name="textQuery"- defaultValue={textQuery.current}- variant="outlined"- onChange={event => {- textQuery.current = event.target.value;- }}- size="small"- style={{- width: 'calc(100% - 80px)'- }}- inputRef={mainSearchField}- margin="dense"- autoFocus- onKeyDown={startSearch}- placeholder={i18n.t('core:searchTitle')}- InputProps={{- startAdornment: (- <InputAdornment position="start" style={{ marginRight: 0 }}>- {isDesktop ? (- <>- <Tooltip- classes={{ tooltip: classes.customWidth }}- title={- <span style={{ fontSize: 14 }}>- {i18n.t('searchScope')}:- <br />- • {i18n.t('location')} -{' '}- {i18n.t('searchPlaceholder')}- <br />- • {i18n.t('folder')} -{' '}- {i18n.t('searchCurrentFolderWithSubFolders')}- <br />- • {i18n.t('globalSearch')} -{' '}- {i18n.t('searchInAllLocationTooltip')} (- {i18n.t('betaStatus')})<br />- </span>- }- >- <Typography- variant="overline"- display="block"- onClick={toggleSearchBoxing}- style={{- border: '1px solid gray',- borderRadius: 5,- lineHeight: 'inherit',- paddingLeft: 3,- paddingRight: 3- }}- >- {searchBoxingName}- </Typography>- </Tooltip>- <HelpTooltip classes={classes} />- </>- ) : (- <HelpTooltip classes={classes} />- )}- </InputAdornment>- ),- endAdornment: (- <InputAdornment position="end">- {isDesktop && (- <Tooltip title={i18n.t('core:savedSearchesTitle')}>- <IconButton- size="small"- edge="end"- onClick={handleOpenSavedSearches}- >- <ExpandMoreIcon />- </IconButton>- </Tooltip>- )}- <Tooltip title={i18n.t('clearSearch') + ' (ESC)'}>- <IconButton- id="clearSearchID"- onClick={() => {- clearSearch();- // props.openCurrentDirectory();- }}- size="small"- edge="end"- >- <ClearSearchIcon />- </IconButton>- </Tooltip>- </InputAdornment>- )- }}- />- <Tooltip title={indexing ? i18n.t('searchDisabledWhileIndexing') : ''}>- <Button- id="searchButton"- variant="outlined"- size="small"- disabled={indexing}- style={{- marginRight: 10,- marginLeft: 10- }}- color="primary"- onClick={clickSearchButton}- >- {i18n.t('searchTitle')}- </Button>- </Tooltip>- </div>- <SavedSearchesMenu- anchorEl={openSavedSearches}- open={Boolean(openSavedSearches)}- onClose={() => setOpenSavedSearches(null)}- />- </>- );-}--function mapStateToProps(state) {- return {- indexing: isIndexing(state),- searchQuery: getSearchQuery(state),- isDesktop: isDesktopMode(state),- currentDirectory: getDirectoryPath(state),- indexedEntriesCount: getIndexedEntriesCount(state),- maxSearchResults: getMaxSearchResults(state),- showUnixHiddenEntries: getShowUnixHiddenEntries(state),- language: getCurrentLanguage(state)- };-}--function mapDispatchToProps(dispatch) {- return bindActionCreators(- {- searchAllLocations: LocationIndexActions.searchAllLocations,- setSearchQuery: LocationIndexActions.setSearchQuery,- searchLocationIndex: LocationIndexActions.searchLocationIndex,- createLocationsIndexes: LocationIndexActions.createLocationsIndexes,- // loadDirectoryContent: AppActions.loadDirectoryContent,- openLink: AppActions.openLink,- openURLExternally: AppActions.openURLExternally,- // openCurrentDirectory: AppActions.openCurrentDirectory,- watchForChanges: AppActions.watchForChanges- },- dispatch- );-}--const areEqual = (prevProp, nextProp) =>- nextProp.open === prevProp.open &&- nextProp.language === prevProp.language &&- nextProp.indexing === prevProp.indexing &&- nextProp.searchQuery === prevProp.searchQuery &&- nextProp.currentDirectory === prevProp.currentDirectory &&- nextProp.indexedEntriesCount === prevProp.indexedEntriesCount;--export default connect(- mapStateToProps,- mapDispatchToProps-)(React.memo(SearchInline, areEqual));-*/diff --git a/app/components/SearchPopover.tsx b/app/components/SearchPopover.tsxindex a6f46254c..66e73198b 100644--- a/app/components/SearchPopover.tsx+++ b/app/components/SearchPopover.tsx@@ -31,13 +31,16 @@ import NoteIcon from '@mui/icons-material/Note';import AudioIcon from '@mui/icons-material/MusicVideo';import VideoIcon from '@mui/icons-material/OndemandVideo';import ArchiveIcon from '@mui/icons-material/Archive';+import DialogActions from '@mui/material/DialogActions';import FolderIcon from '@mui/icons-material/FolderOpen';import UntaggedIcon from '@mui/icons-material/LabelOffOutlined';import FileIcon from '@mui/icons-material/InsertDriveFileOutlined';+import EditIcon from '@mui/icons-material/Edit';import BookmarkIcon from '@mui/icons-material/BookmarkBorder';import BookIcon from '@mui/icons-material/LocalLibraryOutlined';import DateIcon from '@mui/icons-material/DateRange';import Button from '@mui/material/Button';+import Grid from '@mui/material/Grid';import Input from '@mui/material/Input';import OutlinedInput from '@mui/material/OutlinedInput';import TextField from '@mui/material/TextField';@@ -58,7 +61,6 @@ import TagsSelect from './TagsSelect';import { actions as AppActions, getDirectoryPath } from '../reducers/app';import {actions as LocationIndexActions,- getIndexedEntriesCount,isIndexing,getSearchQuery} from '../reducers/location-index';@@ -77,6 +79,8 @@ import { getSearches } from '-/reducers/searches';import { TS } from '-/tagspaces.namespace';import { ProLabel, BetaLabel, ProTooltip } from '-/components/HelperComponents';import Links from '-/content/links';+import { CreateFileIcon } from '-/components/CommonIcons';+import GlobalSearch from '-/services/search-index';const SaveSearchDialog = Pro && Pro.UI ? Pro.UI.SaveSearchDialog : false;@@ -97,14 +101,13 @@ interface Props {exitSearchMode: () => void;setSearchQuery: (searchQuery: TS.SearchQuery) => void;currentDirectory: string;- indexedEntriesCount: number;maxSearchResults: number;indexing: boolean;searches: Array<TS.SearchQuery>;showUnixHiddenEntries: boolean;// openSearchPanel: () => void;onClose: () => void;- getTextQuery: () => string;+ textQuery: string;setTextQuery: (value: string) => void;}@@ -156,7 +159,7 @@ function SearchPopover(props: Props) {props.searchQuery.fileSize ? props.searchQuery.fileSize : '');- /* useEffect(() => {+ /*useEffect(() => {props.setTextQuery(props.searchQuery.textQuery);}, [props.searchQuery]);*/@@ -299,6 +302,12 @@ function SearchPopover(props: Props) {}};+ const handleSearchTermChange = event => {+ const { target } = event;+ const { value } = target;+ props.setTextQuery(value);+ };+const handleTimePeriodChange = event => {const { target } = event;const { value } = target;@@ -393,24 +402,24 @@ function SearchPopover(props: Props) {const saveSearch = (isNew = true) => {const tagsAND = mergeWithExtractedTags(- props.getTextQuery(),+ props.textQuery,props.searchQuery.tagsAND,'+');const tagsOR = mergeWithExtractedTags(- props.getTextQuery(),+ props.textQuery,props.searchQuery.tagsOR,'|');const tagsNOT = mergeWithExtractedTags(- props.getTextQuery(),+ props.textQuery,props.searchQuery.tagsNOT,'-');setSaveSearchDialogOpened({uuid: isNew ? undefined : props.searchQuery.uuid,title: props.searchQuery.title,- textQuery: props.getTextQuery(),+ textQuery: props.textQuery,tagsAND,tagsOR,tagsNOT,@@ -452,22 +461,22 @@ function SearchPopover(props: Props) {const executeSearch = () => {const tagsAND = mergeWithExtractedTags(- props.getTextQuery(),+ props.textQuery,props.searchQuery.tagsAND,'+');const tagsOR = mergeWithExtractedTags(- props.getTextQuery(),+ props.textQuery,props.searchQuery.tagsOR,'|');const tagsNOT = mergeWithExtractedTags(- props.getTextQuery(),+ props.textQuery,props.searchQuery.tagsNOT,'-');const searchQuery: TS.SearchQuery = {- textQuery: props.getTextQuery(),+ textQuery: props.textQuery,tagsAND,tagsOR,tagsNOT,@@ -491,10 +500,9 @@ function SearchPopover(props: Props) {props.onClose();};- const { indexing, indexedEntriesCount } = props;-- const indexStatus = indexedEntriesCount- ? indexedEntriesCount + ' indexed entries'+ const { indexing } = props;+ const indexStatus = GlobalSearch.getInstance().getIndex()+ ? GlobalSearch.getInstance().getIndex().length + ' indexed entries': '';return (<div@@ -504,9 +512,6 @@ function SearchPopover(props: Props) {}}><div className={classes.toolbar}>- <Typography variant="button" style={{ margin: '12px 0 10px 10px' }}>- {i18n.t('core:advancedSearch')}- </Typography><IconButtonsize="medium"data-tid="helpSearchTID"@@ -517,6 +522,9 @@ function SearchPopover(props: Props) {><HelpIcon /></IconButton>+ {/*<Typography variant="button" style={{ margin: '12px 0 10px 10px' }}>+ {i18n.t('core:advancedSearch')}+ </Typography>*/}<Typographyvariant="caption"className={classes.header}@@ -534,68 +542,94 @@ function SearchPopover(props: Props) {</IconButton></div><div className={classes.searchArea} data-tid="searchAdvancedTID">- <FormControl- className={classes.formControl}- style={{ marginTop: 5 }}- disabled={indexing || !Pro}+ <Grid+ container+ spacing={2}+ style={{ marginBottom: 15 }}+ direction="row"+ justifyContent="center"+ alignItems="flex-end">- <ProTooltip tooltip={i18n.t('storedSearchQueriesTooltip')}>- <InputLabel shrink htmlFor="saved-searches">- {i18n.t('core:savedSearchesTitle')}- </InputLabel>- <Select- onChange={handleSavedSearchChange}- input={- <OutlinedInput- name="savedSearch"- id="saved-searches"- label={i18n.t('core:savedSearchesTitle')}- />- }- displayEmpty- fullWidth- value={props.searchQuery.uuid ? props.searchQuery.uuid : -1}+ <Grid item xs={9}>+ <ProTooltip tooltip={i18n.t('storedSearchQueriesTooltip')}>+ <InputLabel shrink htmlFor="saved-searches">+ {i18n.t('core:savedSearchesTitle')}+ </InputLabel>+ <Select+ disabled={indexing || !Pro}+ onChange={handleSavedSearchChange}+ inputProps={{+ endAdornment: (+ <InputAdornment position="end">+ {props.searchQuery.uuid && (+ <IconButton+ data-tid="editSearchBtnTID"+ size="small"+ onClick={() => saveSearch(false)}+ >+ <EditIcon />+ </IconButton>+ )}+ </InputAdornment>+ )+ }}+ input={<Input name="savedSearch" id="saved-searches" />}+ displayEmpty+ fullWidth+ value={props.searchQuery.uuid ? props.searchQuery.uuid : -1}+ >+ <MenuItem value={-1} style={{ display: 'none' }} />+ {props.searches.length < 1 && (+ <MenuItem>{i18n.t('noSavedSearches')}</MenuItem>+ )}+ {props.searches.map(search => (+ <MenuItem key={search.uuid} value={search.uuid}>+ <span style={{ width: '100%' }}>{search.title}</span>+ </MenuItem>+ ))}+ </Select>+ </ProTooltip>+ </Grid>+ <Grid item xs={3}>+ <ButtonGroup+ style={{+ textAlign: 'center',+ width: '100%'+ }}>- <MenuItem value={-1} style={{ display: 'none' }} />- {props.searches.length < 1 && (- <MenuItem>{i18n.t('noSavedSearches')}</MenuItem>+ {props.searchQuery.uuid && (+ <IconButton+ data-tid="editSearchBtnTID"+ size="small"+ onClick={() => saveSearch(false)}+ >+ <EditIcon />+ </IconButton>)}- {props.searches.map(search => (- <MenuItem key={search.uuid} value={search.uuid}>- <span style={{ width: '100%' }}>{search.title}</span>- </MenuItem>- ))}- </Select>- </ProTooltip>- </FormControl>- {Pro && (- <FormControl className={classes.formControl}>- <ButtonGroup fullWidth style={{ justifyContent: 'center' }}><Button- data-tid="saveSearchBtnTID"+ disabled={!Pro}+ data-tid="addSearchBtnTID"variant="outlined"color="primary"size="small"- style={{ flex: 1 }}onClick={() => saveSearch()}>- {i18n.t('searchSaveBtn')}+ {'+'}</Button>- {props.searchQuery.uuid && (- <Button- data-tid="editSearchBtnTID"- variant="outlined"- color="primary"- size="small"- style={{ flex: 1 }}- onClick={() => saveSearch(false)}- >- {i18n.t('searchEditBtn')}- </Button>- )}</ButtonGroup>- </FormControl>- )}+ </Grid>+ <Grid item xs={12}>+ <TextField+ id="searchTerm"+ label={i18n.t('searchTitle')}+ value={props.textQuery}+ onChange={handleSearchTermChange}+ onKeyDown={startSearch}+ style={{ width: '100%' }}+ />+ </Grid>+ </Grid>+<FormControl className={classes.formControl} disabled={indexing}><ToggleButtonGrouponChange={switchSearchBoxing}@@ -670,34 +704,6 @@ function SearchPopover(props: Props) {</ToggleButton></ToggleButtonGroup></FormControl>- <FormControl className={classes.formControl} disabled={indexing}>- <ButtonGroup style={{ justifyContent: 'center' }}>- <Button- disabled={indexing}- id="searchButtonAdvTID"- variant="contained"- color="primary"- onClick={executeSearch}- style={{ flex: 1 }}- size="small"- >- {indexing- ? 'Search disabled while indexing'- : i18n.t('searchTitle')}- </Button>- <Tooltip title={i18n.t('clearSearch')}>- <Button- variant="contained"- color="primary"- size="small"- onClick={clearSearch}- id="resetSearchButton"- >- {i18n.t('resetBtn')}- </Button>- </Tooltip>- </ButtonGroup>- </FormControl><FormControl className={classes.formControl} disabled={indexing}><TagsSelectdataTid="searchTagsAndTID"@@ -998,6 +1004,41 @@ function SearchPopover(props: Props) {</>)}</div>+ <div+ style={{+ display: 'flex',+ justifyContent: 'space-between',+ paddingRight: 8+ }}+ >+ <Button+ size="small"+ data-tid="helpSearchButtonTID"+ title={i18n.t('core:help')}+ onClick={() =>+ props.openURLExternally(Links.documentationLinks.search, true)+ }+ >+ {i18n.t('help')}+ </Button>+ <ButtonGroup>+ <Button+ disabled={indexing}+ id="searchButtonAdvTID"+ onClick={executeSearch}+ size="small"+ >+ {indexing+ ? 'Search disabled while indexing'+ : i18n.t('searchTitle')}+ </Button>+ <Tooltip title={i18n.t('clearSearch')}>+ <Button size="small" onClick={clearSearch} id="resetSearchButton">+ {i18n.t('resetBtn')}+ </Button>+ </Tooltip>+ </ButtonGroup>+ </div>{SaveSearchDialog && saveSearchDialogOpened !== undefined && (<SaveSearchDialogopen={true}@@ -1023,7 +1064,6 @@ function mapStateToProps(state) {indexing: isIndexing(state),searchQuery: getSearchQuery(state),currentDirectory: getDirectoryPath(state),- indexedEntriesCount: getIndexedEntriesCount(state),maxSearchResults: getMaxSearchResults(state),searches: getSearches(state),showUnixHiddenEntries: getShowUnixHiddenEntries(state),@@ -1049,8 +1089,8 @@ const areEqual = (prevProp, nextProp) =>nextProp.language === prevProp.language &&nextProp.indexing === prevProp.indexing &&nextProp.searchQuery === prevProp.searchQuery &&+ nextProp.textQuery === prevProp.textQuery &&nextProp.currentDirectory === prevProp.currentDirectory &&- nextProp.indexedEntriesCount === prevProp.indexedEntriesCount &&JSON.stringify(nextProp.searches) === JSON.stringify(prevProp.searches) &&JSON.stringify(nextProp.classes) === JSON.stringify(prevProp.classes);diff --git a/app/perspectives/grid-perspective/components/MainContainer.tsx b/app/perspectives/grid-perspective/components/MainContainer.tsxindex a97abf63b..7d9adee2e 100644--- a/app/perspectives/grid-perspective/components/MainContainer.tsx+++ b/app/perspectives/grid-perspective/components/MainContainer.tsx@@ -183,7 +183,7 @@ function GridPerspective(props: Props) {: defaultSettings.orderBy);const sortedDirContent = useRef<Array<TS.FileSystemEntry>>(- !props.lastSearchTimestamp ? props.directoryContent : GlobalSearch.results+ !props.lastSearchTimestamp ? props.directoryContent : GlobalSearch.getInstance().getResults());const layoutType = useRef<string>(settings && settings.layoutType@@ -324,19 +324,19 @@ function GridPerspective(props: Props) {if (sortBy.current === 'byRelevance') {// initial search results is sorted by relevanceif (orderBy.current) {- sortedDirContent.current = GlobalSearch.results;+ sortedDirContent.current = GlobalSearch.getInstance().getResults();} else {- sortedDirContent.current = [...GlobalSearch.results].reverse();+ sortedDirContent.current = [...GlobalSearch.getInstance().getResults()].reverse();}} else {sortedDirContent.current = sortByCriteria(props.searchFilter- ? GlobalSearch.results.filter(entry =>+ ? GlobalSearch.getInstance().getResults().filter(entry =>entry.name.toLowerCase().includes(props.searchFilter.toLowerCase()))- : GlobalSearch.results,+ : GlobalSearch.getInstance().getResults(),sortBy.current,orderBy.current);@@ -348,7 +348,7 @@ function GridPerspective(props: Props) {useEffect(() => {// HANDLE (ADD/REMOVE sidecar TAGS) IN SEARCH RESULTSif (!firstRender && props.lastSearchTimestamp) {- sortedDirContent.current = GlobalSearch.results;+ sortedDirContent.current = GlobalSearch.getInstance().getResults();forceUpdate();}}, [props.editedEntryPaths]);@@ -519,7 +519,7 @@ function GridPerspective(props: Props) {if (!props.lastSearchTimestamp) {props.setSelectedEntries(props.directoryContent);} else {- props.setSelectedEntries(GlobalSearch.results);+ props.setSelectedEntries(GlobalSearch.getInstance().getResults());}}};diff --git a/app/perspectives/list/components/MainContainer.tsx b/app/perspectives/list/components/MainContainer.tsxindex e3a72d7cb..7fd444dbc 100644--- a/app/perspectives/list/components/MainContainer.tsx+++ b/app/perspectives/list/components/MainContainer.tsx@@ -183,7 +183,7 @@ function GridPerspective(props: Props) {: defaultSettings.orderBy);const sortedDirContent = useRef<Array<TS.FileSystemEntry>>(- !props.lastSearchTimestamp ? props.directoryContent : GlobalSearch.results+ !props.lastSearchTimestamp ? props.directoryContent : GlobalSearch.getInstance().getResults());const layoutType = useRef<string>(settings && settings.layoutType@@ -324,19 +324,19 @@ function GridPerspective(props: Props) {if (sortBy.current === 'byRelevance') {// initial search results is sorted by relevanceif (orderBy.current) {- sortedDirContent.current = GlobalSearch.results;+ sortedDirContent.current = GlobalSearch.getInstance().getResults();} else {- sortedDirContent.current = [...GlobalSearch.results].reverse();+ sortedDirContent.current = [...GlobalSearch.getInstance().getResults()].reverse();}} else {sortedDirContent.current = sortByCriteria(props.searchFilter- ? GlobalSearch.results.filter(entry =>+ ? GlobalSearch.getInstance().getResults().filter(entry =>entry.name.toLowerCase().includes(props.searchFilter.toLowerCase()))- : GlobalSearch.results,+ : GlobalSearch.getInstance().getResults(),sortBy.current,orderBy.current);@@ -348,7 +348,7 @@ function GridPerspective(props: Props) {useEffect(() => {// HANDLE (ADD/REMOVE sidecar TAGS) IN SEARCH RESULTSif (!firstRender && props.lastSearchTimestamp) {- sortedDirContent.current = GlobalSearch.results;+ sortedDirContent.current = GlobalSearch.getInstance().getResults();forceUpdate();}}, [props.editedEntryPaths]);@@ -519,7 +519,7 @@ function GridPerspective(props: Props) {if (!props.lastSearchTimestamp) {props.setSelectedEntries(props.directoryContent);} else {- props.setSelectedEntries(GlobalSearch.results);+ props.setSelectedEntries(GlobalSearch.getInstance().getResults());}}};diff --git a/app/reducers/app.ts b/app/reducers/app.tsindex 055cad542..87ab62e2e 100644--- a/app/reducers/app.ts+++ b/app/reducers/app.ts@@ -553,7 +553,7 @@ export default (state: any = initialState, action: any) => {};}case types.SET_SEARCH_RESULTS: {- GlobalSearch.results = action.searchResults;+ GlobalSearch.getInstance().setResults(action.searchResults);return {...state,lastSearchTimestamp: new Date().getTime(),@@ -561,7 +561,7 @@ export default (state: any = initialState, action: any) => {};}case types.EXIT_SEARCH_MODE: {- GlobalSearch.results = [];+ GlobalSearch.getInstance().setResults([]);return {...state,searchMode: false,@@ -571,7 +571,7 @@ export default (state: any = initialState, action: any) => {};}case types.ENTER_SEARCH_MODE: {- GlobalSearch.results = [];+ GlobalSearch.getInstance().setResults([]);return {...state,searchMode: true,@@ -582,11 +582,14 @@ export default (state: any = initialState, action: any) => {case types.APPEND_SEARCH_RESULTS: {// const newDirEntries = [...state.currentDirectoryEntries];for (let i = 0; i < action.searchResults.length; i += 1) {- const index = GlobalSearch.results.findIndex(- entry => entry.path === action.searchResults[i].path- );+ const index = GlobalSearch.getInstance()+ .getResults()+ .findIndex(entry => entry.path === action.searchResults[i].path);if (index === -1) {- GlobalSearch.results.push(action.searchResults[i]);+ GlobalSearch.getInstance().setResults([+ ...GlobalSearch.getInstance().getResults(),+ action.searchResults[i]+ ]);}}return {@@ -2461,8 +2464,9 @@ export const actions = {) => {const { searchMode } = getState().app;if (searchMode) {- GlobalSearch.results = GlobalSearch.results.map(- (fsEntry: TS.FileSystemEntry) => {+ const results = GlobalSearch.getInstance()+ .getResults()+ .map((fsEntry: TS.FileSystemEntry) => {if (fsEntry.path === path) {return {...fsEntry,@@ -2471,8 +2475,8 @@ export const actions = {};}return fsEntry;- }- );+ });+ GlobalSearch.getInstance().setResults(results);}dispatch(actions.reflectRenameEntryInt(path, newPath));dispatch(LocationIndexActions.reflectRenameEntry(path, newPath));@@ -2489,9 +2493,10 @@ export const actions = {) => {const { searchMode } = getState().app;if (searchMode) {- GlobalSearch.results = updateFsEntries(GlobalSearch.results, [+ const results = updateFsEntries(GlobalSearch.getInstance().getResults(), [{ ...entry, path }]);+ GlobalSearch.getInstance().setResults(results);} else {dispatch(actions.updateCurrentDirEntryInt(path, entry));}diff --git a/app/reducers/location-index.ts b/app/reducers/location-index.tsindex e2de1b5c2..99e84542d 100644--- a/app/reducers/location-index.ts+++ b/app/reducers/location-index.ts@@ -81,11 +81,11 @@ export default (state: any = initialState, action: any) => {};}case types.INDEX_DIRECTORY_CLEAR: {- // GlobalSearch.index.length = 0;- if (GlobalSearch.index) {+ /*if (GlobalSearch.index) {GlobalSearch.index.splice(0, GlobalSearch.index.length);- }- GlobalSearch.indexLoadedOn = undefined;+ }*/+ GlobalSearch.getInstance().setIndex([]);+ GlobalSearch.getInstance().setIndexLoadedOn(undefined);return {...state,isIndexing: false@@ -102,7 +102,6 @@ export default (state: any = initialState, action: any) => {};}case types.INDEX_DIRECTORY_FAILURE: {- // GlobalSearch.index.length = 0;return {...state,lastError: action.error,@@ -110,50 +109,54 @@ export default (state: any = initialState, action: any) => {};}case types.REFLECT_DELETE_ENTRY: {- if (!GlobalSearch.index || GlobalSearch.index.length < 1) {+ const index = GlobalSearch.getInstance().getIndex();+ if (!index || index.length < 1) {return state;}- for (let i = 0; i < GlobalSearch.index.length; i += 1) {- if (GlobalSearch.index[i].path === action.path) {- GlobalSearch.index.splice(i, 1);+ for (let i = 0; i < index.length; i += 1) {+ if (index[i].path === action.path) {+ GlobalSearch.getInstance().setIndex(index.splice(i, 1));i -= 1;}}return state;}case types.REFLECT_CREATE_ENTRY: {- if (!GlobalSearch.index || GlobalSearch.index.length < 1) {+ const index = GlobalSearch.getInstance().getIndex();+ if (!index || index.length < 1) {return state;}let entryFound = false;- for (let i = 0; i < GlobalSearch.index.length; i += 1) {- if (GlobalSearch.index[i].path === action.path) {+ for (let i = 0; i < index.length; i += 1) {+ if (index[i].path === action.path) {entryFound = true;}}if (entryFound) {return state;}- GlobalSearch.index.push(action.newEntry);+ GlobalSearch.getInstance().setIndex([...index, action.newEntry]);return state;}+ // TODO move it from reducer to GlobalSearch singletoncase types.REFLECT_RENAME_ENTRY: {- if (!GlobalSearch.index || GlobalSearch.index.length < 1) {+ const index = GlobalSearch.getInstance().getIndex();+ if (!index || index.length < 1) {return state;}- for (let i = 0; i < GlobalSearch.index.length; i += 1) {- if (GlobalSearch.index[i].path === action.path) {- GlobalSearch.index[i].path = action.newPath;- GlobalSearch.index[i].name = extractFileName(+ for (let i = 0; i < index.length; i += 1) {+ if (index[i].path === action.path) {+ index[i].path = action.newPath;+ index[i].name = extractFileName(action.newPath,PlatformIO.getDirSeparator());- GlobalSearch.index[i].extension = extractFileExtension(+ index[i].extension = extractFileExtension(action.newPath,PlatformIO.getDirSeparator());- GlobalSearch.index[i].tags = [- ...GlobalSearch.index[i].tags.filter(tag => tag.type === 'sidecar'), // add only sidecar tags+ index[i].tags = [+ ...index[i].tags.filter(tag => tag.type === 'sidecar'), // add only sidecar tags...extractTagsAsObjects(action.newPath,AppConfig.tagDelimiter,@@ -165,10 +168,11 @@ export default (state: any = initialState, action: any) => {return state;}case types.REFLECT_UPDATE_SIDECARTAGS: {- for (let i = 0; i < GlobalSearch.index.length; i += 1) {- if (GlobalSearch.index[i].path === action.path) {- GlobalSearch.index[i].tags = [- ...GlobalSearch.index[i].tags.filter(tag => tag.type === 'plain'),+ const index = GlobalSearch.getInstance().getIndex();+ for (let i = 0; i < index.length; i += 1) {+ if (index[i].path === action.path) {+ index[i].tags = [+ ...index[i].tags.filter(tag => tag.type === 'plain'),...action.tags];}@@ -176,10 +180,11 @@ export default (state: any = initialState, action: any) => {return state;}case types.REFLECT_UPDATE_SIDECARMETA: {- for (let i = 0; i < GlobalSearch.index.length; i += 1) {- if (GlobalSearch.index[i].path === action.path) {- GlobalSearch.index[i] = {- ...GlobalSearch.index[i],+ const index = GlobalSearch.getInstance().getIndex();+ for (let i = 0; i < index.length; i += 1) {+ if (index[i].path === action.path) {+ index[i] = {+ ...index[i],...action.entryMeta};}@@ -251,7 +256,7 @@ export const actions = {.then(directoryIndex => {if (isCurrentLocation) {// Load index only if current location- GlobalSearch.index = directoryIndex;+ GlobalSearch.getInstance().setIndex(directoryIndex);}dispatch(actions.indexDirectorySuccess());/* if (Pro && Pro.Indexer) {@@ -398,10 +403,11 @@ export const actions = {));setTimeout(async () => {+ const index = GlobalSearch.getInstance().getIndex();// Workaround used to show the start search notificationconst currentTime = new Date().getTime();- const indexAge = GlobalSearch.indexLoadedOn- ? currentTime - GlobalSearch.indexLoadedOn+ const indexAge = GlobalSearch.getInstance().getIndexLoadedOn()+ ? currentTime - GlobalSearch.getInstance().getIndexLoadedOn(): 0;const maxIndexAge = currentLocation.maxIndexAge? currentLocation.maxIndexAge@@ -409,13 +415,13 @@ export const actions = {if (searchQuery.forceIndexing ||(!currentLocation.disableIndexing &&- (!GlobalSearch.index ||- GlobalSearch.index.length < 1 ||+ (!index ||+ index.length < 1 ||indexAge > maxIndexAge))) {const currentPath = PlatformIO.getLocationPath(currentLocation);console.log('Start creating index for : ' + currentPath);- GlobalSearch.index = await createDirectoryIndex(+ const newIndex = await createDirectoryIndex({path: currentPath,locationID: currentLocation.uuid,@@ -425,16 +431,17 @@ export const actions = {currentLocation.ignorePatternPaths,state.settings.enableWS);+ GlobalSearch.getInstance().setIndex(newIndex);- if (GlobalSearch.index && GlobalSearch.index.length > 0) {- GlobalSearch.indexLoadedOn = new Date().getTime();+ if (newIndex && newIndex.length > 0) {+ GlobalSearch.getInstance().setIndexLoadedOn(new Date().getTime());}} else if (isCloudLocation ||- !GlobalSearch.index ||- GlobalSearch.index.length === 0+ !index ||+ index.length === 0) {- GlobalSearch.index = await loadIndex(+ const newIndex = await loadIndex({path: PlatformIO.getLocationPath(currentLocation),locationID: currentLocation.uuid,@@ -443,8 +450,9 @@ export const actions = {PlatformIO.getDirSeparator(),PlatformIO.loadTextFilePromise);+ GlobalSearch.getInstance().setIndex(newIndex);}- Search.searchLocationIndex(GlobalSearch.index, searchQuery)+ Search.searchLocationIndex(GlobalSearch.getInstance().getIndex(), searchQuery).then(searchResults => {if (isCloudLocation) {searchResults.forEach((entry: TS.FileSystemEntry) => {@@ -706,7 +714,5 @@ export const actions = {};// Selectors-export const getIndexedEntriesCount = (state: any) =>- GlobalSearch.index ? GlobalSearch.index.length : 0;export const isIndexing = (state: any) => state.locationIndex.isIndexing;export const getSearchQuery = (state: any) => state.locationIndex.searchQuery;diff --git a/app/reducers/tagging-actions.ts b/app/reducers/tagging-actions.tsindex ff03d64e1..8c5f11ddc 100644--- a/app/reducers/tagging-actions.ts+++ b/app/reducers/tagging-actions.ts@@ -813,7 +813,7 @@ const actions = {) => {const { settings } = getState();- if (GlobalSearch.index.length < 1) {+ if (GlobalSearch.getInstance().getIndex().length < 1) {dispatch(AppActions.showNotification('Please index location first',@@ -825,7 +825,7 @@ const actions = {}const uniqueTags = collectTagsFromIndex(- GlobalSearch.index,+ GlobalSearch.getInstance().getIndex(),tagGroup,settings);diff --git a/app/services/search-index.ts b/app/services/search-index.tsindex 113b1831e..16b2c3a78 100644--- a/app/services/search-index.ts+++ b/app/services/search-index.ts@@ -16,9 +16,44 @@**/-const GlobalSearch = {+/*const GlobalSearch = {indexLoadedOn: undefined,index: [],results: []-};+};*/++const GlobalSearch = function() {+ let instance;++ function init() {+ let indexLoadedOn = undefined;+ let index = [];+ let results = [];++ return {+ setIndexLoadedOn: function(loaded) {+ indexLoadedOn = loaded;+ },+ getIndexLoadedOn: () => indexLoadedOn,+ setIndex: function(i) {+ index = i;+ },+ getIndex: () => index,+ setResults: function(r) {+ results = r;+ },+ getResults: () => results+ };+ }++ return {+ // get the singleton instance if it exists, or create one if it doesn't+ getInstance: function() {+ if (!instance) {+ instance = init();+ }+ return instance;+ }+ };+}();export default GlobalSearch;