Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(library): address library folders, pages and files by id in the URL (#21923)

Lobehub Coder211538bf35b1
diff --git a/apps/server/src/routers/lambda/__tests__/document.test.ts b/apps/server/src/routers/lambda/__tests__/document.test.ts
index 3725e0e9109..f20fbdd121d 100644
--- a/apps/server/src/routers/lambda/__tests__/document.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/document.test.ts
@@ -527,3 +527,47 @@ describe('documentRouter updateDocument mention notifications', () => {
expect(mocks.notifyDocumentMention).not.toHaveBeenCalled();
});
});
+
+describe('documentRouter getFolderBreadcrumb', () => {
+ const caller = () =>
+ documentRouter.createCaller({
+ serverDB: {},
+ userId: 'member-1',
+ workspaceId: 'ws-1',
+ workspaceRole: 'member',
+ } as any);
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ // Folder URLs moved from `/<folderSlug>` to `folder/<folderId>`, so the chain
+ // must resolve from an id as well as from a legacy slug.
+ it('resolves the chain from a folder id', async () => {
+ mocks.findBySlug.mockResolvedValue(undefined);
+ mocks.findById.mockImplementation(async (id: string) =>
+ id === 'docs_child'
+ ? { id: 'docs_child', parentId: 'docs_root', slug: 'child', title: 'Child' }
+ : { id: 'docs_root', parentId: null, slug: 'root', title: 'Root' },
+ );
+
+ await expect(caller().getFolderBreadcrumb({ slug: 'docs_child' })).resolves.toEqual([
+ { id: 'docs_root', name: 'Root', slug: 'root' },
+ { id: 'docs_child', name: 'Child', slug: 'child' },
+ ]);
+ });
+
+ it('still resolves a legacy slug', async () => {
+ mocks.findBySlug.mockResolvedValue({
+ id: 'docs_root',
+ parentId: null,
+ slug: 'root',
+ title: 'Root',
+ });
+
+ await expect(caller().getFolderBreadcrumb({ slug: 'root' })).resolves.toEqual([
+ { id: 'docs_root', name: 'Root', slug: 'root' },
+ ]);
+ expect(mocks.findById).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/routers/lambda/__tests__/file.test.ts b/apps/server/src/routers/lambda/__tests__/file.test.ts
index dc4d8615ae8..4f51158450a 100644
--- a/apps/server/src/routers/lambda/__tests__/file.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/file.test.ts
@@ -1107,12 +1107,12 @@ describe('fileRouter', () => {
await expect(caller.getFileItemById({ id: 'invalid-id' })).rejects.toThrow(TRPCError);
});
- it('should return proxy URL format ${APP_URL}/f/:id', async () => {
- mockFileModelFindById.mockResolvedValue(mockFile);
-
+ it('should return proxy URL format ${APP_URL}/f/:id and the parent folder', async () => {
+ mockFileModelFindById.mockResolvedValue({ ...mockFile, parentId: 'docs_folder' });
const result = await caller.getFileItemById({ id: 'test-id' });
expect(result?.url).toBe('https://lobehub.com/f/test-id');
+ expect(result?.parentId).toBe('docs_folder');
});
});
diff --git a/apps/server/src/routers/lambda/document.ts b/apps/server/src/routers/lambda/document.ts
index 3a894f68f9c..85ac697ecdb 100644
--- a/apps/server/src/routers/lambda/document.ts
+++ b/apps/server/src/routers/lambda/document.ts
@@ -477,7 +477,10 @@ export const documentRouter = router({
.input(z.object({ slug: z.string() }))
.query(async ({ ctx, input }) => {
const chain = [];
- let currentFolder = await ctx.documentModel.findBySlug(input.slug);
+ // Folder URLs carry the id; older links still carry the slug.
+ let currentFolder =
+ (await ctx.documentModel.findBySlug(input.slug)) ??
+ (await ctx.documentModel.findById(input.slug));
// Build chain from current folder to root
while (currentFolder) {
diff --git a/apps/server/src/routers/lambda/file/queries.ts b/apps/server/src/routers/lambda/file/queries.ts
index 2174a1a6575..f4246221310 100644
--- a/apps/server/src/routers/lambda/file/queries.ts
+++ b/apps/server/src/routers/lambda/file/queries.ts
@@ -94,6 +94,7 @@ export const queriesRouter = router({
id: item.id,
metadata: item.metadata as Record<string, any> | null | undefined,
name: item.name,
+ parentId: item.parentId,
size: item.size,
sourceType: 'file' as const,
updatedAt: item.updatedAt,
diff --git a/src/features/CommandMenu/SearchResults.tsx b/src/features/CommandMenu/SearchResults.tsx
index 795e33aba80..601c5f506c6 100644
--- a/src/features/CommandMenu/SearchResults.tsx
+++ b/src/features/CommandMenu/SearchResults.tsx
@@ -25,6 +25,7 @@ import AgentAvatar from '@/components/AgentAvatar';
import type { FtsSearchResult } from '@/database/repositories/ftsSearch';
import { taskDetailPath } from '@/features/AgentTasks/shared/taskDetailPath';
import { useCommandMenuContext } from '@/features/CommandMenu/CommandMenuContext';
+import { libraryFolderPath, libraryItemPath } from '@/features/ResourceManager/utils/resourcePath';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useImageStore } from '@/store/image';
import { generationTopicSelectors as imageGenerationTopicSelectors } from '@/store/image/slices/generationTopic/selectors';
@@ -121,9 +122,9 @@ const SearchResults = memo<SearchResultsProps>(
break;
}
case 'file': {
- // Navigate to resource library with file parameter
+ // Open the file inside its library, or over the Docs home
const fileUrl = result.knowledgeBaseId
- ? `/resource/library/${result.knowledgeBaseId}?file=${result.id}`
+ ? libraryItemPath(result.knowledgeBaseId, result.id)
: `/resource?file=${result.id}`;
console.info('[SearchResults] File navigation:', {
fileDetails: result,
@@ -133,15 +134,12 @@ const SearchResults = memo<SearchResultsProps>(
break;
}
case 'folder': {
- // Navigate to folder by slug
- if (result.knowledgeBaseId && result.slug) {
- navigate(`/resource/library/${result.knowledgeBaseId}/${result.slug}`);
- } else if (result.slug) {
- navigate(`/resource/library/${result.slug}`);
- } else {
- // Fallback to library root if no slug
- navigate(`/resource/library`);
- }
+ // Open the folder inside its library, or the library gallery without one
+ navigate(
+ result.knowledgeBaseId
+ ? libraryFolderPath(result.knowledgeBaseId, result.id)
+ : '/resource/library',
+ );
break;
}
case 'page': {
diff --git a/src/features/ResourceLibrary/index.tsx b/src/features/ResourceLibrary/index.tsx
index c155c78dfd7..d559bd24596 100644
--- a/src/features/ResourceLibrary/index.tsx
+++ b/src/features/ResourceLibrary/index.tsx
@@ -1,7 +1,7 @@
'use client';
import { memo, useLayoutEffect } from 'react';
-import { useLocation, useParams } from 'react-router';
+import { Navigate, useLocation, useParams } from 'react-router';
import NotFound from '@/components/404';
import AsyncError from '@/components/AsyncError';
@@ -12,15 +12,32 @@ import ResourceManager from '@/features/ResourceManager';
import { useInitFileCheck } from '@/features/ResourceManager/hooks/useInitFileCheck';
import { useKnowledgeBaseItem } from '@/features/ResourceManager/hooks/useKnowledgeItem';
import { useResourceManagerStore } from '@/features/ResourceManager/store';
+import {
+ legacyLibraryItemRedirect,
+ libraryFolderPath,
+ rebaseLibraryPath,
+} from '@/features/ResourceManager/utils/resourcePath';
+import { useFileStore } from '@/store/file';
import { isForbiddenError } from '@/utils/forbiddenError';
import LibraryHero from './LibraryHero';
const MainContent = memo(() => {
- const { id: knowledgeBaseId, slug } = useParams<{ id: string; slug?: string }>();
+ const {
+ folderId,
+ id: knowledgeBaseId,
+ itemId,
+ slug: legacyFolderSlug,
+ } = useParams<{ folderId?: string; id: string; itemId?: string; slug?: string }>();
const location = useLocation();
const setLibraryId = useResourceManagerStore((s) => s.setLibraryId);
+ // Folders used to open as `/resource/library/<id>/<folderSlug>`; resolve the
+ // slug to the folder id the `folder/<folderId>` route carries now.
+ const useFetchFolderBreadcrumb = useFileStore((s) => s.useFetchFolderBreadcrumb);
+ const { data: legacyFolderChain, isLoading: isLegacyFolderLoading } =
+ useFetchFolderBreadcrumb(legacyFolderSlug);
+
// Load knowledge base data
const { data, isLoading, error, mutate } = useKnowledgeBaseItem(knowledgeBaseId || '');
@@ -42,7 +59,26 @@ const MainContent = memo(() => {
}, [knowledgeBaseId, setLibraryId, location.pathname]);
// Sync file view mode from URL
- useInitFileCheck();
+ useInitFileCheck(itemId);
+
+ // Items used to open as `/resource/library/<id>?file=<itemId>`; keep old links working.
+ const legacyRedirect =
+ knowledgeBaseId && !itemId
+ ? legacyLibraryItemRedirect(location.pathname, location.search, knowledgeBaseId)
+ : null;
+ if (legacyRedirect) return <Navigate replace to={legacyRedirect} />;
+
+ if (knowledgeBaseId && legacyFolderSlug) {
+ const legacyFolderId = legacyFolderChain.at(-1)?.id;
+ if (legacyFolderId) {
+ const pathname = rebaseLibraryPath(
+ location.pathname,
+ libraryFolderPath(knowledgeBaseId, legacyFolderId),
+ );
+ return <Navigate replace to={{ pathname, search: location.search }} />;
+ }
+ return isLegacyFolderLoading ? <RouteLoading /> : <NotFound />;
+ }
// A network / 500 on the KB fetch is NOT "this library doesn't exist" (Read §1.1):
// branch a transient error to a reload state that keeps the URL, and reserve the
@@ -61,7 +97,7 @@ const MainContent = memo(() => {
if (!data) return <NotFound />;
// The cover header belongs to the library's root, not to every folder in it.
- return <ResourceManager explorerHero={slug ? undefined : <LibraryHero library={data} />} />;
+ return <ResourceManager explorerHero={folderId ? undefined : <LibraryHero library={data} />} />;
});
MainContent.displayName = 'LibraryMainContent';
diff --git a/src/features/ResourceManager/components/Explorer/Header/Breadcrumb.tsx b/src/features/ResourceManager/components/Explorer/Header/Breadcrumb.tsx
index 534fc8d2c3a..687040a7347 100644
--- a/src/features/ResourceManager/components/Explorer/Header/Breadcrumb.tsx
+++ b/src/features/ResourceManager/components/Explorer/Header/Breadcrumb.tsx
@@ -5,6 +5,7 @@ import { useSearchParams } from 'react-router';
import { useFolderPath } from '@/features/ResourceManager/hooks/useFolderPath';
import { useResourceManagerStore } from '@/features/ResourceManager/store';
+import { libraryFolderPath } from '@/features/ResourceManager/utils/resourcePath';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useFileStore } from '@/store/file';
import { knowledgeBaseSelectors, useKnowledgeBaseStore } from '@/store/library';
@@ -49,7 +50,7 @@ const Breadcrumb = memo<BreadcrumbProps>(({ category, fileName }) => {
const { t } = useTranslation('file');
const navigate = useWorkspaceAwareNavigate();
const [searchParams] = useSearchParams();
- const { currentFolderSlug, knowledgeBaseId: currentKnowledgeBaseId } = useFolderPath();
+ const { currentFolderId, knowledgeBaseId: currentKnowledgeBaseId } = useFolderPath();
const setMode = useResourceManagerStore((s) => s.setMode);
const setCurrentViewItemId = useResourceManagerStore((s) => s.setCurrentViewItemId);
@@ -61,7 +62,7 @@ const Breadcrumb = memo<BreadcrumbProps>(({ category, fileName }) => {
// Fetch folder breadcrumb chain from backend
const useFetchFolderBreadcrumb = useFileStore((s) => s.useFetchFolderBreadcrumb);
- const { data: folderChain = [] } = useFetchFolderBreadcrumb(currentFolderSlug);
+ const { data: folderChain = [] } = useFetchFolderBreadcrumb(currentFolderId);
// When in inbox mode (no knowledgeBaseId), show category in breadcrumb
if (!baseKnowledgeBaseId) {
@@ -83,7 +84,7 @@ const Breadcrumb = memo<BreadcrumbProps>(({ category, fileName }) => {
);
}
- const handleNavigate = (slug: string | null) => {
+ const handleNavigate = (folderId: string | null) => {
// If navigating while viewing a file, reset the file view mode
if (fileName) {
setMode('explorer');
@@ -96,9 +97,7 @@ const Breadcrumb = memo<BreadcrumbProps>(({ category, fileName }) => {
newParams.delete('file');
const queryString = newParams.toString();
- const basePath = slug
- ? `/resource/library/${baseKnowledgeBaseId}/${slug}`
- : `/resource/library/${baseKnowledgeBaseId}`;
+ const basePath = libraryFolderPath(baseKnowledgeBaseId, folderId);
navigate(queryString ? `${basePath}?${queryString}` : basePath);
};
@@ -128,7 +127,7 @@ const Breadcrumb = memo<BreadcrumbProps>(({ category, fileName }) => {
<span
className={cx(styles.breadcrumbItem, isLast && styles.currentItem)}
style={{ cursor: isLast ? 'default' : 'pointer' }}
- onClick={() => !isLast && handleNavigate(folder.slug)}
+ onClick={() => !isLast && handleNavigate(folder.id)}
>
{folder.name}
</span>
diff --git a/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.test.tsx b/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.test.tsx
index b538d6f5820..86fd2cdc3d7 100644
--- a/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.test.tsx
+++ b/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.test.tsx
@@ -138,7 +138,7 @@ describe('useFileItemDropdown — copy link', () => {
mocks.activeWorkspaceId = 'ws-1';
mocks.activeWorkspaceSlug = 'acme';
await expect(copyLink({ id: 'docs_abc', libraryId: 'kb_1' })).resolves.toBe(
- 'https://app.example.com/acme/resource/library/kb_1?file=docs_abc',
+ 'https://app.example.com/acme/resource/library/kb_1/docs/docs_abc',
);
});
diff --git a/src/features/ResourceManager/components/Explorer/ListView/ListItem/index.tsx b/src/features/ResourceManager/components/Explorer/ListView/ListItem/index.tsx
index d3143fd28d6..45185632de6 100644
--- a/src/features/ResourceManager/components/Explorer/ListView/ListItem/index.tsx
+++ b/src/features/ResourceManager/components/Explorer/ListView/ListItem/index.tsx
@@ -162,7 +162,6 @@ const FileListItem = ({
selected,
showUploader = true,
size,
- slug,
sourceType,
uploader,
url,
@@ -250,9 +249,12 @@ const FileListItem = ({
isPage,
libraryId: resourceManagerState.libraryId,
openInPanel: true,
- slug,
});
- const handleItemDoubleClick = useFileItemDoubleClick({ id, isPage });
+ const handleItemDoubleClick = useFileItemDoubleClick({
+ id,
+ isPage,
+ libraryId: resourceManagerState.libraryId,
+ });
const { menuItems } = useFileItemDropdown({
fileId,
fileType,
diff --git a/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/index.tsx b/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/index.tsx
index 6fd3337fabb..ef5ca286289 100644
--- a/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/index.tsx
+++ b/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/index.tsx
@@ -230,7 +230,6 @@ const MasonryFileItem = memo<MasonryFileItemProps>(
onOpen,
metadata,
sourceType,
- slug,
userId,
visibility,
}) => {
@@ -266,9 +265,12 @@ const MasonryFileItem = memo<MasonryFileItemProps>(
libraryId: knowledgeBaseId,
onOpen,
openInPanel: true,
- slug,
});
- const handleItemDoubleClick = useFileItemDoubleClick({ id, isPage });
+ const handleItemDoubleClick = useFileItemDoubleClick({
+ id,
+ isPage,
+ libraryId: knowledgeBaseId,
+ });
// Memoize drag data to prevent recreation
const dragData = useMemo(
diff --git a/src/features/ResourceManager/components/Explorer/hooks/useFileItemClick.desktop.test.ts b/src/features/ResourceManager/components/Explorer/hooks/useFileItemClick.desktop.test.ts
index b39a0634654..ad8647ffdf8 100644
--- a/src/features/ResourceManager/components/Explorer/hooks/useFileItemClick.desktop.test.ts
+++ b/src/features/ResourceManager/components/Explorer/hooks/useFileItemClick.desktop.test.ts
@@ -118,7 +118,9 @@ describe('useFileItemClick (desktop shell)', () => {
});
await flushPanelOpenDelay();
- expect(getTabRouter(TAB_ID)!.state.location.search).toBe('?view=grid&file=file_1');
+ const { pathname, search } = getTabRouter(TAB_ID)!.state.location;
+ expect(pathname).toBe('/resource/library/kb_1/file/file_1');
+ expect(search).toBe('?view=grid');
expect(useResourceManagerStore.getState().mode).toBe('editor');
expect(useResourceManagerStore.getState().detailPanelId).toBeUndefined();
});
@@ -144,7 +146,7 @@ describe('useFileItemClick (desktop shell)', () => {
it('opens the page editor directly when clicking a page inside a knowledge base', async () => {
const { result } = renderFileClick({
- id: 'page_1',
+ id: 'docs_1',
isFolder: false,
isPage: true,
libraryId: 'kb_1',
@@ -155,7 +157,9 @@ describe('useFileItemClick (desktop shell)', () => {
result.current();
});
- expect(getTabRouter(TAB_ID)!.state.location.search).toBe('?view=grid&file=page_1');
+ const { pathname, search } = getTabRouter(TAB_ID)!.state.location;
+ expect(pathname).toBe('/resource/library/kb_1/docs/docs_1');
+ expect(search).toBe('?view=grid');
expect(useResourceManagerStore.getState().mode).toBe('page');
expect(useResourceManagerStore.getState().detailPanelId).toBeUndefined();
});
@@ -265,7 +269,9 @@ describe('useFileItemClick (desktop shell)', () => {
result.current();
});
- expect(getTabRouter(TAB_ID)!.state.location.search).toBe('?view=grid&file=file_2');
+ const { pathname, search } = getTabRouter(TAB_ID)!.state.location;
+ expect(pathname).toBe('/resource/library/kb_1/file/file_2');
+ expect(search).toBe('?view=grid');
expect(useResourceManagerStore.getState().mode).toBe('editor');
expect(useResourceManagerStore.getState().detailPanelId).toBeUndefined();
});
@@ -284,9 +290,25 @@ describe('useFileItemClick (desktop shell)', () => {
expect(useResourceManagerStore.getState().detailPanelId).toBeUndefined();
});
+ it('opens a library item by path on double click instead of writing ?file=', async () => {
+ const { result } = renderHook(
+ () => useFileItemDoubleClick({ id: 'docs_1', isPage: true, libraryId: 'kb_1' }),
+ { wrapper: shellWrapper },
+ );
+
+ await act(async () => {
+ result.current();
+ });
+
+ const { pathname, search } = getTabRouter(TAB_ID)!.state.location;
+ expect(pathname).toBe('/resource/library/kb_1/docs/docs_1');
+ expect(search).toBe('?view=grid');
+ expect(useResourceManagerStore.getState().mode).toBe('page');
+ });
+
it('preserves the tab url view preferences when selecting a page', async () => {
const { result } = renderFileClick({
- id: 'page_1',
+ id: 'docs_1',
isFolder: false,
isPage: true,
libraryId: 'kb_1',
@@ -296,15 +318,16 @@ describe('useFileItemClick (desktop shell)', () => {
result.current();
});
- const search = new URLSearchParams(getTabRouter(TAB_ID)!.state.location.search);
- expect(search.get('file')).toBe('page_1');
- expect(search.get('view')).toBe('grid');
+ const { pathname, search } = getTabRouter(TAB_ID)!.state.location;
+ expect(pathname).toBe('/resource/library/kb_1/docs/docs_1');
+ expect(new URLSearchParams(search).has('file')).toBe(false);
+ expect(new URLSearchParams(search).get('view')).toBe('grid');
});
it('leaves the permission page when selecting a page from the library sidebar', async () => {
setupActiveTab('/resource/library/kb_1/permission?view=grid');
const { result } = renderFileClick({
- id: 'page_1',
+ id: 'docs_1',
isFolder: false,
isPage: true,
libraryId: 'kb_1',
@@ -315,8 +338,8 @@ describe('useFileItemClick (desktop shell)', () => {
});
const { pathname, search } = getTabRouter(TAB_ID)!.state.location;
- expect(pathname).toBe('/resource/library/kb_1');
- expect(new URLSearchParams(search).get('file')).toBe('page_1');
+ expect(pathname).toBe('/resource/library/kb_1/docs/docs_1');
+ expect(new URLSearchParams(search).has('file')).toBe(false);
expect(new URLSearchParams(search).get('view')).toBe('grid');
});
@@ -326,7 +349,6 @@ describe('useFileItemClick (desktop shell)', () => {
isFolder: true,
libraryId: 'kb_1',
isPage: false,
- slug: 'folder-slug',
});
await act(async () => {
@@ -334,7 +356,7 @@ describe('useFileItemClick (desktop shell)', () => {
});
const { pathname, search } = getTabRouter(TAB_ID)!.state.location;
- expect(pathname).toBe('/resource/library/kb_1/folder-slug');
+ expect(pathname).toBe('/resource/library/kb_1/folder/folder_1');
expect(new URLSearchParams(search).has('file')).toBe(false);
expect(screen.getByTestId('shell-search').textContent).toBe('');
});
diff --git a/src/features/ResourceManager/components/Explorer/hooks/useFileItemClick.ts b/src/features/ResourceManager/components/Explorer/hooks/useFileItemClick.ts
index 30e53372086..734ac566e96 100644
--- a/src/features/ResourceManager/components/Explorer/hooks/useFileItemClick.ts
+++ b/src/features/ResourceManager/components/Explorer/hooks/useFileItemClick.ts
@@ -1,6 +1,7 @@
import { useCallback } from 'react';
import { useResourceManagerStore } from '@/features/ResourceManager/store';
+import { libraryFolderPath, libraryItemPath } from '@/features/ResourceManager/utils/resourcePath';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useActiveLocation } from '@/hooks/useActiveLocation';
@@ -19,7 +20,6 @@ export interface UseFileItemClickOptions {
* fullscreen editor.
*/
openInPanel?: boolean;
- slug?: string | null;
}
/**
@@ -29,6 +29,26 @@ export interface UseFileItemClickOptions {
*/
export const DETAIL_PANEL_OPEN_DELAY_MS = 250;
+/**
+ * Open an item: inside a library by path (`/resource/library/<id>/{docs,file}/<itemId>`),
+ * elsewhere through the `?file=` query. View and sort preferences in the query are kept.
+ */
+const openItemUrl = (
+ id: string,
+ libraryId: string | null | undefined,
+ search: string,
+): { pathname?: string; search: string } => {
+ const params = new URLSearchParams(search);
+ if (!libraryId) {
+ params.set('file', id);
+ return { search: `?${params.toString()}` };
+ }
+
+ params.delete('file');
+ const query = params.toString();
+ return { pathname: libraryItemPath(libraryId, id), search: query ? `?${query}` : '' };
+};
+
let pendingPanelOpen: ReturnType<typeof setTimeout> | undefined;
const cancelPendingPanelOpen = () => {
@@ -43,7 +63,6 @@ const cancelPendingPanelOpen = () => {
*/
export const useFileItemClick = ({
id,
- slug,
libraryId,
isFolder,
isPage,
@@ -54,7 +73,7 @@ export const useFileItemClick = ({
// Read/write the URL through the active-tab facade rather than
// `useSearchParams`: this hook also runs in the library sidebar, which Electron
// portals into the shell's frozen root router.
- const { pathname, search } = useActiveLocation();
+ const { search } = useActiveLocation();
const setMode = useResourceManagerStore((s) => s.setMode);
const setCurrentViewItemId = useResourceManagerStore((s) => s.setCurrentViewItemId);
const openDetailPanel = useResourceManagerStore((s) => s.openDetailPanel);
@@ -62,25 +81,18 @@ export const useFileItemClick = ({
const handleClick = useCallback(() => {
const selectFile = () => {
- const newParams = new URLSearchParams(search);
- newParams.set('file', id);
-
- // The library sidebar stays mounted on the standalone Permissions page.
- // A search-only navigation there would keep the tab on `/permission`, so
- // selecting a page/file appeared to do nothing. Return to the library
- // surface first, then let its `file` query restore the selected content.
- if (libraryId && pathname.endsWith(`/resource/library/${libraryId}/permission`)) {
- navigate(`/resource/library/${libraryId}?${newParams.toString()}`);
+ const target = openItemUrl(id, libraryId, search);
+
+ // Inside a library the item has its own path (also leaves the Permissions page).
+ if (target.pathname) {
+ navigate(`${target.pathname}${target.search}`);
return;
}
- navigate({ search: `?${newParams.toString()}` }, { replace: true });
+ navigate({ search: target.search }, { replace: true });
};
if (isFolder) {
- // Navigate to folder using slug-based routing (Google Drive style)
- const folderSlug = slug || id;
-
if (libraryId) {
// Preserve existing query parameters (view and sort preferences)
const newParams = new URLSearchParams(search);
@@ -88,7 +100,7 @@ export const useFileItemClick = ({
newParams.delete('file');
const queryString = newParams.toString();
- const basePath = `/resource/library/${libraryId}/${folderSlug}`;
+ const basePath = libraryFolderPath(libraryId, id);
navigate(queryString ? `${basePath}?${queryString}` : basePath);
}
return;
@@ -128,13 +140,11 @@ export const useFileItemClick = ({
onOpen?.(id);
}, [
isFolder,
- slug,
id,
libraryId,
isPage,
navigate,
openInPanel,
- pathname,
search,
setMode,
setCurrentViewItemId,
@@ -148,14 +158,22 @@ export const useFileItemClick = ({
/**
* Double click = the committed "open this item" gesture: leave the list into
- * the fullscreen page editor or file editor. Keeps the `?file=` deep-link write
- * so a restored tab still lands on this item.
+ * the fullscreen page editor or file editor. Writes the item's path (library) or
+ * `?file=` query so a restored tab still lands on this item.
*/
-export const useFileItemDoubleClick = ({ id, isPage }: { id: string; isPage: boolean }) => {
+export const useFileItemDoubleClick = ({
+ id,
+ isPage,
+ libraryId,
+}: {
+ id: string;
+ isPage: boolean;
+ libraryId?: string | null;
+}) => {
const setMode = useResourceManagerStore((s) => s.setMode);
const setCurrentViewItemId = useResourceManagerStore((s) => s.setCurrentViewItemId);
const closeDetailPanel = useResourceManagerStore((s) => s.closeDetailPanel);
- const { search } = useActiveLocation();
+ const { pathname, search } = useActiveLocation();
const navigate = useWorkspaceAwareNavigate();
return useCallback(() => {
@@ -165,8 +183,24 @@ export const useFileItemDoubleClick = ({ id, isPage }: { id: string; isPage: boo
setCurrentViewItemId(id);
setMode(isPage ? 'page' : 'editor');
- const newParams = new URLSearchParams(search);
- newParams.set('file', id);
- navigate({ search: `?${newParams.toString()}` }, { replace: true });
- }, [closeDetailPanel, id, isPage, setCurrentViewItemId, setMode, navigate, search]);
+ const target = openItemUrl(id, libraryId, search);
+ if (target.pathname) {
+ // The single click already opened the item; don't stack a second entry.
+ if (pathname.endsWith(target.pathname)) return;
+ navigate(`${target.pathname}${target.search}`);
+ return;
+ }
+
+ navigate({ search: target.search }, { replace: true });
+ }, [
+ closeDetailPanel,
+ id,
+ isPage,
+ libraryId,
+ setCurrentViewItemId,
+ setMode,
+ navigate,
+ pathname,
+ search,
+ ]);
};
diff --git a/src/features/ResourceManager/components/Explorer/hooks/useResetSelectionOnQueryChange.test.tsx b/src/features/ResourceManager/components/Explorer/hooks/useResetSelectionOnQueryChange.test.tsx
index abb0ad79a3b..0a22ef0730b 100644
--- a/src/features/ResourceManager/components/Explorer/hooks/useResetSelectionOnQueryChange.test.tsx
+++ b/src/features/ResourceManager/components/Explorer/hooks/useResetSelectionOnQueryChange.test.tsx
@@ -17,7 +17,7 @@ describe('useResetSelectionOnQueryChange', () => {
(props: { searchQuery: string | null }) =>
useResetSelectionOnQueryChange({
category: FilesTabs.All,
- currentFolderSlug: 'folder-a',
+ currentFolderId: 'folder-a',
libraryId: undefined,
searchQuery: props.searchQuery,
}),
@@ -45,15 +45,15 @@ describe('useResetSelectionOnQueryChange', () => {
it('should clear selection when the folder changes', () => {
const { rerender } = renderHook(
- (props: { currentFolderSlug: string | null }) =>
+ (props: { currentFolderId: string | null }) =>
useResetSelectionOnQueryChange({
category: FilesTabs.All,
- currentFolderSlug: props.currentFolderSlug,
+ currentFolderId: props.currentFolderId,
libraryId: undefined,
searchQuery: null,
}),
{
- initialProps: { currentFolderSlug: 'folder-a' },
+ initialProps: { currentFolderId: 'folder-a' },
},
);
@@ -65,7 +65,7 @@ describe('useResetSelectionOnQueryChange', () => {
});
act(() => {
- rerender({ currentFolderSlug: 'folder-b' });
+ rerender({ currentFolderId: 'folder-b' });
});
expect(useResourceManagerStore.getState()).toMatchObject({
diff --git a/src/features/ResourceManager/components/Explorer/hooks/useResetSelectionOnQueryChange.ts b/src/features/ResourceManager/components/Explorer/hooks/useResetSelectionOnQueryChange.ts
index ed3869b6767..944292b1c91 100644
--- a/src/features/ResourceManager/components/Explorer/hooks/useResetSelectionOnQueryChange.ts
+++ b/src/features/ResourceManager/components/Explorer/hooks/useResetSelectionOnQueryChange.ts
@@ -5,14 +5,14 @@ import type { FilesTabs } from '@/types/files';
interface ResetSelectionOnQueryChangeOptions {
category: FilesTabs;
- currentFolderSlug?: string | null;
+ currentFolderId?: string | null;
libraryId?: string;
searchQuery: string | null;
}
export const useResetSelectionOnQueryChange = ({
category,
- currentFolderSlug,
+ currentFolderId,
libraryId,
searchQuery,
}: ResetSelectionOnQueryChangeOptions) => {
@@ -20,5 +20,5 @@ export const useResetSelectionOnQueryChange = ({
useEffect(() => {
clearSelectAllState();
- }, [category, clearSelectAllState, currentFolderSlug, libraryId, searchQuery]);
+ }, [category, clearSelectAllState, currentFolderId, libraryId, searchQuery]);
};
diff --git a/src/features/ResourceManager/components/Explorer/index.test.tsx b/src/features/ResourceManager/components/Explorer/index.test.tsx
index 5dc10aaa63e..89d9634de87 100644
--- a/src/features/ResourceManager/components/Explorer/index.test.tsx
+++ b/src/features/ResourceManager/components/Explorer/index.test.tsx
@@ -22,7 +22,7 @@ const mocks = vi.hoisted(() => ({
}));
vi.mock('@/features/ResourceManager/hooks/useFolderPath', () => ({
- useFolderPath: () => ({ currentFolderSlug: null }),
+ useFolderPath: () => ({ currentFolderId: null }),
}));
vi.mock('@/features/ResourceManager/hooks/useResourceManagerUrlSync', () => ({
diff --git a/src/features/ResourceManager/components/Explorer/index.tsx b/src/features/ResourceManager/components/Explorer/index.tsx
index 0033f48dbcc..a0717befb21 100644
--- a/src/features/ResourceManager/components/Explorer/index.tsx
+++ b/src/features/ResourceManager/components/Explorer/index.tsx
@@ -63,7 +63,7 @@ const ResourceExplorer = memo<ResourceExplorerProps>(({ hero }) => {
]);
// Get folder path for empty state check
- const { currentFolderSlug } = useFolderPath();
+ const { currentFolderId } = useFolderPath();
// Build query params for SWR
const queryParams = useMemo(
@@ -76,7 +76,7 @@ const ResourceExplorer = memo<ResourceExplorerProps>(({ hero }) => {
filesOnly: !libraryId,
includeContentPreview: viewMode === 'masonry',
libraryId,
- parentId: currentFolderSlug || null,
+ parentId: currentFolderId || null,
showFilesInKnowledgeBase: !libraryId,
sortType,
sorter,
@@ -89,7 +89,7 @@ const ResourceExplorer = memo<ResourceExplorerProps>(({ hero }) => {
[
category,
libraryId,
- currentFolderSlug,
+ currentFolderId,
sortType,
sorter,
listVisibility,
@@ -129,7 +129,7 @@ const ResourceExplorer = memo<ResourceExplorerProps>(({ hero }) => {
useResetSelectionOnQueryChange({
category,
- currentFolderSlug,
+ currentFolderId,
libraryId,
searchQuery,
});
diff --git a/src/features/ResourceManager/components/LibraryHierarchy/HierarchyNode.tsx b/src/features/ResourceManager/components/LibraryHierarchy/HierarchyNode.tsx
index 47171dead5a..d6ae5391856 100644
--- a/src/features/ResourceManager/components/LibraryHierarchy/HierarchyNode.tsx
+++ b/src/features/ResourceManager/components/LibraryHierarchy/HierarchyNode.tsx
@@ -28,6 +28,7 @@ import {
useSetCurrentDrag,
} from '@/features/ResourceManager/DndContextWrapper';
import { useResourceManagerStore } from '@/features/ResourceManager/store';
+import { libraryFolderPath } from '@/features/ResourceManager/utils/resourcePath';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { showContextMenu } from '@/libs/contextMenu';
import type { TreeItem } from '@/store/tree';
@@ -275,13 +276,11 @@ export const HierarchyNode = memo<HierarchyNodeProps>(
isFolder: item.isFolder,
isPage,
libraryId,
- slug: item.slug,
});
const handleFolderClick = useCallback(
- (folderId: string, folderSlug?: string | null) => {
- const navKey = folderSlug || folderId;
- navigate(`/resource/library/${libraryId}/${navKey}`);
+ (folderId: string) => {
+ if (libraryId) navigate(libraryFolderPath(libraryId, folderId));
setMode('explorer');
},
@@ -316,7 +315,7 @@ export const HierarchyNode = memo<HierarchyNodeProps>(
style={{
paddingInlineStart: level * 12 + 4,
}}
- onClick={() => handleFolderClick(item.id, item.slug)}
+ onClick={() => handleFolderClick(item.id)}
onDragEnd={handleDragEnd}
onDragLeave={handleDragLeave}
onDragOver={handleDragOver}
diff --git a/src/features/ResourceManager/components/LibraryHierarchy/SearchResults.tsx b/src/features/ResourceManager/components/LibraryHierarchy/SearchResults.tsx
index 47dc7c4f244..e63db804ca5 100644
--- a/src/features/ResourceManager/components/LibraryHierarchy/SearchResults.tsx
+++ b/src/features/ResourceManager/components/LibraryHierarchy/SearchResults.tsx
@@ -43,9 +43,9 @@ interface SearchResultsProps {
*/
const SearchResults = memo<SearchResultsProps>(({ libraryId, query }) => {
const { t } = useTranslation('file');
- const { currentFolderSlug } = useFolderPath();
+ const { currentFolderId } = useFolderPath();
const currentViewItemId = useResourceManagerStore((s) => s.currentViewItemId);
- const selectedKey = resolveHierarchySelectedKey({ currentFolderSlug, currentViewItemId });
+ const selectedKey = resolveHierarchySelectedKey({ currentFolderId, currentViewItemId });
// Debounce here rather than in the input so the store always holds what the
// user sees; only the network request lags behind the keystrokes.
const debouncedQuery = useDebounce(query.trim(), { wait: 300 });
diff --git a/src/features/ResourceManager/components/LibraryHierarchy/index.tsx b/src/features/ResourceManager/components/LibraryHierarchy/index.tsx
index 25fbd87a702..166a53ea562 100644
--- a/src/features/ResourceManager/components/LibraryHierarchy/index.tsx
+++ b/src/features/ResourceManager/components/LibraryHierarchy/index.tsx
@@ -23,7 +23,7 @@ import { buildVisibleNodes } from './visibleNodes';
const LibraryHierarchy = memo(() => {
const { t } = useTranslation('file');
- const { currentFolderSlug } = useFolderPath();
+ const { currentFolderId } = useFolderPath();
const [currentViewItemId, librarySearchQuery] = useResourceManagerStore((s) => [
s.currentViewItemId,
s.librarySearchQuery,
@@ -42,7 +42,7 @@ const LibraryHierarchy = memo(() => {
// Reuse Explorer Breadcrumb's SWR cache so the sidebar doesn't double-fetch
// document.getFolderBreadcrumb when navigating into a folder.
const useFetchFolderBreadcrumb = useFileStore((s) => s.useFetchFolderBreadcrumb);
- const { data: folderChain } = useFetchFolderBreadcrumb(currentFolderSlug);
+ const { data: folderChain } = useFetchFolderBreadcrumb(currentFolderId);
// Effect 2: Folder navigation → expand ancestors once breadcrumb resolves
useEffect(() => {
@@ -54,7 +54,7 @@ const LibraryHierarchy = memo(() => {
const visibleNodes = useMemo(() => buildVisibleNodes(children, expanded), [children, expanded]);
- const selectedKey = resolveHierarchySelectedKey({ currentFolderSlug, currentViewItemId });
+ const selectedKey = resolveHierarchySelectedKey({ currentFolderId, currentViewItemId });
const hasData = visibleNodes.length > 0;
// The root fetch is in flight with nothing cached yet.
diff --git a/src/features/ResourceManager/components/LibraryHierarchy/selection.test.ts b/src/features/ResourceManager/components/LibraryHierarchy/selection.test.ts
index acefd978de9..30ec95a2d74 100644
--- a/src/features/ResourceManager/components/LibraryHierarchy/selection.test.ts
+++ b/src/features/ResourceManager/components/LibraryHierarchy/selection.test.ts
@@ -10,12 +10,12 @@ import {
describe('resolveHierarchySelectedKey', () => {
it('prefers the opened file over the current folder', () => {
expect(
- resolveHierarchySelectedKey({ currentFolderSlug: 'folder-a', currentViewItemId: 'file_1' }),
+ resolveHierarchySelectedKey({ currentFolderId: 'folder-a', currentViewItemId: 'file_1' }),
).toBe('file_1');
});
it('falls back to the current folder', () => {
- expect(resolveHierarchySelectedKey({ currentFolderSlug: 'folder-a' })).toBe('folder-a');
+ expect(resolveHierarchySelectedKey({ currentFolderId: 'folder-a' })).toBe('folder-a');
expect(resolveHierarchySelectedKey({})).toBeNull();
});
});
@@ -29,9 +29,10 @@ describe('isHierarchyNodeActive', () => {
expect(isHierarchyNodeActive(file, 'my-page')).toBe(false);
});
- it('marks the current folder active by slug with id fallback', () => {
- expect(isHierarchyNodeActive(folder, 'folder-a')).toBe(true);
- expect(isHierarchyNodeActive({ ...folder, slug: null }, 'folder_1')).toBe(true);
+ // Folder routes carry the id (`folder/<folderId>`), never the slug.
+ it('marks the current folder active by id, not slug', () => {
+ expect(isHierarchyNodeActive(folder, 'folder_1')).toBe(true);
+ expect(isHierarchyNodeActive(folder, 'folder-a')).toBe(false);
});
it('drops folder highlight once a file is opened', () => {
@@ -55,11 +56,11 @@ describe('hierarchySubtreeHoldsSelection', () => {
} as any;
it('matches the folder the explorer is parked in', () => {
- expect(hierarchySubtreeHoldsSelection(folderA, children, 'folder-a')).toBe(true);
+ expect(hierarchySubtreeHoldsSelection(folderA, children, 'folder_a')).toBe(true);
});
it('matches an ancestor of the current folder', () => {
- expect(hierarchySubtreeHoldsSelection(folderA, children, 'folder-b')).toBe(true);
+ expect(hierarchySubtreeHoldsSelection(folderA, children, 'folder_b')).toBe(true);
});
it('matches an ancestor of the opened file', () => {
@@ -67,7 +68,7 @@ describe('hierarchySubtreeHoldsSelection', () => {
});
it('ignores a sibling subtree', () => {
- expect(hierarchySubtreeHoldsSelection(folderB, children, 'folder-a')).toBe(false);
+ expect(hierarchySubtreeHoldsSelection(folderB, children, 'folder_a')).toBe(false);
});
it('ignores an empty selection', () => {
@@ -75,7 +76,7 @@ describe('hierarchySubtreeHoldsSelection', () => {
});
it('stays put for a subtree the sidebar never loaded', () => {
- expect(hierarchySubtreeHoldsSelection(folderA, { '': [folderA] } as any, 'folder-b')).toBe(
+ expect(hierarchySubtreeHoldsSelection(folderA, { '': [folderA] } as any, 'folder_b')).toBe(
false,
);
});
@@ -96,8 +97,8 @@ describe('resolveDeletedFolderRedirect', () => {
const base = { children, item: folderB, libraryId: 'kb_1', parentKey: 'folder_a' };
it("steps out to the deleted folder's parent", () => {
- expect(resolveDeletedFolderRedirect({ ...base, selectedKey: 'folder-b' })).toBe(
- '/resource/library/kb_1/folder-a',
+ expect(resolveDeletedFolderRedirect({ ...base, selectedKey: 'folder_b' })).toBe(
+ '/resource/library/kb_1/folder/folder_a',
);
});
@@ -107,7 +108,7 @@ describe('resolveDeletedFolderRedirect', () => {
...base,
item: folderA,
parentKey: '',
- selectedKey: 'folder-a',
+ selectedKey: 'folder_a',
}),
).toBe('/resource/library/kb_1');
});
@@ -142,7 +143,7 @@ describe('resolveDeletedFolderRedirect', () => {
// The user switched library while the delete was in flight.
it('stays put without a live library', () => {
expect(
- resolveDeletedFolderRedirect({ ...base, libraryId: undefined, selectedKey: 'folder-b' }),
+ resolveDeletedFolderRedirect({ ...base, libraryId: undefined, selectedKey: 'folder_b' }),
).toBeNull();
});
});
diff --git a/src/features/ResourceManager/components/LibraryHierarchy/selection.ts b/src/features/ResourceManager/components/LibraryHierarchy/selection.ts
index 4fe6e12ce74..0f7abaf731e 100644
--- a/src/features/ResourceManager/components/LibraryHierarchy/selection.ts
+++ b/src/features/ResourceManager/components/LibraryHierarchy/selection.ts
@@ -1,23 +1,20 @@
+import { libraryFolderPath } from '@/features/ResourceManager/utils/resourcePath';
import type { TreeItem } from '@/store/tree';
interface SelectionSource {
- currentFolderSlug?: string | null;
+ currentFolderId?: string | null;
currentViewItemId?: string | null;
}
export const resolveHierarchySelectedKey = ({
- currentFolderSlug,
+ currentFolderId,
currentViewItemId,
-}: SelectionSource): string | null => currentViewItemId ?? currentFolderSlug ?? null;
+}: SelectionSource): string | null => currentViewItemId ?? currentFolderId ?? null;
export const isHierarchyNodeActive = (
- item: Pick<TreeItem, 'id' | 'isFolder' | 'slug'>,
+ item: Pick<TreeItem, 'id'>,
selectedKey: string | null,
-): boolean => {
- if (!selectedKey) return false;
-
- return item.isFolder ? selectedKey === (item.slug || item.id) : selectedKey === item.id;
-};
+): boolean => !!selectedKey && selectedKey === item.id;
/**
* Whether `selectedKey` points at this folder or at anything inside it.
@@ -30,7 +27,7 @@ export const isHierarchyNodeActive = (
* folders it has not fetched.
*/
export const hierarchySubtreeHoldsSelection = (
- root: Pick<TreeItem, 'id' | 'isFolder' | 'slug'>,
+ root: Pick<TreeItem, 'id' | 'isFolder'>,
children: Record<string, TreeItem[]>,
selectedKey: string | null,
): boolean => {
@@ -56,7 +53,7 @@ export const hierarchySubtreeHoldsSelection = (
interface DeletedFolderRedirect {
children: Record<string, TreeItem[]>;
- item: Pick<TreeItem, 'id' | 'isFolder' | 'slug'>;
+ item: Pick<TreeItem, 'id' | 'isFolder'>;
libraryId?: string | null;
parentKey?: string;
selectedKey: string | null;
@@ -84,12 +81,5 @@ export const resolveDeletedFolderRedirect = ({
if (!item.isFolder || !libraryId) return null;
if (!hierarchySubtreeHoldsSelection(item, children, selectedKey)) return null;
- const parent = parentKey
- ? Object.values(children)
- .flat()
- .find((row) => row.id === parentKey)
- : undefined;
- const navKey = parent ? parent.slug || parent.id : '';
-
- return `/resource/library/${libraryId}${navKey ? `/${navKey}` : ''}`;
+ return libraryFolderPath(libraryId, parentKey);
};
diff --git a/src/features/ResourceManager/hooks/useCurrentFolderId.ts b/src/features/ResourceManager/hooks/useCurrentFolderId.ts
index 3c1b5b85402..6ac5f6b3fde 100644
--- a/src/features/ResourceManager/hooks/useCurrentFolderId.ts
+++ b/src/features/ResourceManager/hooks/useCurrentFolderId.ts
@@ -1,9 +1,4 @@
-import { useResourceManagerFetchFolderBreadcrumb } from '../store';
import { useFolderPath } from './useFolderPath';
-export const useCurrentFolderId = () => {
- const { currentFolderSlug } = useFolderPath();
- const { data: folderBreadcrumb } = useResourceManagerFetchFolderBreadcrumb(currentFolderSlug);
-
- return folderBreadcrumb?.at(-1)?.id || null;
-};
+/** The folder the URL (`/resource/library/<id>/folder/<folderId>`) points at. */
+export const useCurrentFolderId = () => useFolderPath().currentFolderId;
diff --git a/src/features/ResourceManager/hooks/useFolderPath.ts b/src/features/ResourceManager/hooks/useFolderPath.ts
index e8546b1ab80..45fe2322978 100644
--- a/src/features/ResourceManager/hooks/useFolderPath.ts
+++ b/src/features/ResourceManager/hooks/useFolderPath.ts
@@ -2,18 +2,17 @@ import { useActiveLocation } from '@/hooks/useActiveLocation';
import { useActiveRouteParams } from '@/hooks/useActiveRouteParams';
/**
- * Hook to extract folder slug from URL
- * Supports Google Drive-style slug-based folder navigation
+ * Hook to extract the current folder from URL
*
* Example URLs:
- * - /resource/library/kb_123 -> { knowledgeBaseId: 'kb_123', currentFolderSlug: null, isInKnowledgeBase: true }
- * - /resource/library/kb_123/folder-slug-1 -> { knowledgeBaseId: 'kb_123', currentFolderSlug: 'folder-slug-1', isInKnowledgeBase: true }
- * - /knowledge -> { knowledgeBaseId: null, currentFolderSlug: null, isInKnowledgeBase: false }
+ * - /resource/library/kb_123 -> { knowledgeBaseId: 'kb_123', currentFolderId: null, isInKnowledgeBase: true }
+ * - /resource/library/kb_123/folder/docs_1 -> { knowledgeBaseId: 'kb_123', currentFolderId: 'docs_1', isInKnowledgeBase: true }
+ * - /knowledge -> { knowledgeBaseId: null, currentFolderId: null, isInKnowledgeBase: false }
*/
export const useFolderPath = () => {
// Active-tab variants, not the raw router hooks: `LibraryHierarchy` renders in
// the sidebar, which Electron portals into the shell's frozen root router.
- const params = useActiveRouteParams<{ id: string; slug?: string }>();
+ const params = useActiveRouteParams<{ folderId?: string; id: string }>();
const location = useActiveLocation();
// Extract knowledge base ID from params
@@ -22,11 +21,10 @@ export const useFolderPath = () => {
// Determine if we're in a knowledge base context
const isInKnowledgeBase = location.pathname.includes('/resource/library/');
- // Extract folder slug from params (single slug, not nested paths)
- const currentFolderSlug = params.slug || null;
+ const currentFolderId = params.folderId || null;
return {
- currentFolderSlug,
+ currentFolderId,
isInKnowledgeBase,
knowledgeBaseId,
};
diff --git a/src/features/ResourceManager/hooks/useInitFileCheck.ts b/src/features/ResourceManager/hooks/useInitFileCheck.ts
index 5ed84d2dd2b..2977e52a9d0 100644
--- a/src/features/ResourceManager/hooks/useInitFileCheck.ts
+++ b/src/features/ResourceManager/hooks/useInitFileCheck.ts
@@ -15,6 +15,7 @@ import { useResourceManagerStore } from '../store';
* /resource/drive?file=xxxxxx
*
* `pathFileId` is the item a route path names (`/resource/file/:id`,
+ * `/resource/library/:id/{docs,file}/:itemId`,
* `/resource/page/:id`); it wins over the `?file=` query.
*/
export const useInitFileCheck = (pathFileId?: string | null) => {
diff --git a/src/features/ResourceManager/hooks/useLibraryItemBackPath.test.ts b/src/features/ResourceManager/hooks/useLibraryItemBackPath.test.ts
new file mode 100644
index 00000000000..771aa343b03
--- /dev/null
+++ b/src/features/ResourceManager/hooks/useLibraryItemBackPath.test.ts
@@ -0,0 +1,171 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { act, cleanup, renderHook, waitFor } from '@testing-library/react';
+import type { PropsWithChildren } from 'react';
+import { createElement, useEffect } from 'react';
+import { SWRConfig, useSWRConfig } from 'swr';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { cacheScope } from '@/libs/replica';
+import { setScopedMutate } from '@/libs/swr/mutate';
+import { lambdaClient } from '@/libs/trpc/client';
+import { useFileStore } from '@/store/file';
+import { type TreeItem, useTreeStore } from '@/store/tree';
+
+import { findLoadedParentId, useLibraryItemBackPath } from './useLibraryItemBackPath';
+
+vi.mock('@/libs/trpc/client', () => ({
+ lambdaClient: {
+ document: { getDocumentById: { query: vi.fn() } },
+ file: { getFileItemById: { query: vi.fn() } },
+ },
+}));
+
+const MutateBridge = () => {
+ const { mutate } = useSWRConfig();
+ useEffect(() => setScopedMutate(mutate), [mutate]);
+ return null;
+};
+
+const wrapper = ({ children }: PropsWithChildren) =>
+ createElement(
+ SWRConfig,
+ { value: { dedupingInterval: 0, provider: () => new Map() } },
+ createElement(MutateBridge),
+ children,
+ );
+
+const doc = (id: string, fields: { parentId?: string | null }) => ({
+ createdAt: new Date(0),
+ fileType: 'custom/document',
+ id,
+ parentId: fields.parentId ?? null,
+ title: id,
+ updatedAt: new Date(0),
+});
+
+const treeRow = (id: string): TreeItem => ({
+ fileType: 'custom/document',
+ id,
+ isFolder: false,
+ name: id,
+ url: '',
+});
+
+/** Never-resolving fetch: the item's detail is still in flight. */
+const pending = () => new Promise<never>(() => {});
+
+/** @example Back from a library item returns to the folder that holds it. */
+describe('useLibraryItemBackPath', () => {
+ beforeEach(() => {
+ vi.spyOn(cacheScope, 'get').mockReturnValue('test:personal');
+ vi.spyOn(cacheScope, 'use').mockReturnValue('test:personal');
+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(false);
+ act(() => {
+ useFileStore.setState({ fileDetailMap: {}, resourceMap: new Map() });
+ useTreeStore.setState({ children: {} });
+ });
+ });
+
+ afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+ vi.clearAllMocks();
+ });
+
+ // ROOT CAUSE:
+ //
+ // Library items moved from `/resource/library/<kb>/<folder>?file=<id>` to
+ // `/resource/library/<kb>/docs/<id>`, so the path no longer names the folder
+ // and Back landed on the library root instead of the item's folder.
+ it('returns to the folder of a deep-linked page', async () => {
+ vi.mocked(lambdaClient.document.getDocumentById.query).mockResolvedValue(
+ doc('docs_page', { parentId: 'docs_folder' }) as any,
+ );
+
+ const { result } = renderHook(() => useLibraryItemBackPath('kb_1', 'docs_page'), { wrapper });
+
+ await waitFor(() => expect(result.current).toBe('/resource/library/kb_1/folder/docs_folder'));
+ });
+
+ it('returns to the folder of an uploaded file', async () => {
+ vi.mocked(lambdaClient.file.getFileItemById.query).mockResolvedValue({
+ id: 'file_1',
+ name: 'a.pdf',
+ parentId: 'docs_folder',
+ } as any);
+
+ const { result } = renderHook(() => useLibraryItemBackPath('kb_1', 'file_1'), { wrapper });
+
+ await waitFor(() => expect(result.current).toBe('/resource/library/kb_1/folder/docs_folder'));
+ });
+
+ it('returns the library root for an item at the top level', async () => {
+ vi.mocked(lambdaClient.file.getFileItemById.query).mockResolvedValue({
+ id: 'file_1',
+ name: 'a.pdf',
+ parentId: null,
+ } as any);
+
+ const { result } = renderHook(() => useLibraryItemBackPath('kb_1', 'file_1'), { wrapper });
+
+ await waitFor(() =>
+ expect(useFileStore.getState().fileDetailMap['file_1']?.file).toBeDefined(),
+ );
+ expect(result.current).toBe('/resource/library/kb_1');
+ });
+
+ // ROOT CAUSE:
+ //
+ // The hook read only the item's detail, fetched after it opened, so Back
+ // pressed before that request landed (or after it failed) went to the
+ // library root even though the row the item was opened from knew its folder.
+ it('uses the sidebar tree while the detail is still loading', () => {
+ vi.mocked(lambdaClient.document.getDocumentById.query).mockImplementation(pending as any);
+ act(() => {
+ useTreeStore.setState({ children: { docs_folder: [treeRow('docs_page')] } });
+ });
+
+ const { result } = renderHook(() => useLibraryItemBackPath('kb_1', 'docs_page'), { wrapper });
+
+ expect(result.current).toBe('/resource/library/kb_1/folder/docs_folder');
+ });
+
+ it('uses the explorer row when the detail request fails', async () => {
+ vi.mocked(lambdaClient.file.getFileItemById.query).mockRejectedValue(new Error('offline'));
+ act(() => {
+ useFileStore.setState({
+ resourceMap: new Map([['file_1', { id: 'file_1', parentId: 'docs_folder' } as any]]),
+ });
+ });
+
+ const { result } = renderHook(() => useLibraryItemBackPath('kb_1', 'file_1'), { wrapper });
+
+ await waitFor(() => expect(lambdaClient.file.getFileItemById.query).toHaveBeenCalled());
+ expect(result.current).toBe('/resource/library/kb_1/folder/docs_folder');
+ });
+
+ it('lets the loaded detail win over a stale row', async () => {
+ vi.mocked(lambdaClient.document.getDocumentById.query).mockResolvedValue(
+ doc('docs_page', { parentId: 'docs_moved' }) as any,
+ );
+ act(() => {
+ useTreeStore.setState({ children: { docs_folder: [treeRow('docs_page')] } });
+ });
+
+ const { result } = renderHook(() => useLibraryItemBackPath('kb_1', 'docs_page'), { wrapper });
+
+ await waitFor(() => expect(result.current).toBe('/resource/library/kb_1/folder/docs_moved'));
+ });
+});
+
+describe('findLoadedParentId', () => {
+ it('returns the group key holding the item, null for the root group', () => {
+ const children = { '': [treeRow('docs_top')], 'docs_folder': [treeRow('docs_page')] };
+
+ expect(findLoadedParentId(children, 'docs_page')).toBe('docs_folder');
+ expect(findLoadedParentId(children, 'docs_top')).toBeNull();
+ expect(findLoadedParentId(children, 'docs_missing')).toBeUndefined();
+ });
+});
diff --git a/src/features/ResourceManager/hooks/useLibraryItemBackPath.ts b/src/features/ResourceManager/hooks/useLibraryItemBackPath.ts
new file mode 100644
index 00000000000..d1f37a62a9a
--- /dev/null
+++ b/src/features/ResourceManager/hooks/useLibraryItemBackPath.ts
@@ -0,0 +1,47 @@
+import { libraryFolderPath } from '@/features/ResourceManager/utils/resourcePath';
+import { documentSelectors, useFileStore } from '@/store/file';
+import { type TreeItem, useTreeStore } from '@/store/tree';
+
+/**
+ * Parent of an item the library sidebar has already loaded: the key of the
+ * `children` group holding it (`null` for the root group), or `undefined` when
+ * the item is not in the tree.
+ */
+export const findLoadedParentId = (
+ children: Record<string, TreeItem[]>,
+ itemId: string,
+): string | null | undefined => {
+ for (const [parentKey, rows] of Object.entries(children)) {
+ if (rows.some((row) => row.id === itemId)) return parentKey || null;
+ }
+};
+
+/**
+ * Where Back leaves an item opened inside a library: the folder that holds it
+ * (`/resource/library/<id>/folder/<parentId>`), or the library root when it
+ * sits at the top level.
+ *
+ * The item's detail is fetched after it opens, so until it lands (or when it
+ * fails) the parent comes from the rows the item was opened from: the sidebar
+ * tree, then the explorer list. `undefined` means no source knows yet; `null`
+ * is a confirmed top-level item.
+ *
+ * Pass no `itemId` outside a library item route; nothing is fetched then.
+ */
+export const useLibraryItemBackPath = (libraryId?: string | null, itemId?: string): string => {
+ const useFetchKnowledgeItem = useFileStore((s) => s.useFetchKnowledgeItem);
+ const { data: item } = useFetchKnowledgeItem(itemId);
+ const document = useFileStore(documentSelectors.getDocumentById(itemId));
+ const rowParentId = useFileStore((s) =>
+ itemId ? s.resourceMap.get(itemId)?.parentId : undefined,
+ );
+ const treeParentId = useTreeStore((s) =>
+ itemId ? findLoadedParentId(s.children, itemId) : undefined,
+ );
+
+ const parentId = [item?.parentId, document?.parentId, treeParentId, rowParentId].find(
+ (candidate) => candidate !== undefined,
+ );
+
+ return libraryId ? libraryFolderPath(libraryId, parentId) : '';
+};
diff --git a/src/features/ResourceManager/index.tsx b/src/features/ResourceManager/index.tsx
index bdbd4e49bb9..aafddd94e25 100644
--- a/src/features/ResourceManager/index.tsx
+++ b/src/features/ResourceManager/index.tsx
@@ -7,7 +7,9 @@ import { useLocation, useSearchParams } from 'react-router';
import DragUploadZone from '@/components/DragUploadZone';
import { PageEditor } from '@/features/PageEditor';
import { RESOURCE_HOME_PATH } from '@/features/ResourceHome/paths';
+import { useLibraryItemBackPath } from '@/features/ResourceManager/hooks/useLibraryItemBackPath';
import { useResourceManagerStore } from '@/features/ResourceManager/store';
+import { LIBRARY_ITEM_PATH } from '@/features/ResourceManager/utils/resourcePath';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { usePermission } from '@/hooks/usePermission';
import dynamic from '@/libs/next/dynamic';
@@ -118,6 +120,12 @@ const ResourceManager = memo<ResourceManagerProps>(({ content, explorerHero }) =
// persisted projection on the first frame and the network only confirms it.
useFetchDocumentDetail(currentViewItemId);
+ const isLibraryItemRoute = LIBRARY_ITEM_PATH.test(location.pathname);
+ const libraryBackPath = useLibraryItemBackPath(
+ libraryId,
+ isLibraryItemRoute ? currentViewItemId : undefined,
+ );
+
const handleBack = () => {
setMode('explorer');
setCurrentViewItemId(undefined);
@@ -126,6 +134,12 @@ const ResourceManager = memo<ResourceManagerProps>(({ content, explorerHero }) =
navigate(RESOURCE_HOME_PATH);
return;
}
+ // An item opened inside a library (`/resource/library/:id/{docs,file}/:itemId`)
+ // goes back to the folder that holds it.
+ if (isLibraryItemRoute && libraryBackPath) {
+ navigate(libraryBackPath);
+ return;
+ }
// Remove the file query parameter from URL
setSearchParams((prev) => {
prev.delete('file');
diff --git a/src/features/ResourceManager/utils/resourcePath.test.ts b/src/features/ResourceManager/utils/resourcePath.test.ts
index 4e857595357..b3eaff44fd1 100644
--- a/src/features/ResourceManager/utils/resourcePath.test.ts
+++ b/src/features/ResourceManager/utils/resourcePath.test.ts
@@ -1,6 +1,12 @@
import { describe, expect, it } from 'vitest';
-import { buildLibraryPath, buildPagePath } from './resourcePath';
+import {
+ buildLibraryPath,
+ buildPagePath,
+ legacyLibraryItemRedirect,
+ LIBRARY_ITEM_PATH,
+ libraryItemPath,
+} from './resourcePath';
/** @example Links and detail windows built by hand land inside the workspace. */
describe('resourcePath', () => {
@@ -26,15 +32,53 @@ describe('resourcePath', () => {
it('keeps a library page inside the workspace', () => {
expect(buildPagePath('docs_abc', 'acme', 'kb_1')).toBe(
- '/acme/resource/library/kb_1?file=docs_abc',
+ '/acme/resource/library/kb_1/docs/docs_abc',
);
});
it('leaves the personal-scope page path unprefixed', () => {
expect(buildPagePath('docs_abc', null)).toBe('/resource?file=docs_abc');
expect(buildPagePath('docs_abc', undefined, 'kb_1')).toBe(
- '/resource/library/kb_1?file=docs_abc',
+ '/resource/library/kb_1/docs/docs_abc',
);
});
});
+
+ describe('libraryItemPath', () => {
+ it('opens a page under the docs segment', () => {
+ expect(libraryItemPath('kb_1', 'docs_abc')).toBe('/resource/library/kb_1/docs/docs_abc');
+ });
+
+ it('opens an uploaded file under the file segment', () => {
+ expect(libraryItemPath('kb_1', 'file_abc')).toBe('/resource/library/kb_1/file/file_abc');
+ });
+
+ it('is recognised as an opened library item, unlike a folder', () => {
+ expect(LIBRARY_ITEM_PATH.test('/acme/resource/library/kb_1/docs/docs_abc')).toBe(true);
+ expect(LIBRARY_ITEM_PATH.test('/resource/library/kb_1/file/file_abc')).toBe(true);
+ expect(LIBRARY_ITEM_PATH.test('/resource/library/kb_1/folder-slug')).toBe(false);
+ });
+ });
+
+ describe('legacyLibraryItemRedirect', () => {
+ it('moves a ?file= link onto the item path, keeping the workspace and other query', () => {
+ expect(
+ legacyLibraryItemRedirect(
+ '/acme/resource/library/kb_1',
+ '?file=docs_abc&view=grid',
+ 'kb_1',
+ ),
+ ).toEqual({ pathname: '/acme/resource/library/kb_1/docs/docs_abc', search: '?view=grid' });
+ });
+
+ it('drops the folder a legacy link was opened from', () => {
+ expect(
+ legacyLibraryItemRedirect('/resource/library/kb_1/folder-slug', '?file=file_abc', 'kb_1'),
+ ).toEqual({ pathname: '/resource/library/kb_1/file/file_abc', search: '' });
+ });
+
+ it('leaves non-legacy URLs alone', () => {
+ expect(legacyLibraryItemRedirect('/resource/library/kb_1', '?view=grid', 'kb_1')).toBeNull();
+ });
+ });
});
diff --git a/src/features/ResourceManager/utils/resourcePath.ts b/src/features/ResourceManager/utils/resourcePath.ts
index bc041b8368f..eb302a73599 100644
--- a/src/features/ResourceManager/utils/resourcePath.ts
+++ b/src/features/ResourceManager/utils/resourcePath.ts
@@ -10,6 +10,50 @@ import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath
* resolve.
*/
+/**
+ * Library path segment of an item: pages (`docs_` ids) open under `docs`,
+ * everything else under `file`.
+ */
+export const libraryItemSegment = (itemId: string): 'docs' | 'file' =>
+ itemId.startsWith('docs_') ? 'docs' : 'file';
+
+/** Where an item opens inside a library: `/resource/library/<id>/{docs,file}/<itemId>`. */
+export const libraryItemPath = (libraryId: string, itemId: string): string =>
+ `/resource/library/${libraryId}/${libraryItemSegment(itemId)}/${encodeURIComponent(itemId)}`;
+
+/** A page or file opened inside a library by path. */
+export const LIBRARY_ITEM_PATH = /\/resource\/library\/[^/]+\/(?:docs|file)\/[^/]+\/?$/;
+
+/** Swap the `/resource/library/…` tail of `pathname` for `path`, keeping a workspace prefix. */
+export const rebaseLibraryPath = (pathname: string, path: string): string =>
+ pathname.replace(/\/resource\/library\/.*$/, path);
+
+/**
+ * Library items used to open as `/resource/library/<id>[/<folder>]?file=<itemId>`.
+ * Returns where such a URL lives now (workspace prefix and other query kept),
+ * or `null` when it is not a legacy item link.
+ */
+export const legacyLibraryItemRedirect = (
+ pathname: string,
+ search: string,
+ libraryId: string,
+): { pathname: string; search: string } | null => {
+ const params = new URLSearchParams(search);
+ const itemId = params.get('file');
+ if (!itemId || LIBRARY_ITEM_PATH.test(pathname)) return null;
+
+ params.delete('file');
+ const query = params.toString();
+ return {
+ pathname: rebaseLibraryPath(pathname, libraryItemPath(libraryId, itemId)),
+ search: query ? `?${query}` : '',
+ };
+};
+
+/** A library's explorer, or one of its folders: `/resource/library/<id>[/folder/<folderId>]`. */
+export const libraryFolderPath = (libraryId: string, folderId?: string | null): string =>
+ `/resource/library/${libraryId}${folderId ? `/folder/${encodeURIComponent(folderId)}` : ''}`;
+
/** Path of a library's explorer: `/resource/library/<id>`. */
export const buildLibraryPath = (
libraryId: string,
@@ -18,7 +62,7 @@ export const buildLibraryPath = (
/**
* Path that opens a page: `/resource?file=<id>`, or the library-scoped
- * `/resource/library/<libraryId>?file=<id>` when the page lives in a library.
+ * `/resource/library/<libraryId>/docs/<id>` when the page lives in a library.
*/
export const buildPagePath = (
fileId: string,
@@ -26,6 +70,6 @@ export const buildPagePath = (
libraryId?: string | null,
): string =>
buildWorkspaceAwarePath(
- libraryId ? `/resource/library/${libraryId}?file=${fileId}` : `/resource?file=${fileId}`,
+ libraryId ? libraryItemPath(libraryId, fileId) : `/resource?file=${fileId}`,
activeWorkspaceSlug,
);
diff --git a/src/spa/router/resourceRoutes.tsx b/src/spa/router/resourceRoutes.tsx
index 192c82a792f..d48a0622e04 100644
--- a/src/spa/router/resourceRoutes.tsx
+++ b/src/spa/router/resourceRoutes.tsx
@@ -5,6 +5,7 @@ import {
FilePenIcon,
FilesIcon,
FileText,
+ FolderIcon,
HardDriveIcon,
ImageIcon,
LibraryBigIcon,
@@ -172,6 +173,23 @@ export const resourceRoute: RouteObject = {
},
path: 'permission',
},
+ // A folder (`folder/<docs_id>`), page (`docs/<docs_id>`) or file
+ // (`file/<file_id>`) opened inside the library, all addressed by id.
+ ...(
+ [
+ { icon: FolderIcon, path: 'folder/:folderId' },
+ { icon: FilePenIcon, path: 'docs/:itemId' },
+ { icon: FilesIcon, path: 'file/:itemId' },
+ ] as const
+ ).map(({ icon, path }) => ({
+ element: dynamicElement(
+ () => import('@/routes/(main)/resource/library'),
+ `Desktop > Resource > Library > ${path}`,
+ ),
+ handle: { meta: routeMeta({ icon, titleKey: 'navigation.knowledgeBase' }) },
+ path,
+ })),
+ // Legacy folder links (`/resource/library/<id>/<folderSlug>`) redirect to `folder/<id>`.
{
element: dynamicElement(
() => import('@/routes/(main)/resource/library/[slug]'),