refactor(knowledge): extract folder tree helpers and unit-test them

The upload-path builder, breadcrumb/ancestor derivation, folder lookup and
tree flattening were inline in the view and the sidebar component. Moving
them into folderTree.ts follows the convention of kbListMerge.ts and
wikiStatusRefresh.ts, removes the duplicated webkitRelativePath handling,
and makes the folder navigation logic directly testable.
main
lyingbug 2026-08-04 09:17:04 +00:00 committed by lyingbug
parent f747d390a8
commit 27efebbd1c
4 changed files with 229 additions and 64 deletions

View File

@ -58,6 +58,12 @@ import {
shouldRefreshWikiStatusAfterKnowledgePoll,
} from './wikiStatusRefresh';
import { listMoveTargets, moveKnowledge, getKnowledgeMoveProgress } from '@/api/knowledge-base';
import {
buildUploadFileName,
folderBreadcrumbs as buildFolderBreadcrumbs,
folderPathExists as folderExistsInTree,
isFolderUpload,
} from './folderTree';
import { useI18n } from 'vue-i18n';
import { useMarqueeSelect } from '@/hooks/useMarqueeSelect';
import type { ParserEngineInfo } from '@/api/system';
@ -627,15 +633,7 @@ const showFolderTree = computed(() => !isFAQ.value && (hasFolders.value || selec
const showDocumentFolderPath = computed(
() => hasFolders.value && (selectedFolderPath.value === null || folderRecursive.value),
);
const folderBreadcrumbs = computed(() => {
const path = selectedFolderPath.value;
if (!path) return [];
const segments = path.split('/');
return segments.map((name, index) => ({
name,
path: segments.slice(0, index + 1).join('/'),
}));
});
const folderBreadcrumbs = computed(() => buildFolderBreadcrumbs(selectedFolderPath.value));
// Uploads land in the folder currently being browsed; "all documents" and the
// root row both mean "no prefix".
const uploadTargetFolder = computed(() => selectedFolderPath.value || '');
@ -765,7 +763,7 @@ const loadFolderTree = async (kbIdValue: string) => {
// A folder can disappear (its last document was deleted or moved); fall
// back to the flat list instead of leaving an empty, unreachable view.
const path = selectedFolderPath.value;
if (path && !folderPathExists(path)) {
if (path && !folderExistsInTree(folderTree.value?.folders || [], path)) {
selectedFolderPath.value = null;
}
} catch (error) {
@ -779,12 +777,6 @@ const loadFolderTree = async (kbIdValue: string) => {
}
};
const folderPathExists = (path: string): boolean => {
const walk = (nodes: KnowledgeFolderTree['folders']): boolean =>
nodes.some((node) => node.path === path || walk(node.children || []));
return walk(folderTree.value?.folders || []);
};
const handleFolderSelect = (path: string | null) => {
if (selectedFolderPath.value === path) return;
selectedFolderPath.value = path;
@ -1515,32 +1507,8 @@ const AUDIO_EXTENSIONS = ['mp3', 'wav', 'm4a', 'flac', 'ogg'];
const uploadConfirmStore = useUploadConfirmStore();
// A browser only sets webkitRelativePath when the file came from a directory
// picker or a dropped directory, which is exactly what distinguishes a folder
// upload from picking individual files.
const isFolderUpload = (file: File) =>
!!(file as File & { webkitRelativePath?: string }).webkitRelativePath;
/**
* Build the path-qualified `fileName` the backend splits into folder_path +
* file_name. Two sources are combined: the folder currently open in the sidebar
* (so uploads land where the user is looking) and the browser's
* webkitRelativePath for folder uploads, whose picked directory becomes the
* top-level tree node. Returns undefined for a plain single-file upload at the
* knowledge base root, which keeps that request byte-identical to before.
*/
const getFolderUploadFileName = (file: File) => {
const segments: string[] = [];
if (uploadTargetFolder.value) {
segments.push(uploadTargetFolder.value);
}
const relativePath = (file as File & { webkitRelativePath?: string }).webkitRelativePath;
if (relativePath) {
segments.push(...relativePath.split('/').filter(Boolean).slice(0, -1));
}
if (segments.length === 0) return undefined;
return `${segments.join('/')}/${file.name}`;
};
const getFolderUploadFileName = (file: File) =>
buildUploadFileName(file, uploadTargetFolder.value);
const showUploadResultMessages = (
successCount: number,

View File

@ -113,7 +113,8 @@
<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import type { KnowledgeFolderNode, KnowledgeFolderTree } from '@/api/knowledge-base/index'
import type { KnowledgeFolderTree } from '@/api/knowledge-base/index'
import { flattenFolderRows, folderAncestorPaths } from '../folderTree'
const props = withDefaults(defineProps<{
tree: KnowledgeFolderTree | null
@ -144,21 +145,7 @@ const expanded = ref(new Set<string>())
*/
const showRootRow = computed(() => (props.tree?.folders?.length ?? 0) > 0)
type FolderRow = { node: KnowledgeFolderNode; depth: number }
const rows = computed<FolderRow[]>(() => {
const result: FolderRow[] = []
const walk = (nodes: KnowledgeFolderNode[], depth: number) => {
nodes.forEach((node) => {
result.push({ node, depth })
if (node.children?.length && expanded.value.has(node.path)) {
walk(node.children, depth + 1)
}
})
}
walk(props.tree?.folders ?? [], 0)
return result
})
const rows = computed(() => flattenFolderRows(props.tree?.folders ?? [], expanded.value))
const toggle = (path: string) => {
const next = new Set(expanded.value)
@ -173,13 +160,10 @@ const toggle = (path: string) => {
watch(
() => [props.selectedPath, props.tree] as const,
() => {
const path = props.selectedPath
if (!path) return
const ancestors = folderAncestorPaths(props.selectedPath)
if (ancestors.length === 0) return
const next = new Set(expanded.value)
const segments = path.split('/')
for (let i = 1; i <= segments.length; i++) {
next.add(segments.slice(0, i).join('/'))
}
ancestors.forEach((path) => next.add(path))
expanded.value = next
},
{ immediate: true },

View File

@ -0,0 +1,120 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import {
buildUploadFileName,
flattenFolderRows,
folderAncestorPaths,
folderBreadcrumbs,
folderPathExists,
isFolderUpload,
} from './folderTree.ts'
const tree = [
{
path: 'handbook',
name: 'handbook',
document_count: 1,
total_count: 4,
children: [
{
path: 'handbook/onboarding',
name: 'onboarding',
document_count: 2,
total_count: 3,
children: [
{ path: 'handbook/onboarding/day-one', name: 'day-one', document_count: 1, total_count: 1 },
],
},
],
},
{ path: 'design', name: 'design', document_count: 1, total_count: 1 },
]
test('a plain single-file upload at the root sends no path-qualified name', () => {
assert.equal(buildUploadFileName({ name: 'report.pdf' }, null), undefined)
assert.equal(buildUploadFileName({ name: 'report.pdf' }, ''), undefined)
})
test('a folder upload keeps the picked directory as the top-level folder', () => {
assert.equal(
buildUploadFileName({ name: 'day-one.md', webkitRelativePath: 'handbook/onboarding/day-one.md' }, null),
'handbook/onboarding/day-one.md',
)
assert.equal(
buildUploadFileName({ name: 'README.md', webkitRelativePath: 'handbook/README.md' }, null),
'handbook/README.md',
)
})
test('uploads land in the folder currently open in the sidebar', () => {
assert.equal(
buildUploadFileName({ name: 'report.pdf' }, 'handbook/policies'),
'handbook/policies/report.pdf',
)
})
test('browsing a folder and uploading a folder nests one inside the other', () => {
assert.equal(
buildUploadFileName({ name: 'tokens.md', webkitRelativePath: 'design/tokens.md' }, 'handbook'),
'handbook/design/tokens.md',
)
})
test('only directory-sourced files count as a folder upload', () => {
assert.equal(isFolderUpload({ name: 'a.md', webkitRelativePath: 'docs/a.md' }), true)
assert.equal(isFolderUpload({ name: 'a.md' }), false)
})
test('breadcrumbs walk from the top level down to the selected folder', () => {
assert.deepEqual(folderBreadcrumbs('handbook/onboarding'), [
{ name: 'handbook', path: 'handbook' },
{ name: 'onboarding', path: 'handbook/onboarding' },
])
// "all documents" and the knowledge base root have no folder crumbs.
assert.deepEqual(folderBreadcrumbs(null), [])
assert.deepEqual(folderBreadcrumbs(''), [])
})
test('ancestor paths include the folder itself so the selected row stays visible', () => {
assert.deepEqual(folderAncestorPaths('a/b/c'), ['a', 'a/b', 'a/b/c'])
assert.deepEqual(folderAncestorPaths(null), [])
})
test('folder lookup searches the whole depth of the tree', () => {
assert.equal(folderPathExists(tree, 'handbook/onboarding/day-one'), true)
assert.equal(folderPathExists(tree, 'design'), true)
assert.equal(folderPathExists(tree, 'handbook/policies'), false)
})
test('collapsed folders hide their subtree', () => {
const rows = flattenFolderRows(tree, new Set())
assert.deepEqual(
rows.map((row) => [row.node.path, row.depth]),
[
['handbook', 0],
['design', 0],
],
)
})
test('expanding a folder reveals its children indented one level deeper', () => {
const rows = flattenFolderRows(tree, new Set(['handbook', 'handbook/onboarding']))
assert.deepEqual(
rows.map((row) => [row.node.path, row.depth]),
[
['handbook', 0],
['handbook/onboarding', 1],
['handbook/onboarding/day-one', 2],
['design', 0],
],
)
})
test('expanding a child without its parent keeps the child hidden', () => {
const rows = flattenFolderRows(tree, new Set(['handbook/onboarding']))
assert.deepEqual(
rows.map((row) => row.node.path),
['handbook', 'design'],
)
})

View File

@ -0,0 +1,93 @@
import type { KnowledgeFolderNode } from '@/api/knowledge-base/index'
/**
* Pure helpers behind the knowledge base folder sidebar. The document page keeps
* folder state as a single value with three meanings, so it is worth naming:
* `null` browses every folder (the historical flat list), `''` is the knowledge
* base root, and any other string is a folder path such as "docs/spec".
*/
export type FolderSelection = string | null
/** Minimal shape of the browser File objects the upload flow deals with. */
export type UploadFileLike = {
name: string
webkitRelativePath?: string
}
/** One rendered row of the flattened tree. */
export type FolderRow = {
node: KnowledgeFolderNode
depth: number
}
/**
* A browser only sets webkitRelativePath when the file came from a directory
* picker or a dropped directory, which is exactly what distinguishes a folder
* upload from picking individual files.
*/
export function isFolderUpload(file: UploadFileLike): boolean {
return !!file.webkitRelativePath
}
/**
* Build the path-qualified `fileName` form field that the backend splits into
* folder_path + file_name. Two sources are combined: the folder currently open
* in the sidebar (so uploads land where the user is looking) and the browser's
* webkitRelativePath, whose picked directory becomes the top-level tree node.
*
* Returns undefined for a plain single-file upload at the knowledge base root so
* that request stays byte-identical to the pre-folder behaviour.
*/
export function buildUploadFileName(
file: UploadFileLike,
currentFolder: FolderSelection,
): string | undefined {
const segments: string[] = []
if (currentFolder) segments.push(currentFolder)
if (file.webkitRelativePath) {
segments.push(...file.webkitRelativePath.split('/').filter(Boolean).slice(0, -1))
}
if (segments.length === 0) return undefined
return `${segments.join('/')}/${file.name}`
}
/** Breadcrumb entries for a folder path, from the top level down to the leaf. */
export function folderBreadcrumbs(path: FolderSelection): Array<{ name: string; path: string }> {
if (!path) return []
const segments = path.split('/')
return segments.map((name, index) => ({
name,
path: segments.slice(0, index + 1).join('/'),
}))
}
/**
* The path itself plus every ancestor, used to keep the selected folder
* reachable by expanding the rows above it.
*/
export function folderAncestorPaths(path: FolderSelection): string[] {
if (!path) return []
const segments = path.split('/')
return segments.map((_, index) => segments.slice(0, index + 1).join('/'))
}
/** Depth-first search for a folder path in the tree. */
export function folderPathExists(folders: KnowledgeFolderNode[], path: string): boolean {
return folders.some((node) => node.path === path || folderPathExists(node.children || [], path))
}
/** Flatten the tree into the visible rows, honouring the expanded folder set. */
export function flattenFolderRows(
folders: KnowledgeFolderNode[],
expanded: Set<string>,
depth = 0,
): FolderRow[] {
const rows: FolderRow[] = []
folders.forEach((node) => {
rows.push({ node, depth })
if (node.children?.length && expanded.has(node.path)) {
rows.push(...flattenFolderRows(node.children, expanded, depth + 1))
}
})
return rows
}