Skip to content

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

Fix location tags (#2301)

Stanimirefd7d527d13d
diff --git a/src/renderer/components/SearchAutocomplete.tsx b/src/renderer/components/SearchAutocomplete.tsx
index 3d727986b..114238fca 100644
--- a/src/renderer/components/SearchAutocomplete.tsx
+++ b/src/renderer/components/SearchAutocomplete.tsx
@@ -73,6 +73,7 @@ import { useTranslation } from 'react-i18next';
import { useDispatch, useSelector } from 'react-redux';
import { actions as AppActions, AppDispatch } from '../reducers/app';
import { useHistoryContext } from '-/hooks/useHistoryContext';
+import { useEditedTagLibraryContext } from '-/hooks/useEditedTagLibraryContext';
interface Props {
style?: any;
@@ -105,6 +106,7 @@ function SearchAutocomplete(props: Props) {
} = useDirectoryContentContext();
const { tempSearchQuery, setTempSearchQuery } = useSearchQueryContext();
const { openHistoryItem } = useBrowserHistoryContext();
+ const { tagGroups } = useEditedTagLibraryContext();
const { isIndexing, searchAllLocations, searchLocationIndex } =
useLocationIndexContext();
const { searches } = useSavedSearchesContext();
@@ -663,7 +665,6 @@ function SearchAutocomplete(props: Props) {
) {
currentOptions.current = action;
const searchAction = toExecAction(action);
- const tagGroups = getTagLibrary();
const options = [];
for (let j = 0; j < tagGroups.length; j++) {
tagGroups[j].children.forEach((tag: TS.Tag) => {
diff --git a/src/renderer/components/TagLibrary.tsx b/src/renderer/components/TagLibrary.tsx
index 3840e89a7..b474afa4e 100644
--- a/src/renderer/components/TagLibrary.tsx
+++ b/src/renderer/components/TagLibrary.tsx
@@ -34,9 +34,7 @@ import TagMenu from '-/components/menus/TagMenu';
import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';
import { useEditedTagLibraryContext } from '-/hooks/useEditedTagLibraryContext';
import { useSelectedEntriesContext } from '-/hooks/useSelectedEntriesContext';
-import { useTagGroupsLocationContext } from '-/hooks/useTagGroupsLocationContext';
import { useTaggingActionsContext } from '-/hooks/useTaggingActionsContext';
-import { Pro } from '-/pro';
import { AppDispatch } from '-/reducers/app';
import {
actions as SettingsActions,
@@ -46,15 +44,15 @@ import {
getTagTextColor,
} from '-/reducers/settings';
import SmartTags from '-/reducers/smart-tags';
-import { getAllTags, getTagLibrary } from '-/services/taglibrary-utils';
+import { getAllTags } from '-/services/taglibrary-utils';
import { TS } from '-/tagspaces.namespace';
import { CommonLocation } from '-/utils/CommonLocation';
-import useFirstRender from '-/utils/useFirstRender';
import { Box } from '@mui/material';
import Collapse from '@mui/material/Collapse';
-import React, { useCallback, useEffect, useState } from 'react';
+import React, { useCallback, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useDispatch, useSelector } from 'react-redux';
+import CustomDragLayer from '-/components/CustomDragLayer';
interface Props {
style?: any;
@@ -70,11 +68,9 @@ function TagLibrary(props: Props) {
changeTagOrder,
moveTag,
moveTagGroup,
- importTagGroups,
} = useTaggingActionsContext();
- const { getTagGroups } = useTagGroupsLocationContext();
const { selectedEntries } = useSelectedEntriesContext();
- const { findLocation, locations } = useCurrentLocationContext();
+ const { findLocation } = useCurrentLocationContext();
const { tagGroups } = useEditedTagLibraryContext();
const dispatch: AppDispatch = useDispatch();
const tagBackgroundColor = useSelector(getTagColor);
@@ -106,7 +102,7 @@ function TagLibrary(props: Props) {
const [isDeleteTagDialogOpened, setIsDeleteTagDialogOpened] =
useState<boolean>(false);
const saveTagInLocation: boolean = useSelector(getSaveTagInLocation);
- const firstRender = useFirstRender();
+ /*const firstRender = useFirstRender();
useEffect(() => {
if (Pro && saveTagInLocation && firstRender) {
@@ -143,7 +139,7 @@ function TagLibrary(props: Props) {
newGroup.modified_date <= oldGroup.modified_date,
),
);
- }
+ }*/
const handleTagGroupMenu = (
event: React.ChangeEvent<HTMLInputElement>,
@@ -226,6 +222,7 @@ function TagLibrary(props: Props) {
tagGroupCollapsed={tagGroupCollapsed}
isReadOnly={tagGroup.readOnly}
/>
+ <CustomDragLayer />
<Collapse in={tagGroup.expanded} unmountOnExit>
<TagGroupContainer taggroup={tagGroup}>
{tagGroup.children &&
@@ -364,7 +361,6 @@ function TagLibrary(props: Props) {
open={Boolean(tagLibraryMenuAnchorEl)}
onClose={() => setTagLibraryMenuAnchorEl(null)}
showCreateTagGroupDialog={showCreateTagGroupDialog}
- refreshTagsFromLocation={refreshTagsFromLocation}
/>
{Boolean(tagMenuAnchorEl) && (
<TagMenu
diff --git a/src/renderer/components/TagsSelect.tsx b/src/renderer/components/TagsSelect.tsx
index e20bdd600..a13965161 100644
--- a/src/renderer/components/TagsSelect.tsx
+++ b/src/renderer/components/TagsSelect.tsx
@@ -37,6 +37,7 @@ import { getUuid } from '@tagspaces/tagspaces-common/utils-io';
import React, { useReducer, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useSelector } from 'react-redux';
+import { useEditedTagLibraryContext } from '-/hooks/useEditedTagLibraryContext';
interface Props {
dataTid?: string;
@@ -55,6 +56,7 @@ interface Props {
function TagsSelect(props: Props) {
const { t } = useTranslation();
const { currentLocation } = useCurrentLocationContext();
+ const { tagGroups } = useEditedTagLibraryContext();
const desktopMode = useSelector(isDesktopMode);
const isUseOnlyTagsFromTagLibrary = useSelector(useOnlyTagsFromTagLibrary);
const [tagMenuAnchorEl, setTagMenuAnchorEl] = useState<null | HTMLElement>(
@@ -63,7 +65,7 @@ function TagsSelect(props: Props) {
const [selectedTag, setSelectedTag] = useState(undefined);
const tagsError = useRef<boolean>(false);
- const allTags = useRef<Array<TS.Tag>>(getAllTags());
+ const allTags = useRef<Array<TS.Tag>>(getAllTags(tagGroups));
const defaultBackgroundColor = useSelector(getTagColor);
const defaultTextColor = useSelector(getTagTextColor);
diff --git a/src/renderer/components/dialogs/AddTagToTagGroupDialog.tsx b/src/renderer/components/dialogs/AddTagToTagGroupDialog.tsx
index 33590cc83..526f25c1c 100644
--- a/src/renderer/components/dialogs/AddTagToTagGroupDialog.tsx
+++ b/src/renderer/components/dialogs/AddTagToTagGroupDialog.tsx
@@ -22,7 +22,6 @@ import TsSelect from '-/components/TsSelect';
import TsDialogActions from '-/components/dialogs/components/TsDialogActions';
import { useTaggingActionsContext } from '-/hooks/useTaggingActionsContext';
import { getTagColor, getTagTextColor } from '-/reducers/settings';
-import { getTagLibrary } from '-/services/taglibrary-utils';
import { TS } from '-/tagspaces.namespace';
import { Paper, useTheme } from '@mui/material';
import Dialog from '@mui/material/Dialog';
@@ -34,6 +33,7 @@ import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useSelector } from 'react-redux';
import TsDialogTitle from './components/TsDialogTitle';
+import { useEditedTagLibraryContext } from '-/hooks/useEditedTagLibraryContext';
interface Props {
open: boolean;
@@ -46,6 +46,7 @@ interface Props {
function AddTagToTagGroupDialog(props: Props) {
const { t } = useTranslation();
const { addTag } = useTaggingActionsContext();
+ const { tagGroups } = useEditedTagLibraryContext();
const [tagGroup, setTagGroup] = useState<string>(undefined);
const defaultBackgroundColor = useSelector(getTagColor);
const defaultTextColor = useSelector(getTagTextColor);
@@ -117,7 +118,7 @@ function AddTagToTagGroupDialog(props: Props) {
value={tagGroup}
onChange={handleTagGroupChange}
>
- {getTagLibrary().map((tg) => (
+ {tagGroups.map((tg) => (
<MenuItem value={tg.uuid}>{tg.title}</MenuItem>
))}
</TsSelect>
diff --git a/src/renderer/components/menus/TagLibraryMenu.tsx b/src/renderer/components/menus/TagLibraryMenu.tsx
index 19ea2a74c..99ba08847 100644
--- a/src/renderer/components/menus/TagLibraryMenu.tsx
+++ b/src/renderer/components/menus/TagLibraryMenu.tsx
@@ -47,13 +47,12 @@ interface Props {
open: boolean;
onClose: () => void;
showCreateTagGroupDialog: () => void;
- refreshTagsFromLocation: () => void;
}
function TagLibraryMenu(props: Props) {
const { t } = useTranslation();
const { showNotification } = useNotificationContext();
- const { tagGroups } = useEditedTagLibraryContext();
+ const { tagGroups, refreshTagLibrary } = useEditedTagLibraryContext();
const saveTagInLocation: boolean = useSelector(getSaveTagInLocation);
const fileInput = useRef<HTMLInputElement>(null);
@@ -136,7 +135,7 @@ function TagLibraryMenu(props: Props) {
disabled={!Pro || !saveTagInLocation}
data-tid="refreshTagGroups"
onClick={() => {
- props.refreshTagsFromLocation();
+ refreshTagLibrary(true);
props.onClose();
}}
>
diff --git a/src/renderer/containers/Root.tsx b/src/renderer/containers/Root.tsx
index 2d554fa8a..735602528 100644
--- a/src/renderer/containers/Root.tsx
+++ b/src/renderer/containers/Root.tsx
@@ -80,17 +80,17 @@ export default function Root({ store, persistor }: RootType) {
<CurrentLocationContextProvider>
<EditedEntryContextProvider>
<EditedEntryMetaContextProvider>
- <EditedTagLibraryContextProvider>
- <PerspectiveActionsContextProvider>
- <SelectedEntryContextProvider>
- <DirectoryContentContextProvider>
- <FSWatcherContextProvider>
- <PlatformFacadeContextProvider>
- <LocationIndexContextProvider>
- <IOActionsContextProvider>
- <EntryPropsTabsContextProvider>
- <OpenedEntryContextProvider>
- <TagGroupsLocationContextProvider>
+ <PerspectiveActionsContextProvider>
+ <SelectedEntryContextProvider>
+ <DirectoryContentContextProvider>
+ <FSWatcherContextProvider>
+ <PlatformFacadeContextProvider>
+ <LocationIndexContextProvider>
+ <IOActionsContextProvider>
+ <EntryPropsTabsContextProvider>
+ <OpenedEntryContextProvider>
+ <TagGroupsLocationContextProvider>
+ <EditedTagLibraryContextProvider>
<TaggingActionsContextProvider>
<DndProvider backend={HTML5Backend}>
<ExtensionsContextProvider>
@@ -130,17 +130,17 @@ export default function Root({ store, persistor }: RootType) {
</ExtensionsContextProvider>
</DndProvider>
</TaggingActionsContextProvider>
- </TagGroupsLocationContextProvider>
- </OpenedEntryContextProvider>
- </EntryPropsTabsContextProvider>
- </IOActionsContextProvider>
- </LocationIndexContextProvider>
- </PlatformFacadeContextProvider>
- </FSWatcherContextProvider>
- </DirectoryContentContextProvider>
- </SelectedEntryContextProvider>
- </PerspectiveActionsContextProvider>
- </EditedTagLibraryContextProvider>
+ </EditedTagLibraryContextProvider>
+ </TagGroupsLocationContextProvider>
+ </OpenedEntryContextProvider>
+ </EntryPropsTabsContextProvider>
+ </IOActionsContextProvider>
+ </LocationIndexContextProvider>
+ </PlatformFacadeContextProvider>
+ </FSWatcherContextProvider>
+ </DirectoryContentContextProvider>
+ </SelectedEntryContextProvider>
+ </PerspectiveActionsContextProvider>
</EditedEntryMetaContextProvider>
</EditedEntryContextProvider>
</CurrentLocationContextProvider>
diff --git a/src/renderer/hooks/ChatProvider.tsx b/src/renderer/hooks/ChatProvider.tsx
index 6eec846eb..487f13e1c 100644
--- a/src/renderer/hooks/ChatProvider.tsx
+++ b/src/renderer/hooks/ChatProvider.tsx
@@ -83,6 +83,7 @@ import { useTranslation } from 'react-i18next';
import { useDispatch, useSelector } from 'react-redux';
import { zodToJsonSchema } from 'zod-to-json-schema';
import useFirstRender from '-/utils/useFirstRender';
+import { useEditedTagLibraryContext } from '-/hooks/useEditedTagLibraryContext';
/*export type TimelineItem = {
request: string;
@@ -203,6 +204,7 @@ export const ChatContextProvider = ({ children }: ChatContextProviderProps) => {
const { showNotification } = useNotificationContext();
const { deleteDirectory } = useIOActionsContext();
const { addTagsToFsEntry } = useTaggingActionsContext();
+ const { tagGroups } = useEditedTagLibraryContext();
const { openFileUploadDialog } = useFileUploadDialogContext();
const { selectedEntries } = useSelectedEntriesContext();
const { findLocation } = useCurrentLocationContext();
@@ -893,9 +895,8 @@ export const ChatContextProvider = ({ children }: ChatContextProviderProps) => {
generationSettings.current.tagsFromLibrary &&
generationSettings.current.tagGroupsIds.length > 0
) {
- const tagLibrary: TS.TagGroup[] = getTagLibrary();
generationSettings.current.tagGroupsIds.forEach((tagGroupId) => {
- const tagGroup = tagLibrary.find((tg) => tg.uuid === tagGroupId);
+ const tagGroup = tagGroups.find((tg) => tg.uuid === tagGroupId);
if (tagGroup) {
tagsFromLibrary.push(...tagGroup.children.map((tag) => tag.title));
}
diff --git a/src/renderer/hooks/EditedTagLibraryContextProvider.tsx b/src/renderer/hooks/EditedTagLibraryContextProvider.tsx
index cedc2c666..049a843cd 100644
--- a/src/renderer/hooks/EditedTagLibraryContextProvider.tsx
+++ b/src/renderer/hooks/EditedTagLibraryContextProvider.tsx
@@ -20,17 +20,23 @@ import React, {
createContext,
useEffect,
useMemo,
- useReducer,
useRef,
+ useState,
} from 'react';
import { TS } from '-/tagspaces.namespace';
import { getTagLibrary } from '-/services/taglibrary-utils';
import { getUuid } from '@tagspaces/tagspaces-common/utils-io';
+import { Pro } from '-/pro';
+import { useTagGroupsLocationContext } from '-/hooks/useTagGroupsLocationContext';
+import { useSelector } from 'react-redux';
+import { getSaveTagInLocation } from '-/reducers/settings';
type EditedTagLibraryContextData = {
tagGroups: TS.TagGroup[];
broadcast: BroadcastChannel;
- reflectTagLibraryChanged: (tg: TS.TagGroup[]) => void;
+ reflectTagLibraryChanged: () => void;
+ refreshTagLibrary: (force?: boolean) => void;
+ setTagGroups: (tg: TS.TagGroup[]) => void;
};
export const EditedTagLibraryContext =
@@ -38,6 +44,8 @@ export const EditedTagLibraryContext =
tagGroups: undefined,
broadcast: undefined,
reflectTagLibraryChanged: undefined,
+ refreshTagLibrary: undefined,
+ setTagGroups: undefined,
});
export type EditedTagLibraryContextProviderProps = {
@@ -47,43 +55,71 @@ export type EditedTagLibraryContextProviderProps = {
export const EditedTagLibraryContextProvider = ({
children,
}: EditedTagLibraryContextProviderProps) => {
- const tagGroups = useRef<TS.TagGroup[]>(getTagLibrary());
+ // INITIAL VALUE from disk
+ const [tagGroups, setTagGroups] = useState<TS.TagGroup[]>(getTagLibrary());
+ const { getTagsFromLocations } = useTagGroupsLocationContext();
+ const saveTagInLocation: boolean = useSelector(getSaveTagInLocation);
+ // Generate a unique ID
+ const instanceId = useRef<string>(getUuid());
+ const broadcast = useMemo(() => new BroadcastChannel('tag-library-sync'), []);
- const [ignored, forceUpdate] = useReducer((x) => x + 1, 0, undefined);
- const broadcast = new BroadcastChannel('tag-library-sync');
- // Generate a unique ID for the tab
- const instanceId = getUuid();
+ useEffect(() => {
+ refreshTagLibrary();
+ }, [saveTagInLocation]);
+ // Listen for incoming broadcasts
useEffect(() => {
- // Listen for messages from other tabs
+ // Listen for messages from other instances
broadcast.onmessage = (event: MessageEvent) => {
const action = event.data as TS.BroadcastMessage;
- if (instanceId !== action.uuid) {
- if (action.type === 'tagLibraryChanged') {
- tagGroups.current = getTagLibrary();
- forceUpdate();
- }
+ if (action.uuid === instanceId.current) return;
+
+ if (action.type === 'tagLibraryChanged') {
+ refreshTagLibrary(true);
}
};
- }, []);
+ // clean up on unmount
+ return () => {
+ broadcast.close();
+ };
+ }, [broadcast]);
- function reflectTagLibraryChanged(tg: TS.TagGroup[]) {
- tagGroups.current = tg;
- const message: TS.BroadcastMessage = {
- uuid: instanceId,
+ function refreshTagLibrary(force = false) {
+ if (Pro && saveTagInLocation) {
+ getTagsFromLocations().then((locationTagGroups) => {
+ if (locationTagGroups && Object.keys(locationTagGroups).length > 0) {
+ // rebuild the flattened array
+ const fresh: TS.TagGroup[] = [
+ ...getTagLibrary(),
+ ...Object.entries(locationTagGroups).flatMap(([uuid, groups]) =>
+ groups.map((g) => ({ ...g, locationId: uuid })),
+ ),
+ ];
+ setTagGroups(fresh);
+ }
+ });
+ } else if (force) {
+ setTagGroups(getTagLibrary());
+ }
+ }
+
+ function reflectTagLibraryChanged() {
+ //refreshTagLibrary(true);
+ broadcast.postMessage({
+ uuid: instanceId.current,
type: 'tagLibraryChanged',
- };
- broadcast.postMessage(message);
- forceUpdate();
+ });
}
const context = useMemo(() => {
return {
- tagGroups: tagGroups.current,
+ tagGroups: tagGroups,
broadcast: broadcast,
+ setTagGroups,
reflectTagLibraryChanged,
+ refreshTagLibrary,
};
- }, [tagGroups.current]);
+ }, [tagGroups]);
return (
<EditedTagLibraryContext.Provider value={context}>
diff --git a/src/renderer/hooks/TagGroupsLocationContextProvider.tsx b/src/renderer/hooks/TagGroupsLocationContextProvider.tsx
index 4085e54eb..b3210299b 100644
--- a/src/renderer/hooks/TagGroupsLocationContextProvider.tsx
+++ b/src/renderer/hooks/TagGroupsLocationContextProvider.tsx
@@ -16,7 +16,7 @@
*
*/
-import React, { createContext, useMemo } from 'react';
+import React, { createContext, useEffect, useMemo } from 'react';
import { TS } from '-/tagspaces.namespace';
import { getDescriptionPreview, mergeFsEntryMeta } from '-/services/utils-io';
import {
@@ -29,6 +29,10 @@ import { usePlatformFacadeContext } from '-/hooks/usePlatformFacadeContext';
import { useSelector } from 'react-redux';
import { getSaveTagInLocation } from '-/reducers/settings';
import { CommonLocation } from '-/utils/CommonLocation';
+import { getTagLibrary } from '-/services/taglibrary-utils';
+import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';
+import { Pro } from '-/pro';
+import useFirstRender from '-/utils/useFirstRender';
type TagGroupsLocationContextData = {
getTagGroups: (location: CommonLocation) => Promise<TS.TagGroup[]>;
@@ -53,6 +57,7 @@ type TagGroupsLocationContextData = {
location: CommonLocation,
metaFile?,
) => Promise<TS.FileSystemEntryMeta>;
+ getTagsFromLocations: () => Promise<TagGroupsByLocation>;
};
export const TagGroupsLocationContext =
@@ -63,8 +68,10 @@ export const TagGroupsLocationContext =
removeLocationTagGroup: undefined,
mergeLocationTagGroup: undefined,
loadLocationDataPromise: undefined,
+ getTagsFromLocations: undefined,
});
+export type TagGroupsByLocation = Record<string, TS.TagGroup[]>;
export type TagGroupsLocationContextProviderProps = {
children: React.ReactNode;
};
@@ -75,8 +82,27 @@ export const TagGroupsLocationContextProvider = ({
const { createDirectoryPromise, saveTextFilePromise } =
usePlatformFacadeContext();
+ const { locations } = useCurrentLocationContext();
+
const saveTagInLocation: boolean = useSelector(getSaveTagInLocation);
+ /*const firstRender = useFirstRender();
+
+ useEffect(() => {
+ if (Pro && saveTagInLocation && firstRender) {
+ refreshTagsFromLocation();
+ }
+ }, [saveTagInLocation]);
+ function refreshTagsFromLocation() {
+ getTagsFromLocations().then((locationTagGroups: TagGroupsByLocation) => {
+ for (const [uuid, groups] of Object.entries(locationTagGroups)) {
+ //console.log(`Location ${uuid} has`, groups);
+ const tGroups: TS.TagGroup[] = groups.map(group => ({...group,locationId: uuid}));
+ tagGroups.current = [...tagGroups.current,...tGroups];
+ }
+ forceUpdate();
+ })
+ }*/
/*useEffect(() => {
if (currentLocation) {
getTagGroups(currentLocation.path).then((groups) => {
@@ -90,6 +116,23 @@ export const TagGroupsLocationContextProvider = ({
}
}, [currentLocation]);*/
+ async function getTagsFromLocations(): Promise<TagGroupsByLocation> {
+ const result: TagGroupsByLocation = {};
+
+ if (locations && locations.length > 0) {
+ const allFetches = locations.map(async (location) => {
+ const groups = await getTagGroups(location);
+ if (groups && groups.length > 0) {
+ result[location.uuid] = groups;
+ }
+ });
+
+ await Promise.all(allFetches);
+ }
+
+ return result;
+ }
+
function getTagGroups(location: CommonLocation): Promise<TS.TagGroup[]> {
return loadLocationDataPromise(location).then(
(fsEntryMeta: TS.FileSystemEntryMeta) => {
@@ -129,7 +172,7 @@ export const TagGroupsLocationContextProvider = ({
location: CommonLocation,
tagGroup: TS.TagGroup,
): Promise<TS.FileSystemEntryMeta> {
- if (!saveTagInLocation) {
+ if (!saveTagInLocation || !Pro || !location) {
return Promise.resolve(undefined);
}
return loadLocationDataPromise(location)
@@ -179,7 +222,7 @@ export const TagGroupsLocationContextProvider = ({
tagGroup: TS.TagGroup,
replaceTags = false,
): Promise<TS.FileSystemEntryMeta> {
- if (!saveTagInLocation) {
+ if (!saveTagInLocation || !Pro || !location) {
return Promise.resolve(undefined);
}
return new Promise((resolve, reject) => {
@@ -254,7 +297,7 @@ export const TagGroupsLocationContextProvider = ({
location: CommonLocation,
tagGroupUuid: string,
): Promise<TS.FileSystemEntryMeta> {
- if (!saveTagInLocation) {
+ if (!saveTagInLocation || !Pro || !location) {
return Promise.resolve(undefined);
}
return new Promise((resolve, reject) => {
@@ -293,7 +336,7 @@ export const TagGroupsLocationContextProvider = ({
location: CommonLocation,
tagGroup: TS.TagGroup,
): Promise<TS.FileSystemEntryMeta> {
- if (!saveTagInLocation) {
+ if (!saveTagInLocation || !Pro || !location) {
return Promise.resolve(undefined);
}
return new Promise((resolve, reject) => {
@@ -345,7 +388,7 @@ export const TagGroupsLocationContextProvider = ({
location: CommonLocation,
metaData: any,
): Promise<any> {
- if (!saveTagInLocation) {
+ if (!saveTagInLocation || !location) {
return Promise.resolve(undefined);
}
// const entryProperties = await location.getPropertiesPromise(location.path);
@@ -398,6 +441,7 @@ export const TagGroupsLocationContextProvider = ({
removeLocationTagGroup,
mergeLocationTagGroup,
loadLocationDataPromise,
+ getTagsFromLocations,
};
}, [saveTagInLocation]);
diff --git a/src/renderer/hooks/TaggingActionsContextProvider.tsx b/src/renderer/hooks/TaggingActionsContextProvider.tsx
index 26bf3b774..405298078 100644
--- a/src/renderer/hooks/TaggingActionsContextProvider.tsx
+++ b/src/renderer/hooks/TaggingActionsContextProvider.tsx
@@ -190,7 +190,8 @@ export const TaggingActionsContextProvider = ({
const { t } = useTranslation();
const { findLocation, persistTagsInSidecarFile } =
useCurrentLocationContext();
- const { tagGroups, reflectTagLibraryChanged } = useEditedTagLibraryContext();
+ const { tagGroups, setTagGroups, reflectTagLibraryChanged } =
+ useEditedTagLibraryContext();
const {
createLocationTagGroup,
editLocationTagGroup,
@@ -749,7 +750,7 @@ export const TaggingActionsContextProvider = ({
// filter existed in tagLibrary
const uniqueTags = tags.filter(
(tag) =>
- getTagLibrary().findIndex(
+ tagGroups.findIndex(
(tagGroup) =>
tagGroup.children.findIndex((obj) => obj.title === tag.title) !==
-1,
@@ -1016,8 +1017,9 @@ export const TaggingActionsContextProvider = ({
}
function saveTagLibrary(tg: TS.TagGroup[]) {
- const tagGroups = setTagLibrary(tg);
- reflectTagLibraryChanged(tagGroups);
+ setTagLibrary(tg); // save in localStorage
+ setTagGroups(tg); // set in EditedTagLibraryContext
+ reflectTagLibraryChanged(); // reflect changes in other instances
}
function saveTags(tags: TS.Tag[], indexForEditing: number) {
@@ -1048,18 +1050,17 @@ export const TaggingActionsContextProvider = ({
...(!entry.created_date && { created_date: new Date().getTime() }),
...(!entry.modified_date && { modified_date: new Date().getTime() }),
};
- if (Pro && entry.locationId) {
- const location: CommonLocation = findLocation(entry.locationId);
- if (location) {
- editLocationTagGroup(location, modifiedEntry, replaceTags);
- }
- }
+ const location: CommonLocation = entry.locationId
+ ? findLocation(entry.locationId)
+ : undefined;
- return saveTagLibrary([
- ...tagGroups.slice(0, indexForEditing),
- modifiedEntry,
- ...tagGroups.slice(indexForEditing + 1),
- ]);
+ editLocationTagGroup(location, modifiedEntry, replaceTags).then(() => {
+ return saveTagLibrary([
+ ...tagGroups.slice(0, indexForEditing),
+ modifiedEntry,
+ ...tagGroups.slice(indexForEditing + 1),
+ ]);
+ });
}
}
@@ -1096,51 +1097,52 @@ export const TaggingActionsContextProvider = ({
created_date: new Date().getTime(),
modified_date: new Date().getTime(),
};
- saveTagLibrary([...tagGroups, newEntry]);
- if (Pro && location) {
- return createLocationTagGroup(location, newEntry).then(() => true);
- }
- return Promise.resolve(true);
+ return createLocationTagGroup(location, newEntry).then(() => {
+ saveTagLibrary([...tagGroups, newEntry]);
+ return true;
+ });
}
function mergeTagGroup(entry: TS.TagGroup) {
- if (Pro && entry.locationId) {
- const location: CommonLocation = findLocation(entry.locationId);
- if (location) {
- mergeLocationTagGroup(location, entry);
+ const location: CommonLocation = entry.locationId
+ ? findLocation(entry.locationId)
+ : undefined;
+ mergeLocationTagGroup(location, entry).then(() => {
+ const indexForEditing = tagGroups.findIndex(
+ (obj) => obj.uuid === entry.uuid,
+ );
+ if (indexForEditing > -1) {
+ const tags = [
+ ...tagGroups[indexForEditing].children,
+ ...entry.children,
+ ];
+ tags.splice(0, tags.length - maxCollectedTag);
+ saveTagLibrary([
+ ...tagGroups.slice(0, indexForEditing),
+ {
+ uuid: entry.uuid,
+ title: entry.title,
+ children: tags,
+ created_date: entry.created_date,
+ modified_date: new Date().getTime(),
+ },
+ ...tagGroups.slice(indexForEditing + 1),
+ ]);
+ } else {
+ saveTagLibrary([
+ ...tagGroups,
+ {
+ uuid: entry.uuid || getUuid(),
+ title: entry.title,
+ color: entry.color,
+ textcolor: entry.textcolor,
+ children: entry.children,
+ created_date: new Date().getTime(),
+ modified_date: new Date().getTime(),
+ },
+ ]);
}
- }
- const indexForEditing = tagGroups.findIndex(
- (obj) => obj.uuid === entry.uuid,
- );
- if (indexForEditing > -1) {
- const tags = [...tagGroups[indexForEditing].children, ...entry.children];
- tags.splice(0, tags.length - maxCollectedTag);
- saveTagLibrary([
- ...tagGroups.slice(0, indexForEditing),
- {
- uuid: entry.uuid,
- title: entry.title,
- children: tags,
- created_date: entry.created_date,
- modified_date: new Date().getTime(),
- },
- ...tagGroups.slice(indexForEditing + 1),
- ]);
- } else {
- saveTagLibrary([
- ...tagGroups,
- {
- uuid: entry.uuid || getUuid(),
- title: entry.title,
- color: entry.color,
- textcolor: entry.textcolor,
- children: entry.children,
- created_date: new Date().getTime(),
- modified_date: new Date().getTime(),
- },
- ]);
- }
+ });
}
function removeTagGroup(parentTagGroupUuid: TS.Uuid) {
@@ -1149,23 +1151,22 @@ export const TaggingActionsContextProvider = ({
);
if (indexForRemoving >= 0) {
const tagGroup: TS.TagGroup = tagGroups[indexForRemoving];
- if (Pro && tagGroup && tagGroup.locationId) {
- const location: CommonLocation = findLocation(tagGroup.locationId);
- if (location) {
- removeLocationTagGroup(location, parentTagGroupUuid);
- }
- }
-
- saveTagLibrary([
- ...tagGroups.slice(0, indexForRemoving),
- ...tagGroups.slice(indexForRemoving + 1),
- ]);
+ const location: CommonLocation =
+ tagGroup && tagGroup.locationId
+ ? findLocation(tagGroup.locationId)
+ : undefined;
+ removeLocationTagGroup(location, parentTagGroupUuid).then(() => {
+ saveTagLibrary([
+ ...tagGroups.slice(0, indexForRemoving),
+ ...tagGroups.slice(indexForRemoving + 1),
+ ]);
+ });
}
}
/**
* Add tag to tagGroup
- * @param tag
+ * @param tags
* @param parentTagGroupUuid - tagGroup ID to add in
*/
function addTag(tags: TS.Tag[], parentTagGroupUuid: TS.Uuid) {
@@ -1183,15 +1184,17 @@ export const TaggingActionsContextProvider = ({
...(!tag.textcolor && { textcolor: tagGroup.textcolor }),
})),
];
- saveTags(newTags, tgIndex);
- if (Pro && tagGroup && tagGroup.locationId) {
- const location: CommonLocation = findLocation(tagGroup.locationId);
- if (location) {
- tagGroup.children = newTags;
- editLocationTagGroup(location, tagGroup);
- }
- }
+ const location: CommonLocation =
+ tagGroup && tagGroup.locationId
+ ? findLocation(tagGroup.locationId)
+ : undefined;
+
+ editLocationTagGroup(location, { ...tagGroup, children: newTags }).then(
+ () => {
+ saveTags(newTags, tgIndex);
+ },
+ );
}
}
@@ -1292,7 +1295,29 @@ export const TaggingActionsContextProvider = ({
),
];
}
- saveTagLibrary(newTagLibrary);
+ const locationFrom: CommonLocation = newTagLibrary[indexFromGroup]
+ .locationId
+ ? findLocation(newTagLibrary[indexFromGroup].locationId)
+ : undefined;
+
+ const locationTo: CommonLocation = newTagLibrary[indexToGroup]
+ .locationId
+ ? findLocation(newTagLibrary[indexToGroup].locationId)
+ : undefined;
+
+ editLocationTagGroup(
+ locationFrom,
+ newTagLibrary[indexFromGroup],
+ true,
+ ).then(() => {
+ editLocationTagGroup(
+ locationTo,
+ newTagLibrary[indexToGroup],
+ true,
+ ).then(() => {
+ return saveTagLibrary(newTagLibrary);
+ });
+ });
}
console.log('Tag with this title already exists in the target tag group');
}
@@ -1411,7 +1436,12 @@ export const TaggingActionsContextProvider = ({
if (exist) {
arr = arr.map((tGroup) => {
if (tGroup.uuid === tagGroup.uuid) {
- return tagGroup;
+ return {
+ ...tagGroup,
+ ...(location && {
+ locationId: location.uuid,
+ }),
+ };
}
return tGroup;
});
diff --git a/src/renderer/services/taglibrary-utils.ts b/src/renderer/services/taglibrary-utils.ts
index bdb89fe88..47621c357 100644
--- a/src/renderer/services/taglibrary-utils.ts
+++ b/src/renderer/services/taglibrary-utils.ts
@@ -23,14 +23,15 @@ export function getTagLibrary(): TS.TagGroup[] {
return defaultTagLibrary;
}
-export function setTagLibrary(
- tagGroups: Array<TS.TagGroup>,
-): Array<TS.TagGroup> {
- if (tagGroups && tagGroups.length > 0) {
- localStorage.setItem(tagLibraryKey, JSON.stringify(tagGroups));
- //broadcast.postMessage({ type: 'tagLibraryChanged' });
+export function setTagLibrary(tagGroups: TS.TagGroup[]) {
+ if (tagGroups) {
+ localStorage.setItem(
+ tagLibraryKey,
+ JSON.stringify(
+ tagGroups.filter((tg) => tg.locationId === undefined && !tg.readOnly),
+ ),
+ );
}
- return tagGroups;
}
export function getAllTags(tagGroups?: Array<TS.TagGroup>) {
diff --git a/tests/e2e/general.helpers.js b/tests/e2e/general.helpers.js
index 17dd49cd1..1b4e9717f 100644
--- a/tests/e2e/general.helpers.js
+++ b/tests/e2e/general.helpers.js
@@ -4,6 +4,11 @@ import AppConfig from '../../src/renderer/AppConfig';
import { dataTidFormat } from '../../src/renderer/services/test';
import { delay } from './hook';
import { firstFile, openContextEntryMenu, toContainTID } from './test-utils';
+import {
+ createPwLocation,
+ createPwMinioLocation,
+ createS3Location,
+} from './location.helpers';
// export const defaultLocationPath = './testdata-tmp/file-structure/supported-filestypes';
export const defaultLocationName = 'supported-filestypes';
@@ -468,44 +473,21 @@ export async function expectElementExist(
}
export async function createLocation(
- locationPath,
- locationName,
+ { isMinio, isS3, testDataDir },
+ locationPath = '',
+ locationName = defaultLocationName,
isDefault = false,
) {
- // locationPerspective = locationPerspective || 'Grid';
- const locationManagerMenu = await global.client.$(
- '[data-tid=locationManagerPanel]',
- );
- await locationManagerMenu.click();
- const elem = await global.client.$('[data-tid=createNewLocationTID]');
- await elem.click();
- const lPath = await global.client.$('[data-tid=locationPath]');
- await lPath.click();
- const locationPathInput = await global.client.$(
- '[data-tid=locationPath] input',
- );
- await locationPathInput.keys(locationPath); // || defaultLocationPath);
- // keys is workarround for not working setValue await global.client.$('[data-tid=locationPath] input').setValue(locationPath || defaultLocationPath);
- const lName = await global.client.$('[data-tid=locationName]');
- await lName.click();
- const locationNameInput = await global.client.$(
- '[data-tid=locationName] input',
- );
- locationNameInput.keys(
- locationName || 'Test Location' + new Date().getTime(),
- );
- if (isDefault) {
- await delay(1000);
- const locationIsDefault = await global.client.$(
- '[data-tid=locationIsDefault]',
- );
- await locationIsDefault.click();
+ await clickOn('[data-tid=locationManager]');
+ if (isMinio) {
+ await createPwMinioLocation(locationPath, locationName, isDefault);
+ } else if (isS3) {
+ await createS3Location(locationPath, locationName, isDefault);
+ } else {
+ await createPwLocation(testDataDir + locationPath, locationName, isDefault);
}
- const confirmLocationCreation = await global.client.$(
- '[data-tid=confirmLocationCreation]',
- );
- await confirmLocationCreation.waitForDisplayed();
- await confirmLocationCreation.click();
+ await clickOn('[data-tid=location_' + locationName + ']');
+ await expectElementExist(getGridFileSelector('empty_folder'), true, 8000);
}
export async function setGridOptions(
@@ -812,7 +794,7 @@ export async function expectFileContain(
async () => {
const fLocator = await frameLocator('iframe[allowfullscreen]');
const bodyTxt = await fLocator.locator('body').innerText();
- //console.log(bodyTxt);
+ console.log(bodyTxt);
return toContainTID(bodyTxt, [txtToContain]);
},
{
diff --git a/tests/e2e/tag.pw.e2e.js b/tests/e2e/tag.pw.e2e.js
index 9c1b9bfe5..6961cb361 100644
--- a/tests/e2e/tag.pw.e2e.js
+++ b/tests/e2e/tag.pw.e2e.js
@@ -4,12 +4,12 @@ import { formatDateTime4Tag } from '@tagspaces/tagspaces-common/misc';
import {
checkSettings,
clickOn,
+ createLocation,
dnd,
expectElementExist,
expectMetaFilesExist,
getGridFileSelector,
setInputValue,
- takeScreenshot,
} from './general.helpers';
import { createFile, createFileS3, startTestingApp, stopApp } from './hook';
import { clearDataStorage, closeWelcomePlaywright } from './welcome.helpers';
@@ -25,37 +25,30 @@ import {
createTagGroup,
deleteTagGroup,
editedGroupName,
- newTagName,
tagMenu,
testGroup,
testTagName,
} from './tag.helpers';
import { dataTidFormat } from '../../src/renderer/services/test';
-test.beforeAll(async ({ isWeb, isS3, webServerPort }, testInfo) => {
+const tslContent =
+ '{"appName":"TagSpaces","appVersion":"5.3.6","description":"","lastUpdated":"2023-06-08T16:51:23.926Z","tagGroups":[{"uuid":"collected_tag_group_id","title":"Collected Tags","color":"#61DD61","textcolor":"white","children":[{"title":"Stanimir","color":"#61DD61","textcolor":"white","type":"sidecar"}],"created_date":1686119562860,"modified_date":1686243083871,"expanded":true,"locationId":"dc1ffaaeeb5747e39dd171c7e551afd6"}]}';
+
+test.afterEach(async () => {
+ await clearDataStorage();
+ await stopApp();
+});
+
+test.beforeEach(async ({ isWeb, isS3, webServerPort }, testInfo) => {
if (isS3) {
await startTestingApp({ isWeb, isS3, webServerPort, testInfo });
- await closeWelcomePlaywright();
+ //await closeWelcomePlaywright();
} else {
await startTestingApp(
{ isWeb, isS3, webServerPort, testInfo },
'extconfig.js',
);
}
-});
-
-test.afterAll(async () => {
- await stopApp();
-});
-
-test.afterEach(async ({ page }, testInfo) => {
- /*if (testInfo.status !== testInfo.expectedStatus) {
- await takeScreenshot(testInfo);
- }*/
- await clearDataStorage();
-});
-
-test.beforeEach(async () => {
await closeWelcomePlaywright();
await clickOn('[data-tid=tagLibrary]');
});
@@ -268,16 +261,7 @@ test.describe('TST04 - Testing the tag library:', () => {
isMinio,
testDataDir,
}) => {
- await clickOn('[data-tid=locationManager]');
- if (isMinio) {
- await createPwMinioLocation('', defaultLocationName, true);
- } else if (isS3) {
- await createS3Location('', defaultLocationName, true);
- } else {
- await createPwLocation(testDataDir, defaultLocationName, true);
- }
- await clickOn('[data-tid=location_' + defaultLocationName + ']');
- await expectElementExist(getGridFileSelector('empty_folder'), true, 8000);
+ await createLocation({ isMinio, isS3, testDataDir });
await clickOn('[data-tid=tagLibrary]');
await checkSettings(
'[data-tid=saveTagInLocationTID]',
@@ -298,29 +282,31 @@ test.describe('TST04 - Testing the tag library:', () => {
isMinio,
testDataDir,
}) => {
- const tslContent =
- '{"appName":"TagSpaces","appVersion":"5.3.6","description":"","lastUpdated":"2023-06-08T16:51:23.926Z","tagGroups":[{"uuid":"collected_tag_group_id","title":"Collected Tags","color":"#61DD61","textcolor":"white","children":[{"title":"Stanimir","color":"#61DD61","textcolor":"white","type":"sidecar"}],"created_date":1686119562860,"modified_date":1686243083871,"expanded":true,"locationId":"dc1ffaaeeb5747e39dd171c7e551afd6"}]}';
+ const testTagName = 'Stanimir';
+ await createLocation({ isMinio, isS3, testDataDir });
+
if (isS3) {
await createFileS3('tsl.json', tslContent, '.ts');
} else {
await createFile(testDataDir, 'tsl.json', tslContent, '.ts');
}
+ // check tag exist in tsl.json
+ /*await checkSettings('[data-tid=settingsSetShowUnixHiddenEntries]', true);
+ await openFolder(AppConfig.metaFolder);
+ await openFile('tsl.json');
+ await expectFileContain(testTagName, 10000);*/
+
await checkSettings(
'[data-tid=saveTagInLocationTID]',
true,
'[data-tid=advancedSettingsDialogTID]',
);
- await clickOn('[data-tid=locationManager]');
- if (isMinio) {
- await createPwMinioLocation('', defaultLocationName, true);
- } else if (isS3) {
- await createS3Location('', defaultLocationName, true);
- } else {
- await createPwLocation(testDataDir, defaultLocationName, true);
- }
- await clickOn('[data-tid=location_' + defaultLocationName + ']');
+
await clickOn('[data-tid=tagLibrary]');
- await expectElementExist('[data-tid=tagContainer_Stanimir]', true);
+ await expectElementExist(
+ '[data-tid=tagContainer_' + testTagName + ']',
+ true,
+ );
});
test('TST0421 - Move tag to another tag group with DnD [web,electron]', async () => {
@@ -346,11 +332,22 @@ test.describe('TST04 - Testing the tag library:', () => {
);
});
- test('TST0422 - Add custom date smarttag [web,electron,_pro]', async () => {
+ test('TST0422 - Add custom date smarttag [web,electron,_pro]', async ({
+ isS3,
+ isMinio,
+ testDataDir,
+ }) => {
const tagName = 'custom-date';
const sourceTagGroup = 'Smart Tags';
await clickOn('[data-tid=locationManager]');
+ if (isMinio) {
+ await createPwMinioLocation('', defaultLocationName, true);
+ } else if (isS3) {
+ await createS3Location('', defaultLocationName, true);
+ } else {
+ await createPwLocation(testDataDir, defaultLocationName, true);
+ }
await clickOn('[data-tid=location_' + defaultLocationName + ']');
await clickOn('[data-tid=tagLibrary]');
await expectElementExist(
@@ -373,4 +370,63 @@ test.describe('TST04 - Testing the tag library:', () => {
'[data-tid=perspectiveGridFileTable]',
);
});
+
+ test('TST0425 - Delete tag in location tag group and check tsl.json [web,electron,_pro]', async ({
+ isS3,
+ isMinio,
+ testDataDir,
+ }) => {
+ await createLocation({ isMinio, isS3, testDataDir });
+
+ if (isS3) {
+ await createFileS3('tsl.json', tslContent, '.ts');
+ } else {
+ await createFile(testDataDir, 'tsl.json', tslContent, '.ts');
+ }
+ await checkSettings(
+ '[data-tid=saveTagInLocationTID]',
+ true,
+ '[data-tid=advancedSettingsDialogTID]',
+ );
+
+ await clickOn('[data-tid=tagLibrary]');
+ await expectElementExist('[data-tid=tagContainer_Stanimir]', true);
+
+ await tagMenu('Stanimir', 'deleteTagDialog');
+ await clickOn('[data-tid=confirmDeleteTagDialogTagMenu]');
+ await expectElementExist('[data-tid=tagContainer_Stanimir]', false);
+ //TODO check in tsl.json content
+ });
+
+ test('TST0426 - Rename tag in location tag group and check tsl.json [web,electron,_pro]', async ({
+ isS3,
+ isMinio,
+ testDataDir,
+ }) => {
+ await createLocation({ isMinio, isS3, testDataDir });
+
+ if (isS3) {
+ await createFileS3('tsl.json', tslContent, '.ts');
+ } else {
+ await createFile(testDataDir, 'tsl.json', tslContent, '.ts');
+ }
+ await checkSettings(
+ '[data-tid=saveTagInLocationTID]',
+ true,
+ '[data-tid=advancedSettingsDialogTID]',
+ );
+
+ await clickOn('[data-tid=tagLibrary]');
+ await expectElementExist('[data-tid=tagContainer_Stanimir]', true, 100000);
+
+ await tagMenu('Stanimir', 'editTagDialog');
+ await setInputValue('[data-tid=editTagInput] input', testTagName);
+ await clickOn('[data-tid=editTagConfirm]');
+ await expectElementExist(
+ '[data-tid=tagContainer_' + testTagName + ']',
+ true,
+ );
+ await expectElementExist('[data-tid=tagContainer_Stanimir]', false);
+ //TODO check in tsl.json content
+ });
});