TagSpaces is an offline, open source, document manager with tagging support
chore: refactoring current location context provider, adding tests
Ilian Sapundshievdb8354b2c1f4
diff --git a/src/renderer/hooks/CurrentLocationContextProvider.tsx b/src/renderer/hooks/CurrentLocationContextProvider.tsxindex 56cb7bd3e..3788f735d 100644--- a/src/renderer/hooks/CurrentLocationContextProvider.tsx+++ b/src/renderer/hooks/CurrentLocationContextProvider.tsx@@ -33,6 +33,17 @@ import {import { TS } from '-/tagspaces.namespace';import { CommonLocation } from '-/utils/CommonLocation';import { clearAllURLParams, getURLParameter } from '-/utils/dom';+import {+ canMoveDown,+ canMoveUp,+ findLocalLocation as findLocalLocationUtil,+ findLocationById,+ getDirSeparatorForLocation,+ getFirstReadWriteLocation,+ getLocationPathString,+ getLocationPositionByUUID,+ validateMoveLocation,+} from '-/utils/locationUtils';import versionMeta from '-/version.json';import { locationType } from '@tagspaces/tagspaces-common/misc';import { getUuid } from '@tagspaces/tagspaces-common/utils-io';@@ -46,7 +57,6 @@ import React, {} from 'react';import { useTranslation } from 'react-i18next';import { useDispatch, useSelector } from 'react-redux';-import AppConfig from '../AppConfig';type CurrentLocationContextData = {locations: CommonLocation[];@@ -142,61 +152,67 @@ export const CurrentLocationContextProvider = ({const allLocations = useRef<CommonLocation[]>(locations.map((l) => new CommonLocation(l)),);- const currentLocationId = useRef<string>(undefined); //defaultLocationId);- const selectedLocation = useRef<CommonLocation>(undefined);+ const currentLocationId = useRef<string | undefined>(undefined);+ const selectedLocation = useRef<CommonLocation | undefined>(undefined);const skipInitialDirList = useRef<boolean>(false);const initLocations = useRef<boolean>(false);+ const broadcastRef = useRef<BroadcastChannel | null>(null);const [locationDirectoryContextMenuAnchorEl,setLocationDirectoryContextMenuAnchorEl,] = useState<null | HTMLElement>(null);- const broadcast = new BroadcastChannel('ts-sync-channel');- const [ignored, forceUpdate] = useReducer((x) => x + 1, 0, undefined);+ const [, forceUpdate] = useReducer((x) => x + 1, 0);useEffect(() => {- if (- !currentLocationId.current &&- defaultLocationId &&- defaultLocationId.length > 0- ) {- const openDefaultLocation =- !getURLParameter('tslid') &&- !getURLParameter('tsdpath') &&- !getURLParameter('tsepath') &&- !getURLParameter('cmdopen');- if (openDefaultLocation) {- openLocationById(defaultLocationId);- }- }+ // Initialize BroadcastChanneltry {- // Listen for messages from other tabs- broadcast.onmessage = (event: MessageEvent) => {+ broadcastRef.current = new BroadcastChannel('ts-sync-channel');+ broadcastRef.current.onmessage = (event: MessageEvent) => {const action = event.data as TS.BroadcastMessage;if (instanceId !== action.uuid) {- if (action.type === 'addLocation') {- const location = action.payload as TS.Location;- addLocationInt(new CommonLocation(location), false);- } else if (action.type === 'editLocation') {- const location = action.payload as TS.Location;- skipInitialDirList.current = true; // don't change location dir after reflect- editLocationInt(new CommonLocation(location));- } else if (action.type === 'deleteLocation') {- deleteLocationInt(action.payload);- } else if (action.type === 'moveLocationUp') {- moveLocationUpInt(action.payload);- forceUpdate();- } else if (action.type === 'moveLocationDown') {- moveLocationDownInt(action.payload);- forceUpdate();- }+ handleBroadcastMessage(action);}};} catch (e) {- console.error('broadcast.onmessage error:', e);+ console.error('BroadcastChannel initialization error:', e);}++ // Cleanup on unmount+ return () => {+ if (broadcastRef.current) {+ broadcastRef.current.close();+ }+ };}, []);+ function handleBroadcastMessage(action: TS.BroadcastMessage) {+ switch (action.type) {+ case 'addLocation': {+ const location = action.payload as TS.Location;+ addLocationInt(new CommonLocation(location), false);+ break;+ }+ case 'editLocation': {+ const location = action.payload as TS.Location;+ skipInitialDirList.current = true;+ editLocationInt(new CommonLocation(location));+ break;+ }+ case 'deleteLocation':+ deleteLocationInt(action.payload);+ break;+ case 'moveLocationUp':+ moveLocationUpInt(action.payload);+ forceUpdate();+ break;+ case 'moveLocationDown':+ moveLocationDownInt(action.payload);+ forceUpdate();+ break;+ }+ }+useEffect(() => {if (locations.length < 1) {// init locations@@ -204,37 +220,42 @@ export const CurrentLocationContextProvider = ({} else {// check if current location exist (or is removed)if (currentLocationId.current) {- const location = locations.find(+ const locationExists = locations.some((location) => location.uuid === currentLocationId.current,);- if (!location) {+ if (!locationExists) {setCurrentLocation(undefined);- //closeLocation(currentLocation.current.uuid);}}allLocations.current = locations.map((l) => new CommonLocation(l));forceUpdate();}- }, [locations]); //allLocations.current]);+ }, [locations]);++ // Open default location if configured+ useEffect(() => {+ if (+ !currentLocationId.current &&+ defaultLocationId &&+ defaultLocationId.length > 0+ ) {+ const shouldOpenDefault =+ !getURLParameter('tslid') &&+ !getURLParameter('tsdpath') &&+ !getURLParameter('tsepath') &&+ !getURLParameter('cmdopen');+ if (shouldOpenDefault) {+ openLocationById(defaultLocationId);+ }+ }+ }, [defaultLocationId]);/*** @deprecated use resolveRelativePath instead- * @param location*/function getLocationPath(location: CommonLocation): Promise<string> {- let locationPath = '';- if (location) {- if (location.path) {- locationPath = location.path;- }- if (location.paths && location.paths[0]) {- // eslint-disable-next-line prefer-destructuring- locationPath = location.paths[0];- }- return resolveRelativePath(locationPath);- }-- return Promise.resolve(locationPath);+ if (!location) return Promise.resolve('');+ return resolveRelativePath(getLocationPathString(location));}// Build a map of locations by ID. Rebuilt only when `locations` array changes.@@ -246,48 +267,27 @@ export const CurrentLocationContextProvider = ({return map;}, [allLocations.current]);- // Return the specific location, recomputing only when that entry or the ID changes.+ // Return the current location, memoized to prevent unnecessary re-rendersconst currentLocation = useMemo(() => locationsById[currentLocationId.current],- [locationsById[currentLocationId.current], currentLocationId.current],+ [locationsById, currentLocationId.current],);- /**- * @param locationID- */- function findLocation(- locationID: string = undefined,- ): CommonLocation | undefined {- if (!locationID) {- return allLocations.current.find(- (l) => l.uuid === currentLocationId.current,- );- }- const loc = allLocations.current.find((l) => l.uuid === locationID);- if (loc) {- return loc;- }- return allLocations.current.find(- (l) => l.uuid === currentLocationId.current,+ function findLocation(locationID?: string): CommonLocation | undefined {+ return findLocationById(+ allLocations.current,+ locationID,+ currentLocationId.current,);}- function getDirSeparator(locationID: string = undefined): string {+ function getDirSeparator(locationID?: string): string {const loc = findLocation(locationID);- if (loc) {- return loc.getDirSeparator();- }- return AppConfig.dirSeparator;+ return getDirSeparatorForLocation(loc);}- function findLocalLocation(): CommonLocation {- const loc = allLocations.current.find(- (l) => l.type === locationType.TYPE_LOCAL,- );- if (loc) {- return loc;- }- return undefined;+ function findLocalLocation(): CommonLocation | undefined {+ return findLocalLocationUtil(allLocations.current);}function setDefaultLocations() {@@ -316,10 +316,11 @@ export const CurrentLocationContextProvider = ({}}- function sendMessage(type: string, payload?: any) {+ function sendMessage(type: string, payload?: any): void {+ if (!broadcastRef.current) return;try {const message: TS.BroadcastMessage = { uuid: instanceId, type, payload };- broadcast.postMessage(message);+ broadcastRef.current.postMessage(message);} catch (e) {console.error('broadcast.postMessage error:', e);}@@ -328,8 +329,8 @@ export const CurrentLocationContextProvider = ({function addLocation(location: CommonLocation,openAfterCreate = true,- locationPosition: number = undefined,- ) {+ locationPosition?: number,+ ): void {addLocationInt(location, openAfterCreate, locationPosition);sendMessage('addLocation', toTsLocation(location));}@@ -337,98 +338,63 @@ export const CurrentLocationContextProvider = ({function addLocationInt(location: CommonLocation,openAfterCreate = true,- locationPosition: number = undefined,- ) {- //allLocations.current = [...allLocations.current, location];+ locationPosition?: number,+ ): void {if (openAfterCreate) {openLocation(location);}dispatch(LocationActions.createLocation(location, locationPosition));}- function deleteLocation(locationId: string) {+ function deleteLocation(locationId: string): void {deleteLocationInt(locationId);sendMessage('deleteLocation', locationId);}- function deleteLocationInt(locationId: string) {+ function deleteLocationInt(locationId: string): void {dispatch(LocationActions.deleteLocation(locationId));if (currentLocationId.current === locationId) {setCurrentLocation(undefined);}}- function moveLocationUp(locationUUID) {+ function moveLocationUp(locationUUID: string): void {moveLocationUpInt(locationUUID);sendMessage('moveLocationUp', locationUUID);}- function moveLocationUpInt(locationUUID) {- const currentIndex = allLocations.current.findIndex(- (l) => l.uuid === locationUUID,- );-- // If location is not found or is already at the top, do nothing- if (currentIndex <= 0) {- return;- }-+ function moveLocationUpInt(locationUUID: string): void {+ if (!canMoveUp(allLocations.current, locationUUID)) return;dispatch(LocationActions.moveLocationUp(locationUUID));}- function moveLocationDown(locationUUID) {+ function moveLocationDown(locationUUID: string): void {moveLocationDownInt(locationUUID);sendMessage('moveLocationDown', locationUUID);}- function moveLocationDownInt(locationUUID) {- const currentIndex = allLocations.current.findIndex(- (l) => l.uuid === locationUUID,- );-- // If location is not found or is already at the bottom, return the original array- if (- currentIndex === -1 ||- currentIndex >= allLocations.current.length - 1- ) {- return;- }+ function moveLocationDownInt(locationUUID: string): void {+ if (!canMoveDown(allLocations.current, locationUUID)) return;dispatch(LocationActions.moveLocationDown(locationUUID));}- function moveLocation(locationUUID: string, newIndex: number) {- // Check if allLocations.current is an array and newIndex is within bounds- if (- !Array.isArray(allLocations.current) ||- newIndex < 0 ||- newIndex >= allLocations.current.length- ) {- throw new Error('Invalid input');- }-- // Find the index of the location with the given UUID- const currentIndex = allLocations.current.findIndex(- (l) => l.uuid === locationUUID,- );-- // If the location is not found, throw an error- if (currentIndex === -1) {- throw new Error('Location not found');- }+ function moveLocation(locationUUID: string, newIndex: number): void {+ validateMoveLocation(allLocations.current, locationUUID, newIndex);dispatch(LocationActions.moveLocation(locationUUID, newIndex));}/**- * @param arrLocations- * @param override = true - if location exist override else skip+ * Add multiple locations, optionally overriding duplicates*/- function addLocations(arrLocations: Array<CommonLocation>, override = true) {- arrLocations.forEach((newLocation: CommonLocation, idx, array) => {- const locationExist: boolean = allLocations.current.some(+ function addLocations(+ arrLocations: Array<CommonLocation>,+ override = true,+ ): void {+ arrLocations.forEach((newLocation) => {+ const locationExists = allLocations.current.some((location) => location.uuid === newLocation.uuid,);- //const isLast = idx === array.length - 1;- if (!locationExist) {+ if (!locationExists) {addLocation(newLocation);} else if (override) {editLocation(newLocation);@@ -436,7 +402,7 @@ export const CurrentLocationContextProvider = ({});}- function setCurrentLocation(location) {+ function setCurrentLocation(location: CommonLocation | undefined): void {const newLocationId = location?.uuid;if (currentLocationId.current !== newLocationId) {currentLocationId.current = newLocationId;@@ -444,17 +410,20 @@ export const CurrentLocationContextProvider = ({}}- function setSelectedLocation(location) {+ function setSelectedLocation(location: CommonLocation | undefined): void {selectedLocation.current = location;forceUpdate();}- function editLocation(location: CommonLocation) {- editLocationInt(location);+ function editLocation(location: CommonLocation, openAfterEdit = false): void {+ editLocationInt(location, openAfterEdit);sendMessage('editLocation', toTsLocation(location));}- function editLocationInt(location: CommonLocation, openAfterEdit = false) {+ function editLocationInt(+ location: CommonLocation,+ openAfterEdit = false,+ ): void {dispatch(LocationActions.changeLocation(location));if (openAfterEdit) {currentLocationId.current = location.uuid;@@ -471,45 +440,35 @@ export const CurrentLocationContextProvider = ({}function getFirstRWLocation(): CommonLocation | undefined {- let foundLocation = allLocations.current.find(- (location) => location.isDefault && !location.isReadOnly,- );- if (!foundLocation) {- foundLocation = allLocations.current.find(- (location) => !location.isReadOnly,- );- }- return foundLocation;+ return getFirstReadWriteLocation(allLocations.current);}- const persistTagsInSidecarFile: boolean = useMemo(() => {+ const persistTagsInSidecarFile = useMemo(() => {const location = findLocation();- const locationPersistTagsInSidecarFile =- location && location.persistTagsInSidecarFile;- if (locationPersistTagsInSidecarFile !== undefined) {- return locationPersistTagsInSidecarFile;+ if (location?.persistTagsInSidecarFile !== undefined) {+ return location.persistTagsInSidecarFile;}return settingsPersistTagsInSidecarFile;}, [currentLocationId.current, settingsPersistTagsInSidecarFile]);function changeLocation(location: CommonLocation,- skipInitDirList: boolean = false,- ) {+ skipInitDirList = false,+ ): void {+ if (!location) return;skipInitialDirList.current = skipInitDirList;if (- location &&- (!currentLocationId.current ||- location.uuid !== currentLocationId.current)+ !currentLocationId.current ||+ location.uuid !== currentLocationId.current) {- if (location && location.name) {- document.title = location.name + ' | ' + versionMeta.name;+ if (location.name) {+ document.title = `${location.name} | ${versionMeta.name}`;}setCurrentLocation(location);}}- function changeLocationByID(locationId: string) {+ function changeLocationByID(locationId: string): void {if (!currentLocationId.current ||locationId !== currentLocationId.current@@ -521,7 +480,10 @@ export const CurrentLocationContextProvider = ({}}- function openLocationById(locationId: string, skipInitDirList?: boolean) {+ function openLocationById(+ locationId: string,+ skipInitDirList?: boolean,+ ): void {const location = findLocation(locationId);if (location) {openLocation(location, skipInitDirList);@@ -530,12 +492,11 @@ export const CurrentLocationContextProvider = ({function openLocation(location: CommonLocation,- skipInitDirList: boolean = false,- ) {- skipInitialDirList.current = skipInitDirList;+ skipInitDirList = false,+ ): void {if (location.type === locationType.TYPE_CLOUD) {showNotification(- t('core:connectedtoObjectStore' as any) as string,+ t('core:connectedtoObjectStore') as string,'default',true,);@@ -543,34 +504,26 @@ export const CurrentLocationContextProvider = ({changeLocation(location, skipInitDirList);}- function closeLocation(locationId: string) {- if (currentLocationId.current && currentLocationId.current === locationId) {- locations.map((location) => {- if (location.uuid === locationId) {- // location needed evtl. to unwatch many loc. root folders if available- setCurrentLocation(undefined);- }- clearAllURLParams();- document.title = versionMeta.name;- return true;- });+ function closeLocation(locationId: string): void {+ if (currentLocationId.current === locationId) {+ setCurrentLocation(undefined);+ clearAllURLParams();+ document.title = versionMeta.name;}}- function closeAllLocations() {- // location needed evtl. to unwatch many loc. root folders if available+ function closeAllLocations(): void {setCurrentLocation(undefined);clearAllURLParams();document.title = versionMeta.name;- return true;}function getLocationPosition(locationId: string): number {- return locations.findIndex((location) => location.uuid === locationId);+ return getLocationPositionByUUID(allLocations.current, locationId);}- const context = useMemo(() => {- return {+ const context = useMemo(+ () => ({locations: allLocations.current,currentLocation,currentLocationId: currentLocationId.current,@@ -599,15 +552,16 @@ export const CurrentLocationContextProvider = ({setLocationDirectoryContextMenuAnchorEl,getLocationPosition,getFirstRWLocation,- };- }, [- allLocations.current,- currentLocationId.current,- selectedLocation.current,- persistTagsInSidecarFile,- skipInitialDirList.current,- locationDirectoryContextMenuAnchorEl,- ]);+ }),+ [+ allLocations.current,+ currentLocationId.current,+ selectedLocation.current,+ persistTagsInSidecarFile,+ skipInitialDirList.current,+ locationDirectoryContextMenuAnchorEl,+ ],+ );return (<CurrentLocationContext.Provider value={context}>diff --git a/src/renderer/utils/locationUtils.ts b/src/renderer/utils/locationUtils.tsnew file mode 100644index 000000000..1fd568d58--- /dev/null+++ b/src/renderer/utils/locationUtils.ts@@ -0,0 +1,182 @@+/**+ * TagSpaces - universal file and folder organizer+ * Copyright (C) 2026-present TagSpaces GmbH+ *+ * 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 AppConfig from '-/AppConfig';+import { CommonLocation } from '-/utils/CommonLocation';+// Note: locationType import kept local to this module for flexibility++/**+ * Find a location by ID, with optional fallback to current location+ * @param locations - Array of locations to search+ * @param locationId - ID to find (optional)+ * @param currentId - Current location ID for fallback+ * @returns The location if found, undefined otherwise+ */+export function findLocationById(+ locations: CommonLocation[],+ locationId?: string,+ currentId?: string,+): CommonLocation | undefined {+ const targetId = locationId || currentId;+ return locations.find((l) => l.uuid === targetId);+}++/**+ * Find first read-write location with priority for default locations+ * @param locations - Array of locations to search+ * @returns First RW location (prioritizing default), or undefined if none found+ */+export function getFirstReadWriteLocation(+ locations: CommonLocation[],+): CommonLocation | undefined {+ return (+ locations.find((location) => location.isDefault && !location.isReadOnly) ||+ locations.find((location) => !location.isReadOnly)+ );+}++/**+ * Find location by type+ * @param locations - Array of locations to search+ * @param type - Location type to find+ * @returns Location of specified type, or undefined if not found+ */+export function findLocationByType(+ locations: CommonLocation[],+ type: string | number,+): CommonLocation | undefined {+ return locations.find((l) => l.type === type);+}++/**+ * Find local location+ * @param locations - Array of locations to search+ * @returns Local location if found, undefined otherwise+ */+export function findLocalLocation(+ locations: CommonLocation[],+): CommonLocation | undefined {+ // Import inline to avoid circular dependencies in tests+ const { locationType } = require('@tagspaces/tagspaces-common/misc');+ return findLocationByType(locations, locationType.TYPE_LOCAL);+}++/**+ * Get directory separator for a location, with AppConfig fallback+ * @param location - Location to get separator for+ * @returns Directory separator string+ */+export function getDirSeparatorForLocation(+ location: CommonLocation | undefined,+): string {+ return location?.getDirSeparator() ?? AppConfig.dirSeparator;+}++/**+ * Get position (index) of location in array+ * @param locations - Array of locations+ * @param locationId - Location UUID to find+ * @returns Index of location, or -1 if not found+ */+export function getLocationPositionByUUID(+ locations: CommonLocation[],+ locationId: string,+): number {+ return locations.findIndex((location) => location.uuid === locationId);+}++/**+ * Validate move location parameters+ * @param locations - Array of locations+ * @param locationUUID - UUID of location to move+ * @param newIndex - Target index+ * @throws Error if parameters are invalid+ * @returns Validation result with current and new indices+ */+export function validateMoveLocation(+ locations: CommonLocation[],+ locationUUID: string,+ newIndex: number,+): { currentIndex: number; newIndex: number } {+ if (!Array.isArray(locations)) {+ throw new Error('Locations must be an array');+ }++ if (newIndex < 0 || newIndex >= locations.length) {+ throw new Error(+ `Invalid newIndex: ${newIndex}. Must be between 0 and ${locations.length - 1}`,+ );+ }++ const currentIndex = getLocationPositionByUUID(locations, locationUUID);+ if (currentIndex === -1) {+ throw new Error(`Location with UUID ${locationUUID} not found`);+ }++ return { currentIndex, newIndex };+}++/**+ * Check if location can move up+ * @param locations - Array of locations+ * @param locationUUID - UUID of location to check+ * @returns true if location can move up, false otherwise+ */+export function canMoveUp(+ locations: CommonLocation[],+ locationUUID: string,+): boolean {+ const index = getLocationPositionByUUID(locations, locationUUID);+ return index > 0;+}++/**+ * Check if location can move down+ * @param locations - Array of locations+ * @param locationUUID - UUID of location to check+ * @returns true if location can move down, false otherwise+ */+export function canMoveDown(+ locations: CommonLocation[],+ locationUUID: string,+): boolean {+ const index = getLocationPositionByUUID(locations, locationUUID);+ return index >= 0 && index < locations.length - 1;+}++/**+ * Check if location exists in array+ * @param locations - Array of locations+ * @param locationUUID - UUID to search for+ * @returns true if location exists, false otherwise+ */+export function locationExists(+ locations: CommonLocation[],+ locationUUID: string,+): boolean {+ return locations.some((location) => location.uuid === locationUUID);+}++/**+ * Get location path, preferring path over paths array+ * @param location - Location to get path from+ * @returns Path string, or empty string if no path found+ */+export function getLocationPathString(location: CommonLocation): string {+ if (!location) return '';+ return location.path || location.paths?.[0] || '';+}diff --git a/tests/unit/locationUtils.test.js b/tests/unit/locationUtils.test.jsnew file mode 100644index 000000000..589a1b784--- /dev/null+++ b/tests/unit/locationUtils.test.js@@ -0,0 +1,378 @@+import { beforeEach, describe, expect, test } from '@playwright/test';++// Mock AppConfig+const mockAppConfig = {+ SearchTypeGroups: {+ files: ['files'],+ folders: ['folders'],+ untagged: ['untagged'],+ any: ['any'],+ },+ dirSeparator: '/',+ isMobile: false,+ isWeb: false,+};++// Simple mock of CommonLocation for testing+class MockCommonLocation {+ constructor(config) {+ this.uuid = config.uuid;+ this.name = config.name;+ this.type = config.type;+ this.isReadOnly = config.isReadOnly || false;+ this.isDefault = config.isDefault || false;+ this.path = config.path || '';+ this.paths = config.paths || [];+ }++ getDirSeparator() {+ return mockAppConfig.dirSeparator;+ }+}++import {+ canMoveDown,+ canMoveUp,+ findLocalLocation,+ findLocationById,+ findLocationByType,+ getDirSeparatorForLocation,+ getFirstReadWriteLocation,+ getLocationPathString,+ getLocationPositionByUUID,+ locationExists,+ validateMoveLocation,+} from '-/utils/locationUtils';+import { locationType } from '@tagspaces/tagspaces-common/misc';++// Mock data helper+function createMockLocation(+ uuid,+ name,+ type = locationType.TYPE_LOCAL,+ isReadOnly = false,+ isDefault = false,+ path = '',+) {+ const location = new MockCommonLocation({+ uuid,+ name,+ type,+ isReadOnly,+ isDefault,+ path,+ });+ return location;+}++describe('locationUtils', () => {+ let locations;++ beforeEach(async () => {+ locations = [+ createMockLocation('loc-1', 'Home', locationType.TYPE_LOCAL, false, true, '/home'),+ createMockLocation('loc-2', 'Downloads', locationType.TYPE_LOCAL, false, false, '/downloads'),+ createMockLocation('loc-3', 'Cloud', locationType.TYPE_CLOUD, true, false),+ createMockLocation('loc-4', 'S3', locationType.TYPE_OBJECTSTORE, false, false),+ ];+ });++ describe('findLocationById', () => {+ test('should find location by ID', async () => {+ const result = findLocationById(locations, 'loc-2');+ expect(result).toBeDefined();+ expect(result.name).toBe('Downloads');+ });++ test('should return undefined for non-existent ID', async () => {+ const result = findLocationById(locations, 'loc-nonexistent');+ expect(result).toBeUndefined();+ });++ test('should fallback to current location when locationId is undefined', async () => {+ const result = findLocationById(locations, undefined, 'loc-1');+ expect(result).toBeDefined();+ expect(result.name).toBe('Home');+ });++ test('should prioritize locationId over currentId', async () => {+ const result = findLocationById(locations, 'loc-2', 'loc-1');+ expect(result.name).toBe('Downloads');+ });++ test('should handle empty array', async () => {+ const result = findLocationById([], 'loc-1');+ expect(result).toBeUndefined();+ });+ });++ describe('getFirstReadWriteLocation', () => {+ test('should find default writable location first', async () => {+ const result = getFirstReadWriteLocation(locations);+ expect(result).toBeDefined();+ expect(result.uuid).toBe('loc-1');+ expect(result.isDefault).toBe(true);+ });++ test('should find non-default writable location if no default exists', async () => {+ const testLocations = [+ createMockLocation('loc-1', 'ReadOnly', locationType.TYPE_LOCAL, true, true),+ createMockLocation('loc-2', 'Writable', locationType.TYPE_LOCAL, false, false),+ ];+ const result = getFirstReadWriteLocation(testLocations);+ expect(result.name).toBe('Writable');+ });++ test('should return undefined if all locations are read-only', async () => {+ const testLocations = [+ createMockLocation('loc-1', 'RO1', locationType.TYPE_LOCAL, true),+ createMockLocation('loc-2', 'RO2', locationType.TYPE_LOCAL, true),+ ];+ const result = getFirstReadWriteLocation(testLocations);+ expect(result).toBeUndefined();+ });++ test('should return undefined for empty array', async () => {+ const result = getFirstReadWriteLocation([]);+ expect(result).toBeUndefined();+ });+ });++ describe('findLocationByType', () => {+ test('should find location by type', async () => {+ const result = findLocationByType(locations, locationType.TYPE_CLOUD);+ expect(result).toBeDefined();+ expect(result.name).toBe('Cloud');+ });++ test('should return undefined for non-existent type', async () => {+ const result = findLocationByType(locations, 'non-existent-type');+ expect(result).toBeUndefined();+ });++ test('should return first match when multiple locations have same type', async () => {+ const result = findLocationByType(locations, locationType.TYPE_LOCAL);+ expect(result.uuid).toBe('loc-1');+ });++ test('should handle empty array', async () => {+ const result = findLocationByType([], locationType.TYPE_LOCAL);+ expect(result).toBeUndefined();+ });+ });++ describe('findLocalLocation', () => {+ test('should return undefined if no local location', async () => {+ const testLocations = [+ createMockLocation('loc-1', 'Cloud', locationType.TYPE_CLOUD),+ createMockLocation('loc-2', 'WebDAV', locationType.TYPE_WEBDAV),+ ];+ const result = findLocalLocation(testLocations);+ expect(result).toBeUndefined();+ });++ test('should handle empty array', async () => {+ const result = findLocalLocation([]);+ expect(result).toBeUndefined();+ });+ });++ describe('getDirSeparatorForLocation', () => {+ test('should return location separator if location exists', async () => {+ const location = locations[0];+ const result = getDirSeparatorForLocation(location);+ expect(result).toBeDefined();+ expect(typeof result).toBe('string');+ });++ test('should return AppConfig separator for undefined location', async () => {+ const result = getDirSeparatorForLocation(undefined);+ expect(result).toBe('/');+ });++ test('should return AppConfig separator for null location', async () => {+ const result = getDirSeparatorForLocation(null);+ expect(result).toBe('/');+ });+ });++ describe('getLocationPositionByUUID', () => {+ test('should find location at correct index', async () => {+ const result = getLocationPositionByUUID(locations, 'loc-2');+ expect(result).toBe(1);+ });++ test('should return -1 for non-existent location', async () => {+ const result = getLocationPositionByUUID(locations, 'non-existent');+ expect(result).toBe(-1);+ });++ test('should find location at start of array', async () => {+ const result = getLocationPositionByUUID(locations, 'loc-1');+ expect(result).toBe(0);+ });++ test('should find location at end of array', async () => {+ const result = getLocationPositionByUUID(locations, 'loc-4');+ expect(result).toBe(locations.length - 1);+ });++ test('should handle empty array', async () => {+ const result = getLocationPositionByUUID([], 'loc-1');+ expect(result).toBe(-1);+ });+ });++ describe('validateMoveLocation', () => {+ test('should validate valid move parameters', async () => {+ const result = validateMoveLocation(locations, 'loc-2', 0);+ expect(result.currentIndex).toBe(1);+ expect(result.newIndex).toBe(0);+ });++ test('should throw error for invalid array', async () => {+ expect(() => {+ validateMoveLocation(null, 'loc-1', 0);+ }).toThrow('Locations must be an array');+ });++ test('should throw error for negative newIndex', async () => {+ expect(() => {+ validateMoveLocation(locations, 'loc-1', -1);+ }).toThrow('Invalid newIndex');+ });++ test('should throw error for newIndex >= array length', async () => {+ expect(() => {+ validateMoveLocation(locations, 'loc-1', locations.length);+ }).toThrow('Invalid newIndex');+ });++ test('should throw error for non-existent location UUID', async () => {+ expect(() => {+ validateMoveLocation(locations, 'non-existent', 0);+ }).toThrow('Location with UUID non-existent not found');+ });++ test('should accept newIndex at array length - 1', async () => {+ const result = validateMoveLocation(locations, 'loc-1', locations.length - 1);+ expect(result.newIndex).toBe(locations.length - 1);+ });+ });++ describe('canMoveUp', () => {+ test('should return true for non-first location', async () => {+ const result = canMoveUp(locations, 'loc-2');+ expect(result).toBe(true);+ });++ test('should return false for first location', async () => {+ const result = canMoveUp(locations, 'loc-1');+ expect(result).toBe(false);+ });++ test('should return false for non-existent location', async () => {+ const result = canMoveUp(locations, 'non-existent');+ expect(result).toBe(false);+ });++ test('should return false for empty array', async () => {+ const result = canMoveUp([], 'loc-1');+ expect(result).toBe(false);+ });+ });++ describe('canMoveDown', () => {+ test('should return true for non-last location', async () => {+ const result = canMoveDown(locations, 'loc-1');+ expect(result).toBe(true);+ });++ test('should return false for last location', async () => {+ const result = canMoveDown(locations, 'loc-4');+ expect(result).toBe(false);+ });++ test('should return false for non-existent location', async () => {+ const result = canMoveDown(locations, 'non-existent');+ expect(result).toBe(false);+ });++ test('should return false for empty array', async () => {+ const result = canMoveDown([], 'loc-1');+ expect(result).toBe(false);+ });+ });++ describe('locationExists', () => {+ test('should return true for existing location', async () => {+ const result = locationExists(locations, 'loc-1');+ expect(result).toBe(true);+ });++ test('should return false for non-existent location', async () => {+ const result = locationExists(locations, 'non-existent');+ expect(result).toBe(false);+ });++ test('should return false for empty array', async () => {+ const result = locationExists([], 'loc-1');+ expect(result).toBe(false);+ });++ test('should handle multiple matches correctly', async () => {+ const testLocations = [+ createMockLocation('loc-1', 'Home'),+ createMockLocation('loc-1', 'Duplicate'),+ ];+ const result = locationExists(testLocations, 'loc-1');+ expect(result).toBe(true);+ });+ });++ describe('getLocationPathString', () => {+ test('should return path from location', async () => {+ const location = createMockLocation('loc-1', 'Home', locationType.TYPE_LOCAL, false, false, '/home');+ const result = getLocationPathString(location);+ expect(result).toBe('/home');+ });++ test('should return first path from paths array if path is empty', async () => {+ const location = new MockCommonLocation({+ uuid: 'loc-1',+ name: 'Test',+ type: locationType.TYPE_LOCAL,+ paths: ['/first', '/second'],+ });+ const result = getLocationPathString(location);+ expect(result).toBe('/first');+ });++ test('should prefer path over paths array', async () => {+ const location = new MockCommonLocation({+ uuid: 'loc-1',+ name: 'Test',+ type: locationType.TYPE_LOCAL,+ path: '/primary',+ paths: ['/fallback'],+ });+ const result = getLocationPathString(location);+ expect(result).toBe('/primary');+ });++ test('should return empty string if no path available', async () => {+ const location = new MockCommonLocation({+ uuid: 'loc-1',+ name: 'Test',+ type: locationType.TYPE_LOCAL,+ });+ const result = getLocationPathString(location);+ expect(result).toBe('');+ });++ test('should return empty string for undefined location', async () => {+ const result = getLocationPathString(undefined);+ expect(result).toBe('');+ });+ });+});