TagSpaces is an offline, open source, document manager with tagging support
chore: refactoring the index reflection functionality for adding unit tests
Ilian Sapundshiev12c51b8cefb2
diff --git a/src/renderer/hooks/LocationIndexContextProvider.tsx b/src/renderer/hooks/LocationIndexContextProvider.tsxindex 482234cf3..a5a2599b2 100644--- a/src/renderer/hooks/LocationIndexContextProvider.tsx+++ b/src/renderer/hooks/LocationIndexContextProvider.tsx@@ -34,6 +34,11 @@ import { prepareIndex, fuseOptions } from '@tagspaces/tagspaces-search';import Fuse from 'fuse.js';import { TS } from '-/tagspaces.namespace';import { CommonLocation } from '-/utils/CommonLocation';+import {+ applyCreateToIndex,+ applyDeleteToIndex,+ applyUpdateToIndex,+} from '-/utils/indexReflect';import useFirstRender from '-/utils/useFirstRender';import { locationType } from '@tagspaces/tagspaces-common/misc';import {@@ -288,45 +293,22 @@ export const LocationIndexContextProvider = ({return index.current;}+ // Thin wrappers over the pure transforms in utils/indexReflect (covered+ // by tests/unit/indexReflect.test.js). `apply*` return null when nothing+ // should change, so persisting the result is gated on a truthy next.function reflectDeleteEntry(path: string) {- if (!index.current || index.current.length < 1) {- return;- }- const nextIndex = index.current.filter((entry) => entry.path !== path);- if (nextIndex.length !== index.current.length) {- setIndex(nextIndex, currentLocation);- }+ const next = applyDeleteToIndex(index.current, path);+ if (next) setIndex(next, currentLocation);}function reflectCreateEntry(newEntry: TS.FileSystemEntry) {- if (!index.current || index.current.length < 1) {- return;- }- let entryFound = index.current.some(- (entry) => entry.path === newEntry.path,- );- if (!entryFound) {- setIndex([...index.current, newEntry], currentLocation);- //index.current.push(newEntry);- }- // else todo update index entry ?+ const next = applyCreateToIndex(index.current, newEntry);+ if (next) setIndex(next, currentLocation);}function reflectUpdateEntry(path: string, newEntry: TS.FileSystemEntry) {- if (!index.current || index.current.length < 1) {- return;- }- if (index.current.some((i) => i.path === path)) {- setIndex(- index.current.map((i) => {- if (i.path === path) {- return newEntry;- }- return i;- }),- currentLocation,- );- }+ const next = applyUpdateToIndex(index.current, path, newEntry);+ if (next) setIndex(next, currentLocation);}async function findLinks(diff --git a/src/renderer/utils/indexReflect.ts b/src/renderer/utils/indexReflect.tsnew file mode 100644index 000000000..0e92b9df6--- /dev/null+++ b/src/renderer/utils/indexReflect.ts@@ -0,0 +1,75 @@+/**+ * TagSpaces - universal file and folder organizer+ * Copyright (C) 2024-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.+ */++import { TS } from '-/tagspaces.namespace';++/**+ * Pure transforms that the `reflect*Entry` hook helpers in+ * LocationIndexContextProvider apply to the in-memory index when a+ * file system action fires ("add" / "delete" / "update" / "move").+ *+ * Returning `null` signals "no change — caller should NOT update state".+ * Returning an array is the new index the caller should persist. Keeping+ * these pure (no refs, no setIndex) makes them unit-testable without+ * mounting the whole provider tree.+ *+ * Invariants preserved from the original hook helpers:+ * - Never mutate the input array (always returns a fresh copy on change).+ * - Skip when the current index is undefined or empty. This prevents a+ * reflect action from "bootstrapping" an index the provider never+ * actually loaded — that's the job of loadIndexFromDisk / createIndex.+ */++type Index = TS.FileSystemEntry[] | undefined;++/**+ * Remove the entry at `path` (exact match). Returns the filtered array,+ * or `null` if the entry isn't in the current index / index is empty.+ *+ * NOTE: historically this was implemented with `Array.prototype.splice`+ * which returns the REMOVED slice — the buggy version replaced the index+ * with just the deleted entry instead of the survivors.+ */+export function applyDeleteToIndex(+ current: Index,+ path: string,+): TS.FileSystemEntry[] | null {+ if (!current || current.length < 1) return null;+ const next = current.filter((entry) => entry.path !== path);+ return next.length === current.length ? null : next;+}++/**+ * Append `newEntry` if no entry with the same `path` already exists.+ * Returns the new array, or `null` if the entry is already present or the+ * current index is empty/undefined.+ */+export function applyCreateToIndex(+ current: Index,+ newEntry: TS.FileSystemEntry,+): TS.FileSystemEntry[] | null {+ if (!current || current.length < 1) return null;+ if (current.some((entry) => entry.path === newEntry.path)) return null;+ return [...current, newEntry];+}++/**+ * Replace the entry matching `oldPath` with `newEntry`. Used for both+ * `update` (same path, new meta) and `move` (new path) actions. Returns+ * the new array, or `null` if no entry matches `oldPath`.+ */+export function applyUpdateToIndex(+ current: Index,+ oldPath: string,+ newEntry: TS.FileSystemEntry,+): TS.FileSystemEntry[] | null {+ if (!current || current.length < 1) return null;+ if (!current.some((entry) => entry.path === oldPath)) return null;+ return current.map((entry) => (entry.path === oldPath ? newEntry : entry));+}diff --git a/tests/unit/indexReflect.test.js b/tests/unit/indexReflect.test.jsnew file mode 100644index 000000000..ca542f633--- /dev/null+++ b/tests/unit/indexReflect.test.js@@ -0,0 +1,131 @@+import { describe, expect, test } from '@playwright/test';++import {+ applyCreateToIndex,+ applyDeleteToIndex,+ applyUpdateToIndex,+} from '-/utils/indexReflect';++// Minimal fixture — the reflect helpers only touch `.path`; other fields+// are carried through via the input entry.+const entry = (path, extra = {}) => ({+ name: path.split('/').pop(),+ path,+ isFile: true,+ size: 0,+ lmdt: 0,+ ...extra,+});++describe('applyDeleteToIndex', () => {+ test('removes the matching entry and returns the survivors', () => {+ const index = [entry('a.txt'), entry('b.txt'), entry('c.txt')];+ expect(applyDeleteToIndex(index, 'b.txt')).toEqual([+ entry('a.txt'),+ entry('c.txt'),+ ]);+ });++ test('REGRESSION: returns survivors, not the deleted entry (splice bug)', () => {+ // A naive `splice(i, 1)` implementation returned the REMOVED slice+ // and passed it to setIndex, leaving the index as a single element+ // containing only the deleted file. Guard against that forever.+ const index = [entry('keep1.txt'), entry('victim.txt'), entry('keep2.txt')];+ const result = applyDeleteToIndex(index, 'victim.txt');+ expect(result).toEqual([entry('keep1.txt'), entry('keep2.txt')]);+ // Specifically: result must NOT be the one-element [deleted] array.+ expect(result).not.toEqual([entry('victim.txt')]);+ expect(result.length).toBe(2);+ });++ test('returns null when path is not in the index (no-op)', () => {+ const index = [entry('a.txt'), entry('b.txt')];+ expect(applyDeleteToIndex(index, 'missing.txt')).toBeNull();+ });++ test('returns null for empty or undefined index', () => {+ expect(applyDeleteToIndex([], 'a.txt')).toBeNull();+ expect(applyDeleteToIndex(undefined, 'a.txt')).toBeNull();+ });++ test('does not mutate the input array', () => {+ const index = [entry('a.txt'), entry('b.txt')];+ const snapshot = [...index];+ applyDeleteToIndex(index, 'a.txt');+ expect(index).toEqual(snapshot);+ });+});++describe('applyCreateToIndex', () => {+ test('appends a new entry when its path is not already present', () => {+ const index = [entry('a.txt')];+ expect(applyCreateToIndex(index, entry('b.txt'))).toEqual([+ entry('a.txt'),+ entry('b.txt'),+ ]);+ });++ test('returns null when an entry with the same path already exists', () => {+ const index = [entry('a.txt', { size: 10 })];+ expect(applyCreateToIndex(index, entry('a.txt', { size: 20 }))).toBeNull();+ });++ test('returns null for empty or undefined index (no bootstrap via reflect)', () => {+ expect(applyCreateToIndex([], entry('a.txt'))).toBeNull();+ expect(applyCreateToIndex(undefined, entry('a.txt'))).toBeNull();+ });++ test('does not mutate the input array', () => {+ const index = [entry('a.txt')];+ const snapshot = [...index];+ applyCreateToIndex(index, entry('b.txt'));+ expect(index).toEqual(snapshot);+ });+});++describe('applyUpdateToIndex', () => {+ test('replaces the matching entry in-place (same path, new meta)', () => {+ const index = [+ entry('a.txt'),+ entry('b.txt', { size: 10 }),+ entry('c.txt'),+ ];+ const updated = entry('b.txt', { size: 42 });+ expect(applyUpdateToIndex(index, 'b.txt', updated)).toEqual([+ entry('a.txt'),+ updated,+ entry('c.txt'),+ ]);+ });++ test('also handles rename/move — oldPath differs from newEntry.path', () => {+ // The useEffect action dispatcher maps both "update" and "move" to+ // reflectUpdateEntry. A move changes the entry's path; the replacement+ // is indexed by oldPath but the new entry carries the new path.+ const index = [entry('old-name.txt'), entry('other.txt')];+ const moved = entry('new-name.txt', { size: 100 });+ expect(applyUpdateToIndex(index, 'old-name.txt', moved)).toEqual([+ moved,+ entry('other.txt'),+ ]);+ });++ test('returns null when oldPath is not in the index', () => {+ const index = [entry('a.txt'), entry('b.txt')];+ expect(+ applyUpdateToIndex(index, 'missing.txt', entry('missing.txt')),+ ).toBeNull();+ });++ test('returns null for empty or undefined index', () => {+ expect(applyUpdateToIndex([], 'a.txt', entry('a.txt'))).toBeNull();+ expect(applyUpdateToIndex(undefined, 'a.txt', entry('a.txt'))).toBeNull();+ });++ test('does not mutate the input array', () => {+ const index = [entry('a.txt'), entry('b.txt')];+ const snapshot = [...index];+ applyUpdateToIndex(index, 'a.txt', entry('a.txt', { size: 99 }));+ expect(index).toEqual(snapshot);+ });+});