feat(wiki): implement folder management features in wiki API

Add new API functions for managing wiki folders, including creating, updating, deleting, and listing folders. Introduce a new WikiFolder interface to represent folder structure and enhance the WikiBrowser component with folder actions. Update internationalization strings for folder-related actions in English, Korean, Russian, and Chinese locales. Refactor existing code to accommodate folder hierarchy and improve user experience in the wiki browser.
This commit is contained in:
wizardchen
2026-06-16 23:48:35 +08:00
committed by lyingbug
parent 83eeec0ddf
commit e76738d054
24 changed files with 1903 additions and 399 deletions
+58 -17
View File
@@ -42,12 +42,27 @@ export interface WikiPageListResponse {
total_pages: number;
}
export interface WikiCategoryPathListResponse {
paths: { path: string[]; count: number }[];
total: number;
page: number;
page_size: number;
total_pages: number;
export interface WikiFolder {
id: string;
tenant_id: number;
knowledge_base_id: string;
parent_id: string;
name: string;
path: string;
depth: number;
sort_order: number;
created_at: string;
updated_at: string;
}
export interface WikiFolderNode extends WikiFolder {
page_count: number;
has_children: boolean;
}
export interface WikiFolderListResponse {
parent_id: string;
folders: WikiFolderNode[];
}
export interface WikiGraphMeta {
@@ -114,18 +129,44 @@ export function listWikiPages(kbId: string, params?: {
return get(`/api/v1/knowledgebase/${kbId}/wiki/pages${qs ? '?' + qs : ''}`);
}
export function listWikiCategories(kbId: string, params: {
page_type: string;
parent_path?: string;
page?: number;
page_size?: number;
}) {
// listWikiFolders returns the direct child folders of parentId ("" = root),
// each enriched with a recursive page_count and a has_children flag so the tree
// can render expand affordances and empty folders without a second request.
// pageTypes scopes the view to a sidebar tab: only folders whose subtree holds
// a page of those types (or are entirely empty) come back, and page_count is
// counted within those types.
export function listWikiFolders(kbId: string, parentId = '', pageTypes = '') {
const query = new URLSearchParams();
query.set('page_type', params.page_type);
if (params.parent_path) query.set('parent_path', params.parent_path);
if (params.page !== undefined) query.set('page', String(params.page));
if (params.page_size !== undefined) query.set('page_size', String(params.page_size));
return get(`/api/v1/knowledgebase/${kbId}/wiki/categories?${query.toString()}`);
if (parentId) query.set('parent_id', parentId);
if (pageTypes) query.set('page_types', pageTypes);
const qs = query.toString();
return get(`/api/v1/knowledgebase/${kbId}/wiki/folders${qs ? '?' + qs : ''}`);
}
// createWikiFolder creates a new empty folder under parentId ("" = root).
export function createWikiFolder(kbId: string, parentId: string, name: string) {
return post(`/api/v1/knowledgebase/${kbId}/wiki/folders`, { parent_id: parentId, name });
}
// updateWikiFolder renames and/or reparents a folder. Pass move_parent: true
// (and parent_id) to reparent; omit it for a pure rename.
export function updateWikiFolder(
kbId: string,
folderId: string,
data: { name?: string; parent_id?: string; move_parent?: boolean },
) {
return put(`/api/v1/knowledgebase/${kbId}/wiki/folders/${folderId}`, data);
}
// deleteWikiFolder removes an empty folder (no pages, no sub-folders).
export function deleteWikiFolder(kbId: string, folderId: string) {
return del(`/api/v1/knowledgebase/${kbId}/wiki/folders/${folderId}`);
}
// moveWikiPage relocates a page into folderId ("" = root). The slug is sent in
// the body because wiki slugs are hierarchical.
export function moveWikiPage(kbId: string, slug: string, folderId: string) {
return put(`/api/v1/knowledgebase/${kbId}/wiki/move-page`, { slug, folder_id: folderId });
}
export function createWikiPage(kbId: string, data: Partial<WikiPage>) {
+23 -1
View File
@@ -2520,7 +2520,29 @@ export default {
searchNoResults: 'No matching pages found',
loadMore: 'Load more ({remaining} remaining)',
filterAll: 'All Types',
loadMoreFolders: 'Load more folders',
newFolder: 'New Folder',
newRootFolder: 'New Folder',
newSubfolder: 'New Subfolder',
folderActions: 'Folder actions',
folderNamePlaceholder: 'Enter folder name',
createFolderSuccess: 'Folder created',
createFolderFailed: 'Failed to create folder',
movePageSuccess: 'Page moved',
movePageFailed: 'Failed to move page',
renameFolder: 'Rename Folder',
renameFolderSuccess: 'Folder renamed',
renameFolderFailed: 'Failed to rename folder',
deleteFolder: 'Delete Folder',
deleteFolderConfirm: 'Delete folder "{name}"?',
deleteFolderSuccess: 'Folder deleted',
deleteFolderFailed: 'Failed to delete folder',
deleteFolderNotEmpty: 'Folder is not empty. Remove its pages and sub-folders first.',
moveFolderSuccess: 'Folder moved',
moveFolderFailed: 'Failed to move folder',
moveFolderIntoSelf: 'Cannot move a folder into itself or its descendant',
moveConfirm: 'Move to "{target}"?',
rootFolderLabel: 'Root',
dropToRoot: 'Drop here to move to root',
filterSummary: 'Summaries',
filterKnowledge: 'Knowledge',
filterEntity: 'Entities',
+23 -1
View File
@@ -3379,7 +3379,29 @@ export default {
searchNoResults: "일치하는 페이지가 없습니다",
loadMore: "더 불러오기 ({remaining}개 남음)",
filterAll: "전체 유형",
loadMoreFolders: "더 많은 디렉터리 불러오기",
newFolder: "새 디렉터리",
newRootFolder: "새 디렉터리",
newSubfolder: "새 하위 디렉터리",
folderActions: "디렉터리 작업",
folderNamePlaceholder: "디렉터리 이름을 입력하세요",
createFolderSuccess: "디렉터리가 생성되었습니다",
createFolderFailed: "디렉터리 생성 실패",
movePageSuccess: "페이지가 이동되었습니다",
movePageFailed: "페이지 이동 실패",
renameFolder: "디렉터리 이름 변경",
renameFolderSuccess: "디렉터리 이름이 변경되었습니다",
renameFolderFailed: "디렉터리 이름 변경 실패",
deleteFolder: "디렉터리 삭제",
deleteFolderConfirm: "디렉터리 \"{name}\"을(를) 삭제하시겠습니까?",
deleteFolderSuccess: "디렉터리가 삭제되었습니다",
deleteFolderFailed: "디렉터리 삭제 실패",
deleteFolderNotEmpty: "디렉터리가 비어 있지 않습니다. 먼저 페이지와 하위 디렉터리를 제거하세요.",
moveFolderSuccess: "디렉터리가 이동되었습니다",
moveFolderFailed: "디렉터리 이동 실패",
moveFolderIntoSelf: "디렉터리를 자기 자신이나 하위 디렉터리로 이동할 수 없습니다",
moveConfirm: "'{target}'(으)로 이동할까요?",
rootFolderLabel: "루트",
dropToRoot: "여기에 놓아 루트로 이동",
filterSummary: "요약",
filterKnowledge: "지식",
filterEntity: "엔티티",
+23 -1
View File
@@ -2884,7 +2884,29 @@ export default {
searchNoResults: 'Страницы не найдены',
loadMore: 'Загрузить ещё (осталось {remaining})',
filterAll: 'Все типы',
loadMoreFolders: 'Загрузить ещё каталоги',
newFolder: 'Новый каталог',
newRootFolder: 'Новый каталог',
newSubfolder: 'Новый подкаталог',
folderActions: 'Действия с каталогом',
folderNamePlaceholder: 'Введите название каталога',
createFolderSuccess: 'Каталог создан',
createFolderFailed: 'Не удалось создать каталог',
movePageSuccess: 'Страница перемещена',
movePageFailed: 'Не удалось переместить страницу',
renameFolder: 'Переименовать каталог',
renameFolderSuccess: 'Каталог переименован',
renameFolderFailed: 'Не удалось переименовать каталог',
deleteFolder: 'Удалить каталог',
deleteFolderConfirm: 'Удалить каталог «{name}»?',
deleteFolderSuccess: 'Каталог удалён',
deleteFolderFailed: 'Не удалось удалить каталог',
deleteFolderNotEmpty: 'Каталог не пуст. Сначала удалите страницы и подкаталоги.',
moveFolderSuccess: 'Каталог перемещён',
moveFolderFailed: 'Не удалось переместить каталог',
moveFolderIntoSelf: 'Нельзя переместить каталог в себя или свой подкаталог',
moveConfirm: 'Переместить в «{target}»?',
rootFolderLabel: 'Корень',
dropToRoot: 'Перетащите сюда, чтобы переместить в корень',
filterSummary: 'Резюме',
filterKnowledge: 'Знания',
filterEntity: 'Сущности',
+23 -1
View File
@@ -3384,7 +3384,29 @@ export default {
searchNoResults: "没有找到匹配的页面",
loadMore: "加载更多(还剩 {remaining} 条)",
filterAll: "全部类型",
loadMoreFolders: "加载更多目录",
newFolder: "新建目录",
newRootFolder: "新建目录",
newSubfolder: "新建子目录",
folderActions: "目录操作",
folderNamePlaceholder: "请输入目录名称",
createFolderSuccess: "目录已创建",
createFolderFailed: "创建目录失败",
movePageSuccess: "页面已移动",
movePageFailed: "移动页面失败",
renameFolder: "重命名目录",
renameFolderSuccess: "目录已重命名",
renameFolderFailed: "重命名目录失败",
deleteFolder: "删除目录",
deleteFolderConfirm: "确定要删除目录“{name}”吗?",
deleteFolderSuccess: "目录已删除",
deleteFolderFailed: "删除目录失败",
deleteFolderNotEmpty: "目录非空,请先移除其中的页面和子目录",
moveFolderSuccess: "目录已移动",
moveFolderFailed: "移动目录失败",
moveFolderIntoSelf: "不能将目录移动到自身或其子目录中",
moveConfirm: "移动到「{target}」?",
rootFolderLabel: "根目录",
dropToRoot: "拖到空白处移动到根目录",
filterSummary: "摘要",
filterKnowledge: "知识",
filterEntity: "实体",
+5 -2
View File
@@ -47,9 +47,12 @@ const DEFAULT_VALID_TYPES = new Set(["pdf", "txt", "md", "docx", "doc", "pptx",
* @param validTypes - override the default extension whitelist with a dynamic set (e.g. from engine registry).
*/
export function kbFileTypeVerification(file: any, silent = false, validTypes?: Set<string> | string[]) {
const allowed = validTypes
const provided = validTypes
? (validTypes instanceof Set ? validTypes : new Set(validTypes))
: DEFAULT_VALID_TYPES;
: undefined;
// An empty whitelist means the engine registry hasn't loaded yet; fall back to
// the default set rather than rejecting every file.
const allowed = provided && provided.size > 0 ? provided : DEFAULT_VALID_TYPES;
const type = file.name.substring(file.name.lastIndexOf(".") + 1).toLowerCase();
if (!allowed.has(type)) {
@@ -31,11 +31,15 @@ export function filterUploadFiles(
options: FilterUploadFilesOptions = {},
): FilterUploadFilesResult {
const list = Array.from(files)
const dynamicTypes = options.supportedFileTypes
const dynamicTypesRaw = options.supportedFileTypes
? options.supportedFileTypes instanceof Set
? options.supportedFileTypes
: new Set(options.supportedFileTypes)
: undefined
// An empty set means the parser-engine list hasn't loaded yet (race with the
// async fetch on mount). Treat it as "unknown" and fall back to the default
// whitelist instead of rejecting every file as unsupported.
const dynamicTypes = dynamicTypesRaw && dynamicTypesRaw.size > 0 ? dynamicTypesRaw : undefined
const validFiles: File[] = []
let skippedCount = 0
+408 -76
View File
@@ -290,21 +290,67 @@
<!-- Active-tab list -->
<template v-if="activeGroup">
<div ref="treeListRef" class="wiki-tree-list">
<!-- Toolbar row: right-aligned "new root folder". Always present
so it never shifts the list mid-drag. -->
<div class="wiki-tree-toolbar">
<WikiFolderActions
create-only
:label="$t('knowledgeEditor.wikiBrowser.newRootFolder')"
@create="(name: string) => createFolder('', [], name)"
/>
</div>
<!-- The list container is itself the "move to root" drop target;
folder rows stop propagation so their own drop wins. This
avoids inserting/removing a drop bar during the drag, which
was cancelling the native drag after the first success. -->
<div
ref="treeListRef"
:class="['wiki-tree-list', { 'wiki-tree-list--root-drop': dropTargetKey === '__root__' }]"
@dragover.prevent="onRootDragOver"
@dragleave="onDirectoryDragLeave('__root__')"
@drop.prevent="onDropOnDirectory($event, '', [])"
>
<template
v-for="item in activeTreeRows"
:key="item.rowKey"
>
<div
v-if="item.kind === 'directory'"
class="wiki-directory-item"
:class="['wiki-directory-item', { 'wiki-directory-item--drop': dropTargetKey === item.pathKey }]"
:style="{ paddingLeft: `${6 + item.depth * 14}px` }"
:draggable="editingFolderId !== item.folderId"
@click="toggleDirectory(item.pathKey)"
@dragstart="onFolderDragStart($event, item.folderId, item.path)"
@dragend="onPageDragEnd"
@dragover.prevent.stop="onDirectoryDragOver($event, item.pathKey)"
@dragleave.stop="onDirectoryDragLeave(item.pathKey)"
@drop.prevent.stop="onDropOnDirectory($event, item.folderId, item.path)"
>
<t-icon :name="item.collapsed ? 'chevron-right' : 'chevron-down'" class="wiki-directory-toggle" />
<t-icon name="folder" class="wiki-directory-icon" />
<span class="wiki-directory-title">{{ item.label }}</span>
<span class="wiki-directory-count">{{ item.count }}</span>
<input
v-if="editingFolderId === item.folderId"
v-model="editingName"
class="wiki-directory-rename-input"
:placeholder="$t('knowledgeEditor.wikiBrowser.folderNamePlaceholder')"
@click.stop
@keydown.enter="commitRenameFolder(item.folderId, item.label)"
@keydown.esc="cancelRenameFolder"
@blur="commitRenameFolder(item.folderId, item.label)"
/>
<template v-else>
<span class="wiki-directory-title">{{ item.label }}</span>
<span class="wiki-directory-count">{{ item.count }}</span>
<WikiFolderActions
v-if="item.folderId"
:name="item.label"
:page-count="item.count"
:has-children="item.hasChildren"
@create="(name: string) => createFolder(item.folderId, item.path, name)"
@rename="() => startRenameFolder(item.folderId, item.label)"
@delete="() => deleteFolder(item.folderId)"
/>
</template>
</div>
<div
v-else-if="item.kind === 'load-more'"
@@ -319,25 +365,15 @@
<span>{{ $t('knowledgeEditor.wikiBrowser.logLoadMore') }}</span>
</template>
</div>
<div
v-else-if="item.kind === 'load-more-dirs'"
class="wiki-directory-load-more"
:data-loadmore-key="item.rowKey"
:style="{ paddingLeft: `${12 + item.depth * 14}px` }"
@click="loadCategoriesForType(item.type, { parentPath: item.path })"
>
<t-loading v-if="item.loading" size="small" />
<template v-else>
<t-icon name="folder-open" />
<span>{{ $t('knowledgeEditor.wikiBrowser.loadMoreFolders') }}</span>
</template>
</div>
<div
v-else
:class="['wiki-page-item', 'wiki-page-item--tree', { active: selectedPage?.id === item.page.id }]"
:style="{ paddingLeft: `${12 + item.depth * 14}px` }"
:title="item.page.title"
draggable="true"
@click="selectPage(item.page)"
@dragstart="onPageDragStart($event, item.page)"
@dragend="onPageDragEnd"
>
<t-icon :name="getPageIcon(item.page)" :class="['wiki-page-file-icon', `wiki-page-file-icon--${item.page.page_type}`]" />
<span class="wiki-page-item-title">{{ item.page.title }}</span>
@@ -666,6 +702,30 @@
:embeddedMode="true"
/>
</t-drawer>
<!-- In-place move confirmation, anchored at the drop point. Confirming runs
the actual move API; cancelling discards the staged move. -->
<teleport to="body">
<div v-if="pendingMove" class="wiki-move-confirm-mask" @click="cancelPendingMove">
<div
class="wiki-move-confirm"
:style="{ left: `${pendingMove.x}px`, top: `${pendingMove.y}px` }"
@click.stop
>
<div class="wiki-move-confirm-text">
{{ $t('knowledgeEditor.wikiBrowser.moveConfirm', { target: pendingMove.targetLabel }) }}
</div>
<div class="wiki-move-confirm-footer">
<t-button size="small" variant="outline" @click="cancelPendingMove">
{{ $t('common.cancel') }}
</t-button>
<t-button size="small" theme="primary" @click="confirmPendingMove">
{{ $t('common.confirm') }}
</t-button>
</div>
</div>
</div>
</teleport>
</div>
</template>
@@ -679,11 +739,16 @@ import { marked } from 'marked'
import { MessagePlugin } from 'tdesign-vue-next'
import { hydrateProtectedFileImages } from '@/utils/security'
import picturePreview from '@/components/picture-preview.vue'
import WikiFolderActions from './WikiFolderActions.vue'
import { createSessions } from '@/api/chat'
import ChatView from '@/views/chat/index.vue'
import {
listWikiPages,
listWikiCategories,
listWikiFolders,
createWikiFolder,
updateWikiFolder,
deleteWikiFolder,
moveWikiPage,
getWikiPage,
getWikiIndex,
getWikiLog,
@@ -693,6 +758,7 @@ import {
listWikiIssues,
updateWikiIssueStatus,
type WikiPage,
type WikiFolderNode,
type WikiGraphData,
type WikiStats,
type WikiPageIssue,
@@ -748,6 +814,10 @@ interface PageTypeBucket {
loading: boolean
initialized: boolean // true once the first page has been fetched
categoryPaths: Array<{ path: string[]; count: number }>
// folderIdByPath maps a materialized folder path ("AI/LLM") to its stable
// wiki_folders id, populated as folder levels load. Drag-and-drop and the
// directory rows resolve a folder's id through this map.
folderIdByPath: Record<string, string>
categoriesLoading: boolean
categoriesInitialized: boolean
// categoryPages tracks the directory-skeleton pagination per parent level,
@@ -769,9 +839,8 @@ interface DirectoryCategoryState {
initialized: boolean
}
type WikiTreeRow =
| { kind: 'directory'; rowKey: string; pathKey: string; label: string; depth: number; count: number; collapsed: boolean }
| { kind: 'directory'; rowKey: string; pathKey: string; folderId: string; path: string[]; label: string; depth: number; count: number; hasChildren: boolean; collapsed: boolean }
| { kind: 'load-more'; rowKey: string; type: string; path: string[]; depth: number; loading: boolean }
| { kind: 'load-more-dirs'; rowKey: string; type: string; path: string[]; depth: number; loading: boolean }
| { kind: 'page'; rowKey: string; page: WikiPage; depth: number }
interface WikiTreeDirectory {
label: string
@@ -1545,24 +1614,6 @@ const activeTreeRows = computed<WikiTreeRow[]>(() => {
cursor.pages.push(page)
}
// appendDirLoadMore renders a "load more folders" row when the directory
// skeleton for `parentPath` has more pages to pull.
function appendDirLoadMore(parentPath: string[], depth: number) {
const catKey = directoryPathKey(groupType, parentPath)
const catState = bucket?.categoryPages[catKey]
if (!catState) return
const hasMore = catState.initialized && catState.nextPage <= catState.totalPages
if (!catState.loading && !hasMore) return
rows.push({
kind: 'load-more-dirs',
rowKey: `load-more-dirs:${catKey}`,
type: groupType,
path: parentPath,
depth,
loading: !!catState.loading,
})
}
function appendDirectory(dir: WikiTreeDirectory, depth: number) {
const key = directoryPathKey(groupType, dir.path)
const collapsed = collapsedDirectories.value.has(key)
@@ -1570,9 +1621,12 @@ const activeTreeRows = computed<WikiTreeRow[]>(() => {
kind: 'directory',
rowKey: `dir:${key}`,
pathKey: key,
folderId: bucket?.folderIdByPath[dir.path.join('/')] || '',
path: dir.path,
label: dir.label,
depth,
count: dir.count,
hasChildren: dir.dirs.size > 0,
collapsed,
})
if (collapsed) return
@@ -1580,7 +1634,6 @@ const activeTreeRows = computed<WikiTreeRow[]>(() => {
for (const child of dir.dirs.values()) {
appendDirectory(child, depth + 1)
}
appendDirLoadMore(dir.path, depth + 1)
for (const page of dir.pages) {
rows.push({
kind: 'page',
@@ -1606,7 +1659,6 @@ const activeTreeRows = computed<WikiTreeRow[]>(() => {
for (const dir of root.dirs.values()) {
appendDirectory(dir, 0)
}
appendDirLoadMore([], 0)
for (const page of root.pages) {
rows.push({
kind: 'page',
@@ -1673,8 +1725,6 @@ function dispatchLoadMore(rowKey: string) {
if (!row) return
if (row.kind === 'load-more') {
loadPagesForType(row.type, { categoryPath: row.path })
} else if (row.kind === 'load-more-dirs') {
loadCategoriesForType(row.type, { parentPath: row.path })
}
}
@@ -1807,11 +1857,6 @@ function handleContentClick(e: MouseEvent) {
// for common wikis. Later pages are pulled on scroll.
const WIKI_SIDEBAR_PAGE_SIZE = 100
// WIKI_CATEGORY_PAGE_SIZE is the directory-skeleton fetch batch per level. A
// level is paged in on demand; when more siblings remain a "load more folders"
// row is rendered to pull the next page.
const WIKI_CATEGORY_PAGE_SIZE = 100
function emptyBucket(): PageTypeBucket {
return {
items: [],
@@ -1820,6 +1865,7 @@ function emptyBucket(): PageTypeBucket {
loading: false,
initialized: false,
categoryPaths: [],
folderIdByPath: {},
categoriesLoading: false,
categoriesInitialized: false,
categoryPages: {},
@@ -1834,11 +1880,13 @@ function ensureBucket(type: string): PageTypeBucket {
return pagesByType.value[type]
}
// loadCategoriesForType pages the directory skeleton one level at a time. Each
// call fetches the next unloaded page of `parentPath`'s direct children;
// deeper levels are pulled lazily when their folder is expanded (see
// toggleDirectory), and a "load more folders" row pulls the next page within a
// level. Re-expanding an already-loaded level does not refetch.
// loadCategoriesForType pulls the child folders of one directory level from the
// authoritative wiki_folders tree. The folder tree is the single source of
// truth for placement, so empty folders show up here too (they carry a 0
// page_count). The parent level is resolved to its stable folder id through
// bucket.folderIdByPath; the root level uses id "". Each level's children are
// returned in one shot (the tree is navigation-sized), so there is no
// per-level "load more folders" pagination anymore.
async function loadCategoriesForType(type: string, opts: { reset?: boolean; parentPath?: string[] } = {}) {
const bucket = ensureBucket(type)
const parentPath = opts.parentPath || []
@@ -1846,13 +1894,19 @@ async function loadCategoriesForType(type: string, opts: { reset?: boolean; pare
const isRoot = parentPath.length === 0
if (opts.reset) {
bucket.categoryPaths = []
bucket.folderIdByPath = {}
bucket.categoriesInitialized = false
bucket.categoryPages = {}
}
const parentId = isRoot ? '' : bucket.folderIdByPath[parentPath.join('/')]
// A deeper level whose parent folder id we have not yet recorded cannot be
// resolved against the (id-based) folders endpoint — skip until it loads.
if (!isRoot && parentId === undefined) return
let state = bucket.categoryPages[parentKey]
if (state?.loading) return
if (state && state.initialized && state.nextPage > state.totalPages) return
if (state && state.initialized) return // a level is loaded in a single request
if (!state) {
state = { nextPage: 1, totalPages: 1, loading: false, initialized: false }
}
@@ -1863,46 +1917,250 @@ async function loadCategoriesForType(type: string, opts: { reset?: boolean; pare
setState({ ...state, loading: true })
if (isRoot) bucket.categoriesLoading = true
try {
const res = await listWikiCategories(props.knowledgeBaseId, {
page_type: tabPageTypes(type),
parent_path: parentPath.join('/'),
page: state.nextPage,
page_size: WIKI_CATEGORY_PAGE_SIZE,
})
const res = await listWikiFolders(props.knowledgeBaseId, parentId || '', tabPageTypes(type))
const body: any = (res as any).data || res
const paths = Array.isArray(body?.paths) ? body.paths : []
const incoming: Array<{ path: string[]; count: number }> = paths
.map((entry: any) => ({
path: Array.isArray(entry?.path)
? entry.path.map((part: unknown) => String(part || '').trim()).filter(Boolean)
: [],
count: Number(entry?.count) || 0,
const folders: WikiFolderNode[] = Array.isArray(body?.folders) ? body.folders : []
const incoming = folders
.map(folder => ({
path: String(folder.path || '').split('/').map(part => part.trim()).filter(Boolean),
count: Number(folder.page_count) || 0,
id: String(folder.id || ''),
}))
.filter((entry: { path: string[]; count: number }) => entry.path.length > 0)
.filter(entry => entry.path.length > 0)
const existing = new Map(bucket.categoryPaths.map(entry => [directoryPathKey(type, entry.path), entry]))
const folderIds = { ...bucket.folderIdByPath }
for (const entry of incoming) {
existing.set(directoryPathKey(type, entry.path), entry)
existing.set(directoryPathKey(type, entry.path), { path: entry.path, count: entry.count })
folderIds[entry.path.join('/')] = entry.id
}
bucket.categoryPaths = Array.from(existing.values())
setState({
nextPage: state.nextPage + 1,
totalPages: Number(body?.total_pages) || 1,
loading: false,
initialized: true,
})
bucket.folderIdByPath = folderIds
setState({ nextPage: 2, totalPages: 1, loading: false, initialized: true })
if (isRoot) bucket.categoriesInitialized = true
initializeDefaultCollapsedDirectories(type, incoming.map((entry: { path: string[]; count: number }) => ({
initializeDefaultCollapsedDirectories(type, incoming.map(entry => ({
category_path: entry.path,
} as WikiPage)))
} catch (e) {
console.error(`Failed to load wiki categories of type ${type}:`, e)
console.error(`Failed to load wiki folders of type ${type}:`, e)
setState({ ...state, loading: false })
} finally {
if (isRoot) bucket.categoriesLoading = false
}
}
// reloadDirectoryForType resets and reloads both the folder skeleton and the
// pages for one tab. Used after a structural mutation (move page, create /
// rename / delete folder) so the tree reflects the new layout authoritatively
// instead of guessing at the optimistic delta.
async function reloadDirectoryForType(type: string) {
clearDirectoryStateForType(type)
await loadPagesForType(type, { reset: true })
await loadCategoriesForType(type, { reset: true })
}
// --- Drag-and-drop: move a page or folder into a folder ------------------
// draggedItem holds whatever is being dragged — a page (move into folder) or a
// folder (reparent). dropTargetKey is the row highlighted as the hover target
// ("__root__" for the toolbar drop zone). Both clear on dragend / drop so a
// cancelled drag leaves no sticky highlight.
type DraggedItem =
| { kind: 'page'; page: WikiPage }
| { kind: 'folder'; folderId: string; path: string[] }
const draggedItem = ref<DraggedItem | null>(null)
const dropTargetKey = ref<string>('')
// primeDragData sets dataTransfer so the native HTML5 drag actually starts.
// Firefox refuses to initiate a drag unless some data is set, and without an
// explicit effectAllowed/dropEffect the cursor shows "no-drop" and the drop
// event never fires — which is why the move felt impossible to trigger.
function primeDragData(e: DragEvent) {
if (!e.dataTransfer) return
e.dataTransfer.effectAllowed = 'move'
try {
e.dataTransfer.setData('text/plain', '')
} catch {
// Some browsers throw if setData is called outside a real dragstart; ignore.
}
}
function onPageDragStart(e: DragEvent, page: WikiPage) {
draggedItem.value = { kind: 'page', page }
primeDragData(e)
}
function onFolderDragStart(e: DragEvent, folderId: string, path: string[]) {
if (!folderId) return
draggedItem.value = { kind: 'folder', folderId, path }
primeDragData(e)
}
function onPageDragEnd() {
draggedItem.value = null
dropTargetKey.value = ''
}
function onDirectoryDragOver(e: DragEvent, pathKey: string) {
if (!draggedItem.value) return
if (e.dataTransfer) e.dataTransfer.dropEffect = 'move'
dropTargetKey.value = pathKey
}
// onRootDragOver fires on the list container itself. Folder rows stop their
// dragover from bubbling here, so reaching this handler means the cursor is
// over empty list space (or a page row) — i.e. a "move to root" target.
function onRootDragOver(e: DragEvent) {
if (!draggedItem.value) return
if (e.dataTransfer) e.dataTransfer.dropEffect = 'move'
dropTargetKey.value = '__root__'
}
function onDirectoryDragLeave(pathKey: string) {
if (dropTargetKey.value === pathKey) dropTargetKey.value = ''
}
// A move is staged here on drop and only executed once the user confirms via
// the in-place confirmation popup (anchored at the drop point). This avoids
// silently mutating the tree on an accidental drag.
const pendingMove = ref<
| { item: DraggedItem; folderId: string; targetLabel: string; x: number; y: number }
| null
>(null)
function onDropOnDirectory(e: DragEvent, folderId: string, path: string[]) {
const item = draggedItem.value
draggedItem.value = null
dropTargetKey.value = ''
if (!item) return
const targetPath = path.join('/')
if (item.kind === 'page') {
// No-op when the page already lives in this folder.
if ((pageCategoryPath(item.page) || []).join('/') === targetPath) return
} else {
// Folder reparent. Reject no-op (same parent) and the illegal move of a
// folder into itself or one of its descendants.
const sourcePath = item.path.join('/')
if (sourcePath === targetPath) return
if (folderId === item.folderId) return
if (targetPath === sourcePath || targetPath.startsWith(`${sourcePath}/`)) {
MessagePlugin.warning(t('knowledgeEditor.wikiBrowser.moveFolderIntoSelf'))
return
}
}
const targetLabel = path.length > 0
? path[path.length - 1]
: t('knowledgeEditor.wikiBrowser.rootFolderLabel')
pendingMove.value = { item, folderId, targetLabel, x: e.clientX, y: e.clientY }
}
function cancelPendingMove() {
pendingMove.value = null
}
async function confirmPendingMove() {
const move = pendingMove.value
pendingMove.value = null
if (!move) return
const { item, folderId } = move
if (item.kind === 'page') {
try {
await moveWikiPage(props.knowledgeBaseId, item.page.slug, folderId)
MessagePlugin.success(t('knowledgeEditor.wikiBrowser.movePageSuccess'))
await reloadDirectoryForType(activeTab.value)
} catch (e) {
console.error('Failed to move wiki page:', e)
MessagePlugin.error(t('knowledgeEditor.wikiBrowser.movePageFailed'))
}
return
}
try {
await updateWikiFolder(props.knowledgeBaseId, item.folderId, { parent_id: folderId, move_parent: true })
MessagePlugin.success(t('knowledgeEditor.wikiBrowser.moveFolderSuccess'))
await reloadDirectoryForType(activeTab.value)
} catch (e: any) {
console.error('Failed to move wiki folder:', e)
MessagePlugin.error(
e?.response?.data?.message || t('knowledgeEditor.wikiBrowser.moveFolderFailed'),
)
}
}
// --- Folder create / rename / delete -------------------------------------
// These are invoked by the in-place WikiFolderActions popup (no full-page
// dialog). The popup owns the input / confirm surface; these handlers only do
// the API call, surface a toast, and reload the affected tab so the tree
// reflects the new layout authoritatively.
async function createFolder(parentId: string, parentPath: string[], name: string) {
try {
await createWikiFolder(props.knowledgeBaseId, parentId, name)
MessagePlugin.success(t('knowledgeEditor.wikiBrowser.createFolderSuccess'))
// Keep the parent expanded so the new child is visible.
if (parentPath.length > 0) {
collapsedDirectories.value = new Set(
[...collapsedDirectories.value].filter(k => k !== directoryPathKey(activeTab.value, parentPath)),
)
}
await reloadDirectoryForType(activeTab.value)
} catch (e: any) {
console.error('Failed to create wiki folder:', e)
MessagePlugin.error(e?.response?.data?.message || t('knowledgeEditor.wikiBrowser.createFolderFailed'))
}
}
// Inline rename: the directory row swaps its label for a text input instead
// of opening a popup. editingFolderId marks the active row; editingName backs
// the input. Committed on Enter / blur, abandoned on Escape.
const editingFolderId = ref('')
const editingName = ref('')
function startRenameFolder(folderId: string, currentName: string) {
if (!folderId) return
editingFolderId.value = folderId
editingName.value = currentName
// Only one rename input exists at a time; focus + select it once rendered.
nextTick(() => {
const el = document.querySelector('.wiki-directory-rename-input') as HTMLInputElement | null
el?.focus()
el?.select()
})
}
function cancelRenameFolder() {
editingFolderId.value = ''
editingName.value = ''
}
async function commitRenameFolder(folderId: string, originalName: string) {
if (editingFolderId.value !== folderId) return
const name = editingName.value.trim()
cancelRenameFolder()
if (!name || name === originalName) return
try {
await updateWikiFolder(props.knowledgeBaseId, folderId, { name })
MessagePlugin.success(t('knowledgeEditor.wikiBrowser.renameFolderSuccess'))
await reloadDirectoryForType(activeTab.value)
} catch (e: any) {
console.error('Failed to rename wiki folder:', e)
MessagePlugin.error(e?.response?.data?.message || t('knowledgeEditor.wikiBrowser.renameFolderFailed'))
}
}
async function deleteFolder(folderId: string) {
if (!folderId) return
try {
await deleteWikiFolder(props.knowledgeBaseId, folderId)
MessagePlugin.success(t('knowledgeEditor.wikiBrowser.deleteFolderSuccess'))
await reloadDirectoryForType(activeTab.value)
} catch (e: any) {
console.error('Failed to delete wiki folder:', e)
MessagePlugin.error(e?.response?.data?.message || t('knowledgeEditor.wikiBrowser.deleteFolderFailed'))
}
}
// loadPagesForType fetches the next page for a single type bucket. The
// first call seeds `total` from the backend so subsequent `hasMore`
// checks work without another round-trip. Guard against concurrent
@@ -4271,6 +4529,9 @@ onUnmounted(() => {
border-radius: 6px;
cursor: pointer;
margin-bottom: 2px;
// Without this, mousedown-drag on the title text starts a text selection
// instead of an HTML5 drag, so the page never picks up.
user-select: none;
transition: background 0.15s;
&:hover {
@@ -4295,14 +4556,85 @@ onUnmounted(() => {
margin: 1px 0;
color: var(--td-text-color-secondary);
background: transparent;
user-select: none;
transition: background 0.15s, color 0.15s;
&:hover {
background: var(--td-bg-color-container-hover);
color: var(--td-text-color-primary);
:deep(.wiki-directory-action--reveal) {
opacity: 1;
}
}
}
.wiki-directory-rename-input {
flex: 1;
min-width: 0;
height: 24px;
border: 1px solid var(--td-brand-color);
border-radius: 4px;
padding: 0 6px;
font-size: 13px;
color: var(--td-text-color-primary);
background: var(--td-bg-color-container);
outline: none;
}
.wiki-directory-item--drop {
background: var(--td-brand-color-light);
box-shadow: inset 0 0 0 1px var(--td-brand-color);
}
.wiki-tree-toolbar {
display: flex;
justify-content: flex-end;
align-items: center;
padding: 2px 6px 0;
}
// While dragging, the whole list is the "move to root" target; a subtle inset
// ring signals it without inserting any element that would shift the layout.
.wiki-tree-list--root-drop {
border-radius: 6px;
box-shadow: inset 0 0 0 1px var(--td-brand-color);
}
// In-place move confirmation anchored at the drop point (teleported to body).
.wiki-move-confirm-mask {
position: fixed;
inset: 0;
z-index: 3500;
}
.wiki-move-confirm {
position: fixed;
// x/y are the drop coords; nudge so the card sits just below-right of the
// cursor. max-width + viewport clamping keep it on-screen for edge drops.
transform: translate(8px, 8px);
max-width: min(280px, calc(100vw - 24px));
padding: 12px;
border-radius: 8px;
background: var(--td-bg-color-container);
box-shadow: var(--td-shadow-2);
border: 1px solid var(--td-component-border);
}
.wiki-move-confirm-text {
font-size: 13px;
line-height: 1.4;
color: var(--td-text-color-primary);
word-break: break-word;
}
.wiki-move-confirm-footer {
display: flex;
justify-content: flex-end;
gap: 8px;
margin-top: 12px;
}
.wiki-directory-toggle,
.wiki-directory-icon,
.wiki-page-file-icon {
@@ -0,0 +1,230 @@
<template>
<!-- Anchored in-place popup for folder actions. The trigger is icon-only to
keep the directory row compact; everything (menu, name input, delete
confirm) happens inside this one popup so no full-page dialog is spawned.
click.stop on the trigger and content prevents the surrounding directory
row from treating the interaction as an expand/collapse toggle. -->
<t-popup
v-model:visible="open"
trigger="click"
placement="bottom-start"
destroy-on-close
overlay-class-name="card-more-popup wiki-folder-action-overlay"
@visible-change="onVisibleChange"
>
<span
:class="[
'wiki-directory-action',
{ 'wiki-directory-action--reveal': !createOnly, 'is-open': open, 'wiki-directory-action--labeled': createOnly && label },
]"
:title="createOnly ? t('knowledgeEditor.wikiBrowser.newFolder') : t('knowledgeEditor.wikiBrowser.folderActions')"
@click.stop
@dragstart.prevent.stop
>
<t-icon :name="createOnly ? 'folder-add' : 'more'" />
<span v-if="createOnly && label" class="wiki-directory-action-label">{{ label }}</span>
</span>
<template #content>
<div class="wiki-folder-menu" @click.stop>
<div v-if="mode === 'menu'" class="popup-menu">
<div class="popup-menu-item" @click="enterMode('create')">
<t-icon name="folder-add" class="menu-icon" />
<span>{{ t('knowledgeEditor.wikiBrowser.newSubfolder') }}</span>
</div>
<div class="popup-menu-item" @click="emitRename">
<t-icon name="edit" class="menu-icon" />
<span>{{ t('knowledgeEditor.wikiBrowser.renameFolder') }}</span>
</div>
<div class="popup-menu-item delete" @click="enterMode('delete')">
<t-icon name="delete" class="menu-icon" />
<span>{{ t('knowledgeEditor.wikiBrowser.deleteFolder') }}</span>
</div>
</div>
<template v-else-if="mode === 'create'">
<t-input
ref="inputRef"
v-model="nameInput"
:placeholder="t('knowledgeEditor.wikiBrowser.folderNamePlaceholder')"
@enter="submitName"
/>
<div class="wiki-folder-menu-footer">
<t-button size="small" variant="outline" @click="open = false">
{{ t('common.cancel') }}
</t-button>
<t-button size="small" theme="primary" :disabled="!nameInput.trim()" @click="submitName">
{{ t('common.confirm') }}
</t-button>
</div>
</template>
<template v-else>
<div v-if="!deletable" class="wiki-folder-confirm">
{{ t('knowledgeEditor.wikiBrowser.deleteFolderNotEmpty') }}
</div>
<div v-else class="wiki-folder-confirm">
{{ t('knowledgeEditor.wikiBrowser.deleteFolderConfirm', { name }) }}
</div>
<div class="wiki-folder-menu-footer">
<t-button size="small" variant="outline" @click="open = false">
{{ deletable ? t('common.cancel') : t('common.confirm') }}
</t-button>
<t-button v-if="deletable" size="small" theme="danger" @click="submitDelete">
{{ t('common.confirm') }}
</t-button>
</div>
</template>
</div>
</template>
</t-popup>
</template>
<script setup lang="ts">
import { ref, computed, nextTick } from 'vue'
import { useI18n } from 'vue-i18n'
const props = withDefaults(defineProps<{
name?: string
pageCount?: number
hasChildren?: boolean
// createOnly turns the trigger into a single "new folder" affordance that
// opens straight to the name input (used by the root-folder toolbar entry).
createOnly?: boolean
// label, when set on a createOnly trigger, renders text next to the icon so
// the toolbar entry reads as a button instead of a bare icon.
label?: string
}>(), {
name: '',
pageCount: 0,
hasChildren: false,
createOnly: false,
label: '',
})
const emit = defineEmits<{
(e: 'create', name: string): void
(e: 'rename'): void
(e: 'delete'): void
}>()
const { t } = useI18n()
const open = ref(false)
const mode = ref<'menu' | 'create' | 'delete'>('menu')
const nameInput = ref('')
const inputRef = ref<{ focus: () => void } | null>(null)
const deletable = computed(() => props.pageCount === 0 && !props.hasChildren)
function onVisibleChange(visible: boolean) {
if (!visible) {
mode.value = 'menu'
nameInput.value = ''
return
}
// createOnly skips the menu and lands directly on the name input.
if (props.createOnly) {
enterMode('create')
} else {
mode.value = 'menu'
}
}
function enterMode(next: 'create' | 'delete') {
mode.value = next
if (next === 'create') {
nameInput.value = ''
nextTick(() => inputRef.value?.focus())
}
}
function emitRename() {
emit('rename')
open.value = false
}
function submitName() {
const value = nameInput.value.trim()
if (!value) return
emit('create', value)
open.value = false
}
function submitDelete() {
emit('delete')
open.value = false
}
</script>
<style lang="less" scoped>
.wiki-directory-action {
flex: 0 0 auto;
display: inline-flex;
align-items: center;
font-size: 15px;
color: var(--td-text-color-placeholder);
cursor: pointer;
transition: color 0.15s, opacity 0.15s;
&:hover {
color: var(--td-brand-color);
}
}
// Hover-reveal for the per-folder "more" trigger: hidden by default, shown when
// the row is hovered (parent supplies that rule via :deep) or the popup is open.
.wiki-directory-action--reveal {
opacity: 0;
&.is-open {
opacity: 1;
}
}
// Labeled variant: the toolbar "new folder" button reads as icon + text.
.wiki-directory-action--labeled {
gap: 4px;
padding: 2px 6px;
border-radius: 6px;
font-size: 12px;
color: var(--td-text-color-secondary);
&:hover {
color: var(--td-brand-color);
background: var(--td-bg-color-container-hover);
}
}
.wiki-directory-action-label {
line-height: 1;
}
</style>
<style lang="less">
// Popup content teleports to <body>, so these must be global. The menu chrome
// (background, border, shadow, item styling) comes from the shared
// `card-more-popup` + `.popup-menu` rules in assets/dropdown-menu.less so this
// menu matches every other dropdown in the app; only the create-input and
// delete-confirm panes need a little extra layout here.
.wiki-folder-action-overlay {
.wiki-folder-menu {
min-width: 188px;
}
.wiki-folder-confirm {
font-size: 13px;
line-height: 1.5;
color: var(--td-text-color-primary);
padding: 4px 6px 8px;
max-width: 280px;
}
.wiki-folder-menu-footer {
display: flex;
justify-content: flex-end;
gap: 8px;
margin-top: 8px;
padding: 0 2px;
}
}
</style>
+14
View File
@@ -135,8 +135,19 @@ const checkKnowledgeBaseInitialization = async (): Promise<boolean> => {
}
// isFileDrag distinguishes an OS file drag (the only thing the global upload
// drop zone cares about) from an in-app element drag such as the wiki
// folder/page drag-and-drop. Element drags carry only "text/*" types, never
// "Files", so we bail out and let the originating component handle the drop.
const isFileDrag = (event: DragEvent): boolean => {
const types = event.dataTransfer?.types
if (!types) return false
return Array.from(types).includes('Files')
}
// 全局拖拽事件处理
const handleGlobalDragEnter = (event: DragEvent) => {
if (!isFileDrag(event)) return;
event.preventDefault();
dragCounter++;
if (event.dataTransfer) {
@@ -146,6 +157,7 @@ const handleGlobalDragEnter = (event: DragEvent) => {
}
const handleGlobalDragOver = (event: DragEvent) => {
if (!isFileDrag(event)) return;
event.preventDefault();
if (event.dataTransfer) {
event.dataTransfer.dropEffect = 'copy';
@@ -153,6 +165,7 @@ const handleGlobalDragOver = (event: DragEvent) => {
}
const handleGlobalDragLeave = (event: DragEvent) => {
if (!isFileDrag(event)) return;
event.preventDefault();
dragCounter--;
if (dragCounter === 0) {
@@ -161,6 +174,7 @@ const handleGlobalDragLeave = (event: DragEvent) => {
}
const handleGlobalDrop = async (event: DragEvent) => {
if (!isFileDrag(event)) return;
event.preventDefault();
dragCounter = 0;
ismask.value = false;