chore: 项目基线(基于 WeKnora 定制版,整理文件忽略规则)
This commit is contained in:
commit
9097ee699d
5769 files changed
+1446466
No files matched your search
@@ -0,0 +1,227 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import { collectDroppedFiles } from './collectDroppedFiles.ts'
|
||||
|
||||
function makeFile(name: string, content = 'x'): File {
|
||||
return new File([content], name)
|
||||
}
|
||||
|
||||
function fileEntry(file: File) {
|
||||
return {
|
||||
isFile: true,
|
||||
isDirectory: false,
|
||||
name: file.name,
|
||||
file: (ok: (f: File) => void, _err?: (err?: unknown) => void) => {
|
||||
queueMicrotask(() => ok(file))
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
function dirEntry(name: string, children: unknown[], batches?: unknown[][]) {
|
||||
return {
|
||||
isFile: false,
|
||||
isDirectory: true,
|
||||
name,
|
||||
createReader: () => {
|
||||
const pages = batches ?? [children]
|
||||
let index = 0
|
||||
return {
|
||||
readEntries: (ok: (entries: unknown[]) => void) => {
|
||||
const page = index < pages.length ? pages[index] : []
|
||||
index += 1
|
||||
queueMicrotask(() => ok(page as unknown[]))
|
||||
},
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
function phantomDirFile(name: string): File {
|
||||
return new File([], name)
|
||||
}
|
||||
|
||||
function makeDragEvent(opts: {
|
||||
items: Array<{ kind?: string; entry?: unknown; file?: File | null; throwOnEntry?: boolean }>
|
||||
files?: File[]
|
||||
}): DragEvent {
|
||||
const items = opts.items.map((item) => ({
|
||||
kind: item.kind ?? 'file',
|
||||
webkitGetAsEntry: item.throwOnEntry
|
||||
? () => {
|
||||
throw new Error('entry failed')
|
||||
}
|
||||
: item.entry === undefined
|
||||
? undefined
|
||||
: () => item.entry,
|
||||
getAsFile: () => item.file ?? null,
|
||||
}))
|
||||
return {
|
||||
dataTransfer: {
|
||||
items,
|
||||
files: opts.files ?? [],
|
||||
},
|
||||
} as unknown as DragEvent
|
||||
}
|
||||
|
||||
function relativePath(file: File): string {
|
||||
return (file as File & { webkitRelativePath?: string }).webkitRelativePath || ''
|
||||
}
|
||||
|
||||
test('folder drop enumerates files and sets webkitRelativePath', async () => {
|
||||
const nested = makeFile('day-one.md')
|
||||
const readme = makeFile('README.md')
|
||||
const event = makeDragEvent({
|
||||
items: [{
|
||||
entry: dirEntry('handbook', [
|
||||
fileEntry(readme),
|
||||
dirEntry('onboarding', [fileEntry(nested)]),
|
||||
]),
|
||||
file: phantomDirFile('handbook'),
|
||||
}],
|
||||
files: [phantomDirFile('handbook')],
|
||||
})
|
||||
|
||||
const files = await collectDroppedFiles(event)
|
||||
assert.deepEqual(
|
||||
files.map(f => relativePath(f) || f.name).sort(),
|
||||
['handbook/README.md', 'handbook/onboarding/day-one.md'],
|
||||
)
|
||||
})
|
||||
|
||||
test('empty folder does not fall back to Chrome phantom directory files', async () => {
|
||||
const phantom = phantomDirFile('empty')
|
||||
const event = makeDragEvent({
|
||||
items: [{ entry: dirEntry('empty', []), file: phantom }],
|
||||
files: [phantom],
|
||||
})
|
||||
|
||||
const files = await collectDroppedFiles(event)
|
||||
assert.deepEqual(files, [])
|
||||
})
|
||||
|
||||
test('hidden-only folder does not fall back to phantom directory files', async () => {
|
||||
const phantom = phantomDirFile('.git')
|
||||
const event = makeDragEvent({
|
||||
items: [{
|
||||
entry: dirEntry('.git', [fileEntry(makeFile('HEAD'))]),
|
||||
file: phantom,
|
||||
}],
|
||||
files: [phantom],
|
||||
})
|
||||
|
||||
const files = await collectDroppedFiles(event)
|
||||
assert.deepEqual(files, [])
|
||||
})
|
||||
|
||||
test('hidden files and directories inside a folder are skipped', async () => {
|
||||
const keep = makeFile('notes.md')
|
||||
const event = makeDragEvent({
|
||||
items: [{
|
||||
entry: dirEntry('docs', [
|
||||
fileEntry(keep),
|
||||
fileEntry(makeFile('.env')),
|
||||
dirEntry('.cache', [fileEntry(makeFile('index.json'))]),
|
||||
]),
|
||||
}],
|
||||
files: [phantomDirFile('docs')],
|
||||
})
|
||||
|
||||
const files = await collectDroppedFiles(event)
|
||||
assert.equal(files.length, 1)
|
||||
assert.equal(relativePath(files[0]), 'docs/notes.md')
|
||||
})
|
||||
|
||||
test('top-level files keep an empty webkitRelativePath', async () => {
|
||||
const file = makeFile('report.pdf')
|
||||
const event = makeDragEvent({
|
||||
items: [{ entry: fileEntry(file), file }],
|
||||
files: [file],
|
||||
})
|
||||
|
||||
const files = await collectDroppedFiles(event)
|
||||
assert.equal(files.length, 1)
|
||||
assert.equal(files[0], file)
|
||||
assert.equal(relativePath(files[0]), '')
|
||||
})
|
||||
|
||||
test('falls back to FileList when webkitGetAsEntry is unavailable', async () => {
|
||||
const file = makeFile('report.pdf')
|
||||
const event = makeDragEvent({
|
||||
items: [{ file }],
|
||||
files: [file],
|
||||
})
|
||||
|
||||
const files = await collectDroppedFiles(event)
|
||||
assert.deepEqual(files, [file])
|
||||
})
|
||||
|
||||
test('mixed file and folder drops collect both', async () => {
|
||||
const loose = makeFile('loose.pdf')
|
||||
const nested = makeFile('inside.md')
|
||||
const event = makeDragEvent({
|
||||
items: [
|
||||
{ entry: fileEntry(loose), file: loose },
|
||||
{ entry: dirEntry('docs', [fileEntry(nested)]), file: phantomDirFile('docs') },
|
||||
],
|
||||
files: [loose, phantomDirFile('docs')],
|
||||
})
|
||||
|
||||
const files = await collectDroppedFiles(event)
|
||||
assert.equal(files.length, 2)
|
||||
assert.equal(files[0], loose)
|
||||
assert.equal(relativePath(files[0]), '')
|
||||
assert.equal(relativePath(files[1]), 'docs/inside.md')
|
||||
})
|
||||
|
||||
test('a directory whose reader throws does not revive the phantom file', async () => {
|
||||
const keep = makeFile('keep.md')
|
||||
const badDir = {
|
||||
isFile: false,
|
||||
isDirectory: true,
|
||||
name: 'bad',
|
||||
createReader: () => {
|
||||
throw new Error('no reader')
|
||||
},
|
||||
}
|
||||
const event = makeDragEvent({
|
||||
items: [
|
||||
{ entry: badDir, file: phantomDirFile('bad') },
|
||||
{ entry: fileEntry(keep), file: keep },
|
||||
],
|
||||
files: [phantomDirFile('bad'), keep],
|
||||
})
|
||||
|
||||
const files = await collectDroppedFiles(event)
|
||||
assert.deepEqual(files, [keep])
|
||||
})
|
||||
|
||||
test('a throwing top-level entry does not drop the rest of the batch', async () => {
|
||||
const keep = makeFile('keep.md')
|
||||
const event = makeDragEvent({
|
||||
items: [
|
||||
{ throwOnEntry: true, file: null },
|
||||
{ entry: fileEntry(keep), file: keep },
|
||||
],
|
||||
files: [keep],
|
||||
})
|
||||
|
||||
const files = await collectDroppedFiles(event)
|
||||
assert.deepEqual(files, [keep])
|
||||
})
|
||||
|
||||
test('readEntries is drained across partial batches', async () => {
|
||||
const a = makeFile('a.md')
|
||||
const b = makeFile('b.md')
|
||||
const event = makeDragEvent({
|
||||
items: [{
|
||||
entry: dirEntry('docs', [], [[fileEntry(a)], [fileEntry(b)]]),
|
||||
}],
|
||||
})
|
||||
|
||||
const files = await collectDroppedFiles(event)
|
||||
assert.deepEqual(
|
||||
files.map(f => relativePath(f)).sort(),
|
||||
['docs/a.md', 'docs/b.md'],
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,140 @@
|
||||
// 拖拽文件夹时,Chrome/Edge 会用"假"目录条目(size 0、无扩展名)填充
|
||||
// dataTransfer.files,而非文件夹内的真实文件。只有 webkitGetAsEntry()
|
||||
// 能递归遍历拖入的目录,因此必须优先尝试它,仅在入口 API 不可用时才回退
|
||||
// 到 dataTransfer.files。Firefox 在拖拽文件夹时 dataTransfer.files 为空,
|
||||
// 同样需要走 entry 遍历路径。
|
||||
|
||||
const isHiddenSegment = (segment: string): boolean => segment.startsWith('.')
|
||||
|
||||
export const setRelativePath = (file: File, relativePath: string): void => {
|
||||
try {
|
||||
Object.defineProperty(file, 'webkitRelativePath', {
|
||||
value: relativePath,
|
||||
writable: false,
|
||||
enumerable: true,
|
||||
configurable: true,
|
||||
})
|
||||
} catch {
|
||||
// 旧版 Safari 可能拒绝在 File 上 defineProperty,这些文件
|
||||
// 不会携带相对路径,将以平铺方式上传。
|
||||
}
|
||||
}
|
||||
|
||||
const readAllDirEntries = (reader: { readEntries: Function }): Promise<any[]> => {
|
||||
return new Promise((resolve) => {
|
||||
const collected: any[] = []
|
||||
const readBatch = () => {
|
||||
reader.readEntries((entries: any[]) => {
|
||||
if (!entries || entries.length === 0) {
|
||||
resolve(collected)
|
||||
} else {
|
||||
collected.push(...entries)
|
||||
readBatch()
|
||||
}
|
||||
}, () => resolve(collected))
|
||||
}
|
||||
readBatch()
|
||||
})
|
||||
}
|
||||
|
||||
export const traverseEntry = (entry: any, path: string): Promise<File[]> => {
|
||||
return new Promise((resolve) => {
|
||||
try {
|
||||
if (!entry) {
|
||||
resolve([])
|
||||
return
|
||||
}
|
||||
if (entry.isFile) {
|
||||
if (typeof entry.file !== 'function') {
|
||||
resolve([])
|
||||
return
|
||||
}
|
||||
entry.file((file: File) => {
|
||||
// 仅对目录内的文件设置 webkitRelativePath,与
|
||||
// <input webkitdirectory> 行为一致。顶层拖入的文件
|
||||
// 保持空值,作为普通文件上传。
|
||||
if (path) {
|
||||
const relativePath = `${path}/${file.name}`
|
||||
if (relativePath.split('/').some(isHiddenSegment)) {
|
||||
resolve([])
|
||||
return
|
||||
}
|
||||
setRelativePath(file, relativePath)
|
||||
}
|
||||
resolve([file])
|
||||
}, () => resolve([]))
|
||||
} else if (entry.isDirectory) {
|
||||
const dirPath = path ? `${path}/${entry.name}` : entry.name
|
||||
// 跳过隐藏目录(.git、.DS_Store 等)
|
||||
if (dirPath.split('/').some(isHiddenSegment)) {
|
||||
resolve([])
|
||||
return
|
||||
}
|
||||
if (typeof entry.createReader !== 'function') {
|
||||
resolve([])
|
||||
return
|
||||
}
|
||||
readAllDirEntries(entry.createReader())
|
||||
.then(children => Promise.all(
|
||||
children.map(c => traverseEntry(c, dirPath).catch(() => [] as File[])),
|
||||
))
|
||||
.then(results => resolve(results.flat()))
|
||||
.catch(() => resolve([]))
|
||||
} else {
|
||||
resolve([])
|
||||
}
|
||||
} catch {
|
||||
resolve([])
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export const collectDroppedFiles = async (event: DragEvent): Promise<File[]> => {
|
||||
const dataTransfer = event.dataTransfer
|
||||
const items = dataTransfer?.items ? Array.from(dataTransfer.items) : []
|
||||
// DataTransfer 仅在 drop 同步阶段保证可用,回退列表必须先拷贝。
|
||||
const fallbackFiles = dataTransfer?.files ? Array.from(dataTransfer.files) : []
|
||||
|
||||
if (items.length === 0) {
|
||||
return fallbackFiles
|
||||
}
|
||||
|
||||
const fileItems = items.filter(item => item.kind === 'file')
|
||||
if (fileItems.length === 0) {
|
||||
return fallbackFiles
|
||||
}
|
||||
|
||||
const pairs = fileItems.map(item => {
|
||||
try {
|
||||
return { item, entry: (item as any).webkitGetAsEntry?.() ?? null }
|
||||
} catch {
|
||||
return { item, entry: null }
|
||||
}
|
||||
})
|
||||
const usable = pairs.filter(p => p.entry != null)
|
||||
if (usable.length === 0) {
|
||||
// 浏览器不支持 webkitGetAsEntry,退回已快照的 FileList。
|
||||
return fallbackFiles
|
||||
}
|
||||
|
||||
const results = await Promise.all(usable.map(async ({ item, entry }) => {
|
||||
try {
|
||||
if (entry.isDirectory) {
|
||||
return await traverseEntry(entry, '')
|
||||
}
|
||||
// 顶层文件用 getAsFile:同步、保留空 webkitRelativePath。
|
||||
const file = item.getAsFile()
|
||||
if (file) return [file]
|
||||
return await traverseEntry(entry, '')
|
||||
} catch {
|
||||
if (entry?.isDirectory) return []
|
||||
const file = item.getAsFile()
|
||||
return file ? [file] : []
|
||||
}
|
||||
}))
|
||||
|
||||
// 只要拿到了 FileSystemEntry,就采信遍历结果(包括空数组)。
|
||||
// 空文件夹 / 全是隐藏文件时若再回退 dataTransfer.files,
|
||||
// Chrome/Edge 会再次交出 size 0 的幽灵目录项。
|
||||
return results.flat()
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { runInNewContext } from 'node:vm'
|
||||
import test from 'node:test'
|
||||
import ts from 'typescript'
|
||||
import { ref } from 'vue'
|
||||
|
||||
const source = readFileSync(new URL('./index.vue', import.meta.url), 'utf8')
|
||||
const handlers = ts.transpile(source.slice(
|
||||
source.indexOf('let dragCounter = 0'),
|
||||
source.indexOf('// 组件挂载时添加全局事件监听器'),
|
||||
))
|
||||
|
||||
function fixture(name, { kbId, settingsOpen = false } = {}) {
|
||||
const route = { name, params: { kbId } }
|
||||
const uiStore = { showSettingsModal: settingsOpen }
|
||||
const ismask = ref(false)
|
||||
const messages = []
|
||||
const requests = []
|
||||
const dispatched = []
|
||||
let collected = 0
|
||||
const api = runInNewContext(`${handlers}; ({
|
||||
handleGlobalDragEnter, handleGlobalDragOver, handleGlobalDragLeave, handleGlobalDrop,
|
||||
})`, {
|
||||
route, uiStore, ismask,
|
||||
t: key => key,
|
||||
MessagePlugin: {
|
||||
error: message => messages.push(message),
|
||||
warning: message => messages.push(message),
|
||||
},
|
||||
collectDroppedFiles: async event => { collected++; return event.dataTransfer.files },
|
||||
getKnowledgeBaseById: async id => {
|
||||
requests.push(id)
|
||||
return { data: { summary_model_id: 'chat-model', embedding_model_id: 'embedding-model' } }
|
||||
},
|
||||
CustomEvent: class {
|
||||
constructor(type, options) { this.type = type; this.detail = options.detail }
|
||||
},
|
||||
window: { dispatchEvent: event => dispatched.push(event) },
|
||||
})
|
||||
return { ...api, route, uiStore, ismask, messages, requests, dispatched, collected: () => collected }
|
||||
}
|
||||
|
||||
function fileDrag(types = ['Files']) {
|
||||
return {
|
||||
dataTransfer: { types, files: [{ name: 'skill.zip' }] },
|
||||
defaultPrevented: false,
|
||||
propagationStopped: false,
|
||||
preventDefault() { this.defaultPrevented = true },
|
||||
stopPropagation() { this.propagationStopped = true },
|
||||
}
|
||||
}
|
||||
|
||||
test('skill ZIP drops on settings never enter knowledge upload or consume the local drop', async () => {
|
||||
const f = fixture('settings')
|
||||
for (let attempt = 0; attempt < 3; attempt++) {
|
||||
const event = fileDrag()
|
||||
f.handleGlobalDragEnter(event)
|
||||
f.handleGlobalDragOver(event)
|
||||
await f.handleGlobalDrop(event)
|
||||
assert.equal(f.ismask.value, false)
|
||||
assert.equal(event.propagationStopped, false)
|
||||
assert.deepEqual(f.messages, [])
|
||||
assert.deepEqual(f.requests, [])
|
||||
assert.deepEqual(f.dispatched, [])
|
||||
assert.equal(f.collected(), 0)
|
||||
}
|
||||
})
|
||||
|
||||
test('settings opened over a knowledge base or chat own their file drops', async () => {
|
||||
for (const name of ['knowledgeBaseDetail', 'chat', 'globalCreatChat', 'kbCreatChat']) {
|
||||
const f = fixture(name, { kbId: 'kb-1', settingsOpen: true })
|
||||
const event = fileDrag()
|
||||
f.handleGlobalDragEnter(event)
|
||||
await f.handleGlobalDrop(event)
|
||||
assert.equal(f.ismask.value, false)
|
||||
assert.equal(event.propagationStopped, false)
|
||||
assert.deepEqual(f.messages, [])
|
||||
assert.deepEqual(f.requests, [])
|
||||
assert.deepEqual(f.dispatched, [])
|
||||
assert.equal(f.collected(), 0)
|
||||
}
|
||||
})
|
||||
|
||||
test('unrelated pages and a knowledge route without an ID ignore global upload', async () => {
|
||||
for (const name of ['knowledgeBaseList', 'agentList', 'organizationList', 'knowledgeBaseDetail']) {
|
||||
const f = fixture(name)
|
||||
f.handleGlobalDragEnter(fileDrag())
|
||||
await f.handleGlobalDrop(fileDrag())
|
||||
assert.equal(f.ismask.value, false)
|
||||
assert.deepEqual(f.messages, [])
|
||||
assert.equal(f.collected(), 0)
|
||||
}
|
||||
})
|
||||
|
||||
test('knowledge file drops still validate initialization and reach the knowledge page', async () => {
|
||||
const f = fixture('knowledgeBaseDetail', { kbId: 'kb-1' })
|
||||
const event = fileDrag()
|
||||
f.handleGlobalDragEnter(event)
|
||||
assert.equal(f.ismask.value, true)
|
||||
await f.handleGlobalDrop(event)
|
||||
assert.equal(f.ismask.value, false)
|
||||
assert.deepEqual(f.requests, ['kb-1'])
|
||||
assert.equal(f.dispatched[0].type, 'weknora:knowledge-file-drop')
|
||||
assert.equal(f.dispatched[0].detail.kbId, 'kb-1')
|
||||
assert.equal(f.dispatched[0].detail.files, event.dataTransfer.files)
|
||||
})
|
||||
|
||||
test('chat file drops still dispatch attachments without knowledge initialization', async () => {
|
||||
for (const name of ['chat', 'globalCreatChat', 'kbCreatChat']) {
|
||||
const f = fixture(name, { kbId: 'kb-1' })
|
||||
const event = fileDrag()
|
||||
await f.handleGlobalDrop(event)
|
||||
assert.deepEqual(f.requests, [])
|
||||
assert.deepEqual(f.messages, [])
|
||||
assert.equal(f.dispatched[0].type, 'weknora:chat-file-drop')
|
||||
assert.equal(f.dispatched[0].detail.files, event.dataTransfer.files)
|
||||
}
|
||||
})
|
||||
|
||||
test('in-app text drags do not activate upload', async () => {
|
||||
const f = fixture('knowledgeBaseDetail', { kbId: 'kb-1' })
|
||||
const event = fileDrag(['text/plain'])
|
||||
f.handleGlobalDragEnter(event)
|
||||
await f.handleGlobalDrop(event)
|
||||
assert.equal(event.defaultPrevented, false)
|
||||
assert.equal(f.ismask.value, false)
|
||||
assert.equal(f.collected(), 0)
|
||||
})
|
||||
|
||||
test('opening settings during a drag clears the global upload mask', async () => {
|
||||
const f = fixture('chat')
|
||||
f.handleGlobalDragEnter(fileDrag())
|
||||
assert.equal(f.ismask.value, true)
|
||||
f.uiStore.showSettingsModal = true
|
||||
f.handleGlobalDragOver(fileDrag())
|
||||
assert.equal(f.ismask.value, false)
|
||||
await f.handleGlobalDrop(fileDrag())
|
||||
assert.deepEqual(f.dispatched, [])
|
||||
})
|
||||
@@ -0,0 +1,293 @@
|
||||
<template>
|
||||
<div class="main" ref="dropzone" :style="{ '--sidebar-width': `${uiStore.sidebarDisplayWidth}px` }">
|
||||
<Menu></Menu>
|
||||
<div v-if="isRouterAlive" class="platform-route-outlet">
|
||||
<RouterView />
|
||||
</div>
|
||||
<!-- WeKnora 助手:停靠时作为布局右栏挤压页面,悬浮时浮在页面上;都不加遮罩,
|
||||
跨页面保留会话,从侧栏、右侧边缘按钮或命令面板唤出(设置里可选) -->
|
||||
<AssistantPanel />
|
||||
<AssistantLauncher />
|
||||
<AssistantPageBridge />
|
||||
<div class="upload-mask" v-show="ismask">
|
||||
<UploadMask></UploadMask>
|
||||
</div>
|
||||
<!-- 全局设置模态框,供所有 platform 子路由使用 -->
|
||||
<Settings />
|
||||
<!-- 全局命令面板 (⌘K),随 platform 路由存活 -->
|
||||
<GlobalCommandPalette />
|
||||
<!-- 知识库文件上传进度浮层:上传队列放在 store 里,切换页面不中断 -->
|
||||
<UploadTasksPanel />
|
||||
<!-- 带遮罩层的新手引导:首次进入自动开启,可从用户菜单顶部昵称旁帮助按钮重新打开 -->
|
||||
<NewUserGuide />
|
||||
</div>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import Menu from '@/components/menu.vue'
|
||||
import { ref, onMounted, onUnmounted, nextTick, provide, watch } from 'vue';
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import UploadMask from '@/components/upload-mask.vue'
|
||||
import Settings from '@/views/settings/Settings.vue'
|
||||
import GlobalCommandPalette from '@/components/GlobalCommandPalette.vue'
|
||||
import AssistantPanel from '@/components/assistant/AssistantPanel.vue'
|
||||
import AssistantLauncher from '@/components/assistant/AssistantLauncher.vue'
|
||||
import AssistantPageBridge from '@/components/assistant/AssistantPageBridge.vue'
|
||||
import UploadTasksPanel from '@/components/upload-tasks/UploadTasksPanel.vue'
|
||||
import NewUserGuide from '@/components/NewUserGuide.vue'
|
||||
import { useCommandPaletteStore } from '@/stores/commandPalette'
|
||||
import { useChatResourcesStore } from '@/stores/chatResources'
|
||||
import { useUIStore } from '@/stores/ui'
|
||||
import { getKnowledgeBaseById } from '@/api/knowledge-base/index'
|
||||
import { MessagePlugin } from 'tdesign-vue-next'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { collectDroppedFiles } from './collectDroppedFiles'
|
||||
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const commandPaletteStore = useCommandPaletteStore();
|
||||
const uiStore = useUIStore();
|
||||
let ismask = ref(false)
|
||||
const { t } = useI18n();
|
||||
|
||||
const isRouterAlive = ref(true)
|
||||
const reloadApp = () => {
|
||||
isRouterAlive.value = false
|
||||
nextTick(() => {
|
||||
isRouterAlive.value = true
|
||||
})
|
||||
}
|
||||
provide('app:reload', reloadApp)
|
||||
|
||||
// 仅在 Wails 桌面端运行时拦截 Cmd/Ctrl+R:
|
||||
// 桌面端没有浏览器地址栏,整页重载会白屏,所以用前端软刷新替代。
|
||||
// 浏览器(含 Web 版 / 非 Lite 部署)里不拦截,交给浏览器做真正的整页刷新,
|
||||
// 否则会出现左侧菜单、全局设置、Pinia store 等不随"刷新"一起重置的问题。
|
||||
// @ts-ignore
|
||||
const isWailsDesktop = typeof window !== 'undefined' && !!(window as any).runtime?.EventsOn
|
||||
|
||||
const handleGlobalKeyDown = (e: KeyboardEvent) => {
|
||||
if (!isWailsDesktop) return
|
||||
if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'r') {
|
||||
e.preventDefault()
|
||||
reloadApp()
|
||||
}
|
||||
}
|
||||
|
||||
// 用于跟踪拖拽进入/离开的计数器,解决子元素触发 dragleave 的问题
|
||||
let dragCounter = 0;
|
||||
|
||||
// 获取当前知识库ID
|
||||
const getCurrentKbId = (): string | null => {
|
||||
return (route.params as any)?.kbId as string || null
|
||||
}
|
||||
|
||||
const CHAT_DROP_ROUTE_NAMES = new Set(['chat', 'globalCreatChat', 'kbCreatChat']);
|
||||
|
||||
const isChatDropRoute = () => {
|
||||
return CHAT_DROP_ROUTE_NAMES.has(String(route.name || ''));
|
||||
}
|
||||
|
||||
// 检查知识库初始化状态
|
||||
const checkKnowledgeBaseInitialization = async (): Promise<boolean> => {
|
||||
const currentKbId = getCurrentKbId();
|
||||
|
||||
if (!currentKbId) {
|
||||
MessagePlugin.error(t('knowledgeBase.missingId'));
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
const kbResponse = await getKnowledgeBaseById(currentKbId);
|
||||
const kb = kbResponse.data;
|
||||
|
||||
if (!kb.summary_model_id) {
|
||||
MessagePlugin.warning(t('knowledgeBase.notInitialized'));
|
||||
return false;
|
||||
}
|
||||
const strategy = kb.indexing_strategy;
|
||||
const needsEmbedding = !strategy || strategy.vector_enabled || strategy.keyword_enabled;
|
||||
if (needsEmbedding && !kb.embedding_model_id) {
|
||||
MessagePlugin.warning(t('knowledgeBase.notInitialized'));
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
} catch (error) {
|
||||
MessagePlugin.error(t('knowledgeBase.getInfoFailed'));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 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 shouldHandleGlobalFileDrag = (event: DragEvent): boolean => {
|
||||
if (!isFileDrag(event)) return false;
|
||||
// Keep the browser from opening dropped files, even outside upload pages.
|
||||
event.preventDefault();
|
||||
// Settings and its teleported skill drawers own their uploads. This runs
|
||||
// in document capture, before a local drop handler can stop propagation.
|
||||
const enabled = !uiStore.showSettingsModal && (
|
||||
isChatDropRoute() || (route.name === 'knowledgeBaseDetail' && !!getCurrentKbId())
|
||||
);
|
||||
if (!enabled) {
|
||||
dragCounter = 0;
|
||||
ismask.value = false;
|
||||
}
|
||||
return enabled;
|
||||
}
|
||||
|
||||
// 全局拖拽事件处理
|
||||
const handleGlobalDragEnter = (event: DragEvent) => {
|
||||
if (!shouldHandleGlobalFileDrag(event)) return;
|
||||
dragCounter++;
|
||||
if (event.dataTransfer) {
|
||||
event.dataTransfer.effectAllowed = 'all';
|
||||
}
|
||||
ismask.value = true;
|
||||
}
|
||||
|
||||
const handleGlobalDragOver = (event: DragEvent) => {
|
||||
if (!shouldHandleGlobalFileDrag(event)) return;
|
||||
if (event.dataTransfer) {
|
||||
event.dataTransfer.dropEffect = 'copy';
|
||||
}
|
||||
}
|
||||
|
||||
const handleGlobalDragLeave = (event: DragEvent) => {
|
||||
if (!shouldHandleGlobalFileDrag(event)) return;
|
||||
dragCounter--;
|
||||
if (dragCounter === 0) {
|
||||
ismask.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
const handleGlobalDrop = async (event: DragEvent) => {
|
||||
if (!shouldHandleGlobalFileDrag(event)) return;
|
||||
dragCounter = 0;
|
||||
ismask.value = false;
|
||||
|
||||
const droppedFiles = await collectDroppedFiles(event);
|
||||
if (droppedFiles.length === 0) {
|
||||
MessagePlugin.warning(t('knowledgeBase.dragFileNotText'));
|
||||
return;
|
||||
}
|
||||
|
||||
if (isChatDropRoute()) {
|
||||
event.stopPropagation();
|
||||
window.dispatchEvent(new CustomEvent('weknora:chat-file-drop', {
|
||||
detail: { files: droppedFiles }
|
||||
}));
|
||||
return;
|
||||
}
|
||||
|
||||
const isInitialized = await checkKnowledgeBaseInitialization();
|
||||
if (!isInitialized) {
|
||||
return;
|
||||
}
|
||||
|
||||
window.dispatchEvent(new CustomEvent('weknora:knowledge-file-drop', {
|
||||
detail: { kbId: getCurrentKbId(), files: droppedFiles }
|
||||
}));
|
||||
}
|
||||
|
||||
// 组件挂载时添加全局事件监听器
|
||||
onMounted(() => {
|
||||
document.addEventListener('dragenter', handleGlobalDragEnter, true);
|
||||
document.addEventListener('dragover', handleGlobalDragOver, true);
|
||||
document.addEventListener('dragleave', handleGlobalDragLeave, true);
|
||||
document.addEventListener('drop', handleGlobalDrop, true);
|
||||
if (isWailsDesktop) {
|
||||
window.addEventListener('keydown', handleGlobalKeyDown);
|
||||
// @ts-ignore
|
||||
window.runtime.EventsOn('app:reload', () => {
|
||||
reloadApp()
|
||||
})
|
||||
}
|
||||
// 支持通过 URL 查询参数打开全局命令面板,例如旧路径
|
||||
// /platform/knowledge-search?q=foo 重定向后携带 ?cmdk=foo
|
||||
maybeOpenCmdkFromRoute()
|
||||
// 后台预取对话输入栏资源,进入 creatChat / chat 时复用缓存
|
||||
void useChatResourcesStore().prefetchChatInput()
|
||||
});
|
||||
|
||||
// 监听路由变化,兼容 SPA 内部跳转时的 ?cmdk= 参数
|
||||
watch(() => route.query.cmdk, () => {
|
||||
maybeOpenCmdkFromRoute()
|
||||
})
|
||||
|
||||
function maybeOpenCmdkFromRoute() {
|
||||
if (!('cmdk' in route.query)) return
|
||||
const q = String(route.query.cmdk ?? '')
|
||||
commandPaletteStore.openPalette(q)
|
||||
// 清除 query,避免回退/刷新时反复触发
|
||||
const newQuery = { ...route.query }
|
||||
delete (newQuery as any).cmdk
|
||||
router.replace({ path: route.path, query: newQuery, hash: route.hash })
|
||||
}
|
||||
|
||||
// 组件卸载时移除全局事件监听器
|
||||
onUnmounted(() => {
|
||||
document.removeEventListener('dragenter', handleGlobalDragEnter, true);
|
||||
document.removeEventListener('dragover', handleGlobalDragOver, true);
|
||||
document.removeEventListener('dragleave', handleGlobalDragLeave, true);
|
||||
document.removeEventListener('drop', handleGlobalDrop, true);
|
||||
if (isWailsDesktop) {
|
||||
window.removeEventListener('keydown', handleGlobalKeyDown);
|
||||
// @ts-ignore
|
||||
if (window.runtime?.EventsOff) {
|
||||
// @ts-ignore
|
||||
window.runtime.EventsOff('app:reload')
|
||||
}
|
||||
}
|
||||
dragCounter = 0;
|
||||
});
|
||||
</script>
|
||||
<style lang="less">
|
||||
.main {
|
||||
display: flex;
|
||||
align-items: stretch;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
min-width: 600px;
|
||||
min-height: 0;
|
||||
/* 统一整页背景,让左侧菜单与右侧内容区视觉连贯 */
|
||||
background: var(--td-bg-color-container);
|
||||
}
|
||||
|
||||
/* 右侧路由区:占满剩余宽度与整列高度,并把 min-height:0 传给子页面以便内部 flex 滚动 */
|
||||
.platform-route-outlet {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.upload-mask {
|
||||
background-color: rgba(255, 255, 255, 0.8);
|
||||
position: fixed;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
z-index: 999;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
img {
|
||||
-webkit-user-drag: none;
|
||||
-khtml-user-drag: none;
|
||||
-moz-user-drag: none;
|
||||
-o-user-drag: none;
|
||||
user-drag: none;
|
||||
}
|
||||
</style>
|
||||
Reference in new issue
Block a user