refactor(frontend): 重构前端第三版

This commit is contained in:
sophie committed 2026-06-11 20:11:51 +08:00
1 parent bf32f8b954
commit dc141d19a2
49 files changed
+5333 -4234

No files matched your search

+37
View File
@@ -0,0 +1,37 @@
/**
* scripts/extract-i18n-kb.mjs
* 将 i18n.ts 内联的 kb 相关文案外置至 locales 下 kb.json,并从 i18n.ts 移除。
*/
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const i18nPath = path.resolve(__dirname, '../src/i18n.ts');
const localesDir = path.resolve(__dirname, '../src/locales');
const KB_KEYS = ['kbDifySettings', 'kbDifyHealth', 'kbAdmin', 'kbWorkspace'];
const LOCALE_DIRS = { en: 'en', 'zh-CN': 'zh-CN', 'zh-TW': 'zh-TW', th: 'th' };
const content = fs.readFileSync(i18nPath, 'utf8');
const start = content.indexOf('const messages = {') + 'const messages = '.length;
const end = content.indexOf('const i18n = createI18n');
const messagesStr = content.slice(start, end).trim().replace(/,\s*$/, '');
const messages = new Function(`return ${messagesStr}`)();
for (const [loc, dir] of Object.entries(LOCALE_DIRS)) {
const kbPayload = {};
for (const key of KB_KEYS) {
if (messages[loc]?.[key]) kbPayload[key] = messages[loc][key];
delete messages[loc][key];
}
const outPath = path.join(localesDir, dir, 'kb.json');
fs.writeFileSync(outPath, `${JSON.stringify(kbPayload, null, 2)}\n`, 'utf8');
console.log('Wrote', outPath);
}
const header = content.slice(0, content.indexOf('const messages = {'));
const footer = content.slice(end);
const serialized = JSON.stringify(messages, null, 2);
const newContent = `${header}const messages = ${serialized};\n\n${footer}`;
fs.writeFileSync(i18nPath, newContent, 'utf8');
console.log('Stripped kb keys from i18n.ts');
@@ -0,0 +1,300 @@
/**
* scripts/extract-kb-workspace-composable.mjs
* 将 KbWorkspaceView.vue 的 script 提取为 useKbWorkspace.ts 骨架。
*/
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const vuePath = path.resolve(__dirname, '../src/features/kb/views/KbWorkspaceView.vue');
const outPath = path.resolve(__dirname, '../src/features/kb/composables/useKbWorkspace.ts');
const vue = fs.readFileSync(vuePath, 'utf8');
const scriptMatch = vue.match(/<script setup lang="ts">([\s\S]*?)<\/script>/);
if (!scriptMatch) throw new Error('script block not found');
let body = scriptMatch[1]
.replace(/^\s*\/\*\*[\s\S]*?\*\/\s*/m, '')
.replace(/const props = defineProps<\{[\s\S]*?\}\>\(\);/, 'const embedded = options.embedded ?? false;')
.replace(/props\.embedded/g, 'embedded');
const header = `/**
* features/kb/composables/useKbWorkspace.ts
* 知识库作业面编排:分组导航、文档列表、路径上传、清洗同步与弹窗状态。
*/
import { computed, onMounted, onUnmounted, ref, watch } from 'vue';
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { getStoredAuthUser } from '@/shared/utils/auth';
import {
createKbDocument,
createKbPathUploadJob,
deleteKbPathJobFile,
deleteKbDocument,
getKbDocumentMarkdown,
getKbDocumentSyncRecords,
getKbDocumentVersionSourceFile,
getKbDocumentVersions,
getKbGroupFilesSafe,
getKbGroupsSafe,
getKbJobsSafe,
markKbPathJobFileFailed,
retryFailedKbPathUploadJob,
submitKbDocumentClean,
syncKbDocumentToDify,
uploadKbPathJobFile,
uploadKbDocumentVersion,
updateKbDocumentMarkdown,
type KbDocumentItem,
type KbJob,
type KbDocumentMarkdown,
type KbSyncRecordItem,
type KbDocumentVersionItem,
type KbGroup,
} from '../api/kb.api';
import {
DOCUMENT_PAGE_SIZE_OPTIONS,
FAILURE_PAGE_SIZE,
IDLE_BADGE_CLASS,
PATH_UPLOAD_BATCH_INTERVAL_MS,
PATH_UPLOAD_BATCH_SIZE,
PATH_UPLOAD_CONCURRENCY,
type FailureModalItem,
type KbWorkspaceViewMode,
type LoadListOptions,
type PathUploadTaskItem,
type WorkflowStageState,
} from '../types/kb-workspace.types';
import { mergeStableItems } from '../utils/kb-list.utils';
import {
formatDateTime,
formatFileSize,
getDocumentDisplayDescription,
getDocumentDisplayTitle,
getStatusBadgeClass,
getStatusLabel,
normalizeDuplicateDocumentError,
} from '../utils/kb-display.utils';
import {
getPathUploadJobItems,
getPathUploadJobPriority,
getPathUploadJobProgress,
getPathUploadJobSummary,
hasRetryablePathUploadFailure,
} from '../utils/kb-path-upload.utils';
import {
buildGetLatestJobForDocument,
getDocumentWorkflowState,
getMarkdownUnavailableMessage,
getWorkflowBadges,
normalizeWorkflowErrorMessage,
} from '../utils/kb-workflow.utils';
export interface UseKbWorkspaceOptions {
embedded?: boolean;
}
export function useKbWorkspace(options: UseKbWorkspaceOptions = {}) {
`;
const footer = `
return {
embedded,
router,
t,
isKbAdmin,
isLoading,
isDocumentsLoading,
isSubmitting,
isRecordLoading,
groups,
documents,
jobs,
selectedGroupId,
selectedDocumentId,
activeUploadDocumentId,
syncingDocumentId,
selectedDocumentVersions,
selectedDocumentSyncRecords,
feedback,
feedbackType,
viewMode,
showMarkdownModal,
showRecordModal,
showSourceInfoModal,
showFailureModal,
showPathUploadModal,
showPathUploadHistoryModal,
showDeleteConfirmDialog,
deleteConfirmMessage,
showPathUploadDetails,
fileInputRef,
pathUploadInputRef,
markdownDocumentId,
sourceInfoDocumentId,
markdownContent,
markdownKind,
markdownVersionLabel,
markdownError,
isMarkdownLoading,
isMarkdownSaving,
isSourceInfoLoading,
openingSourceVersionId,
failureModalType,
failureModalPage,
retryingFailureKey,
documentStageFilter,
documentListPage,
documentListPageSize,
documentKeyword,
batchSubmitting,
selectedDocumentIds,
pathUploadDraftText,
pathUploadSelectedFiles,
isPathUploadStaging,
pathUploadJobId,
selectedPathUploadHistoryJobId,
selectedPathUploadHistoryItemKeys,
retryingPathUploadKey,
deletingPathUploadBatch,
openDeleteConfirmDialog,
closeDeleteConfirmDialog,
handleDeleteConfirm,
selectedDocument,
sourceInfoDocument,
selectedGroup,
markdownModalTitle,
sourceInfoVersions,
activeGroupJobs,
pathUploadTask,
groupSummaryItems,
stageFilterTabs,
filteredDocuments,
filteredDocumentTotalPages,
pagedFilteredDocuments,
pagedDocumentRange,
selectedDocuments,
selectedCleanableDocuments,
isAllFilteredSelected,
failureModalItems,
failureModalTotalPages,
pagedFailureModalItems,
failureModalTitle,
documentById,
latestPathUploadJob,
pathUploadHistoryJobs,
selectedPathUploadHistoryJob,
selectedPathUploadHistoryItems,
selectedPathUploadHistorySelectedItems,
isAllPathUploadHistoryItemsSelected,
pathUploadSummary,
recentPathUploadItems,
pathUploadRunning,
kbJobPollingActive,
selectedPathRoots,
loadGroups,
loadJobs,
refreshWorkflowStatusOnly,
refreshCurrentView,
formatDateTime,
formatFileSize,
getDocumentDisplayTitle,
getDocumentDisplayDescription,
getStatusLabel,
getStatusBadgeClass,
getWorkflowBadges,
getDocumentWorkflowState,
openGroupDetail,
backToGroupOverview,
loadDocuments,
loadDocumentVersions,
openDocumentDetail,
closeDocumentDetail,
openSourceInfo,
closeSourceInfoModal,
openOriginalSourceFile,
openFailureModal,
closeFailureModal,
resetPathUploadDraft,
openPathUploadModal,
closePathUploadModal,
triggerPathUploadSelection,
handlePathFilesSelected,
removeSelectedPathFile,
openPathUploadHistoryModal,
closePathUploadHistoryModal,
togglePathUploadHistoryItemSelection,
toggleSelectAllPathUploadHistoryItems,
handleConfirmPathUpload,
handleDeletePathUploadItem,
handleBatchDeletePathUploadItems,
handleRetryFailedPathUpload,
toggleDocumentSelection,
toggleSelectAllFiltered,
handleDeleteDocument,
handleBatchSync,
handleBatchClean,
handleBatchDelete,
handleRetryFailedItem,
triggerUploadForDocument,
handleFileSelected,
triggerMultiUpload,
handleSyncDocument,
openMarkdownEditor,
closeMarkdownModal,
handleSaveMarkdown,
getPathUploadItemDisplayState,
getPathUploadJobItems,
hasRetryablePathUploadFailure,
getPathUploadJobSummary,
DOCUMENT_PAGE_SIZE_OPTIONS,
FAILURE_PAGE_SIZE,
};
}
`;
// Remove duplicate imports from body
body = body.replace(/^import[\s\S]*?from ['"][^'"]+['"];?\s*/gm, '');
body = body.replace(/type WorkflowStageState[\s\S]*?type LoadListOptions[\s\S]*?};\s*/m, '');
body = body.replace(/const FAILURE_PAGE_SIZE[\s\S]*?const DOCUMENT_PAGE_SIZE_OPTIONS[\s\S]*?as const;\s*/m, '');
body = body.replace(/const idleBadgeClass[\s\S]*?;/m, 'const idleBadgeClass = IDLE_BADGE_CLASS;');
body = body.replace(/const mergeStableItems[\s\S]*?};\s*/m, '');
body = body.replace(/const getLatestJobForDocument[\s\S]*?};\s*/m, '');
body = body.replace(/const isUnreadableErrorMessage[\s\S]*?};\s*/m, '');
body = body.replace(/const normalizeWorkflowErrorMessage[\s\S]*?};\s*/m, '');
body = body.replace(/const getDocumentWorkflowState[\s\S]*?};\s*/m, '');
body = body.replace(/const formatDateTime[\s\S]*?};\s*/m, '');
body = body.replace(/const formatFileSize[\s\S]*?};\s*/m, '');
body = body.replace(/const trimPathText[\s\S]*?};\s*/m, '');
body = body.replace(/const getDocumentDisplayTitle[\s\S]*?};\s*/m, '');
body = body.replace(/const getDocumentDisplayDescription[\s\S]*?};\s*/m, '');
body = body.replace(/const normalizeDuplicateDocumentError[\s\S]*?};\s*/m, '');
body = body.replace(/const getStatusLabel[\s\S]*?};\s*/m, '');
body = body.replace(/const getStatusBadgeClass[\s\S]*?};\s*/m, '');
body = body.replace(/const getWorkflowBadges[\s\S]*?};\s*/m, '');
body = body.replace(/const getMarkdownUnavailableMessage[\s\S]*?};\s*/m, '');
body = body.replace(/const getPathUploadJobProgress[\s\S]*?};\s*/m, '');
body = body.replace(/const getPathUploadJobPriority[\s\S]*?};\s*/m, '');
body = body.replace(/const getPathUploadJobItems[\s\S]*?};\s*/m, '');
body = body.replace(/const hasRetryablePathUploadFailure[\s\S]*?;/m, '');
body = body.replace(/const getPathUploadJobSummary[\s\S]*?};\s*/m, '');
const getLatestJobBlock = `
const getLatestJobForDocument = buildGetLatestJobForDocument(() => activeGroupJobs.value);
const resolveWorkflowState = (doc: KbDocumentItem) =>
getDocumentWorkflowState(doc, getLatestJobForDocument);
`;
body = body.replace(
/const groupSummaryItems = computed/,
`${getLatestJobBlock}\nconst groupSummaryItems = computed`,
);
body = body.replace(/getDocumentWorkflowState\(/g, 'resolveWorkflowState(');
body = body.replace(/getWorkflowBadges = \(doc: KbDocumentItem\) => \{[\s\S]*?\};/m,
'const getWorkflowBadgesForDoc = (doc: KbDocumentItem) => getWorkflowBadges(doc, getLatestJobForDocument);');
body = body.replace(/getWorkflowBadges\(/g, 'getWorkflowBadgesForDoc(');
fs.mkdirSync(path.dirname(outPath), { recursive: true });
fs.writeFileSync(outPath, `${header}${body}${footer}`, 'utf8');
console.log('Wrote', outPath);
@@ -0,0 +1,55 @@
/**
* scripts/slim-kb-workspace-view.mjs
* 将 KbWorkspaceView.vue 的 script 替换为 useKbWorkspace 薄壳(kb 单对象绑定)。
*/
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const composablePath = path.resolve(__dirname, '../src/features/kb/composables/useKbWorkspace.ts');
const vuePath = path.resolve(__dirname, '../src/features/kb/views/KbWorkspaceView.vue');
const composable = fs.readFileSync(composablePath, 'utf8');
const returnStart = composable.lastIndexOf('\n return {');
const returnBody = composable.slice(returnStart + '\n return {'.length, composable.lastIndexOf('\n };'));
const keys = returnBody
.split('\n')
.map((line) => line.trim())
.filter(Boolean)
.map((line) => {
const alias = line.match(/^(\w+):\s*(\w+),?$/);
if (alias) return alias[1];
return line.replace(/,$/, '');
});
const script = `<script setup lang="ts">
/**
* features/kb/views/KbWorkspaceView.vue
* 知识库作业面视图壳:模板与弹窗布局,业务逻辑见 useKbWorkspace。
*/
import { ArrowLeft, BookOpen, ChevronDown, ChevronUp, FileText, Info, RefreshCw, Search, Trash2, Upload, X } from 'lucide-vue-next';
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
import { useKbWorkspace } from '../composables/useKbWorkspace';
const props = defineProps<{
embedded?: boolean;
}>();
const kb = useKbWorkspace({ embedded: props.embedded });
</script>`;
let vue = fs.readFileSync(vuePath, 'utf8');
let template = vue.match(/<template>[\s\S]*/)?.[0];
if (!template) throw new Error('template not found');
// 按 key 长度降序,避免短名误替换长名前缀
const sortedKeys = [...keys].sort((a, b) => b.length - a.length);
for (const key of sortedKeys) {
const re = new RegExp(`(?<![.\\w])${key}(?![.\\w])`, 'g');
template = template.replace(re, `kb.${key}`);
}
template = template.replace(/kb\.kb\./g, 'kb.');
fs.writeFileSync(vuePath, `${script}\n\n${template}\n`, 'utf8');
console.log(`Slimmed KbWorkspaceView.vue with kb.* bindings (${keys.length} keys)`);