Skip to content

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

Improve usability tagging dialog-component (#2170)

Stanimir7bb4ce927618
diff --git a/src/renderer/components/TagsSelect.tsx b/src/renderer/components/TagsSelect.tsx
index 931c022b1..e1cfca72d 100644
--- a/src/renderer/components/TagsSelect.tsx
+++ b/src/renderer/components/TagsSelect.tsx
@@ -16,7 +16,7 @@
*
*/
-import React, { useEffect, useRef, useState } from 'react';
+import React, { useReducer, useRef, useState } from 'react';
import { useSelector } from 'react-redux';
import TextField from '@mui/material/TextField';
import Autocomplete from '@mui/material/Autocomplete';
@@ -29,13 +29,17 @@ import { getAllTags } from '-/services/taglibrary-utils';
import { Box } from '@mui/material';
import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';
import { isDesktopMode } from '-/reducers/settings';
+import { tagsValidation } from '-/services/utils-io';
+import FormHelperText from '@mui/material/FormHelperText';
+import { useTranslation } from 'react-i18next';
interface Props {
dataTid?: string;
tags: TS.Tag[];
label?: string;
tagSearchType?: string;
- handleChange?: (param1: any, param2: any, param3?: any) => void;
+ handleChange?: (name: string, value: TS.Tag[], action: string) => void;
+ handleNewTags?: (newTags: TS.Tag[]) => void;
tagMode?: 'default' | 'display' | 'remove';
placeholderText?: string;
selectedEntryPath?: string;
@@ -43,6 +47,7 @@ interface Props {
}
function TagsSelect(props: Props) {
+ const { t } = useTranslation();
const { readOnlyMode } = useCurrentLocationContext();
const desktopMode = useSelector(isDesktopMode);
const [tagMenuAnchorEl, setTagMenuAnchorEl] = useState<null | HTMLElement>(
@@ -50,10 +55,12 @@ function TagsSelect(props: Props) {
);
const [selectedTag, setSelectedTag] = useState(undefined);
+ const tagsError = useRef<boolean>(false);
const allTags = useRef<Array<TS.Tag>>(getAllTags());
const defaultBackgroundColor = useSelector(getTagColor);
const defaultTextColor = useSelector(getTagTextColor);
+ const [ignored, forceUpdate] = useReducer((x) => x + 1, 0, undefined);
const {
placeholderText = '',
label,
@@ -61,6 +68,7 @@ function TagsSelect(props: Props) {
autoFocus = false,
tags = [],
tagMode,
+ handleNewTags,
} = props;
function handleTagChange(
@@ -68,52 +76,71 @@ function TagsSelect(props: Props) {
selectedTags: Array<TS.Tag>,
reason: string,
) {
+ tagsError.current = false;
if (!readOnlyMode) {
- if (reason === 'selectOption') {
- props.handleChange(props.tagSearchType, selectedTags, reason);
- } else if (reason === 'createOption') {
- if (selectedTags && selectedTags.length) {
- const tagsInput = '' + selectedTags[selectedTags.length - 1];
- let tags = tagsInput.split(' ').join(',').split(','); // handle spaces around commas
- tags = [...new Set(tags)]; // remove duplicates
- tags = tags.filter((tag) => tag && tag.length > 0); // zero length tags
-
- const newTags = [];
- tags.map((tag) => {
- const newTag: TS.Tag = {
- id: getUuid(),
- title: '' + tag,
- color: defaultBackgroundColor,
- textcolor: defaultTextColor,
- };
- if (isValidNewOption(newTag.title, selectedTags)) {
- newTags.push(newTag);
- allTags.current.push(newTag);
- }
- });
- selectedTags.pop();
- const allNewTags = [...selectedTags, ...newTags];
- props.handleChange(props.tagSearchType, allNewTags, reason);
+ if (reason === 'blur') {
+ if (handleNewTags) {
+ handleNewTags(undefined);
+ }
+ } else {
+ if (handleNewTags) {
+ handleNewTags([]);
+ }
+ if (reason === 'selectOption') {
+ props.handleChange(props.tagSearchType, selectedTags, reason);
+ } else if (reason === 'createOption') {
+ if (selectedTags && selectedTags.length) {
+ const newTags = parseTagsInput(
+ '' + selectedTags[selectedTags.length - 1],
+ );
+ selectedTags.pop();
+ const allNewTags = [...selectedTags, ...newTags];
+ props.handleChange(props.tagSearchType, allNewTags, reason);
+ }
+ } else if (reason === 'remove-value') {
+ props.handleChange(props.tagSearchType, selectedTags, reason);
+ } else if (reason === 'clear') {
+ props.handleChange(props.tagSearchType, [], reason);
}
- } else if (reason === 'remove-value') {
- props.handleChange(props.tagSearchType, selectedTags, reason);
- } else if (reason === 'clear') {
- props.handleChange(props.tagSearchType, [], reason);
}
} else {
console.debug('tags disabled in read only mode!');
}
}
- function isValidNewOption(inputValue, selectOptions) {
- const trimmedInput = inputValue.trim();
- return (
- trimmedInput.trim().length > 0 &&
- !trimmedInput.includes(' ') &&
- !trimmedInput.includes('#') &&
- !trimmedInput.includes(',') &&
- !selectOptions.find((option) => option.title === inputValue)
- );
+ function parseTagsInput(tagsInput: string): TS.Tag[] {
+ let tags = tagsInput.split(' ').join(',').split(','); // handle spaces around commas
+ tags = [...new Set(tags)]; // remove duplicates
+
+ const newTags = [];
+ tags.map((tag) => {
+ if (tagsValidation(tag)) {
+ const newTag: TS.Tag = {
+ id: getUuid(),
+ title: '' + tag,
+ color: defaultBackgroundColor,
+ textcolor: defaultTextColor,
+ };
+ //if (!allTags.current.find((option) => option.title === newTag.title)) {
+ newTags.push(newTag);
+ //allTags.current.push(newTag);
+ //}
+ } else {
+ tagsError.current = true;
+ forceUpdate();
+ }
+ });
+ return newTags;
+ }
+
+ function handleInputChange(event: any, value: string, reason: string) {
+ tagsError.current = false;
+ if (reason === 'input') {
+ const newTags = parseTagsInput(value);
+ if (handleNewTags) {
+ handleNewTags(newTags);
+ }
+ }
}
const handleTagMenu = (event: React.ChangeEvent<HTMLInputElement>, tag) => {
@@ -146,12 +173,13 @@ function TagsSelect(props: Props) {
options={!readOnlyMode ? allTags.current : []}
getOptionLabel={(option: TS.Tag) => option.title}
freeSolo
+ disableClearable={true}
autoSelect
autoComplete
- disableClearable
size={desktopMode ? 'small' : 'medium'}
value={tags}
onChange={handleTagChange}
+ onInputChange={handleInputChange}
renderTags={(value: readonly TS.Tag[], getTagProps) =>
value.map((option: TS.Tag, index: number) => (
<TagContainer
@@ -169,16 +197,22 @@ function TagsSelect(props: Props) {
</Box>
)}
renderInput={(params) => (
- <TextField
- {...params}
- // variant="filled"
- label={label}
- placeholder={placeholderText}
- margin="normal"
- autoFocus={autoFocus}
- style={{ marginTop: 0, marginBottom: 0, whiteSpace: 'nowrap' }}
- fullWidth
- />
+ <>
+ <TextField
+ {...params}
+ // variant="filled"
+ label={label}
+ placeholder={placeholderText}
+ margin="normal"
+ autoFocus={autoFocus}
+ error={tagsError.current}
+ style={{ marginTop: 0, marginBottom: 0, whiteSpace: 'nowrap' }}
+ fullWidth
+ />
+ {tagsError.current && (
+ <FormHelperText>{t('core:tagTitleHelper')}</FormHelperText>
+ )}
+ </>
)}
/>
{selectedEntryPath && (
diff --git a/src/renderer/components/dialogs/AddRemoveTagsDialog.tsx b/src/renderer/components/dialogs/AddRemoveTagsDialog.tsx
index 9b5525445..15fa88c58 100644
--- a/src/renderer/components/dialogs/AddRemoveTagsDialog.tsx
+++ b/src/renderer/components/dialogs/AddRemoveTagsDialog.tsx
@@ -16,7 +16,7 @@
*
*/
-import React, { useState } from 'react';
+import React, { useReducer, useRef, useState } from 'react';
import Button from '@mui/material/Button';
import Paper from '@mui/material/Paper';
import DialogActions from '@mui/material/DialogActions';
@@ -57,7 +57,9 @@ function AddRemoveTagsDialog(props: Props) {
const { currentLocation } = useCurrentLocationContext();
const { addTags, removeTags, removeAllTags } = useTaggingActionsContext();
- const [newlyAddedTags, setNewlyAddedTags] = useState<Array<TS.Tag>>([]);
+ const [newlyAddedTags, setNewlyAddedTags] = useState<TS.Tag[]>([]);
+ const inputTags = useRef<TS.Tag[]>([]);
+ const [ignored, forceUpdate] = useReducer((x) => x + 1, 0, undefined);
const handleChange = (name: string, value: Array<TS.Tag>, action: string) => {
if (action === 'remove-value') {
@@ -70,6 +72,28 @@ function AddRemoveTagsDialog(props: Props) {
}
};
+ const handleNewTags = (newTags: TS.Tag[]) => {
+ if (newTags === undefined) {
+ if (inputTags.current.length > 0) {
+ setNewlyAddedTags(
+ uniqueTags([...newlyAddedTags, ...inputTags.current]),
+ );
+ }
+ } else {
+ inputTags.current = newTags;
+ forceUpdate();
+ }
+ };
+ function uniqueTags(tagsArray: TS.Tag[]): TS.Tag[] {
+ return tagsArray.reduce((acc: TS.Tag[], current) => {
+ // Check if an object with the same 'id' exists in the accumulator
+ if (!acc.some((item) => item.title === current.title)) {
+ acc.push(current);
+ }
+ return acc;
+ }, []);
+ }
+
const onClose = () => {
onCloseDialog();
};
@@ -82,7 +106,7 @@ function AddRemoveTagsDialog(props: Props) {
const addTagsAction = () => {
if (selected && selected.length > 0) {
const paths = selected.map((entry) => entry.path);
- addTags(paths, newlyAddedTags);
+ addTags(paths, uniqueTags([...newlyAddedTags, ...inputTags.current]));
}
onCloseDialog(true);
};
@@ -90,7 +114,7 @@ function AddRemoveTagsDialog(props: Props) {
const removeTagsAction = () => {
if (selected && selected.length > 0) {
const paths = selected.map((entry) => entry.path);
- removeTags(paths, newlyAddedTags);
+ removeTags(paths, [...newlyAddedTags, ...inputTags.current]);
}
onCloseDialog(true);
};
@@ -105,7 +129,9 @@ function AddRemoveTagsDialog(props: Props) {
const { open } = props;
const disabledButtons =
- !newlyAddedTags || newlyAddedTags.length < 1 || selected.length < 1;
+ (!newlyAddedTags && !inputTags.current) ||
+ (newlyAddedTags.length < 1 && inputTags.current.length < 1) ||
+ selected.length < 1;
const theme = useTheme();
const fullScreen = useMediaQuery(theme.breakpoints.down('md'));
@@ -137,6 +163,7 @@ function AddRemoveTagsDialog(props: Props) {
label={t('core:fileTags')}
tags={newlyAddedTags}
handleChange={handleChange}
+ handleNewTags={handleNewTags}
tagMode="remove"
autoFocus={true}
/>
diff --git a/src/renderer/components/dialogs/EditEntryTagDialog.tsx b/src/renderer/components/dialogs/EditEntryTagDialog.tsx
index a1b9020e3..c707f9c7e 100644
--- a/src/renderer/components/dialogs/EditEntryTagDialog.tsx
+++ b/src/renderer/components/dialogs/EditEntryTagDialog.tsx
@@ -42,6 +42,7 @@ import { useTheme } from '@mui/material/styles';
import useMediaQuery from '@mui/material/useMediaQuery';
import { useTranslation } from 'react-i18next';
import { useTaggingActionsContext } from '-/hooks/useTaggingActionsContext';
+import { tagsValidation } from '-/services/utils-io';
interface Props {
open: boolean;
@@ -92,10 +93,11 @@ function EditEntryTagDialog(props: Props) {
// handleValidation();
}, [title]);
- function handleValidation() {
+ function handleValidation(tagTitle: string) {
// Tags should be at least 1 character long and should not contain: spaces, \, / #
- const tagCheck = RegExp(/^[^#/\\ [\]]{1,}$/);
- if (title && tagCheck.test(title)) {
+ //const tagCheck = RegExp(/^[^#/\\ [\]]{1,}$/);
+ if (tagsValidation(tagTitle)) {
+ // && tagCheck.test(title)) {
setError('tag', false);
return true;
}
@@ -104,7 +106,7 @@ function EditEntryTagDialog(props: Props) {
}
function onConfirm() {
- if (handleValidation() && !haveError()) {
+ if (!haveError()) {
const isNew =
tag.functionality === 'geoTagging' ||
tag.functionality === 'dateTagging'; //path.includes(props.selectedTag.title);
@@ -148,6 +150,7 @@ function EditEntryTagDialog(props: Props) {
label={t('core:editTag')}
onChange={(event: ChangeEvent<HTMLInputElement>) => {
const { target } = event;
+ handleValidation(target.value);
setTitle(target.value);
}}
defaultValue={title}
diff --git a/src/renderer/services/utils-io.ts b/src/renderer/services/utils-io.ts
index cb3c017ca..57163eab4 100644
--- a/src/renderer/services/utils-io.ts
+++ b/src/renderer/services/utils-io.ts
@@ -567,6 +567,22 @@ export function getDescriptionPreview(mdContent, maxLength = 200) {
// return marked.parse(DOMPurify.sanitize(mdContent));
// }
+/**
+ * forbidden characters # \ / * ? " < > | & %
+ * @param tagTitle
+ * return true if valid; false otherwise
+ */
+export function tagsValidation(tagTitle: string): boolean {
+ if (tagTitle.length > 0) {
+ if (tagTitle.trim().length === 0 || tagTitle.includes(' ')) {
+ return false;
+ }
+ const rg1 = /^[^#\\/*?"<>|&%]+$/;
+ return rg1.test(tagTitle);
+ }
+ return false;
+}
+
/**
* forbidden characters # \ / * ? " < > |
* @param dirName