chore: 项目基线(基于 WeKnora 定制版,整理文件忽略规则)
This commit is contained in:
commit
9097ee699d
5769 files changed
+1446466
No files matched your search
@@ -0,0 +1,215 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { createRequire } from 'node:module'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { runInNewContext } from 'node:vm'
|
||||
import test from 'node:test'
|
||||
import { compileScript, parse } from '@vue/compiler-sfc'
|
||||
import ts from 'typescript'
|
||||
import { createRenderer, h, nextTick, reactive } from 'vue'
|
||||
import * as imageProcessingConfig from '../../utils/imageProcessingConfig'
|
||||
|
||||
const require = createRequire(import.meta.url)
|
||||
const filename = fileURLToPath(new URL('./ImagePipelineSettings.vue', import.meta.url))
|
||||
const { descriptor } = parse(readFileSync(filename, 'utf8'), { filename })
|
||||
const script = compileScript(descriptor, { id: 'image-pipeline-settings-test' }).content
|
||||
.replace('__expose();', '')
|
||||
.replace('return __returned__', '__expose(__returned__); return __returned__')
|
||||
const compiled = ts.transpileModule(script, {
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 },
|
||||
}).outputText
|
||||
|
||||
const violation = { message_key: 'imagePipeline.errors.noActionEnabled', field: 'caption_enabled' }
|
||||
const flushUpdates = async () => {
|
||||
await new Promise<void>((resolve) => setImmediate(resolve))
|
||||
await nextTick()
|
||||
}
|
||||
|
||||
type ValidationRequest = {
|
||||
pipelineId: string
|
||||
params: Record<string, unknown>
|
||||
resolve: (value: { violations: typeof violation[] }) => void
|
||||
reject: (reason: Error) => void
|
||||
}
|
||||
|
||||
async function fixture() {
|
||||
const requests: ValidationRequest[] = []
|
||||
const timers = new Map<number, () => void>()
|
||||
let timerID = 0
|
||||
const exports: any = {}
|
||||
runInNewContext(compiled, {
|
||||
exports, console: { ...console, error() {} },
|
||||
setTimeout(callback: () => void) { timers.set(++timerID, callback); return timerID },
|
||||
clearTimeout(id: number) { timers.delete(id) },
|
||||
require(name: string) {
|
||||
if (name === 'vue') return require('vue')
|
||||
if (name === 'vue-i18n') return { useI18n: () => ({ t: (key: string) => key, te: () => false }) }
|
||||
if (name === '@/utils/imageProcessingConfig') return imageProcessingConfig
|
||||
if (name === '@/api/knowledge-base') return {
|
||||
fetchImagePipelines: async () => [{ id: 'default', fields: [] }, { id: 'smartocr', fields: [] }],
|
||||
validateImagePipelines: (pipelineId: string, params: Record<string, unknown>) =>
|
||||
new Promise((resolve, reject) => requests.push({ pipelineId, params, resolve, reject })),
|
||||
}
|
||||
throw new Error(`Unexpected import: ${name}`)
|
||||
},
|
||||
})
|
||||
exports.default.render = () => null
|
||||
const renderer = createRenderer<any, any>({
|
||||
createElement: () => ({}), createText: () => ({}), createComment: () => ({}),
|
||||
insert() {}, remove() {}, setElementText() {}, setText() {}, patchProp() {},
|
||||
parentNode: () => null, nextSibling: () => null,
|
||||
})
|
||||
// The defaults a pipeline declared, each already stored under its own
|
||||
// pipeline's slot — the shape the panel reads and writes.
|
||||
const props = reactive({
|
||||
pipelineId: 'default',
|
||||
params: { 'default.caption_enabled': false, 'default.ocr_enabled': false } as Record<string, unknown>,
|
||||
})
|
||||
const emitted: boolean[] = []
|
||||
let vm: any
|
||||
const app = renderer.createApp({ setup: () => () => h(exports.default, {
|
||||
...props,
|
||||
ref: (value: any) => { vm = value },
|
||||
'onUpdate:params': (params: Record<string, unknown>) => { props.params = params },
|
||||
'onUpdate:pipelineId': (pipelineId: string) => { props.pipelineId = pipelineId },
|
||||
'onUpdate:invalid': (invalid: boolean) => { emitted.push(invalid) },
|
||||
}) })
|
||||
app.mount({})
|
||||
await flushUpdates()
|
||||
return {
|
||||
requests, timers, emitted,
|
||||
get invalid() { return emitted.at(-1) },
|
||||
get validationFailed() { return vm.validationFailed },
|
||||
get params() { return props.params as Record<string, unknown> },
|
||||
async setCaption(enabled: boolean) { vm.onParamChange('caption_enabled', enabled); await flushUpdates() },
|
||||
async setPipeline(id: string) { vm.onPipelineChange(id); await flushUpdates() },
|
||||
async validate() {
|
||||
for (const [id, callback] of [...timers]) { timers.delete(id); callback() }
|
||||
await flushUpdates()
|
||||
},
|
||||
dispose: () => app.unmount(),
|
||||
}
|
||||
}
|
||||
|
||||
test('a late invalid response cannot block saving newer valid parameters', async () => {
|
||||
const f = await fixture()
|
||||
try {
|
||||
await f.validate()
|
||||
await f.setCaption(true)
|
||||
await f.validate()
|
||||
assert.equal(f.requests.length, 2)
|
||||
assert.equal(f.requests[0].params['default.caption_enabled'], false)
|
||||
assert.equal(f.requests[1].params['default.caption_enabled'], true)
|
||||
f.requests[1].resolve({ violations: [] })
|
||||
await flushUpdates()
|
||||
f.requests[0].resolve({ violations: [violation] })
|
||||
await flushUpdates()
|
||||
assert.equal(f.invalid, false)
|
||||
} finally { f.dispose() }
|
||||
})
|
||||
|
||||
for (const response of ['valid', 'error'] as const) {
|
||||
test(`a stale ${response} response cannot erase the current invalid verdict`, async () => {
|
||||
const f = await fixture()
|
||||
try {
|
||||
await f.setCaption(true)
|
||||
await f.validate()
|
||||
await f.setCaption(false)
|
||||
await f.validate()
|
||||
f.requests[1].resolve({ violations: [violation] })
|
||||
await flushUpdates()
|
||||
assert.equal(f.invalid, true)
|
||||
if (response === 'valid') f.requests[0].resolve({ violations: [] })
|
||||
else f.requests[0].reject(new Error('old request failed'))
|
||||
await flushUpdates()
|
||||
assert.equal(f.invalid, true)
|
||||
assert.equal(f.validationFailed, false)
|
||||
} finally { f.dispose() }
|
||||
})
|
||||
}
|
||||
|
||||
test('parameter changes invalidate responses even before the next debounce fires', async () => {
|
||||
const f = await fixture()
|
||||
try {
|
||||
await f.validate()
|
||||
await f.setCaption(true)
|
||||
assert.equal(f.requests.length, 1)
|
||||
f.requests[0].resolve({ violations: [violation] })
|
||||
await flushUpdates()
|
||||
assert.equal(f.invalid, false)
|
||||
} finally { f.dispose() }
|
||||
})
|
||||
|
||||
test('switching pipelines clears the previous verdict and keeps the earlier pick\'s parameters', async () => {
|
||||
const f = await fixture()
|
||||
try {
|
||||
await f.validate()
|
||||
f.requests[0].resolve({ violations: [violation] })
|
||||
await flushUpdates()
|
||||
assert.equal(f.invalid, true)
|
||||
await f.setCaption(true)
|
||||
await f.validate()
|
||||
await f.setPipeline('smartocr')
|
||||
assert.equal(f.invalid, false)
|
||||
await f.validate()
|
||||
assert.equal(f.requests[2].pipelineId, 'smartocr')
|
||||
// The previous pipeline's answers stay: each pipeline reads its own slot,
|
||||
// so there is nothing to clear and switching back finds what was set.
|
||||
assert.deepEqual({ ...f.requests[2].params }, {
|
||||
'default.caption_enabled': true,
|
||||
'default.ocr_enabled': false,
|
||||
})
|
||||
f.requests[2].resolve({ violations: [] })
|
||||
f.requests[1].resolve({ violations: [violation] })
|
||||
await flushUpdates()
|
||||
assert.equal(f.invalid, false)
|
||||
} finally { f.dispose() }
|
||||
})
|
||||
|
||||
test('a control writes under the slot of the pipeline that declared it', async () => {
|
||||
// Regression: the panel used to write bare keys, so two pipelines that
|
||||
// declare the same field key read each other's value.
|
||||
const f = await fixture()
|
||||
try {
|
||||
await f.setPipeline('smartocr')
|
||||
await f.setCaption(false)
|
||||
// Spread into a plain object: the panel builds its params inside the
|
||||
// sandbox realm, whose prototypes strict deepEqual will not accept.
|
||||
assert.deepEqual({ ...f.params }, {
|
||||
'default.caption_enabled': false,
|
||||
'default.ocr_enabled': false,
|
||||
'smartocr.caption_enabled': false,
|
||||
})
|
||||
} finally { f.dispose() }
|
||||
})
|
||||
|
||||
test('unmount cancels scheduled validation and ignores in-flight results', async () => {
|
||||
const f = await fixture()
|
||||
await f.validate()
|
||||
await f.setCaption(true)
|
||||
const emitted = [...f.emitted]
|
||||
f.dispose()
|
||||
assert.equal(f.timers.size, 0)
|
||||
f.requests[0].resolve({ violations: [violation] })
|
||||
await flushUpdates()
|
||||
assert.deepEqual(f.emitted, emitted)
|
||||
await f.validate()
|
||||
assert.equal(f.requests.length, 1)
|
||||
})
|
||||
|
||||
test('a current validation failure still permits saving and is cleared by the next result', async () => {
|
||||
const f = await fixture()
|
||||
try {
|
||||
await f.validate()
|
||||
f.requests[0].reject(new Error('network unavailable'))
|
||||
await flushUpdates()
|
||||
assert.equal(f.invalid, false)
|
||||
assert.equal(f.validationFailed, true)
|
||||
await f.setCaption(true)
|
||||
await f.validate()
|
||||
f.requests[1].resolve({ violations: [] })
|
||||
await flushUpdates()
|
||||
assert.equal(f.validationFailed, false)
|
||||
assert.equal(f.invalid, false)
|
||||
} finally { f.dispose() }
|
||||
})
|
||||
@@ -0,0 +1,547 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* The image-pipeline panel.
|
||||
*
|
||||
* The list of pipelines and of their fields comes from the backend
|
||||
* (GET /api/v1/image-pipelines), so this component names no pipeline and knows
|
||||
* no field: adding one there arrives here as a new option and a new control.
|
||||
* A field is rendered by its declared type, and its label falls back to the
|
||||
* backend's own wording when this locale has nothing for it.
|
||||
*
|
||||
* The panel renders those fields in the order the pipeline declared them, and
|
||||
* that order is part of what a pipeline decides about itself. Nothing here may
|
||||
* sort, group or reorder them — see the note above the field loop.
|
||||
*/
|
||||
import { computed, onBeforeUnmount, onMounted, ref, useSlots, watch } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import {
|
||||
fetchImagePipelines,
|
||||
validateImagePipelines,
|
||||
type ImagePipelineField,
|
||||
type ImagePipelineSpec,
|
||||
type ImagePipelineViolation,
|
||||
} from '@/api/knowledge-base'
|
||||
|
||||
const props = defineProps<{
|
||||
/** The selected pipeline id. */
|
||||
pipelineId: string
|
||||
/**
|
||||
* Every pipeline's private tunables, stored under the slot of the pipeline
|
||||
* that owns each one. A missing key reads the field's declared default, so a
|
||||
* pipeline the operator has never configured still renders real switches.
|
||||
*/
|
||||
params: Record<string, unknown>
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:pipelineId': [value: string]
|
||||
'update:params': [value: Record<string, unknown>]
|
||||
/** Turned on while the current pick is configured to do nothing at all. */
|
||||
'update:invalid': [value: boolean]
|
||||
}>()
|
||||
|
||||
import { pipelineParamKey, readPipelineParam } from '@/utils/imageProcessingConfig'
|
||||
|
||||
const { t, te } = useI18n()
|
||||
|
||||
const pipelines = ref<ImagePipelineSpec[]>([])
|
||||
const loading = ref(false)
|
||||
const loadError = ref('')
|
||||
|
||||
/** The pipeline currently selected, if the registry still carries it. */
|
||||
const current = computed<ImagePipelineSpec | undefined>(() =>
|
||||
pipelines.value.find((pipeline) => pipeline.id === props.pipelineId),
|
||||
)
|
||||
|
||||
/** Its fields, in the order the backend declared them. */
|
||||
const fields = computed<ImagePipelineField[]>(() => current.value?.fields ?? [])
|
||||
|
||||
/**
|
||||
* The run of the panel a field belongs to. A pipeline declares its fields in
|
||||
* three runs — standing switches, advanced switches, notes — and the empty
|
||||
* group is the first of them, so a standing switch says nothing about groups.
|
||||
*/
|
||||
function fieldGroup(field: ImagePipelineField): string {
|
||||
return field.group || 'switch'
|
||||
}
|
||||
|
||||
// Each run keeps the order it was declared in: filter preserves it, and that is
|
||||
// the whole reason nothing here may re-sort (see the note in the template).
|
||||
const standingFields = computed(() => fields.value.filter((f) => fieldGroup(f) === 'switch'))
|
||||
const advancedFields = computed(() => fields.value.filter((f) => fieldGroup(f) === 'advanced'))
|
||||
const noteFields = computed(() => fields.value.filter((f) => fieldGroup(f) === 'note'))
|
||||
|
||||
// Both folded runs start closed: a pipeline declares them to keep them out of
|
||||
// the way rather than to lengthen the panel.
|
||||
const advancedOpen = ref(false)
|
||||
const notesOpen = ref(false)
|
||||
|
||||
// The notes run also carries whatever the host hands over through the slot, and
|
||||
// a pipeline that declares no note of its own must still show that — the smart
|
||||
// pipeline's attribute dictionary is the case it exists for.
|
||||
const slots = useSlots()
|
||||
const hasNotesSlot = computed(() => Boolean(slots.notes))
|
||||
|
||||
/**
|
||||
* The wording of one value of an enum field. A pipeline that wants its options
|
||||
* read as words declares them under the field's own overlay path, so a fourth
|
||||
* mode needs no frontend change; without one the stored value is shown as it is.
|
||||
*/
|
||||
function enumOptionLabel(field: ImagePipelineField, option: string): string {
|
||||
const key = `${fieldKey(field, 'options')}.${option}`
|
||||
return te(key) ? t(key) : option
|
||||
}
|
||||
|
||||
// Every rule the selected pipeline breaks, reported by the backend and in the
|
||||
// backend's own terms: each violation carries the i18n key of its own wording
|
||||
// and the name of the control to point at. Nothing here decides what is
|
||||
// forbidden — the rules travel with the spec, so adding one to a pipeline needs
|
||||
// no change to this file, and a pipeline whose actions are not the user's to
|
||||
// switch off declares none and can never land in this list.
|
||||
const violations = ref<ImagePipelineViolation[]>([])
|
||||
const validationFailed = ref(false)
|
||||
|
||||
const invalid = computed<boolean>(() => violations.value.length > 0)
|
||||
|
||||
watch(invalid, (value) => emit('update:invalid', value), { immediate: true })
|
||||
|
||||
/** The debounce keeps a dribbled change from posting on every keystroke. */
|
||||
let validationTimer: ReturnType<typeof setTimeout> | undefined
|
||||
let validationGeneration = 0
|
||||
let disposed = false
|
||||
|
||||
function scheduleValidation() {
|
||||
if (disposed) return
|
||||
// Invalidate in-flight responses as soon as the inputs change, including
|
||||
// the interval before the next debounced request starts.
|
||||
validationGeneration++
|
||||
violations.value = []
|
||||
validationFailed.value = false
|
||||
if (validationTimer) clearTimeout(validationTimer)
|
||||
validationTimer = setTimeout(() => void validate(), 300)
|
||||
}
|
||||
|
||||
async function validate() {
|
||||
if (disposed) return
|
||||
const generation = ++validationGeneration
|
||||
const spec = current.value
|
||||
if (!spec) {
|
||||
violations.value = []
|
||||
return
|
||||
}
|
||||
try {
|
||||
const result = await validateImagePipelines(spec.id, props.params ?? {})
|
||||
if (generation !== validationGeneration) return
|
||||
violations.value = result.violations ?? []
|
||||
validationFailed.value = false
|
||||
} catch (error) {
|
||||
if (generation !== validationGeneration) return
|
||||
// An unreachable check is not a verdict. The panel must not block saving on
|
||||
// a network hiccup, and the save path asks the backend again anyway.
|
||||
violations.value = []
|
||||
validationFailed.value = true
|
||||
console.error('[ImagePipelineSettings] validation request failed', error)
|
||||
}
|
||||
}
|
||||
|
||||
watch(() => [props.pipelineId, props.params], scheduleValidation)
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
disposed = true
|
||||
validationGeneration++
|
||||
if (validationTimer) clearTimeout(validationTimer)
|
||||
})
|
||||
|
||||
/**
|
||||
* A field's declared default. The backend sends JSON, so an unset key arrives
|
||||
* as undefined; the switch below must still read a value rather than a blank.
|
||||
*/
|
||||
function defaultValue(field: ImagePipelineField): unknown {
|
||||
return field.default ?? false
|
||||
}
|
||||
|
||||
function paramValue(field: ImagePipelineField): unknown {
|
||||
const own = readPipelineParam(props.params, current.value?.id ?? '', field.key)
|
||||
return own === undefined || own === null ? defaultValue(field) : own
|
||||
}
|
||||
|
||||
/** i18n overlay key for one field of one pipeline. */
|
||||
function fieldKey(field: ImagePipelineField, part: 'label' | 'description' | 'options'): string {
|
||||
return `imagePipeline.${current.value?.id ?? ''}.${field.key}.${part}`
|
||||
}
|
||||
|
||||
function fieldLabel(field: ImagePipelineField): string {
|
||||
const key = fieldKey(field, 'label')
|
||||
return te(key) ? t(key) : field.label || field.key
|
||||
}
|
||||
|
||||
function fieldDescription(field: ImagePipelineField): string {
|
||||
const key = fieldKey(field, 'description')
|
||||
return te(key) ? t(key) : field.description ?? ''
|
||||
}
|
||||
|
||||
function pipelineName(pipeline: ImagePipelineSpec): string {
|
||||
const key = `imagePipeline.${pipeline.id}.name`
|
||||
return te(key) ? t(key) : pipeline.name
|
||||
}
|
||||
|
||||
/** How the selected pipeline works, shown under the pick. */
|
||||
function pipelineDescription(pipeline: ImagePipelineSpec): string {
|
||||
const key = `imagePipeline.${pipeline.id}.description`
|
||||
return te(key) ? t(key) : pipeline.description ?? ''
|
||||
}
|
||||
|
||||
function onPipelineChange(value: string) {
|
||||
// The parameters stay: they are stored per pipeline, so switching back finds
|
||||
// the choice that was made here last time. Clearing them used to lose it.
|
||||
emit('update:pipelineId', value)
|
||||
}
|
||||
|
||||
function onParamChange(key: string, value: unknown) {
|
||||
// Stored under the pipeline's own slot, so two pipelines that declare the same
|
||||
// field key never read each other's value, and switching back keeps both.
|
||||
emit('update:params', { ...props.params, [pipelineParamKey(current.value?.id ?? '', key)]: value })
|
||||
}
|
||||
|
||||
async function load() {
|
||||
loading.value = true
|
||||
loadError.value = ''
|
||||
try {
|
||||
pipelines.value = await fetchImagePipelines()
|
||||
} catch (error) {
|
||||
loadError.value = error instanceof Error ? error.message : String(error)
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
// The registry arrived, so the current pick can now be checked against it;
|
||||
// before that there was no rule to check it against.
|
||||
scheduleValidation()
|
||||
}
|
||||
|
||||
onMounted(load)
|
||||
// A dialog may mount before the KB it edits is loaded, so the selection can
|
||||
// arrive after the registry it must be validated against.
|
||||
watch(() => props.pipelineId, () => {
|
||||
if (!loading.value && pipelines.value.length === 0) load()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="image-pipeline-settings">
|
||||
<div v-if="loading" class="image-pipeline-hint">
|
||||
{{ $t('knowledgeEditor.advanced.multimodal.imagePipelineLoading') }}
|
||||
</div>
|
||||
|
||||
<div v-else-if="loadError" class="image-pipeline-hint image-pipeline-hint--error">
|
||||
{{ $t('knowledgeEditor.advanced.multimodal.imagePipelineLoadError') }}:{{ loadError }}
|
||||
</div>
|
||||
|
||||
<template v-else>
|
||||
<!-- Section 1 of 3: which pipeline, and how it differs from the others. -->
|
||||
<div class="image-pipeline-section">
|
||||
<div class="image-pipeline-row">
|
||||
<div class="image-pipeline-info">
|
||||
<label>{{ $t('knowledgeEditor.advanced.multimodal.imagePipelineLabel') }}</label>
|
||||
</div>
|
||||
<div class="image-pipeline-control">
|
||||
<t-select
|
||||
:value="pipelineId"
|
||||
:placeholder="$t('knowledgeEditor.advanced.multimodal.imagePipelinePlaceholder')"
|
||||
@change="onPipelineChange"
|
||||
>
|
||||
<t-option
|
||||
v-for="pipeline in pipelines"
|
||||
:key="pipeline.id"
|
||||
:value="pipeline.id"
|
||||
:label="pipelineName(pipeline)"
|
||||
/>
|
||||
</t-select>
|
||||
</div>
|
||||
</div>
|
||||
<p v-if="current" class="image-pipeline-desc">{{ pipelineDescription(current) }}</p>
|
||||
</div>
|
||||
|
||||
<div v-if="standingFields.length" class="image-pipeline-divider" />
|
||||
|
||||
<!-- Section 2 of 3: the standing switches, each with its own description
|
||||
beside it. Section 3 (the observation attributes) belongs to the host
|
||||
dialog, which is where the attribute registry is read.
|
||||
|
||||
The pipeline declares its fields in three runs — standing switches,
|
||||
advanced switches, notes — and this panel renders them as three
|
||||
places: here, the folded "advanced" block below, and the folded
|
||||
"notes" block under that. A run the pipeline does not declare renders
|
||||
nothing at all: no rows, no fold title, and no rule of its own, so a
|
||||
panel made of one switch looks like one switch.
|
||||
|
||||
==================== DO NOT REORDER THESE ROWS ====================
|
||||
Every row below is a field the SELECTED PIPELINE declared, and the
|
||||
order of its declaration is the order of this panel. What a panel
|
||||
shows, and in what order, is decided in the pipeline's own Go file
|
||||
(internal/application/service/image_pipeline_<id>.go, method Fields)
|
||||
— not here. This component is a renderer and must stay one: it
|
||||
cannot tell a tunable of the describe call from a tunable of the
|
||||
read call, so any sorting or grouping it attempted would be a guess.
|
||||
|
||||
An earlier version of this file regrouped the fields by key prefix —
|
||||
"caption.* first, then ocr.*" — which read well for the smart
|
||||
pipeline and silently scrambled the manual one, whose switches and
|
||||
the thinking tunables that belong to them alternate. If a panel's
|
||||
order looks wrong, fix the declaration. See the Fields() doc on the
|
||||
imagePipeline interface for the full contract.
|
||||
=================================================================== -->
|
||||
<!-- Every declared field is a setting of the selected pipeline, stored in
|
||||
that pipeline's own slot — including the ones the pipeline carries in
|
||||
from the action that owns them. There is no field this panel reads
|
||||
from somewhere else, which is what keeps the value it draws and the
|
||||
value the run reads the same value. -->
|
||||
<div v-if="standingFields.length" class="image-pipeline-section">
|
||||
<div v-for="field in standingFields" :key="field.key" class="image-pipeline-row">
|
||||
<div class="image-pipeline-info">
|
||||
<label>{{ fieldLabel(field) }}</label>
|
||||
<p v-if="fieldDescription(field)" class="desc">{{ fieldDescription(field) }}</p>
|
||||
</div>
|
||||
<div class="image-pipeline-control">
|
||||
<t-switch
|
||||
v-if="field.type === 'bool'"
|
||||
:value="Boolean(paramValue(field))"
|
||||
size="medium"
|
||||
@change="(value: boolean) => onParamChange(field.key, value)"
|
||||
/>
|
||||
<t-select
|
||||
v-else-if="field.type === 'enum'"
|
||||
:value="String(paramValue(field) ?? '')"
|
||||
clearable
|
||||
@change="(value: string) => onParamChange(field.key, value)"
|
||||
>
|
||||
<t-option v-for="opt in field.options ?? []" :key="opt" :value="opt" :label="enumOptionLabel(field, opt)" />
|
||||
</t-select>
|
||||
<t-input
|
||||
v-else
|
||||
:value="String(paramValue(field) ?? '')"
|
||||
@change="(value: string) => onParamChange(field.key, value)"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- The advanced switches, folded away. The toggle is a real button, so
|
||||
the title opens it as well as the arrow. -->
|
||||
<template v-if="advancedFields.length">
|
||||
<div class="image-pipeline-section">
|
||||
<button type="button" class="advanced-toggle" @click="advancedOpen = !advancedOpen">
|
||||
<t-icon name="chevron-right" class="toggle-arrow" :class="{ open: advancedOpen }" />
|
||||
<span>{{ $t('knowledgeEditor.advanced.multimodal.advancedSettingsLabel') }}</span>
|
||||
</button>
|
||||
<div v-if="advancedOpen" class="advanced-section">
|
||||
<div v-for="field in advancedFields" :key="field.key" class="image-pipeline-row">
|
||||
<div class="image-pipeline-info">
|
||||
<label>{{ fieldLabel(field) }}</label>
|
||||
<p v-if="fieldDescription(field)" class="desc">{{ fieldDescription(field) }}</p>
|
||||
</div>
|
||||
<div class="image-pipeline-control">
|
||||
<t-switch
|
||||
v-if="field.type === 'bool'"
|
||||
:value="Boolean(paramValue(field))"
|
||||
size="medium"
|
||||
@change="(value: boolean) => onParamChange(field.key, value)"
|
||||
/>
|
||||
<t-select
|
||||
v-else-if="field.type === 'enum'"
|
||||
:value="String(paramValue(field) ?? '')"
|
||||
clearable
|
||||
@change="(value: string) => onParamChange(field.key, value)"
|
||||
>
|
||||
<t-option v-for="opt in field.options ?? []" :key="opt" :value="opt" :label="enumOptionLabel(field, opt)" />
|
||||
</t-select>
|
||||
<t-input
|
||||
v-else
|
||||
:value="String(paramValue(field) ?? '')"
|
||||
@change="(value: string) => onParamChange(field.key, value)"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- What the pipeline wants said about itself, folded away with it — plus
|
||||
whatever the host folds in here through the slot. For the smart
|
||||
pipeline that is the attribute dictionary: it explains what the OCR
|
||||
policy reads, it comes from the attribute registry rather than from
|
||||
the pipeline, and it belongs in the same place a reader looks for
|
||||
this pipeline's explanation. -->
|
||||
<template v-if="noteFields.length || hasNotesSlot">
|
||||
<div class="image-pipeline-section">
|
||||
<button type="button" class="advanced-toggle" @click="notesOpen = !notesOpen">
|
||||
<t-icon name="chevron-right" class="toggle-arrow" :class="{ open: notesOpen }" />
|
||||
<span>{{ $t('knowledgeEditor.advanced.multimodal.notesLabel') }}</span>
|
||||
</button>
|
||||
<div v-if="notesOpen" class="advanced-section">
|
||||
<div v-for="note in noteFields" :key="note.key" class="image-pipeline-note">
|
||||
<label>{{ fieldLabel(note) }}</label>
|
||||
<p v-if="fieldDescription(note)" class="desc">{{ fieldDescription(note) }}</p>
|
||||
</div>
|
||||
<slot name="notes" />
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- Every broken rule, listed rather than summarised: each line names what
|
||||
is wrong and, through the field it points at, which control to turn
|
||||
back on. Sits at the foot of the panel, next to the button the user
|
||||
has to press to lose it. -->
|
||||
<ul v-if="invalid" class="image-pipeline-violations">
|
||||
<li
|
||||
v-for="violation in violations"
|
||||
:key="`${violation.message_key}:${violation.field ?? ''}`"
|
||||
class="image-pipeline-desc image-pipeline-desc--error"
|
||||
>
|
||||
{{ $t(violation.message_key) || violation.message_key }}
|
||||
</li>
|
||||
</ul>
|
||||
<p v-else-if="validationFailed" class="image-pipeline-desc">
|
||||
{{ $t('knowledgeEditor.advanced.multimodal.imagePipelineValidateError') }}
|
||||
</p>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped lang="less">
|
||||
.image-pipeline-settings {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
|
||||
// The section description above ends here; a wider gap marks where the
|
||||
// controls begin, matching the rhythm of the other setting rows.
|
||||
margin-top: 4px;
|
||||
|
||||
.image-pipeline-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.image-pipeline-info {
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
|
||||
label {
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.desc {
|
||||
margin: 4px 0 0;
|
||||
opacity: 0.75;
|
||||
font-size: var(--app-text-sm);
|
||||
line-height: 1.5;
|
||||
}
|
||||
}
|
||||
|
||||
.image-pipeline-control {
|
||||
flex: 0 0 200px;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.image-pipeline-desc {
|
||||
margin: -4px 0 0;
|
||||
opacity: 0.75;
|
||||
font-size: var(--app-text-sm);
|
||||
line-height: 1.5;
|
||||
|
||||
&--error {
|
||||
margin: 0;
|
||||
opacity: 1;
|
||||
color: var(--error-color, #d54941);
|
||||
}
|
||||
}
|
||||
|
||||
.image-pipeline-hint {
|
||||
opacity: 0.75;
|
||||
font-size: var(--app-text-md);
|
||||
|
||||
&--error {
|
||||
color: var(--error-color, #d54941);
|
||||
}
|
||||
}
|
||||
|
||||
// One line per broken rule, kept compact so that several of them still read
|
||||
// as a footnote to the button rather than as a second form.
|
||||
.image-pipeline-violations {
|
||||
margin: 0;
|
||||
padding-left: 1em;
|
||||
list-style: disc;
|
||||
}
|
||||
}
|
||||
// Sections 1 and 2 of the panel: a rule goes between the sections and never
|
||||
// inside one, so a section reads as a block rather than as a series of rows
|
||||
// separated by lines. Section 3 (the observation attributes) lives in the host
|
||||
// dialog, which is where the attribute registry is read, and brings its own
|
||||
// separating line with it. A folded run the pipeline does not declare draws no
|
||||
// rule either — see the template.
|
||||
.image-pipeline-section {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.image-pipeline-divider {
|
||||
margin: 0;
|
||||
border: 0;
|
||||
border-top: 1px solid var(--td-component-border);
|
||||
}
|
||||
// The folded runs follow the chunking panel's advanced options exactly — same
|
||||
// button, same arrow, same collapse — so "advanced" looks and behaves the same
|
||||
// wherever a knowledge base shows it. The whole row is the button, which is why
|
||||
// the title opens it as well as the arrow.
|
||||
.advanced-toggle {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
background: transparent;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
font-size: var(--app-text-base);
|
||||
font-weight: 500;
|
||||
color: var(--td-text-color-secondary);
|
||||
user-select: none;
|
||||
|
||||
&:hover {
|
||||
color: var(--td-text-color-primary);
|
||||
}
|
||||
}
|
||||
|
||||
.toggle-arrow {
|
||||
font-size: var(--app-text-xl);
|
||||
transition: transform var(--app-motion-fast) ease;
|
||||
|
||||
&.open {
|
||||
transform: rotate(90deg);
|
||||
}
|
||||
}
|
||||
|
||||
.advanced-section {
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
// One declared note: a title and the prose under it, worded like a setting
|
||||
// row's label and description so it reads as part of the same panel.
|
||||
.image-pipeline-note {
|
||||
label {
|
||||
display: block;
|
||||
font-weight: 500;
|
||||
color: var(--td-text-color-primary);
|
||||
}
|
||||
|
||||
.desc {
|
||||
margin: 4px 0 0;
|
||||
opacity: 0.75;
|
||||
font-size: var(--app-text-sm);
|
||||
line-height: 1.5;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,248 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test, { type TestContext } from 'node:test'
|
||||
import * as vue from 'vue'
|
||||
import * as stall from '../../utils/knowledgeProcessingStall.ts'
|
||||
import { change, fixture, flush } from '../../test-utils/vueFixture.ts'
|
||||
|
||||
async function setup(t: TestContext) {
|
||||
const f = fixture(t)
|
||||
const route = vue.reactive({ params: { kbId: 'kb' }, query: {} })
|
||||
const hook = {
|
||||
cardList: vue.ref([{ id: 'doc', parse_status: 'completed' }]), total: vue.ref(1), moreIndex: vue.ref(-1),
|
||||
details: vue.reactive({ id: 'doc' }), getKnowled: t.mock.fn(async () => {}),
|
||||
getCardDetails: t.mock.fn(), getfDetails() {}, onVisibleChange() {},
|
||||
}
|
||||
const listKnowledgeFolders = t.mock.fn(async (_id: string) => ({ data: { folders: [] } }))
|
||||
const batchQueryKnowledge = t.mock.fn(async (query: string) => {
|
||||
const ids = new URLSearchParams(query).getAll('ids')
|
||||
return { success: true, data: hook.cardList.value.filter(card => ids.includes(card.id)).map(card => ({ ...card })) }
|
||||
})
|
||||
const fetchKnowledgeBaseById = t.mock.fn(async (_id: string, _force: boolean) => ({ id: 'kb', type: 'document' }))
|
||||
let settle: () => void = () => {}
|
||||
const waitForKnowledgeDeletion = t.mock.fn((_ids: string[]) => new Promise<string>((resolve) => {
|
||||
settle = () => resolve('completed')
|
||||
}))
|
||||
const page = f.component(new URL('./KnowledgeBase.vue', import.meta.url), {
|
||||
'vue-router': { useRoute: () => route, useRouter: () => ({ replace() {} }) },
|
||||
'vue-i18n': { useI18n: () => ({ t: (key: string) => key }) },
|
||||
'tdesign-vue-next': { MessagePlugin: { success() {}, error() {}, info() {}, warning() {} } },
|
||||
'@/hooks/useKnowledgeBase': () => hook,
|
||||
'@/stores/ui': { useUIStore: () => ({ clearSelectedTagIds() {} }) },
|
||||
'@/stores/organization': { useOrganizationStore: () => ({ sharedKnowledgeBases: [], getKBPermission: () => 'owner' }) },
|
||||
'@/stores/auth': { useAuthStore: () => ({ hasRole: () => true }) },
|
||||
'@/stores/chatResources': { useChatResourcesStore: () => ({
|
||||
fetchKnowledgeBaseById, rawKnowledgeBases: [], async ensureKnowledgeBases() {},
|
||||
}) },
|
||||
'@/stores/editorResources': { useEditorResourcesStore: () => ({ parserEngines: [], async ensureParserEngines() {} }) },
|
||||
'@/stores/uploadConfirm': { useUploadConfirmStore: () => ({}) },
|
||||
'@/stores/uploadTasks': { useUploadTasksStore: () => ({}) },
|
||||
'@/hooks/useMarqueeSelect': { useMarqueeSelect: () => ({}) },
|
||||
'@/composables/useAssistantPageContext': { useAssistantPageContext() {} },
|
||||
'@/utils/kbPermission': {}, '@/utils/knowledgeDeletion': { waitForKnowledgeDeletion }, '@/utils/knowledgeTrace': {},
|
||||
'@/utils/knowledgeProcessingStall': stall, '@/api/wiki': {}, '@/api/knowledge-base': {},
|
||||
'@/api/knowledge-base/index': {
|
||||
listKnowledgeFolders, listKnowledgeTags: async () => ({ data: { data: [], total: 0 } }),
|
||||
batchReparseKnowledge: async () => ({ success: true }),
|
||||
batchQueryKnowledge,
|
||||
},
|
||||
})
|
||||
await flush()
|
||||
page.vm.isCardDetails = true
|
||||
hook.getKnowled.mock.resetCalls()
|
||||
listKnowledgeFolders.mock.resetCalls()
|
||||
fetchKnowledgeBaseById.mock.resetCalls()
|
||||
return {
|
||||
...f, ...page, route, hook, listKnowledgeFolders, fetchKnowledgeBaseById, waitForKnowledgeDeletion, batchQueryKnowledge,
|
||||
settleDeletion: () => settle(),
|
||||
}
|
||||
}
|
||||
|
||||
test('refreshes files and folders for the open KB and ignores unrelated areas and KBs', async t => {
|
||||
const f = await setup(t)
|
||||
f.emit(change('knowledge.create_manual', { knowledge_base_id: ['other'] }))
|
||||
f.emit(change('agent.create'))
|
||||
t.mock.timers.tick(300)
|
||||
assert.equal(f.hook.getKnowled.mock.callCount(), 0)
|
||||
f.emit(change('knowledge.create_manual', { knowledge_base_id: ['kb'] }))
|
||||
f.emit(change('knowledge.rename_folder', { knowledge_base_id: ['kb'] }))
|
||||
t.mock.timers.tick(300)
|
||||
await flush()
|
||||
assert.equal(f.hook.getKnowled.mock.callCount(), 1)
|
||||
assert.equal(f.listKnowledgeFolders.mock.callCount(), 1)
|
||||
assert.equal(f.listKnowledgeFolders.mock.calls[0].arguments[0], 'kb')
|
||||
assert.equal(f.hook.getCardDetails.mock.callCount(), 0)
|
||||
})
|
||||
|
||||
test('reloads KB metadata with force without adding file requests beyond the existing loader', async t => {
|
||||
const f = await setup(t)
|
||||
await f.vm.loadKnowledgeBaseInfo('kb', true)
|
||||
await flush()
|
||||
const fileRequests = f.hook.getKnowled.mock.callCount()
|
||||
f.hook.getKnowled.mock.resetCalls()
|
||||
f.fetchKnowledgeBaseById.mock.resetCalls()
|
||||
f.emit(change('knowledge_base.generate_profile', { knowledge_base_id: ['kb'] }))
|
||||
t.mock.timers.tick(300)
|
||||
await flush()
|
||||
assert.deepEqual(Array.from(f.fetchKnowledgeBaseById.mock.calls[0].arguments), ['kb', true])
|
||||
assert.equal(f.fetchKnowledgeBaseById.mock.callCount(), 1)
|
||||
assert.equal(f.hook.getKnowled.mock.callCount(), fileRequests)
|
||||
})
|
||||
|
||||
for (const operation of ['knowledge.update', 'knowledge.reparse', 'knowledge.cancel_parse', 'chunk.update', 'chunk.revert']) {
|
||||
test(`refreshes the open document on ${operation}`, async t => {
|
||||
const f = await setup(t)
|
||||
f.emit(change(operation, { knowledge_id: ['doc'] }))
|
||||
t.mock.timers.tick(300)
|
||||
await flush()
|
||||
assert.equal(f.hook.getCardDetails.mock.callCount(), 1)
|
||||
assert.deepEqual(structuredClone(f.hook.getCardDetails.mock.calls[0].arguments[0]), { id: 'doc' })
|
||||
assert.equal(f.hook.getKnowled.mock.callCount(), 1)
|
||||
assert.equal(f.vm.isCardDetails, true)
|
||||
})
|
||||
}
|
||||
|
||||
test('ignores chunk changes in another document outside this knowledge base', async t => {
|
||||
const f = await setup(t)
|
||||
f.emit(change('chunk.update', { knowledge_id: ['other-doc'] }))
|
||||
t.mock.timers.tick(300)
|
||||
assert.equal(f.hook.getCardDetails.mock.callCount(), 0)
|
||||
assert.equal(f.hook.getKnowled.mock.callCount(), 0)
|
||||
})
|
||||
|
||||
test('closes a deleted drawer even when the same burst includes an update', async t => {
|
||||
const f = await setup(t)
|
||||
f.emit(change('knowledge.update', { knowledge_id: ['doc'] }))
|
||||
f.emit(change('knowledge.batch_delete', { knowledge_base_id: ['kb'], knowledge_id: ['doc'] }))
|
||||
t.mock.timers.tick(300)
|
||||
assert.equal(f.vm.isCardDetails, false)
|
||||
assert.equal(f.hook.getCardDetails.mock.callCount(), 0)
|
||||
})
|
||||
|
||||
test('refreshes ID-only changes outside the loaded page without refreshing an unrelated drawer', async t => {
|
||||
const f = await setup(t)
|
||||
f.emit(change('knowledge.delete', { knowledge_id: ['unloaded-doc'] }))
|
||||
t.mock.timers.tick(300)
|
||||
assert.equal(f.hook.getKnowled.mock.callCount(), 1)
|
||||
assert.equal(f.hook.getCardDetails.mock.callCount(), 0)
|
||||
assert.equal(f.vm.isCardDetails, true)
|
||||
})
|
||||
|
||||
test('reloads the list again once a delete the assistant started has finished', async t => {
|
||||
const f = await setup(t)
|
||||
f.emit(change('knowledge.delete', { knowledge_id: ['doc'] }))
|
||||
t.mock.timers.tick(300)
|
||||
await flush()
|
||||
assert.equal(f.vm.isCardDetails, false)
|
||||
assert.equal(f.hook.getKnowled.mock.callCount(), 1)
|
||||
assert.deepEqual(Array.from(f.waitForKnowledgeDeletion.mock.calls[0].arguments[0] as string[]), ['doc'])
|
||||
f.settleDeletion()
|
||||
await flush()
|
||||
assert.equal(f.hook.getKnowled.mock.callCount(), 2)
|
||||
})
|
||||
|
||||
test('uses the current route when a queued change fires', async t => {
|
||||
const f = await setup(t)
|
||||
f.emit(change('knowledge.create_manual', { knowledge_base_id: ['kb'] }))
|
||||
f.route.params.kbId = 'other'
|
||||
await flush()
|
||||
f.hook.getKnowled.mock.resetCalls()
|
||||
f.vm.isCardDetails = false
|
||||
t.mock.timers.tick(300)
|
||||
assert.equal(f.hook.getKnowled.mock.callCount(), 0)
|
||||
})
|
||||
|
||||
test('batch reparse preserves loaded pages and updates statuses without reloading the list', async t => {
|
||||
const f = await setup(t)
|
||||
f.hook.cardList.value = Array.from({ length: 70 }, (_, i) => ({ id: `doc-${i}`, parse_status: 'completed' }))
|
||||
await flush()
|
||||
const cards = f.hook.cardList.value
|
||||
f.vm.selectedIds = new Set(['doc-69'])
|
||||
await f.vm.confirmBatchReparse()
|
||||
await flush()
|
||||
assert.equal(cards[69].parse_status, 'pending')
|
||||
t.mock.timers.tick(1500)
|
||||
await flush()
|
||||
assert.equal(f.vm.pendingReparseAck.has('doc-69'), false)
|
||||
assert.equal(f.batchQueryKnowledge.mock.calls[0].arguments[0], 'ids=doc-69&')
|
||||
assert.equal(f.hook.getKnowled.mock.callCount(), 0)
|
||||
assert.equal(f.hook.cardList.value, cards)
|
||||
assert.equal(cards.length, 70)
|
||||
assert.equal(f.vm.docListLoading, false)
|
||||
})
|
||||
|
||||
test('an older batch acknowledgement timeout does not clear a newer batch', async t => {
|
||||
const f = await setup(t)
|
||||
f.vm.pendingReparseAck = new Set(['older'])
|
||||
const older = f.vm.awaitBatchReparseReflection(['older'])
|
||||
for (let i = 0; i < 29; i++) {
|
||||
await flush()
|
||||
t.mock.timers.tick(400)
|
||||
}
|
||||
f.vm.pendingReparseAck.add('newer')
|
||||
await flush()
|
||||
t.mock.timers.tick(400)
|
||||
await older
|
||||
assert.equal(f.vm.pendingReparseAck.has('older'), false)
|
||||
assert.equal(f.vm.pendingReparseAck.has('newer'), true)
|
||||
assert.equal(f.hook.getKnowled.mock.callCount(), 0)
|
||||
})
|
||||
|
||||
test('batch acknowledgement waits stop once their own IDs are acknowledged', async t => {
|
||||
const f = await setup(t)
|
||||
f.vm.pendingReparseAck = new Set(['older', 'newer'])
|
||||
let finished = false
|
||||
const older = f.vm.awaitBatchReparseReflection(['older']).then(() => { finished = true })
|
||||
await flush()
|
||||
f.vm.pendingReparseAck.delete('older')
|
||||
t.mock.timers.tick(400)
|
||||
await flush()
|
||||
assert.equal(finished, true)
|
||||
await older
|
||||
assert.equal(f.vm.pendingReparseAck.has('newer'), true)
|
||||
})
|
||||
|
||||
test('accepts a rebuild completed between polls after the bounded acknowledgement window', async t => {
|
||||
const f = await setup(t)
|
||||
f.hook.cardList.value = [{ id: 'doc', parse_status: 'completed' }]
|
||||
f.batchQueryKnowledge.mock.mockImplementation(async () => ({
|
||||
success: true, data: [{ id: 'doc', parse_status: 'completed' }],
|
||||
}))
|
||||
f.vm.selectedIds = new Set(['doc'])
|
||||
await f.vm.confirmBatchReparse()
|
||||
await flush()
|
||||
for (let i = 0; i < 29; i++) {
|
||||
t.mock.timers.tick(400)
|
||||
await flush()
|
||||
}
|
||||
assert.equal(f.hook.cardList.value[0].parse_status, 'pending')
|
||||
t.mock.timers.tick(400)
|
||||
await flush()
|
||||
assert.equal(f.vm.pendingReparseAck.has('doc'), false)
|
||||
t.mock.timers.tick(1500)
|
||||
await flush()
|
||||
assert.equal(f.hook.cardList.value[0].parse_status, 'completed')
|
||||
assert.equal(f.hook.getKnowled.mock.callCount(), 0)
|
||||
})
|
||||
|
||||
test('a pending rebuild does not reload another folder or KB after navigation or unmount', async t => {
|
||||
const f = await setup(t)
|
||||
f.hook.cardList.value = [{ id: 'doc', parse_status: 'completed' }]
|
||||
f.vm.selectedIds = new Set(['doc'])
|
||||
await f.vm.confirmBatchReparse()
|
||||
await flush()
|
||||
f.vm.selectedFolderPath = '/other-folder'
|
||||
await flush()
|
||||
f.route.params.kbId = 'other'
|
||||
await flush()
|
||||
f.hook.getKnowled.mock.resetCalls()
|
||||
for (let i = 0; i < 5; i++) {
|
||||
t.mock.timers.tick(400)
|
||||
await flush()
|
||||
}
|
||||
f.close()
|
||||
for (let i = 0; i < 30; i++) {
|
||||
t.mock.timers.tick(400)
|
||||
await flush()
|
||||
}
|
||||
assert.equal(f.hook.getKnowled.mock.callCount(), 0)
|
||||
})
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,52 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import test from 'node:test'
|
||||
|
||||
const source = readFileSync(new URL('./KnowledgeBaseEditorModal.vue', import.meta.url), 'utf8')
|
||||
|
||||
test('editing a knowledge base closes the editor after a successful save', () => {
|
||||
assert.match(source, /emit\('success', kbId\)\s*handleClose\(\)/)
|
||||
})
|
||||
|
||||
test('the first successful create stays open for follow-up configuration', () => {
|
||||
const createBranch = source.match(
|
||||
/if \(editorMode\.value === 'create'\) \{([\s\S]*?)^\s{4}\} else \{/m
|
||||
)?.[1]
|
||||
|
||||
assert.ok(createBranch, 'expected to find the create branch')
|
||||
assert.doesNotMatch(createBranch, /handleClose\(\)/)
|
||||
assert.match(createBranch, /savedKbId\.value = createdKbId/)
|
||||
})
|
||||
|
||||
test('save button labels distinguish create from save-and-close', () => {
|
||||
assert.match(
|
||||
source,
|
||||
/const saveButtonLabel = computed\(\(\) =>\s*editorMode\.value === 'create'\s*\? t\('knowledgeEditor\.buttons\.create'\)\s*: t\('knowledgeEditor\.buttons\.saveAndClose'\)\s*\)/
|
||||
)
|
||||
})
|
||||
|
||||
test('shows a post-create hint after the first successful save', () => {
|
||||
assert.match(source, /const isPostCreateSession = computed\(\(\) => !!savedKbId\.value\)/)
|
||||
assert.match(source, /settings-footer-note/)
|
||||
assert.match(source, /knowledgeEditor\.postCreateHint\.followUpDesc/)
|
||||
})
|
||||
|
||||
test('create mode seeds the full default image actions table', () => {
|
||||
// Regression: an empty imageActions in initFormData made the attribute panel
|
||||
// read `undefined.ocr.on` the moment the attribute switch was turned on in the
|
||||
// create dialog, crashing the modal.
|
||||
const initBlock = source.match(/const initFormData[\s\S]*?imageActions: ([^,]+),/)?.[1]
|
||||
assert.ok(initBlock, 'expected to find imageActions in initFormData')
|
||||
assert.match(initBlock, /mergeImageActions\(\)/)
|
||||
})
|
||||
|
||||
test('edit mode forwards image_processing_config in the update payload', () => {
|
||||
// Regression: the edit branch built data.image_processing_config but never
|
||||
// put it into updateConfig, so KB-editor changes to the image classification
|
||||
// settings were silently dropped (create worked, later edits did not).
|
||||
const editBranch = source.match(
|
||||
/(\/\/ 编辑模式:分别更新基本信息[\s\S]*?await updateKnowledgeBase\(kbId, \{)/
|
||||
)?.[1]
|
||||
assert.ok(editBranch, 'expected to find the edit-mode update block')
|
||||
assert.match(editBranch, /if \(data\.image_processing_config\) \{\s*updateConfig\.image_processing_config = data\.image_processing_config\s*\}/)
|
||||
})
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,306 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import test, { type TestContext } from 'node:test'
|
||||
import { createI18n } from 'vue-i18n'
|
||||
import * as vue from 'vue'
|
||||
import * as stall from '../../utils/knowledgeProcessingStall.ts'
|
||||
import { fixture, flush } from '../../test-utils/vueFixture.ts'
|
||||
import enUS from '../../i18n/locales/en-US'
|
||||
import zhCN from '../../i18n/locales/zh-CN'
|
||||
import zhTW from '../../i18n/locales/zh-TW'
|
||||
import jaJP from '../../i18n/locales/ja-JP'
|
||||
import koKR from '../../i18n/locales/ko-KR'
|
||||
import ruRU from '../../i18n/locales/ru-RU'
|
||||
import { pluralRules } from '../../i18n/pluralizationRules'
|
||||
|
||||
const source = readFileSync(new URL('./KnowledgeBase.vue', import.meta.url), 'utf8')
|
||||
|
||||
// Mirrors the deployed DingTalk sync, which produces multi-level folders:
|
||||
// 售后 holds 2 documents of its own plus a video sub-folder with 1 more, so its
|
||||
// direct, sub-folder and recursive numbers are all different. The root has 3
|
||||
// documents of its own and 5 top-level folders, and the whole base holds 17.
|
||||
const syncedTree = {
|
||||
root_document_count: 3,
|
||||
total_document_count: 17,
|
||||
folders: [
|
||||
{ path: '培训材料库', name: '培训材料库', document_count: 3, total_count: 3 },
|
||||
{
|
||||
path: '天诛渗透攻防',
|
||||
name: '天诛渗透攻防',
|
||||
document_count: 0,
|
||||
total_count: 5,
|
||||
children: [
|
||||
{ path: '天诛渗透攻防/FAQ', name: 'FAQ', document_count: 2, total_count: 2 },
|
||||
{
|
||||
path: '天诛渗透攻防/售后',
|
||||
name: '售后',
|
||||
document_count: 2,
|
||||
total_count: 3,
|
||||
children: [
|
||||
{
|
||||
path: '天诛渗透攻防/售后/2024使用培训视频',
|
||||
name: '2024使用培训视频',
|
||||
document_count: 1,
|
||||
total_count: 1,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{ path: '设计规范', name: '设计规范', document_count: 4, total_count: 4 },
|
||||
{ path: '历史归档', name: '历史归档', document_count: 2, total_count: 2 },
|
||||
{ path: '空目录', name: '空目录', document_count: 0, total_count: 0 },
|
||||
],
|
||||
}
|
||||
|
||||
async function setup(t: TestContext, tree: unknown) {
|
||||
const f = fixture(t)
|
||||
const route = vue.reactive({ params: { kbId: 'kb' }, query: {} })
|
||||
const hook = {
|
||||
cardList: vue.ref<any[]>([]), total: vue.ref(0), moreIndex: vue.ref(-1),
|
||||
details: vue.reactive({ id: 'doc' }), getKnowled: t.mock.fn(async () => {}),
|
||||
getCardDetails: t.mock.fn(), getfDetails() {}, onVisibleChange() {},
|
||||
}
|
||||
const listKnowledgeFolders = t.mock.fn(async (_id: string) => ({ data: tree }))
|
||||
const fetchKnowledgeBaseById = t.mock.fn(async (_id: string, _force: boolean) => ({ id: 'kb', type: 'document' }))
|
||||
const page = f.component(new URL('./KnowledgeBase.vue', import.meta.url), {
|
||||
'vue-router': { useRoute: () => route, useRouter: () => ({ replace() {} }) },
|
||||
'vue-i18n': { useI18n: () => ({ t: (key: string) => key }) },
|
||||
'tdesign-vue-next': { MessagePlugin: {} },
|
||||
'@/hooks/useKnowledgeBase': () => hook,
|
||||
'@/stores/ui': { useUIStore: () => ({ clearSelectedTagIds() {} }) },
|
||||
'@/stores/organization': { useOrganizationStore: () => ({ sharedKnowledgeBases: [], getKBPermission: () => 'owner' }) },
|
||||
'@/stores/auth': { useAuthStore: () => ({ hasRole: () => true }) },
|
||||
'@/stores/chatResources': { useChatResourcesStore: () => ({
|
||||
fetchKnowledgeBaseById, rawKnowledgeBases: [], async ensureKnowledgeBases() {},
|
||||
}) },
|
||||
'@/stores/editorResources': { useEditorResourcesStore: () => ({ parserEngines: [], async ensureParserEngines() {} }) },
|
||||
'@/stores/uploadConfirm': { useUploadConfirmStore: () => ({}) },
|
||||
'@/stores/uploadTasks': { useUploadTasksStore: () => ({}) },
|
||||
'@/hooks/useMarqueeSelect': { useMarqueeSelect: () => ({}) },
|
||||
'@/composables/useAssistantPageContext': { useAssistantPageContext() {} },
|
||||
'@/utils/kbPermission': {}, '@/utils/knowledgeDeletion': {}, '@/utils/knowledgeTrace': {},
|
||||
'@/utils/knowledgeProcessingStall': stall, '@/api/wiki': {}, '@/api/knowledge-base': {},
|
||||
'@/api/knowledge-base/index': { listKnowledgeFolders, listKnowledgeTags: async () => ({ data: { data: [], total: 0 } }) },
|
||||
})
|
||||
await flush()
|
||||
return { ...f, ...page, hook, listKnowledgeFolders }
|
||||
}
|
||||
|
||||
async function selectFolder(f: Awaited<ReturnType<typeof setup>>, path: string) {
|
||||
f.vm.selectedFolderPath = path
|
||||
await flush()
|
||||
}
|
||||
|
||||
// ── Breadcrumb ──────────────────────────────────────────────────────────────
|
||||
|
||||
test('the breadcrumb counts the documents and sub-folders the page can show', async t => {
|
||||
const f = await setup(t, syncedTree)
|
||||
f.hook.total.value = 2 // the two documents directly inside 售后
|
||||
await selectFolder(f, '天诛渗透攻防/售后')
|
||||
assert.equal(f.vm.folderContentsCount.documents, 2)
|
||||
assert.equal(f.vm.folderContentsCount.folders, 1)
|
||||
// 3 is the recursive document total (2 direct + 1 in the video sub-folder),
|
||||
// which is what used to be shown next to a list of only 2.
|
||||
assert.notEqual(f.vm.folderContentsCount.documents, 3)
|
||||
// Fed through the real zh-CN bundle, the pair renders as DingTalk does.
|
||||
assert.equal(renderFolderContents('zh-CN', f.vm.folderContentsCount), '2 个文档 / 1 个文件夹')
|
||||
})
|
||||
|
||||
test('the root breadcrumb counts the root documents and the top-level folders', async t => {
|
||||
const f = await setup(t, syncedTree)
|
||||
f.hook.total.value = 3 // the root-level documents only
|
||||
assert.equal(f.vm.selectedFolderPath, '')
|
||||
assert.equal(f.vm.folderContentsCount.documents, 3)
|
||||
assert.equal(f.vm.folderContentsCount.folders, 5)
|
||||
// 17 is the whole knowledge base, not what the root list shows.
|
||||
assert.notEqual(f.vm.folderContentsCount.documents, 17)
|
||||
})
|
||||
|
||||
test('the sub-folder number is direct children, not the documents below them', async t => {
|
||||
const f = await setup(t, syncedTree)
|
||||
f.hook.total.value = 0
|
||||
await selectFolder(f, '天诛渗透攻防')
|
||||
// FAQ and 售后: the two direct sub-folders.
|
||||
assert.equal(f.vm.folderContentsCount.folders, 2)
|
||||
// The empty state still reports the 5 documents inside those sub-folders.
|
||||
assert.equal(f.vm.folderSubfolderDocumentCount, 5)
|
||||
assert.equal(f.vm.folderEmptyState, 'subfolders')
|
||||
})
|
||||
|
||||
test('the breadcrumb omits the folder segment when the folder has no sub-folders', async t => {
|
||||
const f = await setup(t, syncedTree)
|
||||
f.hook.total.value = 2
|
||||
await selectFolder(f, '培训材料库')
|
||||
assert.equal(f.vm.folderContentsCount.folders, 0)
|
||||
assert.equal(f.vm.isFiltering, false)
|
||||
assert.equal(f.vm.showFolderContentsCount, false)
|
||||
// The same branch feeds the existing single-number message; rendered for
|
||||
// real, it cannot contain a "/ 0 folders" tail.
|
||||
const i18n = createI18n({ legacy: false, locale: 'zh-CN', messages: { 'zh-CN': zhCN } })
|
||||
const text = i18n.global.t('knowledgeBase.documentCount', { count: 2 })
|
||||
assert.equal(text, '2 个文档')
|
||||
assert.doesNotMatch(text, /文件夹/)
|
||||
})
|
||||
|
||||
test('filtering keeps the flat result count and adds no folder number', async t => {
|
||||
const f = await setup(t, syncedTree)
|
||||
await selectFolder(f, '天诛渗透攻防/售后')
|
||||
f.hook.total.value = 2 // two matching documents inside the subtree
|
||||
f.vm.docSearchKeyword = 'FAQ'
|
||||
await flush()
|
||||
assert.equal(f.vm.isFiltering, true)
|
||||
assert.equal(f.vm.folderContentsCount.documents, 2)
|
||||
assert.equal(f.vm.folderContentsCount.folders, 0)
|
||||
})
|
||||
|
||||
// ── Sub-folders as list entries ─────────────────────────────────────────────
|
||||
// Browsing a folder lists its direct children, the way a file manager does.
|
||||
// The document list and card grid receive exactly this array.
|
||||
|
||||
test('the page lists exactly the direct sub-folders of the current folder', async t => {
|
||||
const f = await setup(t, syncedTree)
|
||||
await selectFolder(f, '天诛渗透攻防')
|
||||
assert.deepEqual(
|
||||
f.vm.visibleSubFolders.map((node: { path: string }) => node.path),
|
||||
['天诛渗透攻防/FAQ', '天诛渗透攻防/售后'],
|
||||
)
|
||||
|
||||
await selectFolder(f, '')
|
||||
assert.equal(f.vm.visibleSubFolders.length, 5)
|
||||
})
|
||||
|
||||
test('filtering hides sub-folder entries because it lists matching documents', async t => {
|
||||
const f = await setup(t, syncedTree)
|
||||
await selectFolder(f, '天诛渗透攻防')
|
||||
f.vm.docSearchKeyword = 'FAQ'
|
||||
await flush()
|
||||
assert.equal(f.vm.isFiltering, true)
|
||||
assert.equal(f.vm.visibleSubFolders.length, 0)
|
||||
})
|
||||
|
||||
test('an unloaded folder tree contributes no sub-folder entries', async t => {
|
||||
const f = await setup(t, null)
|
||||
await selectFolder(f, '天诛渗透攻防')
|
||||
assert.equal(f.vm.folderTree, null)
|
||||
assert.equal(f.vm.visibleSubFolders.length, 0)
|
||||
})
|
||||
|
||||
test('an unloaded folder tree reports no folders instead of crashing', async t => {
|
||||
const f = await setup(t, null)
|
||||
f.hook.total.value = 4
|
||||
await selectFolder(f, '天诛渗透攻防')
|
||||
assert.equal(f.vm.folderTree, null)
|
||||
assert.equal(f.vm.folderContentsCount.documents, 4)
|
||||
assert.equal(f.vm.folderContentsCount.folders, 0)
|
||||
})
|
||||
|
||||
test('a stale folder path reports no folders instead of crashing', async t => {
|
||||
const f = await setup(t, syncedTree)
|
||||
f.hook.total.value = 2
|
||||
await selectFolder(f, '已删除/目录')
|
||||
assert.equal(f.vm.folderContentsCount.documents, 2)
|
||||
assert.equal(f.vm.folderContentsCount.folders, 0)
|
||||
})
|
||||
|
||||
// ── Wording ─────────────────────────────────────────────────────────────────
|
||||
// The rendered numbers are the pair above; these assertions pin the message the
|
||||
// template feeds them into, so a single-number message cannot come back.
|
||||
const FOLDER_CONTENTS = 'knowledgeBase.folderTree.folderContentsCount'
|
||||
const locales = {
|
||||
'zh-CN': zhCN, 'zh-TW': zhTW, 'en-US': enUS, 'ja-JP': jaJP, 'ko-KR': koKR, 'ru-RU': ruRU,
|
||||
}
|
||||
|
||||
function renderFolderContents(
|
||||
locale: keyof typeof locales,
|
||||
counts: { documents: number; folders: number } = { documents: 2, folders: 1 },
|
||||
): string {
|
||||
const i18n = createI18n({ legacy: false, locale, pluralRules, messages: { [locale]: locales[locale] } })
|
||||
// `count` is what vue-i18n uses to pick the plural form; the folder number is
|
||||
// the noun that changes, so it drives the choice.
|
||||
return i18n.global.t(FOLDER_CONTENTS, { ...counts, count: counts.folders })
|
||||
}
|
||||
|
||||
test('every locale renders both numbers as "documents / folders"', () => {
|
||||
assert.equal(renderFolderContents('zh-CN'), '2 个文档 / 1 个文件夹')
|
||||
assert.equal(renderFolderContents('zh-TW'), '2 個文件 / 1 個資料夾')
|
||||
assert.equal(renderFolderContents('en-US'), '2 documents / 1 folder')
|
||||
assert.equal(renderFolderContents('ja-JP'), '2 件のドキュメント / 1 個のフォルダ')
|
||||
assert.equal(renderFolderContents('ko-KR'), '문서 2개 / 폴더 1개')
|
||||
assert.equal(renderFolderContents('ru-RU'), 'Документов: 2 / 1 папка')
|
||||
})
|
||||
|
||||
test('plural locales inflect the folder noun', () => {
|
||||
assert.equal(renderFolderContents('en-US', { documents: 2, folders: 2 }), '2 documents / 2 folders')
|
||||
assert.equal(renderFolderContents('ru-RU', { documents: 2, folders: 2 }), 'Документов: 2 / 2 папки')
|
||||
assert.equal(renderFolderContents('ru-RU', { documents: 2, folders: 5 }), 'Документов: 2 / 5 папок')
|
||||
// No plural change in these locales; the number alone changes.
|
||||
assert.equal(renderFolderContents('zh-CN', { documents: 2, folders: 2 }), '2 个文档 / 2 个文件夹')
|
||||
assert.equal(renderFolderContents('ja-JP', { documents: 1, folders: 1 }), '1 件のドキュメント / 1 個のフォルダ')
|
||||
assert.equal(renderFolderContents('ko-KR', { documents: 2, folders: 2 }), '문서 2개 / 폴더 2개')
|
||||
})
|
||||
|
||||
// ── Empty state ─────────────────────────────────────────────────────────────
|
||||
|
||||
test('a folder whose documents live in sub-folders is not called empty', async t => {
|
||||
const f = await setup(t, syncedTree)
|
||||
await selectFolder(f, '天诛渗透攻防')
|
||||
assert.equal(f.vm.folderSubfolderDocumentCount, 5)
|
||||
assert.equal(f.vm.folderEmptyState, 'subfolders')
|
||||
})
|
||||
|
||||
test('a folder that really has no documents keeps the plain empty message', async t => {
|
||||
const f = await setup(t, syncedTree)
|
||||
await selectFolder(f, '空目录')
|
||||
assert.equal(f.vm.folderSubfolderDocumentCount, 0)
|
||||
assert.equal(f.vm.folderEmptyState, 'folder')
|
||||
})
|
||||
|
||||
test('filtering keeps the no-match empty message', async t => {
|
||||
const f = await setup(t, syncedTree)
|
||||
await selectFolder(f, '天诛渗透攻防')
|
||||
f.vm.docSearchKeyword = 'nothing matches this'
|
||||
await flush()
|
||||
assert.equal(f.vm.folderEmptyState, 'search')
|
||||
})
|
||||
|
||||
test('a knowledge base without folders keeps the onboarding empty state', async t => {
|
||||
const f = await setup(t, { root_document_count: 0, total_document_count: 0, folders: [] })
|
||||
assert.equal(f.vm.folderEmptyState, 'none')
|
||||
})
|
||||
|
||||
// The rendered count and message come from the template, which the mounted
|
||||
// fixture does not render; these assertions keep the wiring honest.
|
||||
function expectSource(pattern: RegExp) {
|
||||
assert.ok(pattern.test(source), `KnowledgeBase.vue should match ${pattern}`)
|
||||
}
|
||||
|
||||
test('the breadcrumb wires both numbers into the two-part message', () => {
|
||||
expectSource(/\$t\('knowledgeBase\.folderTree\.folderContentsCount', folderContentsMessage\)/)
|
||||
expectSource(
|
||||
/\$t\('knowledgeBase\.folderTree\.filteredCount', \{ count: folderContentsCount\.documents \}\)/,
|
||||
)
|
||||
expectSource(/v-if="isFiltering"/)
|
||||
expectSource(/v-else-if="showFolderContentsCount"/)
|
||||
// With no sub-folders the two-part message would end in "0 folders", so the
|
||||
// breadcrumb falls back to the existing document-only message.
|
||||
expectSource(/\$t\('knowledgeBase\.documentCount', \{ count: folderContentsCount\.documents \}\)/)
|
||||
})
|
||||
|
||||
test('the document views receive the current sub-folders', () => {
|
||||
const passed = source.match(/:sub-folders="visibleSubFolders"/g) || []
|
||||
assert.equal(passed.length, 2, 'both the list and the card grid should receive the folders')
|
||||
})
|
||||
|
||||
test('the empty state tells sub-folder documents apart from an empty folder', () => {
|
||||
const search = source.indexOf("knowledgeBase.folderTree.emptySearch")
|
||||
const subfolders = source.indexOf("knowledgeBase.folderTree.emptyFolderWithSubfolders")
|
||||
const emptyFolder = source.indexOf("knowledgeBase.folderTree.emptyFolder')")
|
||||
|
||||
assert.ok(search >= 0, 'the no-match message should stay')
|
||||
assert.ok(subfolders > search, 'the sub-folder message should follow the no-match one')
|
||||
assert.ok(emptyFolder > subfolders, 'the plain empty message should be the last resort')
|
||||
assert.match(source, /v-else-if="folderEmptyState === 'subfolders'"/)
|
||||
assert.match(source, /emptyFolderWithSubfolders', \{ count: folderSubfolderDocumentCount \}/)
|
||||
assert.match(source, /v-else-if="folderEmptyState === 'folder'"/)
|
||||
})
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,19 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { readFileSync } from 'node:fs'
|
||||
|
||||
const source = readFileSync(new URL('./KnowledgeBase.vue', import.meta.url), 'utf8')
|
||||
const condition = source.match(/<p v-if="([^"]+)" class="parser-hint"/)?.[1]
|
||||
|
||||
function shouldShowParserHint(canEdit: boolean, unsupportedFileTypes: string[]): boolean {
|
||||
assert.ok(condition, 'parser hint has a render condition')
|
||||
return Boolean(new Function('canEdit', 'unsupportedFileTypes', `return ${condition}`)(canEdit, unsupportedFileTypes))
|
||||
}
|
||||
|
||||
test('read-only users do not see the parser-engine warning (#4486)', () => {
|
||||
assert.equal(shouldShowParserHint(false, ['pdf']), false)
|
||||
})
|
||||
|
||||
test('editable users still see the parser-engine warning when needed (#4486)', () => {
|
||||
assert.equal(shouldShowParserHint(true, ['pdf']), true)
|
||||
})
|
||||
@@ -0,0 +1,20 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import test from 'node:test'
|
||||
|
||||
const source = readFileSync(new URL('./KnowledgeBase.vue', import.meta.url), 'utf8')
|
||||
|
||||
test('referenced documents navigate to their containing folder before opening details', () => {
|
||||
const resolveFolder = source.indexOf('await getKnowledgeDetails(targetId)')
|
||||
const selectFolder = source.indexOf('selectedFolderPath.value = detail.folder_path || ROOT_FOLDER_PATH')
|
||||
const openDetails = source.indexOf('openCardDetails(target)', selectFolder)
|
||||
|
||||
assert.ok(resolveFolder >= 0, 'document details should be fetched to resolve folder_path')
|
||||
assert.ok(selectFolder > resolveFolder, 'the containing folder should be selected after details load')
|
||||
assert.ok(openDetails > selectFolder, 'the detail drawer should open after folder navigation')
|
||||
})
|
||||
|
||||
test('a newer referenced-document navigation supersedes an older request', () => {
|
||||
assert.match(source, /const request = \+\+autoOpenRequest/)
|
||||
assert.match(source, /if \(request !== autoOpenRequest\) return;/)
|
||||
})
|
||||
@@ -0,0 +1,148 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import * as vue from 'vue'
|
||||
import * as marked from 'marked'
|
||||
import * as literalTilde from '../../utils/markedLiteralTilde.ts'
|
||||
import * as sorting from '../../utils/resourceSorting.ts'
|
||||
import { change, fixture, flush } from '../../test-utils/vueFixture.ts'
|
||||
|
||||
test('refreshes data source controls after assistant changes and stops on unmount', async t => {
|
||||
const f = fixture(t)
|
||||
const listDataSources = t.mock.fn(async (_id: string) => ({ data: [] }))
|
||||
const { close } = f.component(new URL('./settings/DataSourceSettings.vue', import.meta.url), {
|
||||
'vue-i18n': { useI18n: () => ({ t: (key: string) => key }) },
|
||||
'tdesign-vue-next': { MessagePlugin: { error: assert.fail } },
|
||||
'@/stores/auth': { useAuthStore: () => ({ hasRole: () => true }) },
|
||||
'@/utils/cronHumanize': {},
|
||||
'@/composables/useConnectorLabel': { useConnectorLabel: () => ({ connectorLabel: (type: string) => type }) },
|
||||
'@/api/datasource': { listDataSources },
|
||||
}, { kbId: 'kb' })
|
||||
await flush()
|
||||
listDataSources.mock.resetCalls()
|
||||
f.emit(change('agent.update'))
|
||||
t.mock.timers.tick(300)
|
||||
assert.equal(listDataSources.mock.callCount(), 0)
|
||||
f.emit(change('data_source.pause'))
|
||||
f.emit(change('data_source.sync'))
|
||||
f.emit(change('data_source.update_sync'))
|
||||
t.mock.timers.tick(300)
|
||||
await flush()
|
||||
assert.equal(listDataSources.mock.callCount(), 1)
|
||||
assert.equal(listDataSources.mock.calls[0].arguments[0], 'kb')
|
||||
close()
|
||||
f.emit(change('data_source.resume'))
|
||||
t.mock.timers.tick(300)
|
||||
assert.equal(listDataSources.mock.callCount(), 1)
|
||||
})
|
||||
|
||||
test('refreshes the FAQ entries and tags once per burst for its own KB only', async t => {
|
||||
const f = fixture(t)
|
||||
const listFAQEntries = t.mock.fn(async (_id: string, _params: unknown) => ({ data: { data: [], total: 1 } }))
|
||||
const listKnowledgeTags = t.mock.fn(async (_id: string, _params: unknown) => ({ data: { data: [], total: 0 } }))
|
||||
f.component(new URL('./components/FAQEntryManager.vue', import.meta.url), {
|
||||
'vue-router': { useRouter: () => ({}) },
|
||||
'vue-i18n': { useI18n: () => ({ t: (key: string) => key }) },
|
||||
'tdesign-vue-next': { MessagePlugin: { error: assert.fail } },
|
||||
'@/components/settings/useConfirmDelete': { useConfirmDelete: () => ({}) },
|
||||
'@/stores/auth': { useAuthStore: () => ({ hasRole: () => true }) },
|
||||
'@/stores/ui': { useUIStore: () => ({ clearSelectedTagIds() {} }) },
|
||||
'@/stores/organization': { useOrganizationStore: () => ({ sharedKnowledgeBases: [], async fetchSharedKnowledgeBases() {} }) },
|
||||
'@/stores/chatResources': { useChatResourcesStore: () => ({ rawKnowledgeBases: [], async ensureKnowledgeBases() {} }) },
|
||||
'@/api/knowledge-base': {
|
||||
listFAQEntries, listKnowledgeTags,
|
||||
getKnowledgeBaseById: async () => ({ data: { id: 'kb', type: 'faq' } }),
|
||||
},
|
||||
xlsx: {}, papaparse: {},
|
||||
}, { kbId: 'kb' })
|
||||
await flush()
|
||||
listFAQEntries.mock.resetCalls()
|
||||
listKnowledgeTags.mock.resetCalls()
|
||||
f.emit(change('faq.update_entry', { knowledge_base_id: ['other'] }))
|
||||
f.emit(change('agent.create', { knowledge_base_id: ['kb'] }))
|
||||
t.mock.timers.tick(300)
|
||||
assert.equal(listFAQEntries.mock.callCount(), 0)
|
||||
assert.equal(listKnowledgeTags.mock.callCount(), 0)
|
||||
f.emit(change('faq.batch_update', { knowledge_base_id: ['kb'] }))
|
||||
f.emit(change('faq.delete_entries', { knowledge_base_id: ['kb'] }))
|
||||
t.mock.timers.tick(300)
|
||||
await flush()
|
||||
assert.equal(listFAQEntries.mock.callCount(), 1)
|
||||
assert.equal(listKnowledgeTags.mock.callCount(), 1)
|
||||
assert.equal(listFAQEntries.mock.calls[0].arguments[0], 'kb')
|
||||
assert.equal(listKnowledgeTags.mock.calls[0].arguments[0], 'kb')
|
||||
assert.equal((listKnowledgeTags.mock.calls[0].arguments[1] as any).page, 1)
|
||||
})
|
||||
|
||||
test('refreshes Wiki pages, selected content and statistics for its own KB only', async t => {
|
||||
const f = fixture(t)
|
||||
const page = { id: 'page', slug: 'page', title: 'Updated title', content: '', version: 2 }
|
||||
const getWikiPage = t.mock.fn(async (_id: string, _slug: string) => ({ data: page }))
|
||||
const getWikiIndex = t.mock.fn(async () => ({ groups: [] }))
|
||||
const getWikiStats = t.mock.fn(async () => ({}))
|
||||
const { vm } = f.component(new URL('./wiki/WikiBrowser.vue', import.meta.url), {
|
||||
marked,
|
||||
'vue-router': { useRouter: () => ({}), useRoute: () => ({ query: {} }) },
|
||||
'vue-i18n': { useI18n: () => ({ t: (key: string) => key }) },
|
||||
'tdesign-vue-next': { MessagePlugin: { error: assert.fail } },
|
||||
'@/stores/assistant': { useAssistantStore: () => ({ visible: false }) },
|
||||
'@/composables/useAssistantPageContext': { useAssistantPageContext() {} },
|
||||
'@/stores/settings': { useSettingsStore: () => ({}) },
|
||||
'@/api/wiki': {
|
||||
getWikiPage, getWikiIndex, getWikiStats,
|
||||
listWikiIssues: async () => [], listWikiPages: async () => ({ pages: [], total: 0 }),
|
||||
listWikiFolders: async () => ({ folders: [] }),
|
||||
},
|
||||
'@/utils/security': { sanitizeMarkdownHTML: (html: string) => html, hydrateProtectedFileImages: async () => {} },
|
||||
'@/utils/markedLiteralTilde': literalTilde,
|
||||
'vue-virtual-scroller': {}, '@/api/knowledge-base': {}, '@/api/chat': {},
|
||||
}, { knowledgeBaseId: 'kb' })
|
||||
await flush()
|
||||
vm.selectedPage = { ...page, title: 'Old title' }
|
||||
const reloads = [getWikiPage, getWikiIndex, getWikiStats]
|
||||
reloads.forEach(reload => reload.mock.resetCalls())
|
||||
f.emit(change('wiki.revert', { knowledge_base_id: ['other'] }))
|
||||
f.emit(change('agent.create', { knowledge_base_id: ['kb'] }))
|
||||
t.mock.timers.tick(300)
|
||||
reloads.forEach(reload => assert.equal(reload.mock.callCount(), 0))
|
||||
f.emit(change('wiki.revert', { knowledge_base_id: ['kb'] }))
|
||||
f.emit(change('wiki.revert', { knowledge_base_id: ['kb'] }))
|
||||
t.mock.timers.tick(300)
|
||||
await flush()
|
||||
reloads.forEach(reload => assert.equal(reload.mock.callCount(), 1))
|
||||
assert.deepEqual(Array.from(getWikiPage.mock.calls[0].arguments), ['kb', 'page'])
|
||||
assert.equal(vm.selectedPage.title, 'Updated title')
|
||||
})
|
||||
|
||||
test('refreshes the mounted KB list with force for knowledge_base changes only', async t => {
|
||||
const f = fixture(t)
|
||||
const fetchKnowledgeBasesForList = t.mock.fn(async (_params: unknown, _force: boolean) => [{ id: 'kb', name: 'Updated KB' }])
|
||||
const { vm } = f.component(new URL('./KnowledgeBaseList.vue', import.meta.url), {
|
||||
'vue-router': { useRoute: () => ({ query: {} }), useRouter: () => ({}) },
|
||||
'vue-i18n': { useI18n: () => ({ t: (key: string) => key }) },
|
||||
'tdesign-vue-next': { MessagePlugin: {} },
|
||||
'@/stores/auth': { useAuthStore: () => ({ hasRole: () => true }) },
|
||||
'@/stores/ui': { useUIStore: () => ({}) },
|
||||
'@/stores/organization': { useOrganizationStore: () => ({
|
||||
sharedKnowledgeBases: [], async fetchOrganizations() {}, async fetchSharedKnowledgeBases() {},
|
||||
}) },
|
||||
'@/stores/chatResources': { useChatResourcesStore: () => ({ fetchKnowledgeBasesForList }) },
|
||||
'@/components/settings/useConfirmDelete': { useConfirmDelete: () => ({}) },
|
||||
'@/composables/useTenantModelReadiness': { useTenantModelReadiness: () => ({ loaded: vue.ref(true), isReadyForDocumentKb: vue.ref(true) }) },
|
||||
'@/composables/useListUrlState': { useListUrlState: () => ({ scope: vue.ref('all'), creator: vue.ref('all'), query: vue.ref('') }) },
|
||||
'@/composables/useResourcePins': { useResourcePins: () => ({ favorites: vue.ref([]), recents: vue.ref([]) }) },
|
||||
'@/api/knowledge-base': {}, '@/api/organization': {}, '@/config/contextualGuides': {},
|
||||
'@/utils/index': {}, '@/utils/kbPermission': {},
|
||||
'@/utils/resourceListSearch': {}, '@/utils/card-list-badge': {}, '@/utils/resourceSorting': sorting,
|
||||
})
|
||||
await flush()
|
||||
fetchKnowledgeBasesForList.mock.resetCalls()
|
||||
f.emit(change('unknown.update'))
|
||||
t.mock.timers.tick(300)
|
||||
assert.equal(fetchKnowledgeBasesForList.mock.callCount(), 0)
|
||||
f.emit(change('knowledge_base.generate_profile'))
|
||||
t.mock.timers.tick(300)
|
||||
await flush()
|
||||
assert.equal(fetchKnowledgeBasesForList.mock.callCount(), 1)
|
||||
assert.equal(fetchKnowledgeBasesForList.mock.calls[0].arguments[1], true)
|
||||
assert.equal(vm.kbs[0].name, 'Updated KB')
|
||||
})
|
||||
@@ -0,0 +1,100 @@
|
||||
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 { compileScript, parse } from '@vue/compiler-sfc'
|
||||
import * as vue from 'vue'
|
||||
|
||||
const source = readFileSync(new URL('./BatchTagDialog.vue', import.meta.url), 'utf8')
|
||||
const { descriptor } = parse(source)
|
||||
const compiled = ts.transpileModule(compileScript(descriptor, { id: 'tag-popover-test', inlineTemplate: true }).content, {
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 },
|
||||
}).outputText
|
||||
const translate = (key: string) => key
|
||||
type Host = { type: string; props: Record<string, any>; children: Host[]; text: string; parent?: Host }
|
||||
const node = (type: string): Host => ({ type, props: {}, children: [], text: '' })
|
||||
const renderer = vue.createRenderer<Host, Host>({
|
||||
createElement: node,
|
||||
createText: text => ({ ...node('#text'), text }),
|
||||
createComment: text => ({ ...node('#comment'), text }),
|
||||
patchProp: (el, key, _old, value) => { el.props[key] = value },
|
||||
setText: (el, text) => { el.text = text },
|
||||
setElementText: (el, text) => { el.children = []; el.text = text },
|
||||
parentNode: el => el.parent || null,
|
||||
nextSibling: el => el.parent?.children[el.parent.children.indexOf(el) + 1] || null,
|
||||
insert(el, parent, anchor) {
|
||||
if (el.parent) el.parent.children.splice(el.parent.children.indexOf(el), 1)
|
||||
el.parent = parent
|
||||
const index = anchor ? parent.children.indexOf(anchor) : -1
|
||||
parent.children.splice(index < 0 ? parent.children.length : index, 0, el)
|
||||
},
|
||||
remove(el) {
|
||||
el.parent?.children.splice(el.parent.children.indexOf(el), 1)
|
||||
el.parent = undefined
|
||||
},
|
||||
})
|
||||
const textOf = (el: Host): string => el.type === '#comment' ? '' : el.text + el.children.map(textOf).join('')
|
||||
const all = (el: Host, predicate: (node: Host) => boolean): Host[] => [
|
||||
...(predicate(el) ? [el] : []), ...el.children.flatMap(child => all(child, predicate)),
|
||||
]
|
||||
|
||||
|
||||
async function fixture() {
|
||||
const state = vue.reactive({ visible: false, kbId: 'kb', count: 2, preSelectedTagIds: ['a'], confirmLoading: false })
|
||||
const confirmations: string[][] = []
|
||||
const exports: { default?: vue.Component } = {}
|
||||
runInNewContext(compiled, { exports, require(name: string) {
|
||||
if (name === 'vue') return vue
|
||||
if (name === './KnowledgeTagPicker.vue') return { __esModule: true, default: vue.defineComponent({
|
||||
props: ['selectedIds'], emits: ['update:selectedIds', 'busy-change'],
|
||||
setup: (props, { emit }) => () => vue.h('picker', { selectedIds: props.selectedIds,
|
||||
onSelect: (ids: string[]) => emit('update:selectedIds', ids), onBusy: (busy: boolean) => emit('busy-change', busy),
|
||||
}),
|
||||
}) }
|
||||
throw new Error(name)
|
||||
} })
|
||||
const root = node('root')
|
||||
const app = renderer.createApp({ setup: () => () => vue.h(exports.default!, {
|
||||
...state, 'onUpdate:visible': (value: boolean) => { state.visible = value },
|
||||
onConfirm: (ids: string[]) => confirmations.push([...ids]),
|
||||
}) })
|
||||
app.config.globalProperties.$t = translate as typeof app.config.globalProperties.$t
|
||||
for (const [name, type] of [['t-dialog','dialog'],['t-button','button'],['t-icon','icon']]) {
|
||||
app.component(name!, vue.defineComponent({ setup: (_props,{slots}) => () => vue.h(type!,{},slots.default?.()) }))
|
||||
}
|
||||
app.mount(root)
|
||||
const settle = async () => { for (let i=0;i<5;i++) await vue.nextTick() }
|
||||
const find = (predicate: (el: Host) => boolean) => { const el=all(root,predicate)[0]; assert.ok(el); return el }
|
||||
const fire = async (el: Host,event='onClick',value?: unknown) => { await el.props[event](value); await settle() }
|
||||
state.visible=true; await settle()
|
||||
return { state, confirmations, find, fire, settle, close: () => app.unmount() }
|
||||
}
|
||||
|
||||
test('batch tagging starts with common tags and keeps the draft until the parent completes saving', async t => {
|
||||
const f=await fixture(); t.after(f.close)
|
||||
assert.deepEqual([...f.find(el=>el.type==='picker').props.selectedIds], ['a'])
|
||||
await f.fire(f.find(el=>el.type==='picker'),'onSelect',['a','b'])
|
||||
f.state.preSelectedTagIds=['c']; await f.settle()
|
||||
await f.fire(f.find(el=>el.type==='button'&&textOf(el)==='common.confirm'))
|
||||
assert.deepEqual(f.confirmations, [['a','b']])
|
||||
assert.equal(f.state.visible,true)
|
||||
f.state.visible=false; await f.settle()
|
||||
f.state.visible=true; await f.settle()
|
||||
assert.deepEqual([...f.find(el=>el.type==='picker').props.selectedIds], ['c'])
|
||||
})
|
||||
|
||||
test('tag mutations and batch saving prevent duplicate confirms and closing', async t => {
|
||||
const f=await fixture(); t.after(f.close)
|
||||
await f.fire(f.find(el=>el.type==='picker'),'onBusy',true)
|
||||
await f.fire(f.find(el=>el.type==='button'&&textOf(el)==='common.confirm'))
|
||||
await f.fire(f.find(el=>el.type==='button'&&textOf(el)==='common.cancel'))
|
||||
assert.equal(f.confirmations.length,0)
|
||||
assert.equal(f.state.visible,true)
|
||||
await f.fire(f.find(el=>el.type==='picker'),'onBusy',false)
|
||||
f.state.confirmLoading=true; await f.settle()
|
||||
await f.fire(f.find(el=>el.type==='button'&&textOf(el)==='common.confirm'))
|
||||
await f.fire(f.find(el=>el.type==='button'&&textOf(el)==='common.cancel'))
|
||||
assert.equal(f.confirmations.length,0)
|
||||
assert.equal(f.state.visible,true)
|
||||
})
|
||||
@@ -0,0 +1,166 @@
|
||||
<template>
|
||||
<t-dialog :visible="visible" :footer="false" width="420px" dialog-class-name="batch-tag-dialog"
|
||||
:close-on-overlay-click="false" destroy-on-close @close="handleClose">
|
||||
<template #header>
|
||||
<div class="batch-tag-heading">
|
||||
<div class="batch-tag-heading-row">
|
||||
<t-icon name="discount" size="16px" class="batch-tag-heading-icon" aria-hidden="true" />
|
||||
<span class="batch-tag-title">{{ $t('knowledgeBase.batchTagDialogHeading') }}</span>
|
||||
</div>
|
||||
<p class="batch-tag-subtitle">{{ $t('knowledgeBase.batchTagSubtitle', { count }) }}</p>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<KnowledgeTagPicker v-if="visible" :kb-id="kbId" :selected-ids="selectedIds"
|
||||
@update:selected-ids="selectedIds = $event" @changed="emit('tags-changed', $event)" @busy-change="tagBusy = $event" />
|
||||
|
||||
<div class="batch-tag-footer">
|
||||
<span class="batch-tag-selected-count">
|
||||
{{ $t('knowledgeBase.tagSelectedCount', { count: selectedIds.length }) }}
|
||||
</span>
|
||||
<div class="batch-tag-footer-right">
|
||||
<t-button variant="outline" size="small" :disabled="confirmLoading" @click="handleClose">
|
||||
{{ $t('common.cancel') }}
|
||||
</t-button>
|
||||
<t-button theme="primary" size="small" :loading="confirmLoading" :disabled="tagBusy" @click="handleConfirm">
|
||||
{{ $t('common.confirm') }}
|
||||
</t-button>
|
||||
</div>
|
||||
</div>
|
||||
</t-dialog>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, watch } from 'vue';
|
||||
import KnowledgeTagPicker from './KnowledgeTagPicker.vue';
|
||||
|
||||
const props = defineProps<{
|
||||
visible: boolean;
|
||||
count: number;
|
||||
kbId: string;
|
||||
preSelectedTagIds?: string[];
|
||||
confirmLoading?: boolean;
|
||||
}>();
|
||||
const emit = defineEmits<{
|
||||
(e: 'update:visible', value: boolean): void;
|
||||
(e: 'confirm', tagIds: string[]): void;
|
||||
(e: 'tags-changed', payload?: { deletedTagId?: string }): void;
|
||||
}>();
|
||||
const selectedIds = ref<string[]>([]);
|
||||
const tagBusy = ref(false);
|
||||
watch(() => props.visible, visible => {
|
||||
if (visible) selectedIds.value = [...(props.preSelectedTagIds ?? [])];
|
||||
}, { immediate: true });
|
||||
|
||||
function handleConfirm() {
|
||||
if (props.confirmLoading || tagBusy.value) return;
|
||||
emit('confirm', [...selectedIds.value]);
|
||||
}
|
||||
function handleClose() {
|
||||
if (props.confirmLoading || tagBusy.value) return;
|
||||
emit('update:visible', false);
|
||||
}
|
||||
</script>
|
||||
|
||||
<style>
|
||||
.batch-tag-dialog {
|
||||
overflow: hidden;
|
||||
padding: 0;
|
||||
border-radius: var(--app-radius-xs);
|
||||
}
|
||||
|
||||
.batch-tag-dialog .t-dialog__header {
|
||||
min-height: auto;
|
||||
padding: 20px 20px 0;
|
||||
}
|
||||
|
||||
.batch-tag-dialog .t-dialog__body {
|
||||
padding: 0 20px 20px;
|
||||
}
|
||||
|
||||
.batch-tag-dialog .t-dialog__close {
|
||||
top: 16px;
|
||||
right: 16px;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
border-radius: var(--app-radius-xs);
|
||||
color: var(--td-text-color-secondary);
|
||||
transition: background 0.18s ease;
|
||||
}
|
||||
|
||||
.batch-tag-dialog .t-dialog__close:hover {
|
||||
color: var(--td-text-color-primary);
|
||||
background: var(--td-bg-color-container-hover);
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.batch-tag-dialog {
|
||||
width: calc(100vw - 24px) !important;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
<style scoped>
|
||||
.batch-tag-heading {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
min-width: 0;
|
||||
padding-right: 28px;
|
||||
}
|
||||
|
||||
.batch-tag-heading-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.batch-tag-heading-icon {
|
||||
flex-shrink: 0;
|
||||
color: var(--td-text-color-secondary);
|
||||
}
|
||||
|
||||
.batch-tag-title {
|
||||
color: var(--td-text-color-primary);
|
||||
font-size: var(--app-text-lg);
|
||||
font-weight: 600;
|
||||
line-height: 22px;
|
||||
letter-spacing: 0.2px;
|
||||
}
|
||||
|
||||
.batch-tag-subtitle {
|
||||
margin: 0;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
color: var(--td-text-color-placeholder);
|
||||
font-size: var(--app-text-sm);
|
||||
font-weight: 400;
|
||||
line-height: 18px;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.batch-tag-footer {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
margin-top: 14px;
|
||||
padding-top: 14px;
|
||||
border-top: 1px solid var(--td-component-stroke);
|
||||
}
|
||||
|
||||
.batch-tag-selected-count {
|
||||
font-size: var(--app-text-sm);
|
||||
color: var(--td-text-color-placeholder);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.batch-tag-footer-right {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,193 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
|
||||
interface KnowledgeItem {
|
||||
id: string;
|
||||
file_name?: string;
|
||||
title?: string;
|
||||
type?: string;
|
||||
parse_status?: string;
|
||||
}
|
||||
|
||||
const props = defineProps<{
|
||||
item: KnowledgeItem;
|
||||
canDownload: boolean;
|
||||
canMutateKnowledge: boolean;
|
||||
traceVisible: boolean;
|
||||
/** Whether the knowledge base has a folder structure to file documents into. */
|
||||
foldersAvailable?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'download'): void;
|
||||
(e: 'edit'): void;
|
||||
(e: 'view-trace'): void;
|
||||
(e: 'reparse'): void;
|
||||
(e: 'cancel-parse'): void;
|
||||
(e: 'move'): void;
|
||||
(e: 'move-folder'): void;
|
||||
(e: 'batch-manage'): void;
|
||||
(e: 'delete'): void;
|
||||
}>();
|
||||
|
||||
|
||||
const CANCELABLE_PARSE_STATUSES = new Set(['pending', 'processing', 'finalizing']);
|
||||
|
||||
const isParseInFlight = computed(() =>
|
||||
CANCELABLE_PARSE_STATUSES.has(String(props.item.parse_status ?? ''))
|
||||
);
|
||||
|
||||
const fileName = computed(() => props.item.file_name || props.item.title || props.item.id);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<!-- 下载原始文档 -->
|
||||
<div
|
||||
v-if="canDownload && (item.type === 'file' || item.type === 'manual')"
|
||||
class="doc-action-menu-item"
|
||||
@click.stop="emit('download')"
|
||||
>
|
||||
<t-icon class="icon" name="download" />
|
||||
<span>{{ $t('common.download') }}</span>
|
||||
</div>
|
||||
|
||||
<!-- 编辑文档 -->
|
||||
<div v-if="item.type === 'manual'" class="doc-action-menu-item" @click.stop="emit('edit')">
|
||||
<t-icon class="icon" name="edit" />
|
||||
<span>{{ $t('knowledgeBase.editDocument') }}</span>
|
||||
</div>
|
||||
|
||||
<!-- 查看处理过程 -->
|
||||
<div v-if="traceVisible" class="doc-action-menu-item" @click.stop="emit('view-trace')">
|
||||
<t-icon class="icon" name="chart-bar" />
|
||||
<span>{{ $t('knowledgeStages.viewTrace') }}</span>
|
||||
</div>
|
||||
|
||||
<!-- 重建知识 (in-flight: no popconfirm, just emits) -->
|
||||
<div v-if="isParseInFlight" class="doc-action-menu-item" @click.stop="emit('reparse')">
|
||||
<t-icon class="icon" name="refresh" />
|
||||
<span>{{ $t('knowledgeBase.rebuildDocument') }}</span>
|
||||
</div>
|
||||
|
||||
<!-- 重建知识 (normal: with popconfirm) -->
|
||||
<t-popconfirm v-else theme="warning"
|
||||
:content="$t('knowledgeBase.rebuildConfirm', { fileName })"
|
||||
:confirm-btn="{ content: $t('common.confirm'), theme: 'primary' }"
|
||||
:cancel-btn="{ content: $t('common.cancel') }" placement="left"
|
||||
@confirm="emit('reparse')">
|
||||
<div class="doc-action-menu-item" @click.stop>
|
||||
<t-icon class="icon" name="refresh" />
|
||||
<span>{{ $t('knowledgeBase.rebuildDocument') }}</span>
|
||||
</div>
|
||||
</t-popconfirm>
|
||||
|
||||
<!-- 取消解析 -->
|
||||
<t-popconfirm v-if="isParseInFlight" theme="warning"
|
||||
:content="$t('knowledgeBase.cancelParseConfirmBody', { title: fileName })"
|
||||
:confirm-btn="{ content: $t('knowledgeBase.cancelParse'), theme: 'danger' }"
|
||||
:cancel-btn="{ content: $t('common.cancel') }" placement="left"
|
||||
@confirm="emit('cancel-parse')">
|
||||
<div class="doc-action-menu-item danger" @click.stop>
|
||||
<t-icon class="icon" name="close-circle" />
|
||||
<span>{{ $t('knowledgeBase.cancelParse') }}</span>
|
||||
</div>
|
||||
</t-popconfirm>
|
||||
|
||||
<!-- 移动到目录 -->
|
||||
<div v-if="canMutateKnowledge" class="doc-action-menu-item" @click.stop="emit('move-folder')">
|
||||
<t-icon class="icon" name="folder" />
|
||||
<span>{{ $t('knowledgeBase.moveToFolder.action') }}</span>
|
||||
</div>
|
||||
|
||||
<!-- 移动到其他知识库 -->
|
||||
<div v-if="canMutateKnowledge" class="doc-action-menu-item" @click.stop="emit('move')">
|
||||
<t-icon class="icon" name="swap" />
|
||||
<span>{{ $t('knowledgeBase.moveDocument') }}</span>
|
||||
</div>
|
||||
|
||||
<!-- 批量管理 -->
|
||||
<div v-if="canMutateKnowledge || canDownload" class="doc-action-menu-item" @click.stop="emit('batch-manage')">
|
||||
<t-icon class="icon" name="queue" />
|
||||
<span>{{ $t('menu.batchManage') }}</span>
|
||||
</div>
|
||||
|
||||
<!-- 删除文档 -->
|
||||
<t-popconfirm theme="warning"
|
||||
:content="$t('knowledgeBase.confirmDeleteDocument', { fileName })"
|
||||
:confirm-btn="{ content: $t('knowledgeBase.confirmDelete'), theme: 'danger' }"
|
||||
:cancel-btn="{ content: $t('common.cancel') }" placement="left"
|
||||
@confirm="emit('delete')">
|
||||
<div class="doc-action-menu-item danger" @click.stop>
|
||||
<t-icon class="icon" name="delete" />
|
||||
<span>{{ $t('knowledgeBase.deleteDocument') }}</span>
|
||||
</div>
|
||||
</t-popconfirm>
|
||||
</template>
|
||||
|
||||
<style scoped lang="less">
|
||||
.doc-action-menu-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 6px 10px;
|
||||
font-family: var(--app-font-family);
|
||||
font-size: var(--app-text-base);
|
||||
font-weight: 400;
|
||||
line-height: 20px;
|
||||
color: var(--td-text-color-primary);
|
||||
cursor: pointer;
|
||||
border-radius: var(--app-radius-xs);
|
||||
transition: background-color var(--app-motion-fast) cubic-bezier(0.2, 0, 0, 1);
|
||||
|
||||
&:hover {
|
||||
background: var(--td-bg-color-container-hover);
|
||||
}
|
||||
|
||||
&:active {
|
||||
background: var(--td-bg-color-container-active);
|
||||
}
|
||||
|
||||
.icon {
|
||||
font-size: var(--app-text-2xl);
|
||||
color: var(--td-text-color-secondary);
|
||||
transition: color var(--app-motion-fast) ease;
|
||||
}
|
||||
|
||||
&:hover .icon {
|
||||
color: var(--td-text-color-primary);
|
||||
}
|
||||
|
||||
&.danger {
|
||||
color: var(--td-error-color-6);
|
||||
margin-top: 4px;
|
||||
position: relative;
|
||||
|
||||
&::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: -3px;
|
||||
left: 8px;
|
||||
right: 8px;
|
||||
height: 1px;
|
||||
background: var(--td-component-stroke);
|
||||
}
|
||||
|
||||
.icon {
|
||||
color: var(--td-error-color-6);
|
||||
}
|
||||
|
||||
&:hover {
|
||||
background: var(--td-error-color-1);
|
||||
color: var(--td-error-color-6);
|
||||
|
||||
.icon {
|
||||
color: var(--td-error-color-6);
|
||||
}
|
||||
}
|
||||
|
||||
&:active {
|
||||
background: var(--td-error-color-2);
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,190 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import FolderPickerMenu, { type FolderOption } from './FolderPickerMenu.vue';
|
||||
|
||||
defineProps<{
|
||||
count: number;
|
||||
deleteLoading?: boolean;
|
||||
reparseLoading?: boolean;
|
||||
tagLoading?: boolean;
|
||||
downloadLoading?: boolean;
|
||||
canDownload?: boolean;
|
||||
canMutate?: boolean;
|
||||
// When true the bar stays visible even with 0 selections, so users can exit
|
||||
// batch mode from here without selecting anything first.
|
||||
visible?: boolean;
|
||||
/** Hidden when the knowledge base has no folder structure to file into. */
|
||||
showMoveToFolder?: boolean;
|
||||
folderOptions?: FolderOption[];
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'cancel'): void;
|
||||
(e: 'delete'): void;
|
||||
(e: 'reparse'): void;
|
||||
(e: 'batchTag'): void;
|
||||
(e: 'moveToFolder', folderPath: string): void;
|
||||
(e: 'download'): void;
|
||||
(e: 'selectLoaded'): void;
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
const folderPickerVisible = ref(false);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<transition name="batch-bar-fade">
|
||||
<div v-if="visible || count > 0" class="doc-batch-bar" role="region"
|
||||
:aria-label="t('knowledgeBase.selectedCount', { count })">
|
||||
<div class="batch-bar-inner">
|
||||
<div class="batch-bar-left">
|
||||
<span class="batch-bar-count">{{ t('knowledgeBase.selectedCount', { count }) }}</span>
|
||||
<t-button variant="text" theme="default" size="small" class="batch-bar-clear"
|
||||
:disabled="downloadLoading" @click="emit('selectLoaded')">
|
||||
{{ t('knowledgeBase.selectLoaded') }}
|
||||
</t-button>
|
||||
<t-button variant="text" theme="default" size="small" class="batch-bar-clear"
|
||||
:disabled="downloadLoading" @click="emit('cancel')">
|
||||
{{ t('knowledgeBase.clearSelection') }}
|
||||
</t-button>
|
||||
</div>
|
||||
<div class="batch-bar-actions">
|
||||
<t-tooltip v-if="canDownload" :content="t('knowledgeBase.batchDownloadHint')">
|
||||
<span class="batch-download-trigger">
|
||||
<t-button theme="primary" size="small" :loading="downloadLoading"
|
||||
:disabled="count === 0 || count > 200 || deleteLoading || reparseLoading || tagLoading || downloadLoading"
|
||||
@click="emit('download')">
|
||||
<template #icon><t-icon name="download" size="14px" /></template>
|
||||
{{ t(downloadLoading ? 'knowledgeBase.batchDownloading' : 'knowledgeBase.batchDownload') }}
|
||||
</t-button>
|
||||
</span>
|
||||
</t-tooltip>
|
||||
|
||||
<t-popconfirm v-if="canMutate" theme="warning" :content="t('knowledgeBase.confirmBatchReparseDocument', { count })"
|
||||
:confirm-btn="{ content: t('knowledgeBase.confirmBatchReparse'), theme: 'warning' }"
|
||||
:cancel-btn="{ content: t('common.cancel') }" placement="top" @confirm="emit('reparse')">
|
||||
<t-button theme="default" variant="outline" size="small"
|
||||
:disabled="count === 0 || deleteLoading || reparseLoading || tagLoading || downloadLoading" :loading="reparseLoading" @click.stop>
|
||||
<template #icon><t-icon name="refresh" size="14px" /></template>
|
||||
{{ t('knowledgeBase.rebuildDocument') }}
|
||||
</t-button>
|
||||
</t-popconfirm>
|
||||
|
||||
<t-button v-if="canMutate" theme="default" variant="outline" size="small"
|
||||
:disabled="count === 0 || deleteLoading || reparseLoading || tagLoading || downloadLoading" :loading="tagLoading"
|
||||
@click="emit('batchTag')">
|
||||
<template #icon><t-icon name="tag" size="14px" /></template>
|
||||
{{ t('knowledgeBase.batchTag') }}
|
||||
</t-button>
|
||||
|
||||
<t-popup v-if="canMutate && showMoveToFolder" v-model:visible="folderPickerVisible" trigger="click"
|
||||
placement="top" overlay-class-name="card-more" destroy-on-close>
|
||||
<t-button theme="default" variant="outline" size="small"
|
||||
:disabled="count === 0 || deleteLoading || reparseLoading || tagLoading || downloadLoading">
|
||||
<template #icon><t-icon name="folder" size="14px" /></template>
|
||||
{{ t('knowledgeBase.moveToFolder.action') }}
|
||||
</t-button>
|
||||
<template #content>
|
||||
<div class="card-menu">
|
||||
<FolderPickerMenu :options="folderOptions || []"
|
||||
@confirm="(path: string) => { folderPickerVisible = false; emit('moveToFolder', path) }" />
|
||||
</div>
|
||||
</template>
|
||||
</t-popup>
|
||||
|
||||
<t-popconfirm v-if="canMutate" theme="warning" :content="t('knowledgeBase.confirmBatchDeleteDocument', { count })"
|
||||
:confirm-btn="{ content: t('knowledgeBase.confirmDelete'), theme: 'danger' }"
|
||||
:cancel-btn="{ content: t('common.cancel') }" placement="top" @confirm="emit('delete')">
|
||||
<t-button theme="danger" variant="outline" size="small"
|
||||
:disabled="count === 0 || deleteLoading || reparseLoading || tagLoading || downloadLoading" :loading="deleteLoading" @click.stop>
|
||||
<template #icon><t-icon name="delete" size="14px" /></template>
|
||||
{{ t('knowledgeBase.batchDelete') }}
|
||||
</t-button>
|
||||
</t-popconfirm>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</transition>
|
||||
</template>
|
||||
|
||||
<style scoped lang="less">
|
||||
.doc-batch-bar {
|
||||
position: relative;
|
||||
z-index: 5;
|
||||
width: 100%;
|
||||
max-width: 920px;
|
||||
margin: 0 auto;
|
||||
padding: 0 4px;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.batch-bar-inner {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
padding: 8px 12px;
|
||||
background: var(--td-bg-color-container);
|
||||
border: 1px solid var(--td-component-stroke);
|
||||
border-radius: var(--app-radius-md);
|
||||
box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08);
|
||||
}
|
||||
|
||||
.batch-bar-left {
|
||||
display: flex;
|
||||
flex-wrap: nowrap;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
min-width: 0;
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.batch-bar-count {
|
||||
font-size: var(--app-text-md);
|
||||
font-weight: 500;
|
||||
color: var(--td-text-color-secondary);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.batch-bar-clear {
|
||||
flex-shrink: 0;
|
||||
padding: 0 6px !important;
|
||||
height: 28px !important;
|
||||
font-size: var(--app-text-sm);
|
||||
color: var(--td-text-color-secondary) !important;
|
||||
|
||||
&:hover {
|
||||
color: var(--td-text-color-primary) !important;
|
||||
}
|
||||
}
|
||||
|
||||
.batch-bar-actions {
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.batch-bar-actions > * { flex-shrink: 0; }
|
||||
|
||||
.batch-download-trigger {
|
||||
display: inline-flex;
|
||||
}
|
||||
|
||||
.batch-bar-fade-enter-active,
|
||||
.batch-bar-fade-leave-active {
|
||||
transition: transform var(--app-motion-base) ease, opacity var(--app-motion-base) ease;
|
||||
}
|
||||
|
||||
.batch-bar-fade-enter-from,
|
||||
.batch-bar-fade-leave-to {
|
||||
opacity: 0;
|
||||
transform: translateY(6px);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,35 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { readFileSync } from 'node:fs'
|
||||
|
||||
const knowledgeBase = readFileSync(new URL('../KnowledgeBase.vue', import.meta.url), 'utf8')
|
||||
const batchBar = readFileSync(new URL('./DocumentBatchBar.vue', import.meta.url), 'utf8')
|
||||
const listView = readFileSync(new URL('./DocumentListView.vue', import.meta.url), 'utf8')
|
||||
const knowledgeApi = readFileSync(new URL('../../../api/knowledge-base/index.ts', import.meta.url), 'utf8')
|
||||
const request = readFileSync(new URL('../../../utils/request.ts', import.meta.url), 'utf8')
|
||||
|
||||
test('批量下载使用受认证的 Blob 请求并支持取消', () => {
|
||||
assert.match(knowledgeApi, /knowledge-bases\/\$\{encodeURIComponent\(kbId\)\}\/knowledge\/batch-download/)
|
||||
assert.match(knowledgeApi, /responseType:\s*'blob'/)
|
||||
assert.match(knowledgeApi, /signal,/)
|
||||
assert.match(knowledgeBase, /new AbortController\(\)/)
|
||||
assert.match(knowledgeBase, /batchDownloadController\?\.abort\(\)/)
|
||||
})
|
||||
|
||||
test('批量下载界面限制单批 200 项并保留只读权限边界', () => {
|
||||
assert.match(batchBar, /v-if="canDownload"/)
|
||||
assert.match(batchBar, /count > 200/)
|
||||
assert.match(batchBar, /batch-download-trigger/)
|
||||
assert.match(batchBar, /v-if="canMutate"/)
|
||||
assert.match(knowledgeBase, /isBatchDownloadableKnowledge/)
|
||||
assert.match(knowledgeBase, /ids\.length > MAX_BATCH_DOWNLOAD_FILES/)
|
||||
assert.match(knowledgeBase, /:can-download="canDownloadKnowledge"/)
|
||||
assert.match(knowledgeBase, /@select-loaded="toggleSelectAll\(true\)"/)
|
||||
assert.match(listView, /v-if="canEdit \|\| canDownload"/)
|
||||
})
|
||||
|
||||
test('Blob 格式的 JSON 错误会还原为可读消息', () => {
|
||||
assert.match(request, /error\.response\.data instanceof Blob/)
|
||||
assert.match(request, /JSON\.parse\(text\)/)
|
||||
assert.match(request, /text\.startsWith\('\{'\)/)
|
||||
})
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,44 @@
|
||||
<template>
|
||||
<span v-if="sourceType === 'manual' || sourceType === 'url'" class="document-source-icon"
|
||||
:class="`document-source-icon--${sourceType}`" aria-hidden="true">
|
||||
<svg viewBox="0 0 32 38" fill="none">
|
||||
<path class="file-sheet" d="M6 1.5h13L28.5 11v22A3.5 3.5 0 0 1 25 36.5H6A3.5 3.5 0 0 1 2.5 33V5A3.5 3.5 0 0 1 6 1.5Z" />
|
||||
<path class="file-fold" d="M19 1.5V8a3 3 0 0 0 3 3h6.5" />
|
||||
<path class="file-lines" d="M8 14h9M8 18h14" />
|
||||
</svg>
|
||||
<span class="document-source-icon__badge"><t-icon :name="sourceType === 'manual' ? 'edit' : 'link'" size="13px" /></span>
|
||||
</span>
|
||||
<ArtifactFileIcon v-else :file-name="fileName" />
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import ArtifactFileIcon from '@/views/chat/components/ArtifactFileIcon.vue';
|
||||
defineProps<{ sourceType?: string; fileName: string }>();
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
@import '@/components/css/artifact-file-icon.less';
|
||||
.document-source-icon {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
flex: 0 0 32px;
|
||||
width: 32px;
|
||||
height: 38px;
|
||||
color: #7885ad;
|
||||
&--url { color: #53978e; }
|
||||
> svg { .artifact-file-icon-style(); color: inherit; }
|
||||
&__badge {
|
||||
position: absolute;
|
||||
right: 1px;
|
||||
bottom: 1px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 24px;
|
||||
height: 16px;
|
||||
border-radius: var(--app-radius-xs);
|
||||
background: currentColor;
|
||||
.t-icon { color: #fff; }
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,305 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import test from 'node:test'
|
||||
import { compileScript, parse } from '@vue/compiler-sfc'
|
||||
import ts from 'typescript'
|
||||
import { runInNewContext } from 'node:vm'
|
||||
import * as vue from 'vue'
|
||||
import * as vueI18n from 'vue-i18n'
|
||||
import { createI18n } from 'vue-i18n'
|
||||
import enUS from '../../../i18n/locales/en-US'
|
||||
import * as files from '../../../utils/files.ts'
|
||||
import * as referenceSources from '../../../utils/referenceSources.ts'
|
||||
import * as processingStall from '../../../utils/knowledgeProcessingStall.ts'
|
||||
|
||||
/**
|
||||
* The document list and card grid are rendered for real here: the SFC is
|
||||
* compiled with its template inlined and mounted on a tiny host renderer. The
|
||||
* host tree is enough to assert row order and to click a row, which source
|
||||
* regexes alone cannot do.
|
||||
*/
|
||||
|
||||
type HostNode = {
|
||||
kind: 'element' | 'text' | 'comment'
|
||||
tag?: unknown
|
||||
text?: string
|
||||
props: Record<string, any>
|
||||
children: HostNode[]
|
||||
parent: HostNode | null
|
||||
style?: Record<string, string>
|
||||
}
|
||||
|
||||
function hostElement(tag: unknown): HostNode {
|
||||
return { kind: 'element', tag, text: '', props: {}, children: [], parent: null, style: {} } as HostNode
|
||||
}
|
||||
|
||||
const noopComponent = vue.defineComponent({ name: 'Stub', setup: () => () => null })
|
||||
|
||||
function evaluateModule(source: string, dependencies: Record<string, unknown>): any {
|
||||
const exports: any = {}
|
||||
const teleportTarget = hostElement('teleport-target')
|
||||
const fakeDocument = {
|
||||
querySelector: () => teleportTarget,
|
||||
createElement: () => hostElement('detached'),
|
||||
body: teleportTarget,
|
||||
}
|
||||
runInNewContext(
|
||||
ts.transpileModule(source, {
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 },
|
||||
}).outputText,
|
||||
{
|
||||
exports,
|
||||
console,
|
||||
Set,
|
||||
document: fakeDocument,
|
||||
require(name: string) {
|
||||
if (name in dependencies) return dependencies[name]
|
||||
throw new Error(`Unexpected dependency: ${name}`)
|
||||
},
|
||||
},
|
||||
)
|
||||
return exports
|
||||
}
|
||||
|
||||
const componentCache = new Map<string, any>()
|
||||
|
||||
function loadView(file: URL, extraDependencies: Record<string, unknown> = {}): any {
|
||||
const key = file.pathname
|
||||
const cached = componentCache.get(key)
|
||||
if (cached) return cached
|
||||
const { descriptor } = parse(readFileSync(file, 'utf8'), { filename: file.pathname })
|
||||
const script = compileScript(descriptor, { id: `folder-entry-${key}`, inlineTemplate: true }).content
|
||||
const module = evaluateModule(script, {
|
||||
vue,
|
||||
'vue-i18n': vueI18n,
|
||||
'@/utils/files': files,
|
||||
'@/utils/referenceSources': referenceSources,
|
||||
'@/utils/knowledgeProcessingStall': processingStall,
|
||||
'./KnowledgeTagPopover.vue': noopComponent,
|
||||
'./DocumentFileIcon.vue': noopComponent,
|
||||
'./DocumentActionMenu.vue': noopComponent,
|
||||
'./FolderPickerMenu.vue': noopComponent,
|
||||
'@/components/knowledge-processing-timeline.vue': noopComponent,
|
||||
...extraDependencies,
|
||||
})
|
||||
componentCache.set(key, module.default)
|
||||
return module.default
|
||||
}
|
||||
|
||||
function hostRenderer() {
|
||||
const teleportTarget = hostElement('teleport-target')
|
||||
return vue.createRenderer<HostNode, HostNode>({
|
||||
querySelector: () => teleportTarget,
|
||||
createElement: (tag) => hostElement(tag),
|
||||
insert(child, parent, anchor) {
|
||||
child.parent = parent
|
||||
const index = anchor ? parent.children.indexOf(anchor) : -1
|
||||
if (index >= 0) parent.children.splice(index, 0, child)
|
||||
else parent.children.push(child)
|
||||
},
|
||||
remove(child) {
|
||||
const parent = child.parent
|
||||
if (!parent) return
|
||||
const index = parent.children.indexOf(child)
|
||||
if (index >= 0) parent.children.splice(index, 1)
|
||||
},
|
||||
createText: (text) => ({ kind: 'text', text, props: {}, children: [], parent: null }),
|
||||
createComment: (text) => ({ kind: 'comment', text, props: {}, children: [], parent: null }),
|
||||
setText(node, text) {
|
||||
node.text = text
|
||||
},
|
||||
setElementText(node, text) {
|
||||
node.children = [{ kind: 'text', text, props: {}, children: [], parent: node }]
|
||||
},
|
||||
patchProp(el, key, _previous, next) {
|
||||
el.props[key] = next
|
||||
},
|
||||
parentNode: (node) => node.parent,
|
||||
nextSibling: (node) => {
|
||||
const parent = node.parent
|
||||
if (!parent) return null
|
||||
const index = parent.children.indexOf(node)
|
||||
return parent.children[index + 1] ?? null
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
function mountView(file: URL, props: Record<string, unknown>) {
|
||||
const renderer = hostRenderer()
|
||||
const app = renderer.createApp(loadView(file), {
|
||||
canEdit: false,
|
||||
canDownload: false,
|
||||
canMutateKnowledge: false,
|
||||
moveMenuMode: 'normal',
|
||||
moveTargetKbs: [],
|
||||
moveTargetsLoading: false,
|
||||
moveSelectedTargetName: '',
|
||||
moveMode: 'reuse_vectors',
|
||||
moveSubmitting: false,
|
||||
...props,
|
||||
} as any)
|
||||
app.use(createI18n({ legacy: false, locale: 'en-US', messages: { 'en-US': enUS } }))
|
||||
for (const name of [
|
||||
't-icon',
|
||||
't-checkbox',
|
||||
't-popup',
|
||||
't-tag',
|
||||
't-button',
|
||||
't-radio',
|
||||
't-loading',
|
||||
't-tooltip',
|
||||
't-skeleton',
|
||||
't-input',
|
||||
]) {
|
||||
app.component(
|
||||
name,
|
||||
vue.defineComponent({ name, setup: (_, { slots }) => () => vue.h('span', slots.default?.()) }),
|
||||
)
|
||||
}
|
||||
const root = hostElement('root')
|
||||
const vm = app.mount(root) as any
|
||||
return {
|
||||
root,
|
||||
vm,
|
||||
unmount: () => app.unmount(),
|
||||
}
|
||||
}
|
||||
|
||||
function allElements(node: HostNode): HostNode[] {
|
||||
const elements: HostNode[] = []
|
||||
const walk = (current: HostNode) => {
|
||||
if (current.kind === 'element') elements.push(current)
|
||||
current.children.forEach(walk)
|
||||
}
|
||||
walk(node)
|
||||
return elements
|
||||
}
|
||||
|
||||
function classesOf(node: HostNode): string[] {
|
||||
return String(node.props.class ?? '').split(/\s+/).filter(Boolean)
|
||||
}
|
||||
|
||||
function textOf(node: HostNode): string {
|
||||
if (node.kind === 'text') return node.text ?? ''
|
||||
return node.children.map(textOf).join('')
|
||||
}
|
||||
|
||||
const folder = {
|
||||
path: '培训材料库/2024使用培训视频',
|
||||
name: '2024使用培训视频',
|
||||
document_count: 1,
|
||||
total_count: 1,
|
||||
}
|
||||
|
||||
const documents = [
|
||||
{ id: 'doc-1', file_name: '天诛渗透攻防平台用户手册V202403', parse_status: 'completed', file_type: 'pdf' },
|
||||
{ id: 'doc-2', file_name: '【使用必看】天诛2024新版本', parse_status: 'completed', file_type: 'pdf' },
|
||||
]
|
||||
|
||||
function mountList(overrides: Record<string, unknown> = {}) {
|
||||
return mountView(new URL('./DocumentListView.vue', import.meta.url), {
|
||||
items: documents,
|
||||
subFolders: [folder],
|
||||
kbId: 'kb',
|
||||
selectedIds: new Set<string>(),
|
||||
traceVisibleIds: {},
|
||||
...overrides,
|
||||
})
|
||||
}
|
||||
|
||||
function mountCards(overrides: Record<string, unknown> = {}) {
|
||||
return mountView(new URL('./DocumentCardView.vue', import.meta.url), {
|
||||
items: documents,
|
||||
subFolders: [folder],
|
||||
kbId: 'kb',
|
||||
selectedIds: new Set<string>(),
|
||||
batchMode: false,
|
||||
traceAvailableById: {},
|
||||
...overrides,
|
||||
})
|
||||
}
|
||||
|
||||
test('the list renders one folder row before the document rows', () => {
|
||||
const opened: string[] = []
|
||||
const view = mountList({ onOpenFolder: (path: string) => opened.push(path) })
|
||||
try {
|
||||
const rows = allElements(view.root).filter((element) => classesOf(element).includes('doc-list-row'))
|
||||
const folderRows = rows.filter((row) => row.props['data-folder-path'] !== undefined)
|
||||
const documentRows = rows.filter((row) => row.props['data-folder-path'] === undefined)
|
||||
|
||||
assert.equal(folderRows.length, 1)
|
||||
assert.equal(documentRows.length, 2)
|
||||
assert.ok(rows.indexOf(folderRows[0]) < rows.indexOf(documentRows[0]), 'folder row comes first')
|
||||
assert.equal(folderRows[0].props['data-folder-path'], folder.path)
|
||||
assert.match(textOf(folderRows[0]), /2024使用培训视频/)
|
||||
// The folder takes no part in batch selection: its checkbox cell stays empty.
|
||||
assert.equal(
|
||||
allElements(folderRows[0]).filter((element) => classesOf(element).includes('doc-list-check')).length,
|
||||
0,
|
||||
)
|
||||
|
||||
folderRows[0].props.onClick({ stopPropagation() {} })
|
||||
assert.deepEqual(opened, [folder.path])
|
||||
} finally {
|
||||
view.unmount()
|
||||
}
|
||||
})
|
||||
|
||||
test('the card grid renders one folder card before the document cards', () => {
|
||||
const opened: string[] = []
|
||||
const view = mountCards({ onOpenFolder: (path: string) => opened.push(path) })
|
||||
try {
|
||||
const cards = allElements(view.root).filter((element) => classesOf(element).includes('knowledge-card'))
|
||||
const folderCards = cards.filter((card) => card.props['data-folder-path'] !== undefined)
|
||||
const documentCards = cards.filter((card) => card.props['data-folder-path'] === undefined)
|
||||
|
||||
assert.equal(folderCards.length, 1)
|
||||
assert.equal(documentCards.length, 2)
|
||||
assert.ok(cards.indexOf(folderCards[0]) < cards.indexOf(documentCards[0]), 'folder card comes first')
|
||||
assert.equal(folderCards[0].props['data-folder-path'], folder.path)
|
||||
assert.match(textOf(folderCards[0]), /2024使用培训视频/)
|
||||
|
||||
folderCards[0].props.onClick({ stopPropagation() {} })
|
||||
assert.deepEqual(opened, [folder.path])
|
||||
} finally {
|
||||
view.unmount()
|
||||
}
|
||||
})
|
||||
|
||||
test('no folder rows or cards are rendered when the caller filters them out', () => {
|
||||
const list = mountList({ subFolders: [] })
|
||||
try {
|
||||
const rows = allElements(list.root).filter((element) => classesOf(element).includes('doc-list-row'))
|
||||
assert.equal(rows.filter((row) => row.props['data-folder-path'] !== undefined).length, 0)
|
||||
assert.equal(rows.length, 2)
|
||||
} finally {
|
||||
list.unmount()
|
||||
}
|
||||
|
||||
const cards = mountCards({ subFolders: [] })
|
||||
try {
|
||||
const cardElements = allElements(cards.root).filter((element) => classesOf(element).includes('knowledge-card'))
|
||||
assert.equal(cardElements.filter((card) => card.props['data-folder-path'] !== undefined).length, 0)
|
||||
assert.equal(cardElements.length, 2)
|
||||
} finally {
|
||||
cards.unmount()
|
||||
}
|
||||
})
|
||||
|
||||
test('an absent folder list renders no folder rows and does not crash', () => {
|
||||
const list = mountList({ subFolders: undefined })
|
||||
try {
|
||||
const rows = allElements(list.root).filter((element) => classesOf(element).includes('doc-list-row'))
|
||||
assert.equal(rows.length, 2)
|
||||
} finally {
|
||||
list.unmount()
|
||||
}
|
||||
|
||||
const cards = mountCards({ subFolders: undefined })
|
||||
try {
|
||||
const cardElements = allElements(cards.root).filter((element) => classesOf(element).includes('knowledge-card'))
|
||||
assert.equal(cardElements.length, 2)
|
||||
} finally {
|
||||
cards.unmount()
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,864 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, onMounted, ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { formatFileSize } from '@/utils/files';
|
||||
import KnowledgeTagPopover from './KnowledgeTagPopover.vue';
|
||||
import DocumentFileIcon from './DocumentFileIcon.vue';
|
||||
import DocumentActionMenu from './DocumentActionMenu.vue';
|
||||
import FolderPickerMenu, { type FolderOption } from './FolderPickerMenu.vue';
|
||||
import { shownStall } from '@/utils/knowledgeProcessingStall';
|
||||
import type { FolderEntry } from '../folderTree';
|
||||
|
||||
interface Tag {
|
||||
id: string;
|
||||
name: string;
|
||||
color?: string;
|
||||
}
|
||||
|
||||
interface KnowledgeItem {
|
||||
id: string;
|
||||
file_name: string;
|
||||
original_file_name?: string;
|
||||
folder_path?: string;
|
||||
file_type?: string;
|
||||
file_size?: number | string;
|
||||
type?: string;
|
||||
tags?: Tag[];
|
||||
parse_status?: string;
|
||||
summary_status?: string;
|
||||
updated_at?: string;
|
||||
source?: string;
|
||||
description?: string;
|
||||
channel?: string;
|
||||
isMore?: boolean;
|
||||
stalled_minutes?: number;
|
||||
stall_state?: string;
|
||||
}
|
||||
|
||||
const props = defineProps<{
|
||||
items: KnowledgeItem[];
|
||||
kbId: string;
|
||||
selectedIds: Set<string>;
|
||||
canEdit: boolean;
|
||||
canDownload: boolean;
|
||||
canMutateKnowledge: boolean;
|
||||
traceVisibleIds: Record<string, boolean>;
|
||||
loading?: boolean;
|
||||
/** Every folder of the knowledge base, for the "move to folder" picker. */
|
||||
folderOptions?: FolderOption[];
|
||||
/**
|
||||
* Direct sub-folders of the folder being browsed. They are listed ahead of
|
||||
* the documents, the way a file manager shows folders before files. Filtering
|
||||
* searches the subtree for documents, so the caller passes an empty list.
|
||||
*/
|
||||
subFolders?: FolderEntry[];
|
||||
/**
|
||||
* Show each row's folder under its name. Only useful when the list spans
|
||||
* several folders, i.e. while filtering; inside one folder the path would be
|
||||
* identical on every row.
|
||||
*/
|
||||
showFolderPath?: boolean;
|
||||
// Move sub-flow state
|
||||
moveMenuMode: 'normal' | 'targets' | 'confirm';
|
||||
moveTargetKbs: any[];
|
||||
moveTargetsLoading: boolean;
|
||||
moveSelectedTargetName: string;
|
||||
moveMode: 'reuse_vectors' | 'reparse';
|
||||
moveSubmitting: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'open', item: KnowledgeItem): void;
|
||||
(e: 'toggle-row', id: string, checked: boolean, shiftKey: boolean): void;
|
||||
(e: 'toggle-all', checked: boolean): void;
|
||||
(e: 'action', action: 'download' | 'edit' | 'reparse' | 'cancel-parse' | 'move' | 'move-folder' | 'delete' | 'view-trace' | 'batch-manage', item: KnowledgeItem): void;
|
||||
(e: 'probe-trace', item: KnowledgeItem): void;
|
||||
(e: 'tags-changed', payload?: { deletedTagId?: string }): void;
|
||||
(e: 'open-folder', path: string): void;
|
||||
(e: 'move-to-folder', item: KnowledgeItem, folderPath: string): void;
|
||||
// Move sub-flow emits
|
||||
(e: 'move-select-target', kb: any): void;
|
||||
(e: 'move-back'): void;
|
||||
(e: 'move-confirm'): void;
|
||||
(e: 'update:moveMode', mode: 'reuse_vectors' | 'reparse'): void;
|
||||
(e: 'reset-move-state'): void;
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
const tagEditorId = ref<string | null>(null);
|
||||
const subFolderRows = computed(() => props.subFolders || []);
|
||||
const openFolder = (folder: FolderEntry) => emit('open-folder', folder.path);
|
||||
|
||||
const formatTime = (time?: string) => {
|
||||
if (!time) return '--';
|
||||
const d = new Date(time);
|
||||
if (Number.isNaN(d.getTime())) return '--';
|
||||
const yy = String(d.getFullYear()).slice(2);
|
||||
const MM = String(d.getMonth() + 1).padStart(2, '0');
|
||||
const dd = String(d.getDate()).padStart(2, '0');
|
||||
const hh = String(d.getHours()).padStart(2, '0');
|
||||
const mm = String(d.getMinutes()).padStart(2, '0');
|
||||
return `${yy}-${MM}-${dd} ${hh}:${mm}`;
|
||||
};
|
||||
|
||||
const getSourceInfo = (item: KnowledgeItem): { icon: string; label: string } => {
|
||||
const ch = item.channel;
|
||||
if (ch === 'feishu') return { icon: 'cloud-download', label: t('knowledgeBase.channelFeishu') };
|
||||
// Drive (云盘) connectors use their own channel so Drive docs show
|
||||
// "飞书云盘" / "Lark 云盘", distinct from the wiki connector's "飞书".
|
||||
if (ch === 'feishu_drive') return { icon: 'cloud-download', label: t('knowledgeBase.channelFeishuDrive') };
|
||||
if (ch === 'lark_drive') return { icon: 'cloud-download', label: t('knowledgeBase.channelLarkDrive') };
|
||||
if (ch === 'notion') return { icon: 'cloud-download', label: t('knowledgeBase.channelNotion') };
|
||||
if (ch === 'yuque') return { icon: 'cloud-download', label: t('knowledgeBase.channelYuque') };
|
||||
if (ch === 'confluence') return { icon: 'cloud-download', label: t('knowledgeBase.channelConfluence') };
|
||||
if (ch === 'gitlab') return { icon: 'cloud-download', label: t('knowledgeBase.channelGitLab') };
|
||||
if (ch === 'seafile') return { icon: 'cloud-download', label: t('knowledgeBase.channelSeafile') };
|
||||
if (ch === 'ima') return { icon: 'cloud-download', label: t('knowledgeBase.channelIma') };
|
||||
if (ch === 'wechat') return { icon: 'cloud-download', label: t('knowledgeBase.channelWechat') };
|
||||
if (ch === 'wecom') return { icon: 'cloud-download', label: t('knowledgeBase.channelWecom') };
|
||||
if (ch === 'dingtalk') return { icon: 'cloud-download', label: t('knowledgeBase.channelDingtalk') };
|
||||
if (ch === 'slack') return { icon: 'cloud-download', label: t('knowledgeBase.channelSlack') };
|
||||
if (ch === 'im') return { icon: 'cloud-download', label: t('knowledgeBase.channelIm') };
|
||||
if (item.type === 'url') return { icon: 'link', label: t('knowledgeBase.channelUrl') };
|
||||
if (item.type === 'manual') return { icon: 'edit', label: t('knowledgeBase.channelManual') };
|
||||
return { icon: 'upload', label: t('knowledgeBase.channelUpload') };
|
||||
};
|
||||
|
||||
interface StatusInfo {
|
||||
label: string;
|
||||
theme: 'success' | 'warning' | 'danger' | 'primary' | 'default';
|
||||
icon?: string;
|
||||
spin?: boolean;
|
||||
hint?: string;
|
||||
}
|
||||
const computeStatus = (item: KnowledgeItem): StatusInfo => {
|
||||
const stall = shownStall(item.stall_state, item.stalled_minutes);
|
||||
if (stall === 'queued') {
|
||||
return {
|
||||
label: t('knowledgeBase.statusQueued'),
|
||||
theme: 'default',
|
||||
icon: 'time',
|
||||
hint: t('knowledgeBase.queuedHint', { minutes: item.stalled_minutes }),
|
||||
};
|
||||
}
|
||||
if (stall === 'stalled') {
|
||||
return {
|
||||
label: t('knowledgeBase.statusStalled'),
|
||||
theme: 'warning',
|
||||
icon: 'time',
|
||||
hint: t('knowledgeBase.stalledHint', { minutes: item.stalled_minutes }),
|
||||
};
|
||||
}
|
||||
if (item.parse_status === 'pending' || item.parse_status === 'processing') {
|
||||
return { label: t('knowledgeBase.statusProcessing'), theme: 'primary', icon: 'loading', spin: true };
|
||||
}
|
||||
// finalizing = primary parse done, enrichment subtasks still running.
|
||||
// While in this phase, prefer the specific "summary generating" copy
|
||||
// when summary is what's actually outstanding (preserves the old UX
|
||||
// where this label was tied to completed+summary_pending). Otherwise
|
||||
// fall back to the generic "finalizing" label — covers question gen
|
||||
// and graph extract, which the user historically had no visibility on.
|
||||
if (item.parse_status === 'finalizing') {
|
||||
if (item.summary_status === 'pending' || item.summary_status === 'processing') {
|
||||
return { label: t('knowledgeBase.generatingSummary'), theme: 'primary', icon: 'loading', spin: true };
|
||||
}
|
||||
return { label: t('knowledgeBase.statusFinalizing'), theme: 'primary', icon: 'loading', spin: true };
|
||||
}
|
||||
if (item.parse_status === 'failed') {
|
||||
return { label: t('knowledgeBase.statusFailed'), theme: 'danger', icon: 'close-circle' };
|
||||
}
|
||||
if (item.parse_status === 'cancelled') {
|
||||
return { label: t('knowledgeBase.statusCancelled'), theme: 'default', icon: 'stop-circle' };
|
||||
}
|
||||
if (item.parse_status === 'draft') {
|
||||
return { label: t('knowledgeBase.statusDraft'), theme: 'warning' };
|
||||
}
|
||||
// Legacy completed+summary_pending path: kept as a defensive fallback
|
||||
// for rows that bypassed finalizing (no enrichment configured, or
|
||||
// upgraded mid-flight from a pre-finalizing build).
|
||||
if (
|
||||
item.parse_status === 'completed' &&
|
||||
(item.summary_status === 'pending' || item.summary_status === 'processing')
|
||||
) {
|
||||
return { label: t('knowledgeBase.generatingSummary'), theme: 'primary', icon: 'loading', spin: true };
|
||||
}
|
||||
if (item.parse_status === 'completed') {
|
||||
return { label: t('knowledgeBase.statusCompleted'), theme: 'success' };
|
||||
}
|
||||
return { label: '--', theme: 'default' };
|
||||
};
|
||||
|
||||
const statusByRow = computed(() => {
|
||||
const map = new Map<string, StatusInfo>();
|
||||
for (const item of props.items) map.set(item.id, computeStatus(item));
|
||||
return map;
|
||||
});
|
||||
|
||||
const allSelected = computed(() => {
|
||||
return props.items.length > 0 && props.items.every(i => props.selectedIds.has(i.id));
|
||||
});
|
||||
const someSelected = computed(() => {
|
||||
return props.items.some(i => props.selectedIds.has(i.id)) && !allSelected.value;
|
||||
});
|
||||
|
||||
const onHeaderCheckboxChange = (checked: boolean) => {
|
||||
emit('toggle-all', checked);
|
||||
};
|
||||
|
||||
const onRowCheckboxChange = (item: KnowledgeItem, checked: boolean, ctx?: { e?: Event }) => {
|
||||
const me = ctx?.e as MouseEvent | undefined;
|
||||
emit('toggle-row', item.id, checked, !!me?.shiftKey);
|
||||
};
|
||||
|
||||
const moreOpen = ref<string | null>(null);
|
||||
const onMoreVisible = (id: string, visible: boolean) => {
|
||||
if (!visible && moreOpen.value !== id) return;
|
||||
if (visible && moreOpen.value !== id) folderPickerItemId.value = null;
|
||||
moreOpen.value = visible ? id : null;
|
||||
if (visible) {
|
||||
const it = props.items.find(i => i.id === id);
|
||||
if (it) emit('probe-trace', it);
|
||||
} else {
|
||||
folderPickerItemId.value = null;
|
||||
// Reset move state when popup closes naturally
|
||||
emit('reset-move-state');
|
||||
}
|
||||
};
|
||||
|
||||
// 吸顶检测:哨兵离开视口说明 header 已吸附在滚动容器顶部
|
||||
const stickySentinel = ref<HTMLElement | null>(null);
|
||||
const headerStuck = ref(false);
|
||||
let stickyObserver: IntersectionObserver | null = null;
|
||||
onMounted(() => {
|
||||
if (!stickySentinel.value || typeof IntersectionObserver === 'undefined') return;
|
||||
stickyObserver = new IntersectionObserver(
|
||||
(entries) => {
|
||||
headerStuck.value = !entries[0].isIntersecting;
|
||||
},
|
||||
{ threshold: 0 },
|
||||
);
|
||||
stickyObserver.observe(stickySentinel.value);
|
||||
});
|
||||
onBeforeUnmount(() => {
|
||||
stickyObserver?.disconnect();
|
||||
stickyObserver = null;
|
||||
});
|
||||
|
||||
// Which row's action popup is currently showing the folder picker. Kept local so
|
||||
// picking a folder stays inside the menu the user already opened, exactly like
|
||||
// the "move to knowledge base" sub-menu next to it.
|
||||
const folderPickerItemId = ref<string | null>(null);
|
||||
|
||||
const onFolderPicked = (item: KnowledgeItem, path: string) => {
|
||||
folderPickerItemId.value = null;
|
||||
moreOpen.value = null;
|
||||
item.isMore = false;
|
||||
emit('move-to-folder', item, path);
|
||||
};
|
||||
|
||||
const handleAction = (action: 'download' | 'edit' | 'reparse' | 'cancel-parse' | 'move' | 'move-folder' | 'delete' | 'view-trace' | 'batch-manage', item: KnowledgeItem) => {
|
||||
// The folder picker opens inside this same popup, so keep the menu open.
|
||||
if (action === 'move-folder') {
|
||||
folderPickerItemId.value = item.id;
|
||||
return;
|
||||
}
|
||||
// Don't close popup for move — it triggers the move sub-flow
|
||||
if (action !== 'move') {
|
||||
moreOpen.value = null;
|
||||
}
|
||||
item.isMore = false;
|
||||
emit('action', action, item);
|
||||
};
|
||||
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="doc-list-view" :class="{ 'is-loading': loading }" role="table" :aria-label="t('knowledgeEditor.document.title')">
|
||||
<div ref="stickySentinel" class="doc-list-sticky-sentinel" aria-hidden="true"></div>
|
||||
<div class="doc-list-header" :class="{ 'is-stuck': headerStuck }" role="row">
|
||||
<div class="cell cell-check" role="columnheader" @click.stop>
|
||||
<t-checkbox v-if="canEdit || canDownload" class="doc-list-check" size="small" :checked="allSelected" :indeterminate="someSelected"
|
||||
:disabled="!items.length" :title="t('knowledgeBase.selectAll')" @change="onHeaderCheckboxChange" />
|
||||
</div>
|
||||
<div class="cell cell-name" role="columnheader">{{ t('knowledgeBase.columnName') }}</div>
|
||||
<div class="cell cell-tags" role="columnheader">{{ t('knowledgeBase.columnTag') }}</div>
|
||||
<div class="cell cell-status" role="columnheader">{{ t('knowledgeBase.columnStatus') }}</div>
|
||||
<div class="cell cell-actions" role="columnheader" v-if="canEdit"></div>
|
||||
</div>
|
||||
|
||||
<div class="doc-list-body" role="rowgroup">
|
||||
<div v-for="folder in subFolderRows" :key="`folder:${folder.path}`" class="doc-list-row folder-row"
|
||||
:data-folder-path="folder.path" role="row" @click="openFolder(folder)">
|
||||
<!-- Folders are navigation entries, not documents: no batch checkbox. -->
|
||||
<div class="cell cell-check" role="cell"></div>
|
||||
|
||||
<div class="cell cell-name" role="cell">
|
||||
<span class="folder-row-icon" aria-hidden="true">
|
||||
<t-icon name="folder" size="26px" />
|
||||
</span>
|
||||
<div class="row-file-text">
|
||||
<div class="row-title-line">
|
||||
<button type="button" class="row-file-name" :title="folder.path"
|
||||
@click.stop="openFolder(folder)">{{ folder.name }}</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="cell cell-tags" role="cell"></div>
|
||||
<div class="cell cell-status" role="cell"></div>
|
||||
<div class="cell cell-actions" role="cell"></div>
|
||||
</div>
|
||||
|
||||
<div v-for="item in items" :key="item.id" class="doc-list-row"
|
||||
:class="{ selected: selectedIds.has(item.id), 'menu-open': moreOpen === item.id }" :data-select-id="item.id"
|
||||
role="row" @click="emit('open', item)">
|
||||
<div class="cell cell-check" role="cell" @click.stop>
|
||||
<t-checkbox v-if="canEdit || canDownload" class="doc-list-check" size="small" :checked="selectedIds.has(item.id)" :title="item.file_name"
|
||||
@change="(c: boolean, ctx?: { e?: Event }) => onRowCheckboxChange(item, c, ctx)" />
|
||||
</div>
|
||||
|
||||
<div class="cell cell-name" role="cell">
|
||||
<DocumentFileIcon :source-type="item.type"
|
||||
:file-name="item.file_type ? `document.${item.file_type.toLowerCase()}` : (item.original_file_name || item.file_name)" />
|
||||
<div class="row-file-text">
|
||||
<div class="row-title-line">
|
||||
<button type="button" class="row-file-name" :title="item.description ? `${item.file_name}\n${item.description}` : item.file_name"
|
||||
@click.stop="emit('open', item)">{{ item.file_name }}</button>
|
||||
</div>
|
||||
<span class="row-file-meta">
|
||||
<span class="row-source"><t-icon :name="getSourceInfo(item).icon" />{{ getSourceInfo(item).label }}</span>
|
||||
<template v-if="formatFileSize(item.file_size)">
|
||||
<span class="meta-sep" aria-hidden="true">·</span>
|
||||
<span>{{ formatFileSize(item.file_size) }}</span>
|
||||
</template>
|
||||
<span class="meta-sep" aria-hidden="true">·</span>
|
||||
<span :title="t('knowledgeBase.columnUpdatedAt')">{{ formatTime(item.updated_at) }}</span>
|
||||
</span>
|
||||
<button v-if="showFolderPath && item.folder_path" type="button" class="row-file-folder"
|
||||
:title="item.folder_path" @click.stop="emit('open-folder', item.folder_path)">
|
||||
<t-icon name="folder" />
|
||||
<span>{{ item.folder_path }}</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="cell cell-tags" role="cell">
|
||||
<KnowledgeTagPopover :kb-id="kbId" :knowledge-id="item.id" :tags="item.tags || []" :disabled="!canEdit"
|
||||
:visible="tagEditorId === item.id"
|
||||
@update:visible="(visible: boolean) => { if (visible) tagEditorId = item.id; else if (tagEditorId === item.id) tagEditorId = null }"
|
||||
@changed="emit('tags-changed', $event)">
|
||||
<div class="row-tag-trigger">
|
||||
<div v-if="item.tags?.length" class="row-tags">
|
||||
<button v-for="tag in item.tags.slice(0, 5)" :key="tag.id" type="button" class="row-tag"
|
||||
:disabled="!canEdit" :title="tag.name">{{ tag.name }}</button>
|
||||
<button v-if="item.tags.length > 5" type="button" class="row-tag row-tag--overflow"
|
||||
:disabled="!canEdit" :title="item.tags.slice(5).map(tag => tag.name).join(', ')">+{{ item.tags.length - 5 }}</button>
|
||||
</div>
|
||||
<button v-else-if="canEdit" type="button" class="row-tag-add">
|
||||
<t-icon name="add" size="12px" />
|
||||
{{ t('knowledgeBase.tagAddAction') }}
|
||||
</button>
|
||||
</div>
|
||||
</KnowledgeTagPopover>
|
||||
</div>
|
||||
|
||||
<div class="cell cell-status" role="cell">
|
||||
<template v-if="statusByRow.get(item.id) as StatusInfo | undefined">
|
||||
<t-tag v-if="statusByRow.get(item.id)!.label !== '--'" size="small" :theme="statusByRow.get(item.id)!.theme"
|
||||
variant="light" class="row-status-tag" :class="`status-${statusByRow.get(item.id)!.theme}`"
|
||||
:title="statusByRow.get(item.id)!.hint">
|
||||
<template v-if="statusByRow.get(item.id)!.icon" #icon>
|
||||
<t-icon :name="statusByRow.get(item.id)!.icon!"
|
||||
:class="{ 'icon-spin': statusByRow.get(item.id)!.spin }" />
|
||||
</template>
|
||||
{{ statusByRow.get(item.id)!.label }}
|
||||
</t-tag>
|
||||
<span v-else class="row-muted">--</span>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<div class="cell cell-actions" role="cell" v-if="canEdit" @click.stop>
|
||||
<t-popup :visible="moreOpen === item.id" placement="bottom-right" trigger="click" destroy-on-close overlay-class-name="card-more"
|
||||
:on-visible-change="(v: boolean) => onMoreVisible(item.id, v)">
|
||||
<button class="row-more-btn" :class="{ active: moreOpen === item.id }" type="button"
|
||||
:aria-label="`${item.file_name} · ${t('knowledgeBase.columnActions')}`" :aria-expanded="moreOpen === item.id">
|
||||
<t-icon name="more" size="16px" />
|
||||
</button>
|
||||
<template #content>
|
||||
<!-- Move: folder picker (must win over the normal menu while open) -->
|
||||
<div v-if="folderPickerItemId === item.id" class="card-menu move-menu">
|
||||
<FolderPickerMenu
|
||||
:options="folderOptions || []"
|
||||
:current-path="item.folder_path || ''"
|
||||
show-back
|
||||
@back="folderPickerItemId = null"
|
||||
@confirm="(path: string) => onFolderPicked(item, path)"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- Normal menu -->
|
||||
<div v-else-if="moveMenuMode === 'normal'" class="card-menu">
|
||||
<button type="button" class="card-menu-item row-tag-menu-action" @click.stop="moreOpen = null; tagEditorId = item.id">
|
||||
<t-icon name="discount" class="icon" />
|
||||
<span>{{ t('knowledgeBase.tagEditDialogHeading') }}</span>
|
||||
</button>
|
||||
<DocumentActionMenu
|
||||
:item="item"
|
||||
:can-download="canDownload"
|
||||
:can-mutate-knowledge="canMutateKnowledge"
|
||||
:trace-visible="!!traceVisibleIds[item.id] || (item.parse_status === 'pending' || item.parse_status === 'processing' || item.parse_status === 'finalizing')"
|
||||
@download="handleAction('download', item)"
|
||||
@edit="handleAction('edit', item)"
|
||||
@view-trace="handleAction('view-trace', item)"
|
||||
@reparse="handleAction('reparse', item)"
|
||||
@cancel-parse="handleAction('cancel-parse', item)"
|
||||
@move="handleAction('move', item)"
|
||||
@move-folder="handleAction('move-folder', item)"
|
||||
@batch-manage="handleAction('batch-manage', item)"
|
||||
@delete="handleAction('delete', item)"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- Move: target KB list -->
|
||||
<div v-else-if="moveMenuMode === 'targets'" class="card-menu move-menu">
|
||||
<div class="move-menu-header" @click.stop="emit('move-back')">
|
||||
<t-icon name="chevron-left" size="16px" />
|
||||
<span>{{ $t('knowledgeBase.moveToKnowledgeBase') }}</span>
|
||||
</div>
|
||||
<div v-if="moveTargetsLoading" class="move-menu-loading">
|
||||
<t-loading size="small" />
|
||||
</div>
|
||||
<div v-else-if="moveTargetKbs.length === 0" class="move-menu-empty">
|
||||
{{ $t('knowledgeBase.moveNoTargets') }}
|
||||
</div>
|
||||
<template v-else>
|
||||
<div v-for="kb in moveTargetKbs" :key="kb.id" class="card-menu-item"
|
||||
@click.stop="emit('move-select-target', kb)">
|
||||
<t-icon class="icon" name="root-list" />
|
||||
<span class="move-target-name">{{ kb.name }}</span>
|
||||
<span v-if="kb.knowledge_count !== undefined" class="move-target-count">{{ kb.knowledge_count }}</span>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<!-- Move: confirm with mode selection -->
|
||||
<div v-else-if="moveMenuMode === 'confirm'" class="card-menu move-menu">
|
||||
<div class="move-menu-header" @click.stop="emit('move-back')">
|
||||
<t-icon name="chevron-left" size="16px" />
|
||||
<span>{{ $t('knowledgeBase.moveConfirmTitle') }}</span>
|
||||
</div>
|
||||
<div class="move-confirm-body">
|
||||
<div class="move-target-info">
|
||||
<t-icon name="arrow-right" size="14px" />
|
||||
<span>{{ moveSelectedTargetName }}</span>
|
||||
</div>
|
||||
<div class="move-mode-item" :class="{ active: moveMode === 'reuse_vectors' }"
|
||||
@click.stop="emit('update:moveMode', 'reuse_vectors')">
|
||||
<t-radio :checked="moveMode === 'reuse_vectors'" />
|
||||
<div class="move-mode-text">
|
||||
<span class="move-mode-label">{{ $t('knowledgeBase.moveModeReuseVectors') }}</span>
|
||||
<span class="move-mode-desc">{{ $t('knowledgeBase.moveModeReuseVectorsDesc') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="move-mode-item" :class="{ active: moveMode === 'reparse' }"
|
||||
@click.stop="emit('update:moveMode', 'reparse')">
|
||||
<t-radio :checked="moveMode === 'reparse'" />
|
||||
<div class="move-mode-text">
|
||||
<span class="move-mode-label">{{ $t('knowledgeBase.moveModeReparse') }}</span>
|
||||
<span class="move-mode-desc">{{ $t('knowledgeBase.moveModeReparseDesc') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="move-confirm-actions">
|
||||
<t-button size="small" variant="outline" @click.stop="emit('move-back')">{{
|
||||
$t('common.cancel') }}</t-button>
|
||||
<t-button size="small" theme="primary" :loading="moveSubmitting"
|
||||
@click.stop="emit('move-confirm')">{{
|
||||
$t('knowledgeBase.moveConfirm') }}</t-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</t-popup>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped lang="less">
|
||||
@keyframes doc-list-fade-in {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(6px);
|
||||
}
|
||||
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
.doc-list-view {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
width: 100%;
|
||||
background: transparent;
|
||||
/* 不能用 overflow:hidden,否则表头 position:sticky 相对外层滚动区失效 */
|
||||
overflow: visible;
|
||||
animation: doc-list-fade-in 0.32s ease-out;
|
||||
}
|
||||
|
||||
.doc-list-header,
|
||||
.doc-list-row {
|
||||
display: grid;
|
||||
grid-template-columns: 24px minmax(0, 1fr) minmax(180px, 24%) 100px 28px;
|
||||
align-items: center;
|
||||
column-gap: 12px;
|
||||
padding: 0 8px;
|
||||
}
|
||||
|
||||
.doc-list-sticky-sentinel {
|
||||
height: 0;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.doc-list-header {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 3;
|
||||
height: 40px;
|
||||
font-size: var(--app-text-sm);
|
||||
font-weight: 500;
|
||||
font-family: var(--app-font-family);
|
||||
color: var(--td-text-color-secondary);
|
||||
background: var(--td-bg-color-container);
|
||||
border-bottom: 0;
|
||||
transition: border-radius var(--app-motion-fast) ease, box-shadow var(--app-motion-base) ease;
|
||||
|
||||
&.is-stuck {
|
||||
border-radius: 0;
|
||||
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.08);
|
||||
}
|
||||
}
|
||||
|
||||
.doc-list-body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
padding: 6px 0 72px;
|
||||
}
|
||||
|
||||
.doc-list-row {
|
||||
position: relative;
|
||||
min-height: 68px;
|
||||
padding-top: 10px;
|
||||
padding-bottom: 10px;
|
||||
box-sizing: border-box;
|
||||
border-radius: var(--app-radius-md);
|
||||
font-size: var(--app-text-md);
|
||||
color: var(--td-text-color-primary);
|
||||
cursor: pointer;
|
||||
transition: background-color var(--app-motion-base) ease, box-shadow var(--app-motion-base) ease, border-color var(--app-motion-base) ease;
|
||||
|
||||
&:hover:not(.selected),
|
||||
&.menu-open:not(.selected) {
|
||||
background: var(--td-bg-color-secondarycontainer);
|
||||
}
|
||||
|
||||
&:focus-within .row-more-btn,
|
||||
&:hover .row-more-btn,
|
||||
&.menu-open .row-more-btn,
|
||||
&.selected .row-more-btn {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
/* A folder is an entry in the same grid as a document, so every column stays
|
||||
aligned; only the cells a folder has no value for stay empty. */
|
||||
.folder-row {
|
||||
min-height: 56px;
|
||||
}
|
||||
|
||||
.folder-row-icon {
|
||||
flex: 0 0 32px;
|
||||
width: 32px;
|
||||
height: 38px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: var(--td-warning-color);
|
||||
}
|
||||
|
||||
.cell {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
min-width: 0;
|
||||
padding: 0;
|
||||
|
||||
&:first-child {
|
||||
padding-left: 0;
|
||||
}
|
||||
|
||||
&:last-child {
|
||||
padding-right: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.cell-check {
|
||||
justify-content: center;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.cell-name {
|
||||
gap: 12px;
|
||||
font-family: var(--app-font-family);
|
||||
}
|
||||
|
||||
.cell-actions {
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
/* TDesign 勾选框:去掉空白 label、与表格行对齐 */
|
||||
.doc-list-check {
|
||||
margin: 0;
|
||||
|
||||
:deep(.t-checkbox) {
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
:deep(.t-checkbox__label) {
|
||||
display: none !important;
|
||||
width: 0 !important;
|
||||
min-width: 0 !important;
|
||||
margin: 0 !important;
|
||||
padding: 0 !important;
|
||||
}
|
||||
|
||||
:deep(.t-checkbox__input) {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
:deep(.t-checkbox__input-wrapper) {
|
||||
margin: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.row-file-icon-wrap {
|
||||
flex-shrink: 0;
|
||||
width: 32px;
|
||||
height: 38px;
|
||||
border-radius: var(--app-radius-sm);
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 26px;
|
||||
background: transparent;
|
||||
color: var(--td-text-color-secondary);
|
||||
}
|
||||
|
||||
.row-file-text {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.row-file-name {
|
||||
min-width: 0;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
font-size: var(--app-text-base);
|
||||
font-weight: 500;
|
||||
line-height: 1.4;
|
||||
text-align: left;
|
||||
border: 0;
|
||||
padding: 0;
|
||||
background: transparent;
|
||||
font-family: inherit;
|
||||
cursor: pointer;
|
||||
color: var(--td-text-color-primary);
|
||||
}
|
||||
|
||||
.row-file-meta {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
min-width: 0;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
font-size: var(--app-text-sm);
|
||||
color: var(--td-text-color-placeholder);
|
||||
}
|
||||
|
||||
.row-file-folder {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
align-self: flex-start;
|
||||
gap: 4px;
|
||||
max-width: 100%;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: var(--td-text-color-placeholder);
|
||||
font-family: var(--app-font-family);
|
||||
font-size: var(--app-text-sm);
|
||||
cursor: pointer;
|
||||
transition: color var(--app-motion-fast) ease;
|
||||
|
||||
&:hover {
|
||||
color: var(--td-brand-color);
|
||||
}
|
||||
|
||||
span {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.t-icon {
|
||||
flex: 0 0 auto;
|
||||
font-size: var(--app-text-md);
|
||||
}
|
||||
}
|
||||
|
||||
.row-muted {
|
||||
color: var(--td-text-color-disabled);
|
||||
}
|
||||
|
||||
.row-status-tag {
|
||||
background: transparent;
|
||||
border: 0;
|
||||
padding: 0;
|
||||
color: var(--td-text-color-secondary);
|
||||
&.status-success::before { content: ''; width: 5px; height: 5px; margin-right: 6px; border-radius: 50%; background: var(--td-success-color); }
|
||||
&.status-danger { color: var(--td-error-color); }
|
||||
&.status-warning { color: var(--td-warning-color); }
|
||||
&.status-primary { color: var(--td-brand-color); }
|
||||
&.status-default { color: var(--td-text-color-placeholder); }
|
||||
}
|
||||
.row-title-line { display: flex; align-items: center; min-width: 0; }
|
||||
.row-tags { display: flex; flex-wrap: wrap; align-items: center; gap: 5px; min-width: 0; width: 100%; }
|
||||
.row-tag {
|
||||
flex: 0 0 auto;
|
||||
max-width: min(180px, 100%);
|
||||
box-sizing: border-box;
|
||||
padding: 2px 7px;
|
||||
border: 0;
|
||||
border-radius: 5px;
|
||||
background: var(--td-bg-color-secondarycontainer);
|
||||
color: var(--td-text-color-secondary);
|
||||
font: inherit;
|
||||
font-size: var(--app-text-sm);
|
||||
line-height: 18px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
cursor: pointer;
|
||||
&:disabled { cursor: default; }
|
||||
&:not(:disabled):hover { color: var(--td-brand-color); background: var(--td-brand-color-light); }
|
||||
&--overflow { background: transparent; color: var(--td-text-color-placeholder); }
|
||||
}
|
||||
.row-tag-add {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
padding: 2px 7px;
|
||||
border: 1px dashed var(--td-component-stroke);
|
||||
border-radius: 5px;
|
||||
background: transparent;
|
||||
color: var(--td-text-color-placeholder);
|
||||
font: inherit;
|
||||
font-size: var(--app-text-sm);
|
||||
line-height: 18px;
|
||||
white-space: nowrap;
|
||||
cursor: pointer;
|
||||
transition: color var(--app-motion-fast) ease, border-color var(--app-motion-fast) ease, background var(--app-motion-fast) ease;
|
||||
|
||||
&:hover {
|
||||
color: var(--td-brand-color);
|
||||
border-color: var(--td-brand-color);
|
||||
background: var(--td-brand-color-light);
|
||||
}
|
||||
}
|
||||
.row-tag-menu-action {
|
||||
width: 100%; border: 0; background: transparent; text-align: left; font-family: inherit; cursor: pointer;
|
||||
&:hover { background: var(--td-bg-color-container-hover); }
|
||||
}
|
||||
.row-status-tag :deep(.t-icon) {
|
||||
margin-right: 2px;
|
||||
}
|
||||
|
||||
.icon-spin {
|
||||
animation: wk-spin 0.9s linear infinite;
|
||||
}
|
||||
|
||||
.row-more-btn {
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
border-radius: 5px;
|
||||
color: var(--td-text-color-secondary);
|
||||
cursor: pointer;
|
||||
opacity: 0;
|
||||
transition: opacity var(--app-motion-fast) ease, background-color var(--app-motion-fast) ease, color var(--app-motion-fast) ease;
|
||||
|
||||
&:hover {
|
||||
background: var(--td-component-stroke);
|
||||
color: var(--td-text-color-primary);
|
||||
}
|
||||
|
||||
&.active {
|
||||
opacity: 1;
|
||||
background: var(--td-component-stroke);
|
||||
color: var(--td-text-color-primary);
|
||||
}
|
||||
}
|
||||
|
||||
.row-source {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
}
|
||||
.meta-sep { opacity: 0.6; }
|
||||
.doc-list-row.selected { background: var(--app-selection-bg); }
|
||||
.row-file-name:focus-visible,
|
||||
.row-file-folder:focus-visible,
|
||||
.row-more-btn:focus-visible,
|
||||
.row-tag:focus-visible,
|
||||
.row-tag-add:focus-visible {
|
||||
outline: 2px solid var(--app-focus-border);
|
||||
outline-offset: 3px;
|
||||
border-radius: var(--app-radius-xs);
|
||||
}
|
||||
@container doc-card-area (max-width: 720px) {
|
||||
.doc-list-header, .doc-list-row {
|
||||
grid-template-columns: 24px minmax(0, 1fr) 100px 28px;
|
||||
column-gap: 8px;
|
||||
}
|
||||
.doc-list-header .cell-tags { display: none; }
|
||||
.doc-list-row .cell-tags { grid-column: 2; grid-row: 2; padding-left: 44px; }
|
||||
.row-tags { padding-top: 6px; }
|
||||
.row-tag-add { margin-top: 6px; }
|
||||
.cell-status { grid-column: 3; grid-row: 1; }
|
||||
.cell-actions { grid-column: 4; grid-row: 1; }
|
||||
.row-file-meta { flex-wrap: wrap; gap: 2px 6px; }
|
||||
}
|
||||
@media (hover: none) {
|
||||
.row-more-btn { opacity: 1; }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.doc-list-view, .icon-spin { animation: none; }
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,54 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { readFileSync } from 'node:fs'
|
||||
|
||||
const manager = readFileSync(new URL('./FAQEntryManager.vue', import.meta.url), 'utf8')
|
||||
const batchBar = readFileSync(new URL('./FAQBatchBar.vue', import.meta.url), 'utf8')
|
||||
const locales = [
|
||||
readFileSync(new URL('../../../i18n/locales/zh-CN.ts', import.meta.url), 'utf8'),
|
||||
readFileSync(new URL('../../../i18n/locales/en-US.ts', import.meta.url), 'utf8'),
|
||||
readFileSync(new URL('../../../i18n/locales/ko-KR.ts', import.meta.url), 'utf8'),
|
||||
readFileSync(new URL('../../../i18n/locales/ja-JP.ts', import.meta.url), 'utf8'),
|
||||
readFileSync(new URL('../../../i18n/locales/ru-RU.ts', import.meta.url), 'utf8'),
|
||||
]
|
||||
|
||||
test('FAQ 批量操作通过组件事件直接连接,不再依赖全局事件', () => {
|
||||
assert.match(manager, /import FAQBatchBar from '\.\/FAQBatchBar\.vue'/)
|
||||
assert.match(manager, /<FAQBatchBar[\s\S]*?@batch-tag="openBatchTagDialog"/)
|
||||
assert.match(manager, /@enable="handleBatchStatusChange\(true\)"/)
|
||||
assert.match(manager, /@disable="handleBatchStatusChange\(false\)"/)
|
||||
assert.match(manager, /@delete="handleBatchDelete"/)
|
||||
assert.doesNotMatch(manager, /faqMenuAction/)
|
||||
assert.doesNotMatch(manager, /faqSelectionChanged/)
|
||||
})
|
||||
|
||||
test('批量操作条根据选择状态和权限展示有效操作', () => {
|
||||
assert.match(batchBar, /v-if="count > 0 && \(canEdit \|\| canManage\)"/)
|
||||
assert.match(batchBar, /v-if="canEdit && disabledCount > 0"/)
|
||||
assert.match(batchBar, /v-if="canEdit && enabledCount > 0"/)
|
||||
assert.match(batchBar, /<t-popconfirm v-if="canManage"/)
|
||||
assert.match(manager, /const canSelectEntries = computed\(\(\) => canEdit\.value \|\| canManage\.value\)/)
|
||||
assert.match(manager, /if \(!canSelectEntries\.value \|\| batchActionLoading\.value\) return/)
|
||||
})
|
||||
|
||||
test('危险操作需要确认,所有批量请求都防止重复提交', () => {
|
||||
assert.match(batchBar, /confirmBatchDelete/)
|
||||
assert.match(batchBar, /@confirm="emit\('delete'\)"/)
|
||||
assert.match(batchBar, /const actionLoading = computed/)
|
||||
assert.match(manager, /const batchDeleteLoading = ref\(false\)/)
|
||||
assert.match(manager, /const batchTagLoading = ref\(false\)/)
|
||||
assert.match(manager, /const batchStatusAction = ref<'enable' \| 'disable' \| null>\(null\)/)
|
||||
assert.match(manager, /finally \{\s*batchDeleteLoading\.value = false\s*\}/)
|
||||
assert.match(manager, /finally \{\s*batchTagLoading\.value = false\s*\}/)
|
||||
assert.match(manager, /finally \{\s*batchStatusAction\.value = null\s*\}/)
|
||||
})
|
||||
|
||||
test('所有支持的语言都包含 FAQ 批量操作文案', () => {
|
||||
for (const locale of locales) {
|
||||
assert.match(locale, /batchEnable:/)
|
||||
assert.match(locale, /batchDisable:/)
|
||||
assert.match(locale, /batchDelete:/)
|
||||
assert.match(locale, /confirmBatchDelete:/)
|
||||
assert.match(locale, /batchDeleteSuccess:/)
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,145 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
const props = defineProps<{
|
||||
count: number
|
||||
enabledCount: number
|
||||
disabledCount: number
|
||||
canEdit: boolean
|
||||
canManage: boolean
|
||||
tagLoading?: boolean
|
||||
statusAction?: 'enable' | 'disable' | null
|
||||
deleteLoading?: boolean
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
(event: 'cancel'): void
|
||||
(event: 'batchTag'): void
|
||||
(event: 'enable'): void
|
||||
(event: 'disable'): void
|
||||
(event: 'delete'): void
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const actionLoading = computed(() => (
|
||||
props.tagLoading
|
||||
|| props.statusAction != null
|
||||
|| props.deleteLoading
|
||||
))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<transition name="faq-batch-bar-fade">
|
||||
<div v-if="count > 0 && (canEdit || canManage)" class="faq-batch-bar" role="region"
|
||||
:aria-label="t('knowledgeBase.selectedCount', { count })">
|
||||
<div class="faq-batch-bar__inner">
|
||||
<div class="faq-batch-bar__selection">
|
||||
<span class="faq-batch-bar__count">{{ t('knowledgeBase.selectedCount', { count }) }}</span>
|
||||
<t-button variant="text" theme="default" size="small" :disabled="actionLoading"
|
||||
@click="emit('cancel')">
|
||||
{{ t('knowledgeBase.clearSelection') }}
|
||||
</t-button>
|
||||
</div>
|
||||
|
||||
<div class="faq-batch-bar__actions">
|
||||
<t-button v-if="canEdit" theme="default" variant="outline" size="small"
|
||||
:disabled="actionLoading" :loading="tagLoading" @click="emit('batchTag')">
|
||||
<template #icon><t-icon name="discount" size="14px" /></template>
|
||||
{{ t('knowledgeEditor.faq.batchUpdateTag') }}
|
||||
</t-button>
|
||||
|
||||
<t-button v-if="canEdit && disabledCount > 0" theme="default" variant="outline" size="small"
|
||||
:disabled="actionLoading" :loading="statusAction === 'enable'" @click="emit('enable')">
|
||||
<template #icon><t-icon name="check-circle" size="14px" /></template>
|
||||
{{ t('knowledgeEditor.faq.batchEnable') }}
|
||||
</t-button>
|
||||
|
||||
<t-button v-if="canEdit && enabledCount > 0" theme="default" variant="outline" size="small"
|
||||
:disabled="actionLoading" :loading="statusAction === 'disable'" @click="emit('disable')">
|
||||
<template #icon><t-icon name="minus-circle" size="14px" /></template>
|
||||
{{ t('knowledgeEditor.faq.batchDisable') }}
|
||||
</t-button>
|
||||
|
||||
<t-popconfirm v-if="canManage" theme="warning"
|
||||
:content="t('knowledgeEditor.faq.confirmBatchDelete', { count })"
|
||||
:confirm-btn="{ content: t('knowledgeBase.confirmDelete'), theme: 'danger' }"
|
||||
:cancel-btn="{ content: t('common.cancel') }" placement="top" @confirm="emit('delete')">
|
||||
<t-button theme="danger" variant="outline" size="small" :disabled="actionLoading"
|
||||
:loading="deleteLoading" @click.stop>
|
||||
<template #icon><t-icon name="delete" size="14px" /></template>
|
||||
{{ t('knowledgeEditor.faq.batchDelete') }}
|
||||
</t-button>
|
||||
</t-popconfirm>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</transition>
|
||||
</template>
|
||||
|
||||
<style scoped lang="less">
|
||||
.faq-batch-bar {
|
||||
width: 100%;
|
||||
max-width: 760px;
|
||||
padding: 0 4px;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.faq-batch-bar__inner {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
padding: 8px 12px;
|
||||
background: var(--td-bg-color-container);
|
||||
border: 1px solid var(--td-component-stroke);
|
||||
border-radius: var(--app-radius-md);
|
||||
box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08);
|
||||
}
|
||||
|
||||
.faq-batch-bar__selection {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
min-width: 0;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.faq-batch-bar__count {
|
||||
color: var(--td-text-color-secondary);
|
||||
font-size: var(--app-text-md);
|
||||
font-weight: 500;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.faq-batch-bar__actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.faq-batch-bar-fade-enter-active,
|
||||
.faq-batch-bar-fade-leave-active {
|
||||
transition: transform var(--app-motion-base) ease, opacity var(--app-motion-base) ease;
|
||||
}
|
||||
|
||||
.faq-batch-bar-fade-enter-from,
|
||||
.faq-batch-bar-fade-leave-to {
|
||||
opacity: 0;
|
||||
transform: translateY(6px);
|
||||
}
|
||||
|
||||
@media (max-width: 760px) {
|
||||
.faq-batch-bar__inner {
|
||||
align-items: stretch;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.faq-batch-bar__actions {
|
||||
justify-content: flex-start;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,385 @@
|
||||
<template>
|
||||
<div class="folder-picker">
|
||||
<div v-if="showBack" class="folder-picker__header" @click.stop="emit('back')">
|
||||
<t-icon name="chevron-left" size="16px" />
|
||||
<span>{{ t('knowledgeBase.moveToFolder.action') }}</span>
|
||||
</div>
|
||||
|
||||
<div ref="listRef" class="folder-picker__list">
|
||||
<template v-for="row in renderRows" :key="row.key">
|
||||
<div
|
||||
v-if="row.kind === 'folder'"
|
||||
:data-folder-path="row.path || undefined"
|
||||
class="folder-picker__item"
|
||||
:class="{ current: effectiveCurrentPath === row.path }"
|
||||
:style="{ '--folder-picker-depth': row.depth }"
|
||||
:title="row.path || undefined"
|
||||
@click.stop="choose(row.path)"
|
||||
>
|
||||
<t-icon :name="row.isRoot ? 'folder-open' : 'folder'" class="folder-picker__icon" />
|
||||
<span class="folder-picker__name">{{ row.label }}</span>
|
||||
<button
|
||||
type="button"
|
||||
class="folder-picker__add"
|
||||
:title="row.isRoot
|
||||
? t('knowledgeBase.moveToFolder.newFolderAddRoot')
|
||||
: t('knowledgeBase.moveToFolder.newFolderAddUnder', { folder: row.label })"
|
||||
:aria-label="row.isRoot
|
||||
? t('knowledgeBase.moveToFolder.newFolderAddRoot')
|
||||
: t('knowledgeBase.moveToFolder.newFolderAddUnder', { folder: row.label })"
|
||||
@click.stop="startCreatingUnder(row.path)"
|
||||
>
|
||||
<t-icon name="folder-add" />
|
||||
</button>
|
||||
<t-icon v-if="effectiveCurrentPath === row.path" name="check" class="folder-picker__current" />
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-else
|
||||
class="folder-picker__item folder-picker__item--create"
|
||||
:style="{ '--folder-picker-depth': row.depth }"
|
||||
@click.stop
|
||||
>
|
||||
<t-icon name="folder" class="folder-picker__icon" />
|
||||
<input
|
||||
ref="newFolderInputRef"
|
||||
v-model.trim="newFolderName"
|
||||
class="folder-picker__input"
|
||||
:placeholder="t('knowledgeBase.moveToFolder.newFolderPlaceholder')"
|
||||
@keydown.enter.stop="commitNewFolder"
|
||||
@keydown.esc.stop="cancelCreating"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, ref, watch } from 'vue'
|
||||
import { MessagePlugin } from 'tdesign-vue-next'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { folderOptionFromPath, joinFolderPath, normalizeFolderPath, sortFolderOptions } from '../folderTree'
|
||||
|
||||
export type FolderOption = { path: string; name: string; depth: number }
|
||||
|
||||
type FolderRow = {
|
||||
kind: 'folder'
|
||||
key: string
|
||||
path: string
|
||||
label: string
|
||||
depth: number
|
||||
isRoot?: boolean
|
||||
}
|
||||
|
||||
type CreateRow = {
|
||||
kind: 'create'
|
||||
key: string
|
||||
parentPath: string
|
||||
depth: number
|
||||
}
|
||||
|
||||
type RenderRow = FolderRow | CreateRow
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
options: FolderOption[]
|
||||
currentPath?: string
|
||||
showBack?: boolean
|
||||
allowReselect?: boolean
|
||||
}>(), {
|
||||
currentPath: '',
|
||||
showBack: false,
|
||||
allowReselect: false,
|
||||
})
|
||||
|
||||
const emit = defineEmits<{
|
||||
back: []
|
||||
confirm: [folderPath: string]
|
||||
create: [folderPath: string]
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const creatingUnder = ref<string | null>(null)
|
||||
const newFolderName = ref('')
|
||||
const newFolderInputRef = ref<HTMLInputElement | null>(null)
|
||||
const listRef = ref<HTMLElement | null>(null)
|
||||
const localCreatedPaths = ref<string[]>([])
|
||||
const selectedPath = ref<string | null>(null)
|
||||
|
||||
const effectiveCurrentPath = computed(() =>
|
||||
selectedPath.value !== null ? selectedPath.value : (props.currentPath ?? ''),
|
||||
)
|
||||
|
||||
const displayOptions = computed(() => {
|
||||
const byPath = new Map<string, FolderOption>()
|
||||
props.options.forEach((option) => byPath.set(option.path, option))
|
||||
localCreatedPaths.value.forEach((path) => {
|
||||
if (!byPath.has(path)) byPath.set(path, folderOptionFromPath(path))
|
||||
})
|
||||
return sortFolderOptions([...byPath.values()])
|
||||
})
|
||||
|
||||
const renderRows = computed<RenderRow[]>(() => {
|
||||
const rows: RenderRow[] = [{
|
||||
kind: 'folder',
|
||||
key: 'root',
|
||||
path: '',
|
||||
label: t('knowledgeBase.folderTree.rootRow'),
|
||||
depth: 0,
|
||||
isRoot: true,
|
||||
}]
|
||||
|
||||
if (creatingUnder.value === '') {
|
||||
rows.push({
|
||||
kind: 'create',
|
||||
key: 'create-root',
|
||||
parentPath: '',
|
||||
depth: childCreateDepth(''),
|
||||
})
|
||||
}
|
||||
|
||||
displayOptions.value.forEach((option) => {
|
||||
rows.push({
|
||||
kind: 'folder',
|
||||
key: option.path,
|
||||
path: option.path,
|
||||
label: option.name,
|
||||
depth: option.depth,
|
||||
})
|
||||
if (creatingUnder.value === option.path) {
|
||||
rows.push({
|
||||
kind: 'create',
|
||||
key: `create-${option.path}`,
|
||||
parentPath: option.path,
|
||||
depth: childCreateDepth(option.path),
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
return rows
|
||||
})
|
||||
|
||||
watch(
|
||||
creatingUnder,
|
||||
async (value) => {
|
||||
if (value === null) return
|
||||
await nextTick()
|
||||
newFolderInputRef.value?.focus()
|
||||
},
|
||||
)
|
||||
|
||||
watch(
|
||||
() => props.options,
|
||||
(options) => {
|
||||
const existing = new Set(options.map((option) => option.path))
|
||||
localCreatedPaths.value = localCreatedPaths.value.filter((path) => !existing.has(path))
|
||||
},
|
||||
{ deep: true },
|
||||
)
|
||||
|
||||
watch(
|
||||
() => props.currentPath,
|
||||
() => {
|
||||
selectedPath.value = null
|
||||
},
|
||||
)
|
||||
|
||||
function childCreateDepth(parentPath: string): number {
|
||||
return parentPath.split('/').filter(Boolean).length
|
||||
}
|
||||
|
||||
const choose = (path: string) => {
|
||||
if (path === effectiveCurrentPath.value && !props.allowReselect) return
|
||||
selectedPath.value = path
|
||||
emit('confirm', path)
|
||||
}
|
||||
|
||||
const startCreatingUnder = (parentPath: string) => {
|
||||
if (creatingUnder.value === parentPath) {
|
||||
cancelCreating()
|
||||
return
|
||||
}
|
||||
creatingUnder.value = parentPath
|
||||
newFolderName.value = ''
|
||||
}
|
||||
|
||||
const cancelCreating = () => {
|
||||
creatingUnder.value = null
|
||||
newFolderName.value = ''
|
||||
}
|
||||
|
||||
const scrollToFolder = async (path: string) => {
|
||||
await nextTick()
|
||||
const row = listRef.value?.querySelector(`[data-folder-path="${CSS.escape(path)}"]`)
|
||||
row?.scrollIntoView({ block: 'nearest' })
|
||||
}
|
||||
|
||||
const commitNewFolder = async () => {
|
||||
if (creatingUnder.value === null) return
|
||||
const name = normalizeFolderPath(newFolderName.value)
|
||||
if (!name) return
|
||||
const path = joinFolderPath(creatingUnder.value, name)
|
||||
if (displayOptions.value.some((option) => option.path === path)) {
|
||||
MessagePlugin.warning(t('knowledgeBase.moveToFolder.duplicate'))
|
||||
return
|
||||
}
|
||||
|
||||
if (!localCreatedPaths.value.includes(path)) {
|
||||
localCreatedPaths.value = [...localCreatedPaths.value, path]
|
||||
}
|
||||
creatingUnder.value = null
|
||||
newFolderName.value = ''
|
||||
emit('create', path)
|
||||
await scrollToFolder(path)
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
.folder-picker {
|
||||
--folder-picker-indent: 12px;
|
||||
min-width: 208px;
|
||||
max-width: 280px;
|
||||
}
|
||||
|
||||
.folder-picker__header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 6px 10px;
|
||||
margin-bottom: 2px;
|
||||
border-bottom: 1px solid var(--td-component-stroke);
|
||||
color: var(--td-text-color-primary);
|
||||
font-family: var(--app-font-family);
|
||||
font-size: var(--app-text-base);
|
||||
font-weight: 400;
|
||||
line-height: 20px;
|
||||
cursor: pointer;
|
||||
|
||||
&:hover {
|
||||
color: var(--td-text-color-primary);
|
||||
background: var(--td-bg-color-container-hover);
|
||||
}
|
||||
}
|
||||
|
||||
.folder-picker__list {
|
||||
max-height: 260px;
|
||||
overflow-y: auto;
|
||||
scrollbar-width: thin;
|
||||
|
||||
&::-webkit-scrollbar {
|
||||
width: 4px;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-thumb {
|
||||
border-radius: 2px;
|
||||
background: var(--td-scrollbar-color);
|
||||
}
|
||||
}
|
||||
|
||||
.folder-picker__item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
height: 32px;
|
||||
box-sizing: border-box;
|
||||
padding: 0 8px 0 calc(var(--folder-picker-depth, 0) * var(--folder-picker-indent) + 10px);
|
||||
border-radius: var(--app-radius-xs);
|
||||
color: var(--td-text-color-primary);
|
||||
font-family: var(--app-font-family);
|
||||
font-size: var(--app-text-base);
|
||||
font-weight: 400;
|
||||
line-height: 20px;
|
||||
cursor: pointer;
|
||||
transition: background var(--app-motion-fast) ease;
|
||||
|
||||
&:hover {
|
||||
background: var(--td-bg-color-container-hover);
|
||||
|
||||
.folder-picker__add {
|
||||
opacity: 1;
|
||||
pointer-events: auto;
|
||||
}
|
||||
}
|
||||
|
||||
&.current {
|
||||
color: var(--td-text-color-placeholder);
|
||||
cursor: default;
|
||||
|
||||
&:hover {
|
||||
background: transparent;
|
||||
|
||||
.folder-picker__add {
|
||||
opacity: 1;
|
||||
pointer-events: auto;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
&--create {
|
||||
cursor: default;
|
||||
|
||||
&:hover {
|
||||
background: transparent;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.folder-picker__icon {
|
||||
flex: 0 0 auto;
|
||||
font-size: var(--app-text-lg);
|
||||
color: var(--td-text-color-placeholder);
|
||||
}
|
||||
|
||||
.folder-picker__name {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.folder-picker__add {
|
||||
flex: 0 0 auto;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
margin-right: -2px;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
border-radius: var(--app-radius-xs);
|
||||
background: transparent;
|
||||
color: var(--td-text-color-placeholder);
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
cursor: pointer;
|
||||
transition: opacity var(--app-motion-fast) ease, color var(--app-motion-fast) ease, background var(--app-motion-fast) ease;
|
||||
|
||||
&:hover {
|
||||
color: var(--td-brand-color);
|
||||
background: var(--td-bg-color-component);
|
||||
}
|
||||
}
|
||||
|
||||
.folder-picker__current {
|
||||
flex: 0 0 auto;
|
||||
font-size: var(--app-text-base);
|
||||
color: var(--td-text-color-placeholder);
|
||||
}
|
||||
|
||||
.folder-picker__input {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
height: 24px;
|
||||
padding: 0 6px;
|
||||
border: 1px solid var(--td-brand-color);
|
||||
border-radius: var(--app-radius-xs);
|
||||
background: var(--td-bg-color-container);
|
||||
color: var(--td-text-color-primary);
|
||||
font-family: var(--app-font-family);
|
||||
font-size: var(--app-text-md);
|
||||
outline: none;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,139 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test, { after, before } from 'node:test'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { createServer, type ViteDevServer } from 'vite'
|
||||
import vue from '@vitejs/plugin-vue'
|
||||
import { createSSRApp, defineComponent, h, type Component } from 'vue'
|
||||
import { renderToString } from 'vue/server-renderer'
|
||||
import { createI18n } from 'vue-i18n'
|
||||
import en from '../../../i18n/locales/en-US'
|
||||
|
||||
const tree = readFileSync(new URL('./KbFolderTree.vue', import.meta.url), 'utf8')
|
||||
const batchBar = readFileSync(new URL('./DocumentBatchBar.vue', import.meta.url), 'utf8')
|
||||
const cardView = readFileSync(new URL('./DocumentCardView.vue', import.meta.url), 'utf8')
|
||||
const listView = readFileSync(new URL('./DocumentListView.vue', import.meta.url), 'utf8')
|
||||
|
||||
// The root folder's own path IS the empty string, so a falsy "nothing is being
|
||||
// renamed" sentinel matches it and leaves a stray rename input on the root row.
|
||||
// Two independent guards keep that from coming back.
|
||||
test('the rename sentinel cannot collide with the root folder path', () => {
|
||||
assert.match(tree, /const renamingPath = ref<string \| null>\(null\)/)
|
||||
assert.doesNotMatch(tree, /const renamingPath = ref\(''\)/)
|
||||
assert.match(tree, /row\.kind === 'folder' && renamingPath\.value === row\.path/)
|
||||
})
|
||||
|
||||
test('only real folders expose a rename affordance', () => {
|
||||
assert.match(tree, /v-if="canEdit && row\.kind === 'folder'"/)
|
||||
assert.match(tree, /popup-menu-item/)
|
||||
assert.match(tree, /onFolderMenuRename/)
|
||||
})
|
||||
|
||||
// Picking a folder is a small, reversible action, so it stays a popup: in the row
|
||||
// menu it is another level of the menu that is already open, and in the batch bar
|
||||
// it hangs off the button. Neither should escalate to a modal dialog.
|
||||
test('the folder picker is a popup rather than a modal', () => {
|
||||
assert.match(cardView, /folderPickerItemId === item\.id/)
|
||||
assert.match(listView, /folderPickerItemId === item\.id/)
|
||||
assert.match(batchBar, /<t-popup[^>]*v-model:visible="folderPickerVisible"/)
|
||||
for (const source of [cardView, listView, batchBar]) {
|
||||
assert.doesNotMatch(source, /MoveToFolderDialog/)
|
||||
}
|
||||
})
|
||||
|
||||
// The folder picker must render ahead of the normal action menu; otherwise
|
||||
// moveMenuMode === 'normal' keeps the menu visible and clicks look dead.
|
||||
test('the folder picker wins over the normal action menu', () => {
|
||||
for (const source of [cardView, listView]) {
|
||||
const pickerIdx = source.indexOf('v-if="folderPickerItemId === item.id"')
|
||||
const normalIdx = source.indexOf('v-else-if="moveMenuMode === \'normal\'"')
|
||||
assert.ok(pickerIdx >= 0)
|
||||
assert.ok(normalIdx >= 0)
|
||||
assert.ok(pickerIdx < normalIdx)
|
||||
}
|
||||
})
|
||||
|
||||
test('folder navigation cancels stale card hover popovers', () => {
|
||||
assert.match(cardView, /if \(!cardElement\.isConnected/)
|
||||
assert.match(cardView, /watch\(\(\) => props\.items, dismissCardPopover\)/)
|
||||
assert.match(cardView, /const onOpenFolder = \(path: string\)[\s\S]*?dismissCardPopover\(\)[\s\S]*?emit\('open-folder', path\)/)
|
||||
assert.match(cardView, /@click\.stop="onOpenFolder\(item\.folder_path\)"/)
|
||||
})
|
||||
|
||||
// The counts the sidebar shows come from the connector-produced folder tree, so
|
||||
// they have to be rendered for real: a folder whose documents all sit in
|
||||
// sub-folders used to count 0 here, which read as "empty". The rendered HTML is
|
||||
// the assertion, not the template source, so a wrong binding cannot pass.
|
||||
let server: ViteDevServer
|
||||
let KbFolderTree: Component
|
||||
before(async () => {
|
||||
server = await createServer({
|
||||
configFile: false,
|
||||
optimizeDeps: { noDiscovery: true, entries: [] },
|
||||
plugins: [vue()],
|
||||
resolve: { alias: { '@': fileURLToPath(new URL('../../../', import.meta.url)) } },
|
||||
server: { middlewareMode: true },
|
||||
appType: 'custom',
|
||||
})
|
||||
KbFolderTree = (await server.ssrLoadModule('/src/views/knowledge/components/KbFolderTree.vue')).default
|
||||
})
|
||||
after(async () => { await server?.close() })
|
||||
|
||||
// Mirrors the deployed DingTalk-synced knowledge base: multi-level folders, so
|
||||
// the direct document count of a parent is 0 while its subtree holds 5.
|
||||
const folderTree = {
|
||||
root_document_count: 3,
|
||||
total_document_count: 17,
|
||||
folders: [
|
||||
{ path: '培训材料库', name: '培训材料库', document_count: 3, total_count: 17 },
|
||||
{
|
||||
path: '天诛渗透攻防',
|
||||
name: '天诛渗透攻防',
|
||||
document_count: 0,
|
||||
total_count: 5,
|
||||
children: [
|
||||
{ path: '天诛渗透攻防/FAQ', name: 'FAQ', document_count: 2, total_count: 2 },
|
||||
{ path: '天诛渗透攻防/售后', name: '售后', document_count: 2, total_count: 2 },
|
||||
{ path: '天诛渗透攻防/2024使用培训视频', name: '2024使用培训视频', document_count: 1, total_count: 1 },
|
||||
],
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
async function renderTree(props: Record<string, unknown>): Promise<string> {
|
||||
const app = createSSRApp({ render: () => h(KbFolderTree, props) })
|
||||
app.use(createI18n({ legacy: false, locale: 'en-US', messages: { 'en-US': en } }))
|
||||
// The TDesign widgets are registered globally by the app; empty shells keep
|
||||
// the rendered row markup readable here.
|
||||
for (const name of ['t-icon', 't-tooltip', 't-popup', 't-skeleton']) {
|
||||
app.component(name, defineComponent({ setup: (_, { slots }) => () => h('span', slots.default?.()) }))
|
||||
}
|
||||
return renderToString(app)
|
||||
}
|
||||
|
||||
/** Markup of one rendered row, isolated from the rows around it. */
|
||||
function rowHtml(html: string, marker: string): string {
|
||||
const starts = [...html.matchAll(/<div class="[^"]*kb-folder-row[^"]*"/g)].map((match) => match.index!)
|
||||
const row = starts
|
||||
.map((start, index) => html.slice(start, starts[index + 1]))
|
||||
.find((markup) => markup.includes(marker))
|
||||
assert.ok(row, `row ${marker} should render`)
|
||||
return row
|
||||
}
|
||||
|
||||
test('a folder row shows the recursive document count', async () => {
|
||||
const html = await renderTree({ tree: folderTree, selectedPath: '天诛渗透攻防' })
|
||||
const row = rowHtml(html, 'title="天诛渗透攻防"')
|
||||
assert.match(row, /kb-folder-row__count[^>]*>5</)
|
||||
assert.doesNotMatch(row, /kb-folder-row__count[^>]*>0</)
|
||||
// The tooltip keeps the direct/recursive split visible, so the number is not
|
||||
// mistaken for the folder's own contents.
|
||||
assert.match(row, /0 documents in this folder; 5 including subfolders/)
|
||||
})
|
||||
|
||||
test('the root row shows the knowledge base total, not the root-level count', async () => {
|
||||
const html = await renderTree({ tree: folderTree, selectedPath: '' })
|
||||
const row = rowHtml(html, 'is-root')
|
||||
assert.match(row, /kb-folder-row__count[^>]*>17</)
|
||||
assert.doesNotMatch(row, /kb-folder-row__count[^>]*>3</)
|
||||
})
|
||||
@@ -0,0 +1,507 @@
|
||||
<template>
|
||||
<aside class="kb-folder-tree" :class="{ 'is-collapsed': collapsed }">
|
||||
<div class="kb-folder-tree__header">
|
||||
<template v-if="!collapsed">
|
||||
<span class="kb-folder-tree__title">{{ t('knowledgeBase.folderTree.title') }}</span>
|
||||
<span v-if="tree && !loading" class="kb-folder-tree__total"
|
||||
:title="t('knowledgeBase.folderTree.totalDocuments', { count: tree.total_document_count })">
|
||||
{{ t('knowledgeBase.folderTree.totalDocuments', { count: tree.total_document_count }) }}
|
||||
</span>
|
||||
<t-tooltip :content="t('knowledgeBase.folderTree.collapse')" placement="top">
|
||||
<button
|
||||
type="button"
|
||||
class="kb-folder-tree__icon-btn"
|
||||
:aria-label="t('knowledgeBase.folderTree.collapse')"
|
||||
@click="emit('update:collapsed', true)"
|
||||
>
|
||||
<t-icon name="chevron-left-double" size="15px" />
|
||||
</button>
|
||||
</t-tooltip>
|
||||
</template>
|
||||
<t-tooltip v-else :content="t('knowledgeBase.folderTree.expand')" placement="right">
|
||||
<button
|
||||
type="button"
|
||||
class="kb-folder-tree__icon-btn"
|
||||
:aria-label="t('knowledgeBase.folderTree.expand')"
|
||||
@click="emit('update:collapsed', false)"
|
||||
>
|
||||
<t-icon name="chevron-right-double" size="15px" />
|
||||
</button>
|
||||
</t-tooltip>
|
||||
</div>
|
||||
|
||||
<div v-if="!collapsed" class="kb-folder-tree__body">
|
||||
<template v-if="loading && !tree">
|
||||
<div v-for="n in 5" :key="'folder-skel-' + n" class="kb-folder-tree__skeleton">
|
||||
<t-skeleton animation="gradient" :row-col="[{ width: '100%', height: '16px' }]" />
|
||||
</div>
|
||||
</template>
|
||||
<template v-else>
|
||||
<div
|
||||
v-for="row in rows"
|
||||
:key="row.path || '__root__'"
|
||||
class="kb-folder-row"
|
||||
:class="{
|
||||
active: selectedPath === row.path,
|
||||
'is-root': row.kind === 'root',
|
||||
'is-editable': canEdit && row.kind === 'folder',
|
||||
'is-menu-open': menuOpenPath === row.path,
|
||||
}"
|
||||
:style="{ '--kb-folder-depth': row.depth }"
|
||||
:title="row.kind === 'root' ? t('knowledgeBase.folderTree.rootRowTip') : row.path"
|
||||
role="button"
|
||||
tabindex="0"
|
||||
@click="emit('select', row.path)"
|
||||
@keydown.enter.self="emit('select', row.path)"
|
||||
@keydown.space.prevent.self="emit('select', row.path)"
|
||||
>
|
||||
<span
|
||||
v-if="row.hasChildren"
|
||||
class="kb-folder-row__toggle"
|
||||
role="button"
|
||||
tabindex="0"
|
||||
:aria-expanded="isExpanded(row.path)"
|
||||
@keydown.enter.stop.prevent="toggle(row.path)"
|
||||
@keydown.space.stop.prevent="toggle(row.path)"
|
||||
:aria-label="t(isExpanded(row.path)
|
||||
? 'knowledgeBase.folderTree.collapseFolder'
|
||||
: 'knowledgeBase.folderTree.expandFolder')"
|
||||
@click.stop="toggle(row.path)"
|
||||
>
|
||||
<t-icon :name="isExpanded(row.path) ? 'chevron-down' : 'chevron-right'" />
|
||||
</span>
|
||||
<span v-else class="kb-folder-row__toggle-placeholder" aria-hidden="true" />
|
||||
|
||||
<t-icon
|
||||
:name="row.kind === 'root' || (row.hasChildren && isExpanded(row.path)) ? 'folder-open' : 'folder'"
|
||||
class="kb-folder-row__icon"
|
||||
/>
|
||||
|
||||
<input
|
||||
v-if="isRenaming(row)"
|
||||
ref="renameInputRef"
|
||||
v-model="renameValue"
|
||||
class="kb-folder-row__rename"
|
||||
:placeholder="t('knowledgeBase.folderTree.renamePlaceholder')"
|
||||
@click.stop
|
||||
@keydown.enter="commitRename(row)"
|
||||
@keydown.esc="cancelRename"
|
||||
@blur="commitRename(row)"
|
||||
/>
|
||||
<template v-else>
|
||||
<span class="kb-folder-row__label">
|
||||
{{ row.kind === 'root' ? (rootLabel || t('knowledgeBase.folderTree.rootRow')) : row.name }}
|
||||
</span>
|
||||
<span class="kb-folder-row__trailing">
|
||||
<span class="kb-folder-row__count"
|
||||
:title="t('knowledgeBase.folderTree.countHint', { direct: row.documentCount, total: row.totalCount })">
|
||||
{{ row.totalCount }}
|
||||
</span>
|
||||
<t-popup
|
||||
v-if="canEdit && row.kind === 'folder'"
|
||||
:visible="menuOpenPath === row.path"
|
||||
trigger="click"
|
||||
placement="bottom-right"
|
||||
destroy-on-close
|
||||
overlay-class-name="card-more-popup"
|
||||
@visible-change="(visible: boolean) => onFolderMenuVisible(row.path, visible)"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="kb-folder-row__more"
|
||||
:class="{ 'is-open': menuOpenPath === row.path }"
|
||||
:aria-label="t('knowledgeBase.columnActions')"
|
||||
@click.stop
|
||||
>
|
||||
<t-icon name="more" />
|
||||
</button>
|
||||
<template #content>
|
||||
<div class="popup-menu kb-folder-row__menu" @click.stop>
|
||||
<div class="popup-menu-item" @click="onFolderMenuRename(row)">
|
||||
<t-icon name="edit" class="menu-icon" />
|
||||
<span>{{ t('knowledgeBase.folderTree.rename') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</t-popup>
|
||||
<span v-else class="kb-folder-row__more-placeholder" aria-hidden="true"></span>
|
||||
</span>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</aside>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, ref, watch } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import type { KnowledgeFolderTree } from '@/api/knowledge-base/index'
|
||||
import {
|
||||
buildFolderRows,
|
||||
folderAncestorPaths,
|
||||
joinFolderPath,
|
||||
ROOT_FOLDER_PATH,
|
||||
type FolderRow,
|
||||
} from '../folderTree'
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
tree: KnowledgeFolderTree | null
|
||||
/** Selected folder path; the empty string is the knowledge base top level. */
|
||||
rootLabel?: string
|
||||
selectedPath: string
|
||||
loading?: boolean
|
||||
collapsed?: boolean
|
||||
canEdit?: boolean
|
||||
}>(), {
|
||||
loading: false,
|
||||
collapsed: false,
|
||||
canEdit: false,
|
||||
})
|
||||
|
||||
const emit = defineEmits<{
|
||||
select: [path: string]
|
||||
'update:collapsed': [collapsed: boolean]
|
||||
rename: [payload: { from: string; to: string }]
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
// The root starts expanded so the uploaded structure is visible without a click.
|
||||
const expanded = ref(new Set<string>([ROOT_FOLDER_PATH]))
|
||||
// null, not '', because '' is the root's own path: a falsy sentinel would put
|
||||
// the root row into rename mode permanently.
|
||||
const renamingPath = ref<string | null>(null)
|
||||
const menuOpenPath = ref<string | null>(null)
|
||||
const renameValue = ref('')
|
||||
const renameInputRef = ref<HTMLInputElement | HTMLInputElement[] | null>(null)
|
||||
|
||||
const rows = computed(() => buildFolderRows(props.tree, expanded.value))
|
||||
|
||||
const isExpanded = (path: string) => expanded.value.has(path)
|
||||
|
||||
// The root has no name of its own to edit, and excluding it here means no
|
||||
// sentinel value can ever put it into rename mode.
|
||||
const isRenaming = (row: FolderRow) => row.kind === 'folder' && renamingPath.value === row.path
|
||||
|
||||
const toggle = (path: string) => {
|
||||
const next = new Set(expanded.value)
|
||||
if (next.has(path)) next.delete(path)
|
||||
else next.add(path)
|
||||
expanded.value = next
|
||||
}
|
||||
|
||||
const startRename = async (row: FolderRow) => {
|
||||
renamingPath.value = row.path
|
||||
renameValue.value = row.name
|
||||
await nextTick()
|
||||
const input = Array.isArray(renameInputRef.value) ? renameInputRef.value[0] : renameInputRef.value
|
||||
input?.focus()
|
||||
input?.select()
|
||||
}
|
||||
|
||||
const onFolderMenuVisible = (path: string, visible: boolean) => {
|
||||
menuOpenPath.value = visible ? path : null
|
||||
}
|
||||
|
||||
const onFolderMenuRename = async (row: FolderRow) => {
|
||||
menuOpenPath.value = null
|
||||
await startRename(row)
|
||||
}
|
||||
|
||||
const cancelRename = () => {
|
||||
renamingPath.value = null
|
||||
renameValue.value = ''
|
||||
}
|
||||
|
||||
const commitRename = (row: FolderRow) => {
|
||||
if (!isRenaming(row)) return
|
||||
const name = renameValue.value.trim()
|
||||
cancelRename()
|
||||
// Only the last segment is edited here; the folder keeps its place in the tree.
|
||||
if (!name || name === row.name) return
|
||||
const parent = row.path.slice(0, Math.max(0, row.path.length - row.name.length - 1))
|
||||
emit('rename', { from: row.path, to: joinFolderPath(parent, name) })
|
||||
}
|
||||
|
||||
// Keep the selected folder reachable: expand the root and every folder above
|
||||
// the active path, both on first load and when the selection changes from
|
||||
// elsewhere (e.g. opening a folder from the document list).
|
||||
watch(
|
||||
() => [props.selectedPath, props.tree] as const,
|
||||
() => {
|
||||
const next = new Set(expanded.value)
|
||||
folderAncestorPaths(props.selectedPath).forEach((path) => next.add(path))
|
||||
expanded.value = next
|
||||
},
|
||||
{ immediate: true },
|
||||
)
|
||||
|
||||
// First load also opens the top-level folders, so a two-level upload is visible
|
||||
// in full without any expanding.
|
||||
watch(
|
||||
() => props.tree,
|
||||
(tree) => {
|
||||
if (!tree?.folders?.length || expanded.value.size > 1) return
|
||||
const next = new Set(expanded.value)
|
||||
tree.folders.forEach((folder) => next.add(folder.path))
|
||||
expanded.value = next
|
||||
},
|
||||
{ immediate: true },
|
||||
)
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
.kb-folder-tree {
|
||||
--kb-folder-indent: 14px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex-shrink: 0;
|
||||
width: 220px;
|
||||
min-height: 0;
|
||||
padding-right: 12px;
|
||||
margin-right: 16px;
|
||||
border-right: 1px solid var(--td-component-stroke);
|
||||
box-sizing: border-box;
|
||||
|
||||
&.is-collapsed {
|
||||
width: auto;
|
||||
padding-right: 8px;
|
||||
margin-right: 8px;
|
||||
}
|
||||
}
|
||||
|
||||
.kb-folder-tree__header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 6px;
|
||||
height: 32px;
|
||||
padding-bottom: 16px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.kb-folder-tree__title {
|
||||
font-size: var(--app-text-md);
|
||||
font-weight: 500;
|
||||
color: var(--td-text-color-primary);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.kb-folder-tree__total {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
font-size: var(--app-text-xs);
|
||||
font-weight: 400;
|
||||
color: var(--td-text-color-placeholder);
|
||||
}
|
||||
|
||||
.kb-folder-tree__icon-btn {
|
||||
flex-shrink: 0;
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
border-radius: var(--app-radius-sm);
|
||||
background: transparent;
|
||||
color: var(--td-text-color-secondary);
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
cursor: pointer;
|
||||
transition: background-color var(--app-motion-fast) ease, color var(--app-motion-fast) ease;
|
||||
|
||||
&:hover {
|
||||
color: var(--td-brand-color);
|
||||
background: var(--td-bg-color-container-hover);
|
||||
}
|
||||
}
|
||||
|
||||
.kb-folder-tree__body {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
overflow-x: hidden;
|
||||
padding: 8px 0 12px;
|
||||
scrollbar-width: thin;
|
||||
|
||||
&::-webkit-scrollbar {
|
||||
width: 4px;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-thumb {
|
||||
border-radius: 2px;
|
||||
background: var(--td-scrollbar-color);
|
||||
}
|
||||
}
|
||||
|
||||
.kb-folder-tree__skeleton {
|
||||
padding: 7px 8px;
|
||||
}
|
||||
|
||||
.kb-folder-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
box-sizing: border-box;
|
||||
width: 100%;
|
||||
height: 32px;
|
||||
margin-bottom: 2px;
|
||||
padding: 0 4px 0 calc(4px + var(--kb-folder-depth, 0) * var(--kb-folder-indent));
|
||||
border-radius: var(--app-radius-sm);
|
||||
background: transparent;
|
||||
color: var(--td-text-color-primary);
|
||||
font-family: var(--app-font-family);
|
||||
font-size: var(--app-text-md);
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
transition: background var(--app-motion-fast) ease, color var(--app-motion-fast) ease;
|
||||
|
||||
&:hover {
|
||||
background: var(--td-bg-color-container-hover);
|
||||
}
|
||||
|
||||
&:focus-visible {
|
||||
outline: none;
|
||||
outline: 2px solid var(--app-focus-border);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
&.active {
|
||||
background: var(--app-selection-bg);
|
||||
|
||||
.kb-folder-row__label,
|
||||
.kb-folder-row__icon {
|
||||
color: var(--td-brand-color);
|
||||
}
|
||||
.kb-folder-row__label { font-weight: 500; }
|
||||
}
|
||||
|
||||
&.is-root .kb-folder-row__label {
|
||||
font-weight: 500;
|
||||
}
|
||||
}
|
||||
|
||||
.kb-folder-row__toggle,
|
||||
.kb-folder-row__toggle-placeholder {
|
||||
flex: 0 0 auto;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: var(--td-text-color-placeholder);
|
||||
border-radius: var(--app-radius-xs);
|
||||
}
|
||||
|
||||
.kb-folder-row__toggle {
|
||||
cursor: pointer;
|
||||
|
||||
&:hover {
|
||||
color: var(--td-text-color-primary);
|
||||
background: var(--td-bg-color-secondarycontainer);
|
||||
}
|
||||
|
||||
.t-icon {
|
||||
font-size: var(--app-text-base);
|
||||
}
|
||||
}
|
||||
|
||||
.kb-folder-row__icon {
|
||||
flex: 0 0 auto;
|
||||
font-size: var(--app-text-xl);
|
||||
color: var(--td-text-color-secondary);
|
||||
}
|
||||
|
||||
.kb-folder-row__label {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.kb-folder-row__trailing {
|
||||
flex: 0 0 auto;
|
||||
gap: 2px;
|
||||
height: 20px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
margin-left: 2px;
|
||||
}
|
||||
|
||||
.kb-folder-row__count {
|
||||
min-width: 16px;
|
||||
text-align: right;
|
||||
font-size: var(--app-text-xs);
|
||||
color: var(--td-text-color-placeholder);
|
||||
font-variant-numeric: tabular-nums;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.kb-folder-row__more-placeholder { width: 20px; }
|
||||
|
||||
.kb-folder-row__more {
|
||||
display: inline-flex;
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
border-radius: var(--app-radius-xs);
|
||||
background: transparent;
|
||||
color: var(--td-text-color-placeholder);
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
cursor: pointer;
|
||||
transition: color var(--app-motion-fast) ease, background-color var(--app-motion-fast) ease;
|
||||
|
||||
&:hover {
|
||||
color: var(--td-brand-color);
|
||||
background: var(--td-bg-color-secondarycontainer);
|
||||
}
|
||||
|
||||
.t-icon {
|
||||
font-size: var(--app-text-base);
|
||||
}
|
||||
}
|
||||
|
||||
.kb-folder-row.is-editable:hover,
|
||||
.kb-folder-row.is-editable:focus-within,
|
||||
.kb-folder-row.is-menu-open {
|
||||
.kb-folder-row__more {
|
||||
opacity: 1;
|
||||
pointer-events: auto;
|
||||
}
|
||||
}
|
||||
|
||||
.kb-folder-row__more.is-open {
|
||||
color: var(--td-brand-color);
|
||||
}
|
||||
|
||||
.kb-folder-row__menu {
|
||||
min-width: 140px;
|
||||
}
|
||||
|
||||
.kb-folder-row__rename {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
height: 22px;
|
||||
padding: 0 6px;
|
||||
border: 1px solid var(--td-brand-color);
|
||||
border-radius: var(--app-radius-xs);
|
||||
background: var(--td-bg-color-container);
|
||||
color: var(--td-text-color-primary);
|
||||
font-family: var(--app-font-family);
|
||||
font-size: var(--app-text-md);
|
||||
outline: none;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,706 @@
|
||||
<template>
|
||||
<SettingDrawer
|
||||
v-model:visible="drawerVisible"
|
||||
:title="$t('knowledgeBase.tagManageTitle')"
|
||||
:description="$t('knowledgeBase.tagManageDescription')"
|
||||
icon="discount"
|
||||
width="480px"
|
||||
:min-width="420"
|
||||
:max-width="640"
|
||||
resizable
|
||||
storage-key="setting-drawer:width:kb-tag-manage"
|
||||
:hide-footer="true"
|
||||
>
|
||||
<section class="setting-drawer__section">
|
||||
<h4 class="setting-drawer__section-title">{{ $t('knowledgeBase.tagManageListSection') }}</h4>
|
||||
|
||||
<div class="tag-manage-toolbar">
|
||||
<div class="tag-manage-search-wrap">
|
||||
<t-input
|
||||
v-model.trim="searchQuery"
|
||||
size="small"
|
||||
:placeholder="$t('knowledgeBase.tagSearchPlaceholder')"
|
||||
clearable
|
||||
class="tag-manage-search"
|
||||
>
|
||||
<template #prefix-icon>
|
||||
<t-icon name="search" size="14px" />
|
||||
</template>
|
||||
</t-input>
|
||||
</div>
|
||||
<t-tooltip :content="$t('knowledgeBase.tagCreateAction')" placement="top">
|
||||
<t-button
|
||||
size="small"
|
||||
variant="text"
|
||||
class="tag-manage-create-btn"
|
||||
:disabled="creatingTag"
|
||||
:aria-label="$t('knowledgeBase.tagCreateAction')"
|
||||
@click="startCreateTag"
|
||||
>
|
||||
<template #icon><t-icon name="add" size="16px" /></template>
|
||||
</t-button>
|
||||
</t-tooltip>
|
||||
</div>
|
||||
|
||||
<t-loading :loading="loading && !tags.length" size="small" class="tag-manage-loading">
|
||||
<div v-if="!loading && !tags.length && !creatingTag" class="tag-manage-empty">
|
||||
<t-empty :description="$t('knowledgeBase.tagEmptyResult')" />
|
||||
</div>
|
||||
|
||||
<ul v-else class="tag-tile-grid">
|
||||
<template v-if="loading && !tags.length">
|
||||
<li v-for="n in 4" :key="'tag-skel-' + n" class="tag-tile tag-tile--skeleton">
|
||||
<t-skeleton animation="gradient" :row-col="[{ width: '100%', height: '44px', type: 'rect' }]" />
|
||||
</li>
|
||||
</template>
|
||||
|
||||
<template v-else>
|
||||
<li v-if="creatingTag" class="tag-tile tag-tile--editing" @click.stop>
|
||||
<div class="tag-tile__main tag-tile__main--editing">
|
||||
<span class="tag-tile__badge" aria-hidden="true">
|
||||
<t-icon name="discount" size="15px" />
|
||||
</span>
|
||||
<t-input
|
||||
ref="newTagInputRef"
|
||||
v-model="newTagName"
|
||||
size="small"
|
||||
:maxlength="40"
|
||||
class="tag-tile__input"
|
||||
:placeholder="$t('knowledgeBase.tagNamePlaceholder')"
|
||||
@enter="submitCreateTag"
|
||||
@keydown="(_v: string, ctx?: { e?: KeyboardEvent }) => onEditKeydown(ctx, cancelCreateTag)"
|
||||
/>
|
||||
</div>
|
||||
<div class="tag-tile__actions">
|
||||
<t-button
|
||||
variant="text"
|
||||
shape="square"
|
||||
size="small"
|
||||
class="tag-tile__action-btn tag-tile__action-btn--confirm"
|
||||
:loading="creatingTagLoading"
|
||||
:title="$t('common.create')"
|
||||
@click.stop="submitCreateTag"
|
||||
>
|
||||
<template #icon><t-icon name="check" size="14px" /></template>
|
||||
</t-button>
|
||||
<t-button
|
||||
variant="text"
|
||||
shape="square"
|
||||
size="small"
|
||||
class="tag-tile__action-btn"
|
||||
:title="$t('common.cancel')"
|
||||
@click.stop="cancelCreateTag"
|
||||
>
|
||||
<template #icon><t-icon name="close" size="14px" /></template>
|
||||
</t-button>
|
||||
</div>
|
||||
</li>
|
||||
|
||||
<li
|
||||
v-for="tag in tags"
|
||||
:key="tag.id"
|
||||
class="tag-tile"
|
||||
:class="{ 'tag-tile--editing': editingTagId === tag.id }"
|
||||
@click.stop
|
||||
>
|
||||
<template v-if="editingTagId === tag.id">
|
||||
<div class="tag-tile__main tag-tile__main--editing">
|
||||
<span class="tag-tile__badge" aria-hidden="true">
|
||||
<t-icon name="discount" size="15px" />
|
||||
</span>
|
||||
<t-input
|
||||
:ref="(el: any) => setEditingTagInputRef(el, tag.id)"
|
||||
v-model="editingTagName"
|
||||
size="small"
|
||||
:maxlength="40"
|
||||
class="tag-tile__input"
|
||||
:placeholder="$t('knowledgeBase.tagNamePlaceholder')"
|
||||
@enter="submitEditTag"
|
||||
@keydown="(_v: string, ctx?: { e?: KeyboardEvent }) => onEditKeydown(ctx, cancelEditTag)"
|
||||
/>
|
||||
</div>
|
||||
<div class="tag-tile__actions">
|
||||
<t-button
|
||||
variant="text"
|
||||
shape="square"
|
||||
size="small"
|
||||
class="tag-tile__action-btn tag-tile__action-btn--confirm"
|
||||
:loading="editingTagSubmitting"
|
||||
:title="$t('common.save')"
|
||||
@click.stop="submitEditTag"
|
||||
>
|
||||
<template #icon><t-icon name="check" size="14px" /></template>
|
||||
</t-button>
|
||||
<t-button
|
||||
variant="text"
|
||||
shape="square"
|
||||
size="small"
|
||||
class="tag-tile__action-btn"
|
||||
:title="$t('common.cancel')"
|
||||
@click.stop="cancelEditTag"
|
||||
>
|
||||
<template #icon><t-icon name="close" size="14px" /></template>
|
||||
</t-button>
|
||||
</div>
|
||||
</template>
|
||||
<template v-else>
|
||||
<div class="tag-tile__main">
|
||||
<span class="tag-tile__badge" aria-hidden="true">
|
||||
<t-icon name="discount" size="15px" />
|
||||
</span>
|
||||
<span class="tag-tile__text">
|
||||
<span class="tag-tile__name" :title="tag.name">{{ tag.name }}</span>
|
||||
<span class="tag-tile__count">
|
||||
{{
|
||||
isFaq
|
||||
? $t('knowledgeBase.tagManageFaqCount', { count: tag.chunk_count || 0 })
|
||||
: $t('knowledgeBase.tagManageDocCount', { count: tag.knowledge_count || 0 })
|
||||
}}
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
<div class="tag-tile__actions" @click.stop>
|
||||
<t-button
|
||||
variant="text"
|
||||
shape="square"
|
||||
size="small"
|
||||
class="tag-tile__action-btn"
|
||||
:title="$t('knowledgeBase.tagEditAction')"
|
||||
@click="startEditTag(tag)"
|
||||
>
|
||||
<template #icon><t-icon name="edit" size="14px" /></template>
|
||||
</t-button>
|
||||
<t-popconfirm
|
||||
:content="getDeleteConfirmContent(tag)"
|
||||
:confirm-btn="{ content: $t('common.delete'), theme: 'danger' }"
|
||||
:cancel-btn="{ content: $t('common.cancel') }"
|
||||
placement="bottom-right"
|
||||
@confirm="deleteTag(tag)"
|
||||
>
|
||||
<t-button
|
||||
theme="danger"
|
||||
shape="square"
|
||||
variant="text"
|
||||
size="small"
|
||||
class="tag-tile__action-btn"
|
||||
:title="$t('knowledgeBase.tagDeleteAction')"
|
||||
@click.stop
|
||||
>
|
||||
<template #icon><t-icon name="delete" size="14px" /></template>
|
||||
</t-button>
|
||||
</t-popconfirm>
|
||||
</div>
|
||||
</template>
|
||||
</li>
|
||||
</template>
|
||||
</ul>
|
||||
|
||||
<div v-if="hasMore && tags.length" class="tag-load-more">
|
||||
<t-button variant="text" size="small" :loading="loadingMore" @click="loadTags(false)">
|
||||
{{ $t('tenant.loadMore') }}
|
||||
</t-button>
|
||||
</div>
|
||||
</t-loading>
|
||||
</section>
|
||||
</SettingDrawer>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, watch, nextTick, computed, type ComponentPublicInstance } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { MessagePlugin } from 'tdesign-vue-next';
|
||||
import SettingDrawer from '@/components/settings/SettingDrawer.vue';
|
||||
import {
|
||||
listKnowledgeTags,
|
||||
createKnowledgeBaseTag,
|
||||
updateKnowledgeBaseTag,
|
||||
deleteKnowledgeBaseTag,
|
||||
} from '@/api/knowledge-base/index';
|
||||
|
||||
type TagRow = {
|
||||
id: string;
|
||||
seq_id: number;
|
||||
name: string;
|
||||
knowledge_count?: number;
|
||||
chunk_count?: number;
|
||||
};
|
||||
|
||||
type TagInputInstance = ComponentPublicInstance<{ focus: () => void; select: () => void }>;
|
||||
|
||||
const TAG_PAGE_SIZE = 50;
|
||||
|
||||
const props = defineProps<{
|
||||
visible: boolean;
|
||||
kbId: string;
|
||||
isFaq?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:visible': [boolean];
|
||||
changed: [payload?: { deletedTagId?: string }];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
const drawerVisible = computed({
|
||||
get: () => props.visible,
|
||||
set: (value: boolean) => emit('update:visible', value),
|
||||
});
|
||||
|
||||
const tags = ref<TagRow[]>([]);
|
||||
const loading = ref(false);
|
||||
const loadingMore = ref(false);
|
||||
const page = ref(1);
|
||||
const hasMore = ref(false);
|
||||
const total = ref(0);
|
||||
const searchQuery = ref('');
|
||||
let searchDebounce: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
const creatingTag = ref(false);
|
||||
const creatingTagLoading = ref(false);
|
||||
const newTagName = ref('');
|
||||
const newTagInputRef = ref<TagInputInstance | null>(null);
|
||||
|
||||
const editingTagId = ref<string | null>(null);
|
||||
const editingTagName = ref('');
|
||||
const editingTagSubmitting = ref(false);
|
||||
const editingTagInputRefs = new Map<string, TagInputInstance | null>();
|
||||
|
||||
const setEditingTagInputRef = (el: TagInputInstance | null, tagId: string) => {
|
||||
if (el) {
|
||||
editingTagInputRefs.set(tagId, el);
|
||||
} else {
|
||||
editingTagInputRefs.delete(tagId);
|
||||
}
|
||||
};
|
||||
|
||||
const getDeleteConfirmContent = (tag: { name: string }) =>
|
||||
t(props.isFaq ? 'knowledgeBase.tagDeleteDesc' : 'knowledgeBase.tagDeleteDescDoc', { name: tag.name });
|
||||
|
||||
const onEditKeydown = (ctx: { e?: KeyboardEvent } | undefined, cancel: () => void) => {
|
||||
if (ctx?.e?.key === 'Escape') {
|
||||
ctx.e.stopPropagation();
|
||||
ctx.e.preventDefault();
|
||||
cancel();
|
||||
}
|
||||
};
|
||||
|
||||
const resetLocalState = () => {
|
||||
cancelCreateTag();
|
||||
cancelEditTag();
|
||||
searchQuery.value = '';
|
||||
};
|
||||
|
||||
const loadTags = async (reset = false) => {
|
||||
if (!props.kbId) {
|
||||
tags.value = [];
|
||||
total.value = 0;
|
||||
hasMore.value = false;
|
||||
page.value = 1;
|
||||
return;
|
||||
}
|
||||
if (reset) {
|
||||
page.value = 1;
|
||||
tags.value = [];
|
||||
total.value = 0;
|
||||
hasMore.value = false;
|
||||
} else if (loading.value || loadingMore.value) {
|
||||
return;
|
||||
}
|
||||
|
||||
const currentPage = page.value || 1;
|
||||
loading.value = currentPage === 1;
|
||||
loadingMore.value = currentPage > 1;
|
||||
|
||||
try {
|
||||
const res: any = await listKnowledgeTags(props.kbId, {
|
||||
page: currentPage,
|
||||
page_size: TAG_PAGE_SIZE,
|
||||
keyword: searchQuery.value || undefined,
|
||||
});
|
||||
const pageData = (res?.data || {}) as { data?: TagRow[]; total?: number };
|
||||
const pageTags = (pageData.data || []).map((tag) => ({
|
||||
...tag,
|
||||
id: String(tag.id),
|
||||
}));
|
||||
|
||||
if (currentPage === 1) {
|
||||
tags.value = pageTags;
|
||||
} else {
|
||||
tags.value = [...tags.value, ...pageTags];
|
||||
}
|
||||
|
||||
total.value = pageData.total || tags.value.length;
|
||||
hasMore.value = tags.value.length < total.value;
|
||||
if (hasMore.value) {
|
||||
page.value = currentPage + 1;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load tags', error);
|
||||
} finally {
|
||||
loading.value = false;
|
||||
loadingMore.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const startCreateTag = () => {
|
||||
if (!props.kbId || creatingTag.value) return;
|
||||
cancelEditTag();
|
||||
creatingTag.value = true;
|
||||
nextTick(() => {
|
||||
newTagInputRef.value?.focus?.();
|
||||
newTagInputRef.value?.select?.();
|
||||
});
|
||||
};
|
||||
|
||||
const cancelCreateTag = () => {
|
||||
creatingTag.value = false;
|
||||
newTagName.value = '';
|
||||
};
|
||||
|
||||
const submitCreateTag = async () => {
|
||||
if (!props.kbId) return;
|
||||
const name = newTagName.value.trim();
|
||||
if (!name) {
|
||||
MessagePlugin.warning(t('knowledgeBase.tagNameRequired'));
|
||||
return;
|
||||
}
|
||||
creatingTagLoading.value = true;
|
||||
try {
|
||||
await createKnowledgeBaseTag(props.kbId, { name });
|
||||
MessagePlugin.success(t('knowledgeBase.tagCreateSuccess'));
|
||||
cancelCreateTag();
|
||||
await loadTags(true);
|
||||
emit('changed');
|
||||
} catch (error: any) {
|
||||
MessagePlugin.error(error?.message || t('common.operationFailed'));
|
||||
} finally {
|
||||
creatingTagLoading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const startEditTag = (tag: TagRow) => {
|
||||
cancelCreateTag();
|
||||
editingTagId.value = tag.id;
|
||||
editingTagName.value = tag.name;
|
||||
nextTick(() => {
|
||||
editingTagInputRefs.get(tag.id)?.focus?.();
|
||||
editingTagInputRefs.get(tag.id)?.select?.();
|
||||
});
|
||||
};
|
||||
|
||||
const cancelEditTag = () => {
|
||||
editingTagId.value = null;
|
||||
editingTagName.value = '';
|
||||
};
|
||||
|
||||
const submitEditTag = async () => {
|
||||
if (!props.kbId || !editingTagId.value) return;
|
||||
const name = editingTagName.value.trim();
|
||||
if (!name) {
|
||||
MessagePlugin.warning(t('knowledgeBase.tagNameRequired'));
|
||||
return;
|
||||
}
|
||||
const current = tags.value.find((tag) => tag.id === editingTagId.value);
|
||||
if (current && name === current.name) {
|
||||
cancelEditTag();
|
||||
return;
|
||||
}
|
||||
editingTagSubmitting.value = true;
|
||||
try {
|
||||
await updateKnowledgeBaseTag(props.kbId, editingTagId.value, { name });
|
||||
MessagePlugin.success(t('knowledgeBase.tagEditSuccess'));
|
||||
cancelEditTag();
|
||||
await loadTags(true);
|
||||
emit('changed');
|
||||
} catch (error: any) {
|
||||
MessagePlugin.error(error?.message || t('common.operationFailed'));
|
||||
} finally {
|
||||
editingTagSubmitting.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const deleteTag = async (tag: TagRow) => {
|
||||
if (!props.kbId) return;
|
||||
cancelCreateTag();
|
||||
cancelEditTag();
|
||||
try {
|
||||
await deleteKnowledgeBaseTag(props.kbId, tag.seq_id, { force: true });
|
||||
MessagePlugin.success(t('knowledgeBase.tagDeleteSuccess'));
|
||||
await loadTags(true);
|
||||
emit('changed', { deletedTagId: tag.id });
|
||||
void (async () => {
|
||||
await new Promise((resolve) => setTimeout(resolve, 800));
|
||||
emit('changed', { deletedTagId: tag.id });
|
||||
})();
|
||||
} catch (error: any) {
|
||||
MessagePlugin.error(error?.message || t('common.operationFailed'));
|
||||
}
|
||||
};
|
||||
|
||||
watch(
|
||||
() => props.visible,
|
||||
(open) => {
|
||||
if (open && props.kbId) {
|
||||
void loadTags(true);
|
||||
} else if (!open) {
|
||||
resetLocalState();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
watch(searchQuery, (newVal, oldVal) => {
|
||||
if (newVal === oldVal || !props.visible || !props.kbId) return;
|
||||
if (searchDebounce) clearTimeout(searchDebounce);
|
||||
searchDebounce = setTimeout(() => {
|
||||
void loadTags(true);
|
||||
}, 300);
|
||||
});
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
.tag-manage-toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.tag-manage-search-wrap {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.tag-manage-search {
|
||||
width: 100%;
|
||||
|
||||
:deep(.t-input) {
|
||||
font-size: var(--app-text-md);
|
||||
background-color: var(--td-bg-color-secondarycontainer);
|
||||
border-color: transparent;
|
||||
border-radius: var(--app-radius-sm);
|
||||
box-shadow: none !important;
|
||||
|
||||
&:hover,
|
||||
&:focus,
|
||||
&.t-is-focused {
|
||||
border-color: var(--td-component-border);
|
||||
background-color: var(--td-bg-color-container);
|
||||
box-shadow: none !important;
|
||||
}
|
||||
}
|
||||
|
||||
:deep(.t-input__inner) {
|
||||
font-size: var(--app-text-md);
|
||||
}
|
||||
|
||||
:deep(.t-input__prefix-icon) {
|
||||
margin-right: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.tag-manage-create-btn {
|
||||
flex-shrink: 0;
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
padding: 0;
|
||||
border-radius: var(--app-radius-sm);
|
||||
color: var(--td-text-color-secondary);
|
||||
|
||||
:deep(.t-icon) {
|
||||
font-size: var(--app-text-xl);
|
||||
}
|
||||
|
||||
&:hover:not(:disabled) {
|
||||
background: var(--td-bg-color-secondarycontainer);
|
||||
color: var(--td-text-color-primary);
|
||||
}
|
||||
|
||||
&:disabled {
|
||||
opacity: 0.45;
|
||||
}
|
||||
}
|
||||
|
||||
.tag-manage-loading {
|
||||
min-height: 80px;
|
||||
}
|
||||
|
||||
.tag-manage-empty {
|
||||
padding: 24px 0;
|
||||
}
|
||||
|
||||
.tag-tile-grid {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.tag-tile {
|
||||
position: relative;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 4px;
|
||||
min-height: 44px;
|
||||
padding: 5px 6px 5px 8px;
|
||||
border: 1px solid var(--td-component-stroke);
|
||||
border-radius: var(--app-radius-sm);
|
||||
background: var(--td-bg-color-container);
|
||||
box-sizing: border-box;
|
||||
transition: border-color var(--app-motion-fast) ease, background var(--app-motion-fast) ease;
|
||||
|
||||
&:hover:not(.tag-tile--editing):not(.tag-tile--skeleton) {
|
||||
border-color: var(--td-component-border);
|
||||
background: color-mix(in srgb, var(--td-bg-color-secondarycontainer) 40%, var(--td-bg-color-container));
|
||||
}
|
||||
|
||||
&--skeleton {
|
||||
padding: 0;
|
||||
border: none;
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
&--editing {
|
||||
border-color: var(--td-component-border);
|
||||
background: var(--td-bg-color-secondarycontainer);
|
||||
box-shadow: none;
|
||||
|
||||
.tag-tile__actions {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.tag-tile__main {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.tag-tile__input {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
|
||||
:deep(.t-input) {
|
||||
background: transparent;
|
||||
border-color: transparent;
|
||||
box-shadow: none;
|
||||
padding-left: 0;
|
||||
padding-right: 0;
|
||||
}
|
||||
|
||||
:deep(.t-input__wrap) {
|
||||
background: transparent;
|
||||
border-color: transparent;
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
:deep(.t-input__inner) {
|
||||
padding: 0;
|
||||
font-size: var(--app-text-md);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
:deep(.t-input:hover),
|
||||
:deep(.t-input.t-is-focused),
|
||||
:deep(.t-input__wrap:hover),
|
||||
:deep(.t-input__wrap.t-is-focused) {
|
||||
border-color: transparent !important;
|
||||
box-shadow: none !important;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
:deep(.t-input.t-is-focused .t-input__suffix),
|
||||
:deep(.t-input.t-is-focused .t-input__prefix) {
|
||||
box-shadow: none;
|
||||
}
|
||||
}
|
||||
|
||||
.tag-tile__badge {
|
||||
flex-shrink: 0;
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
border-radius: var(--app-radius-sm);
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: var(--td-bg-color-secondarycontainer);
|
||||
color: var(--td-text-color-placeholder);
|
||||
}
|
||||
|
||||
.tag-tile__text {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1px;
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.tag-tile__name {
|
||||
font-size: var(--app-text-md);
|
||||
font-weight: 500;
|
||||
line-height: 1.3;
|
||||
color: var(--td-text-color-primary);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.tag-tile__count {
|
||||
font-size: var(--app-text-xs);
|
||||
line-height: 1.3;
|
||||
color: var(--td-text-color-placeholder);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.tag-tile__actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-shrink: 0;
|
||||
opacity: 0;
|
||||
transition: opacity var(--app-motion-instant) ease;
|
||||
}
|
||||
|
||||
.tag-tile:hover .tag-tile__actions,
|
||||
.tag-tile:focus-within .tag-tile__actions,
|
||||
.tag-tile__actions:focus-within {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
@media (hover: none) {
|
||||
.tag-tile__actions {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
.tag-tile__action-btn {
|
||||
padding: 0 2px;
|
||||
|
||||
&--confirm {
|
||||
color: var(--td-text-color-secondary);
|
||||
|
||||
&:hover,
|
||||
&:focus-visible {
|
||||
color: var(--td-text-color-primary);
|
||||
background: var(--td-bg-color-container);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.tag-load-more {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
padding-top: 8px;
|
||||
|
||||
:deep(.t-button) {
|
||||
font-size: var(--app-text-sm);
|
||||
color: var(--td-text-color-placeholder);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,88 @@
|
||||
<template>
|
||||
<span class="kb-type-avatar" :class="isFaq ? 'is-faq' : 'is-document'" aria-hidden="true">
|
||||
<svg v-if="isFaq" class="kb-type-icon kb-faq-icon" width="16" height="16" viewBox="0 0 24 24"
|
||||
fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M5 4h14a2 2 0 0 1 2 2v11a2 2 0 0 1-2 2H9l-5 3v-3a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2Z" />
|
||||
<g class="kb-faq-question">
|
||||
<path d="M9.5 9a2.5 2.5 0 0 1 5 .5c0 1.5-2.5 1.5-2.5 3" />
|
||||
<circle cx="12" cy="15.5" r="0.8" fill="currentColor" stroke="none" />
|
||||
</g>
|
||||
</svg>
|
||||
<svg v-else class="kb-type-icon kb-folder-icon" width="16" height="16" viewBox="0 0 24 24"
|
||||
fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M3 19V6a2 2 0 0 1 2-2h4l2 3h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2Z" />
|
||||
<g class="kb-folder-paper">
|
||||
<rect x="7" y="8" width="10" height="10" rx="1" />
|
||||
<path d="M10 11h4m-4 3h4" />
|
||||
</g>
|
||||
<path class="kb-folder-front" d="M3 9h18v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z" />
|
||||
</svg>
|
||||
</span>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
|
||||
const props = defineProps<{ type?: string }>()
|
||||
const isFaq = computed(() => props.type === 'faq')
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
.kb-type-icon {
|
||||
display: block;
|
||||
flex-shrink: 0;
|
||||
overflow: visible;
|
||||
transform: var(--kb-icon-transform, none);
|
||||
transition: transform var(--app-motion-slow) cubic-bezier(0.2, 0.8, 0.2, 1);
|
||||
}
|
||||
|
||||
.kb-folder-paper {
|
||||
fill: var(--td-bg-color-container);
|
||||
opacity: var(--kb-folder-paper-opacity, 0);
|
||||
transform: translateY(var(--kb-folder-paper-offset, 3px));
|
||||
transition: transform var(--app-motion-slow) cubic-bezier(0.2, 0.8, 0.2, 1), opacity var(--app-motion-fast) ease;
|
||||
}
|
||||
|
||||
.kb-faq-question {
|
||||
transform-box: fill-box;
|
||||
transform-origin: center;
|
||||
transform: var(--kb-faq-question-transform, none);
|
||||
transition: transform var(--app-motion-slow) cubic-bezier(0.34, 1.56, 0.64, 1);
|
||||
}
|
||||
|
||||
.kb-folder-front {
|
||||
fill: var(--td-bg-color-container);
|
||||
transform-box: fill-box;
|
||||
transform-origin: center bottom;
|
||||
transform: perspective(48px) rotateX(var(--kb-folder-open-angle, 0deg));
|
||||
transition: transform var(--app-motion-base) cubic-bezier(0.2, 0.8, 0.2, 1);
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.kb-type-icon, .kb-folder-front, .kb-folder-paper, .kb-faq-question {
|
||||
transform: none;
|
||||
transition: none;
|
||||
}
|
||||
.kb-folder-paper { opacity: 0; }
|
||||
}
|
||||
|
||||
.kb-type-avatar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex-shrink: 0;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
border-radius: var(--app-radius-md);
|
||||
|
||||
&.is-document {
|
||||
background: linear-gradient(135deg, color-mix(in srgb, var(--td-brand-color) 15%, transparent) 0%, color-mix(in srgb, var(--td-brand-color) 8%, transparent) 100%);
|
||||
color: var(--td-brand-color-active);
|
||||
}
|
||||
|
||||
&.is-faq {
|
||||
background: linear-gradient(135deg, color-mix(in srgb, var(--weknora-faq-color, #0052d9) 15%, transparent) 0%, color-mix(in srgb, var(--weknora-faq-color, #0052d9) 8%, transparent) 100%);
|
||||
color: var(--weknora-faq-color, #0052d9);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,288 @@
|
||||
<template>
|
||||
<div class="kb-upload-source-dropdown">
|
||||
<input
|
||||
ref="fileInputRef"
|
||||
type="file"
|
||||
class="hidden-file-input"
|
||||
multiple
|
||||
:accept="acceptFileTypes || undefined"
|
||||
@change="(e) => handleFilesChange(e, false)"
|
||||
/>
|
||||
<input
|
||||
ref="folderInputRef"
|
||||
type="file"
|
||||
class="hidden-file-input"
|
||||
webkitdirectory
|
||||
multiple
|
||||
@change="(e) => handleFilesChange(e, true)"
|
||||
/>
|
||||
|
||||
<t-tooltip :content="tooltipText" placement="top">
|
||||
<t-dropdown
|
||||
:options="dropdownOptions"
|
||||
trigger="click"
|
||||
:placement="placement"
|
||||
@click="handleActionSelect"
|
||||
>
|
||||
<t-button
|
||||
variant="text"
|
||||
theme="default"
|
||||
:class="['kb-upload-source-trigger', triggerClass]"
|
||||
:data-guide="dataGuide || undefined"
|
||||
:aria-label="tooltipText"
|
||||
size="small"
|
||||
>
|
||||
<template #icon>
|
||||
<component v-if="triggerIconComponent" :is="triggerIconComponent" size="18px" :stroke-width="1.7" class="kb-source-icon" />
|
||||
<t-icon v-else :name="triggerIcon" size="18px" />
|
||||
</template>
|
||||
<span v-if="triggerLabel">{{ triggerLabel }}</span>
|
||||
</t-button>
|
||||
</t-dropdown>
|
||||
</t-tooltip>
|
||||
|
||||
<t-dialog
|
||||
v-model:visible="urlDialogVisible"
|
||||
:header="t('knowledgeBase.importURLTitle')"
|
||||
:confirm-btn="{ content: t('common.confirm'), theme: 'primary' }"
|
||||
:cancel-btn="{ content: t('common.cancel') }"
|
||||
width="500px"
|
||||
@confirm="handleUrlDialogConfirm"
|
||||
@cancel="handleUrlDialogCancel"
|
||||
>
|
||||
<div class="url-import-form">
|
||||
<div class="url-input-label">{{ t('knowledgeBase.urlLabel') }}</div>
|
||||
<t-input
|
||||
v-model="urlInputValue"
|
||||
:placeholder="t('knowledgeBase.urlPlaceholder')"
|
||||
clearable
|
||||
autofocus
|
||||
@enter="handleUrlDialogConfirm"
|
||||
/>
|
||||
<div class="url-input-tip">{{ t('knowledgeBase.urlTip') }}</div>
|
||||
</div>
|
||||
</t-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, h } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { MessagePlugin } from 'tdesign-vue-next'
|
||||
import { AddIcon, FileAddIcon, UploadIcon, FolderAddIcon, LinkIcon, EditIcon, BookIcon } from 'tdesign-icons-vue-next'
|
||||
import { filterUploadFiles } from '../utils/uploadSources'
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
acceptFileTypes?: string
|
||||
supportedFileTypes?: string[]
|
||||
includeManual?: boolean
|
||||
triggerIcon?: string
|
||||
triggerLabel?: string
|
||||
triggerClass?: string
|
||||
dataGuide?: string
|
||||
tooltip?: string
|
||||
placement?: 'top' | 'bottom' | 'bottom-right' | 'bottom-left'
|
||||
/** 业务扩展菜单项(追加在下拉末位,选择后 emit('extra', value)) */
|
||||
extraOptions?: { value: string; label: string }[]
|
||||
}>(), {
|
||||
acceptFileTypes: '',
|
||||
supportedFileTypes: () => [],
|
||||
includeManual: false,
|
||||
triggerIcon: 'file-add',
|
||||
triggerClass: '',
|
||||
dataGuide: '',
|
||||
tooltip: '',
|
||||
placement: 'bottom-right',
|
||||
extraOptions: () => [],
|
||||
})
|
||||
|
||||
const emit = defineEmits<{
|
||||
files: [files: File[]]
|
||||
url: [url: string]
|
||||
manual: []
|
||||
extra: [value: string]
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const fileInputRef = ref<HTMLInputElement | null>(null)
|
||||
const folderInputRef = ref<HTMLInputElement | null>(null)
|
||||
const urlDialogVisible = ref(false)
|
||||
const urlInputValue = ref('')
|
||||
|
||||
const tooltipText = computed(() => props.tooltip || t('knowledgeBase.addDocument'))
|
||||
|
||||
const triggerIconComponent = computed(() => ({
|
||||
add: AddIcon,
|
||||
'file-add': FileAddIcon,
|
||||
upload: UploadIcon,
|
||||
}[props.triggerIcon]));
|
||||
|
||||
const sourceIconProps = { size: '18px', strokeWidth: 1.7, class: 'kb-source-icon' };
|
||||
|
||||
const dropdownOptions = computed(() => {
|
||||
const options = [
|
||||
{
|
||||
content: t('upload.uploadDocument'),
|
||||
value: 'upload',
|
||||
prefixIcon: () => h(FileAddIcon, sourceIconProps),
|
||||
},
|
||||
{
|
||||
content: t('upload.uploadFolder'),
|
||||
value: 'uploadFolder',
|
||||
prefixIcon: () => h(FolderAddIcon, sourceIconProps),
|
||||
},
|
||||
{
|
||||
content: t('knowledgeBase.importURL'),
|
||||
value: 'importURL',
|
||||
prefixIcon: () => h(LinkIcon, sourceIconProps),
|
||||
},
|
||||
]
|
||||
if (props.includeManual) {
|
||||
options.push({
|
||||
content: t('upload.onlineEdit'),
|
||||
value: 'manualCreate',
|
||||
prefixIcon: () => h(EditIcon, sourceIconProps),
|
||||
})
|
||||
}
|
||||
// 业务扩展项(如培训题库 KB 的「Excel 导入题库」),点击后由父级处理
|
||||
for (const extra of props.extraOptions) {
|
||||
options.push({
|
||||
content: extra.label,
|
||||
value: extra.value,
|
||||
prefixIcon: () => h(BookIcon, sourceIconProps),
|
||||
})
|
||||
}
|
||||
return options
|
||||
})
|
||||
|
||||
const handleActionSelect = (data: { value: string }) => {
|
||||
switch (data.value) {
|
||||
case 'upload':
|
||||
fileInputRef.value?.click()
|
||||
break
|
||||
case 'uploadFolder':
|
||||
folderInputRef.value?.click()
|
||||
break
|
||||
case 'importURL':
|
||||
urlInputValue.value = ''
|
||||
urlDialogVisible.value = true
|
||||
break
|
||||
case 'manualCreate':
|
||||
emit('manual')
|
||||
break
|
||||
default:
|
||||
// 扩展项直接上抛
|
||||
emit('extra', data.value)
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
const notifyFilterResult = (result: ReturnType<typeof filterUploadFiles>, emptyAllSkippedKey: string) => {
|
||||
const { validFiles, skippedCount, videoFilteredCount } = result
|
||||
if (validFiles.length === 0) {
|
||||
if (skippedCount > 0) {
|
||||
MessagePlugin.warning(t(emptyAllSkippedKey))
|
||||
}
|
||||
return false
|
||||
}
|
||||
if (videoFilteredCount > 0) {
|
||||
MessagePlugin.warning(t('knowledgeBase.videosFilteredNoVLM', { count: videoFilteredCount }))
|
||||
}
|
||||
if (skippedCount > 0) {
|
||||
MessagePlugin.warning(t('knowledgeBase.filesSkippedNoEngine', { count: skippedCount }))
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
const handleFilesChange = (event: Event, fromFolder: boolean) => {
|
||||
const input = event.target as HTMLInputElement
|
||||
const files = input.files
|
||||
if (!files || files.length === 0) return
|
||||
|
||||
const result = filterUploadFiles(files, {
|
||||
supportedFileTypes: props.supportedFileTypes,
|
||||
fromFolder,
|
||||
multiFile: files.length > 1,
|
||||
})
|
||||
|
||||
if (!notifyFilterResult(result, 'knowledgeBase.allFilesSkippedNoEngine')) {
|
||||
input.value = ''
|
||||
return
|
||||
}
|
||||
|
||||
emit('files', result.validFiles)
|
||||
input.value = ''
|
||||
}
|
||||
|
||||
const handleUrlDialogConfirm = () => {
|
||||
const url = urlInputValue.value.trim()
|
||||
if (!url) {
|
||||
MessagePlugin.warning(t('knowledgeBase.urlRequired'))
|
||||
return
|
||||
}
|
||||
try {
|
||||
new URL(url)
|
||||
} catch {
|
||||
MessagePlugin.warning(t('knowledgeBase.invalidURL'))
|
||||
return
|
||||
}
|
||||
urlDialogVisible.value = false
|
||||
urlInputValue.value = ''
|
||||
emit('url', url)
|
||||
}
|
||||
|
||||
const handleUrlDialogCancel = () => {
|
||||
urlDialogVisible.value = false
|
||||
urlInputValue.value = ''
|
||||
}
|
||||
|
||||
const openUrlDialog = () => {
|
||||
urlInputValue.value = ''
|
||||
urlDialogVisible.value = true
|
||||
}
|
||||
|
||||
defineExpose({ openUrlDialog })
|
||||
</script>
|
||||
|
||||
<style lang="less" scoped>
|
||||
.hidden-file-input {
|
||||
position: absolute;
|
||||
width: 0;
|
||||
height: 0;
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.kb-upload-source-trigger {
|
||||
color: var(--td-text-color-secondary);
|
||||
|
||||
&:hover {
|
||||
color: var(--td-brand-color);
|
||||
}
|
||||
}
|
||||
|
||||
.url-import-form {
|
||||
.url-input-label {
|
||||
margin-bottom: 8px;
|
||||
font-size: var(--app-text-base);
|
||||
font-weight: 500;
|
||||
color: var(--td-text-color-primary);
|
||||
}
|
||||
|
||||
.url-input-tip {
|
||||
margin-top: 8px;
|
||||
font-size: var(--app-text-sm);
|
||||
line-height: 1.5;
|
||||
color: var(--td-text-color-placeholder);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
<style lang="less">
|
||||
// Use consistent rounded strokes for this small family of document-source actions.
|
||||
.kb-source-icon path {
|
||||
stroke-linecap: round;
|
||||
stroke-linejoin: round;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,43 @@
|
||||
<template>
|
||||
<t-tooltip :content="t('knowledgeList.features.wiki')" placement="top">
|
||||
<span class="kb-wiki-badge" role="img" :aria-label="t('knowledgeList.features.wiki')">
|
||||
<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
|
||||
<path d="M12 7v14" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" />
|
||||
<path d="M16 12h2" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" />
|
||||
<path d="M16 8h2" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" />
|
||||
<path
|
||||
d="M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z"
|
||||
stroke="currentColor"
|
||||
stroke-width="1.75"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
/>
|
||||
<path d="M6 12h2" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" />
|
||||
<path d="M6 8h2" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" />
|
||||
</svg>
|
||||
</span>
|
||||
</t-tooltip>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
// Icon: Lucide "book-open-text" (ISC) — https://lucide.dev/icons/book-open-text
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
const { t } = useI18n()
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
.kb-wiki-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex-shrink: 0;
|
||||
color: var(--td-text-color-secondary);
|
||||
|
||||
svg {
|
||||
width: 15px;
|
||||
height: 15px;
|
||||
display: block;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,189 @@
|
||||
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 { compileScript, parse } from '@vue/compiler-sfc'
|
||||
import * as vue from 'vue'
|
||||
|
||||
const source = readFileSync(new URL('./KnowledgeTagFilter.vue', import.meta.url), 'utf8')
|
||||
const { descriptor } = parse(source)
|
||||
const script = compileScript(descriptor, { id: 'tag-filter-test', inlineTemplate: true })
|
||||
const compiled = ts.transpileModule(script.content, {
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 },
|
||||
}).outputText
|
||||
const translate = (key: string, values?: { count: number }) => values ? `${key}:${values.count}` : key
|
||||
const exports: { default?: vue.Component } = {}
|
||||
runInNewContext(compiled, {
|
||||
exports,
|
||||
require(name: string) {
|
||||
if (name === 'vue') return vue
|
||||
if (name === 'vue-i18n') return { useI18n: () => ({ t: translate }) }
|
||||
throw new Error(`Unexpected import: ${name}`)
|
||||
},
|
||||
})
|
||||
|
||||
type Host = { type: string; props: Record<string, any>; children: Host[]; text: string; parent?: Host }
|
||||
const node = (type: string): Host => ({ type, props: {}, children: [], text: '' })
|
||||
const renderer = vue.createRenderer<Host, Host>({
|
||||
createElement: node,
|
||||
createText: text => ({ ...node('#text'), text }),
|
||||
createComment: text => ({ ...node('#comment'), text }),
|
||||
patchProp: (el, key, _old, value) => { el.props[key] = value },
|
||||
setText: (el, text) => { el.text = text },
|
||||
setElementText: (el, text) => { el.children = []; el.text = text },
|
||||
parentNode: el => el.parent || null,
|
||||
nextSibling: el => el.parent?.children[el.parent.children.indexOf(el) + 1] || null,
|
||||
insert(el, parent, anchor) {
|
||||
if (el.parent) el.parent.children.splice(el.parent.children.indexOf(el), 1)
|
||||
el.parent = parent
|
||||
const index = anchor ? parent.children.indexOf(anchor) : -1
|
||||
parent.children.splice(index < 0 ? parent.children.length : index, 0, el)
|
||||
},
|
||||
remove(el) {
|
||||
el.parent?.children.splice(el.parent.children.indexOf(el), 1)
|
||||
el.parent = undefined
|
||||
},
|
||||
})
|
||||
const textOf = (el: Host): string => el.type === '#comment' ? '' : el.text + el.children.map(textOf).join('')
|
||||
const all = (el: Host, predicate: (node: Host) => boolean): Host[] => [
|
||||
...(predicate(el) ? [el] : []), ...el.children.flatMap(child => all(child, predicate)),
|
||||
]
|
||||
const hasClass = (el: Host, name: string) => String(el.props.class || '').split(' ').includes(name)
|
||||
|
||||
function fixture(variant: 'documents' | 'faq') {
|
||||
const state = vue.reactive({
|
||||
variant, tags: [
|
||||
{ id: 'a', name: 'Alpha', knowledge_count: 12, chunk_count: 31 },
|
||||
{ id: 'b', name: 'Beta', knowledge_count: 0, chunk_count: 2 },
|
||||
],
|
||||
selectedIds: [] as string[], total: 7, loading: false, loadingMore: false, hasMore: false,
|
||||
canManage: true, search: '', cleared: false,
|
||||
})
|
||||
const events = { changes: [] as string[][], loadMore: 0, manage: 0 }
|
||||
const root = node('root')
|
||||
const app = renderer.createApp({ setup: () => () => vue.h(exports.default!, {
|
||||
...state,
|
||||
'onUpdate:search': (value: string) => { state.search = value },
|
||||
'onUpdate:cleared': (value: boolean) => { state.cleared = value },
|
||||
onChange: (ids: string[]) => { events.changes.push([...ids]); state.selectedIds = ids },
|
||||
onLoadMore: () => { events.loadMore++ }, onManage: () => { events.manage++ },
|
||||
}) })
|
||||
app.config.globalProperties.$t = translate as typeof app.config.globalProperties.$t
|
||||
app.component('t-popup', vue.defineComponent({
|
||||
props: ['visible'], emits: ['update:visible'],
|
||||
setup: (props, { emit, slots }) => () => vue.h('popup', {
|
||||
visible: props.visible, onOpen: () => emit('update:visible', true),
|
||||
}, [slots.default?.(), props.visible ? vue.h('overlay', {}, slots.content?.()) : null]),
|
||||
}))
|
||||
app.component('t-input', vue.defineComponent({
|
||||
props: ['modelValue', 'modelModifiers'], emits: ['update:modelValue'],
|
||||
setup: (props, { emit }) => () => vue.h('input', {
|
||||
value: props.modelValue, onInput: (value: string) => emit('update:modelValue', value),
|
||||
}),
|
||||
}))
|
||||
for (const [name, type] of [['t-button', 'button'], ['t-icon', 'icon'], ['t-skeleton', 'skeleton']]) {
|
||||
app.component(name!, vue.defineComponent({ setup: (_props, { slots }) => () => vue.h(type!, {}, slots.default?.()) }))
|
||||
}
|
||||
app.mount(root)
|
||||
const elements = (name: string) => all(root, el => hasClass(el, name))
|
||||
const one = (name: string) => {
|
||||
const el = elements(name)[0]; assert.ok(el, `missing .${name}`); return el
|
||||
}
|
||||
const fire = async (el: Host, event = 'onClick', value?: unknown) => {
|
||||
let stopped = false
|
||||
el.props[event](value ?? { stopPropagation() { stopped = true }, preventDefault() {} })
|
||||
await vue.nextTick()
|
||||
return stopped
|
||||
}
|
||||
return {
|
||||
state, events, root, elements, one, fire,
|
||||
open: () => fire(all(root, el => el.type === 'popup')[0]!, 'onOpen'),
|
||||
close: () => app.unmount(),
|
||||
}
|
||||
}
|
||||
|
||||
for (const variant of ['documents', 'faq'] as const) {
|
||||
test(`${variant}: renders counts, labels, selection and tooltips`, async t => {
|
||||
const f = fixture(variant); t.after(f.close)
|
||||
assert.equal(textOf(f.one('doc-tag-filter-trigger__label')), 'knowledgeBase.allTags')
|
||||
await f.open()
|
||||
assert.equal(textOf(f.one('tag-filter-panel__count')), '(7)')
|
||||
assert.equal(textOf(f.elements('tag-filter-chip__count')[0]!), variant === 'documents' ? '12' : '31')
|
||||
assert.equal(f.elements('tag-filter-chip')[0]!.props.title, `Alpha (${variant === 'documents' ? 12 : 31})`)
|
||||
assert.equal(hasClass(f.one('tag-filter-panel'), 'tag-filter-panel--documents'), variant === 'documents')
|
||||
await f.fire(f.elements('tag-filter-chip')[0]!)
|
||||
assert.deepEqual(f.events.changes, [['a']])
|
||||
assert.equal(textOf(f.one('doc-tag-filter-trigger__label')), 'Alpha')
|
||||
assert.equal(f.one('doc-tag-filter-trigger').props.title, 'Alpha')
|
||||
await f.fire(f.elements('tag-filter-chip')[1]!)
|
||||
assert.equal(textOf(f.one('doc-tag-filter-trigger__label')), 'knowledgeBase.tagFilterMulti:2')
|
||||
assert.equal(f.one('doc-tag-filter-trigger').props.title, 'Alpha、Beta')
|
||||
await f.fire(f.elements('tag-filter-chip')[0]!)
|
||||
assert.deepEqual(f.events.changes.at(-1), ['b'])
|
||||
assert.equal(hasClass(f.elements('tag-filter-chip')[0]!, 'active'), false)
|
||||
})
|
||||
|
||||
test(`${variant}: clearing stops propagation and parent resets restore the placeholder`, async t => {
|
||||
const f = fixture(variant); t.after(f.close)
|
||||
f.state.selectedIds = ['a']; await vue.nextTick()
|
||||
assert.equal(f.elements('t-input__clear').length, 0)
|
||||
await f.fire(f.one('doc-tag-filter-trigger'), 'onMouseenter')
|
||||
assert.equal(await f.fire(f.one('t-input__clear')), true)
|
||||
assert.equal(f.state.cleared, true)
|
||||
assert.deepEqual([...f.state.selectedIds], [])
|
||||
assert.equal(textOf(f.one('doc-tag-filter-trigger__label')), 'knowledgeBase.tagFilterPlaceholder')
|
||||
assert.equal(hasClass(f.one('doc-tag-filter-trigger'), 'is-placeholder'), true)
|
||||
await f.open(); await f.fire(f.elements('tag-filter-chip')[0]!)
|
||||
assert.equal(f.state.cleared, false)
|
||||
await f.fire(f.elements('tag-filter-chip')[0]!)
|
||||
assert.equal(textOf(f.one('doc-tag-filter-trigger__label')), 'knowledgeBase.allTags')
|
||||
f.state.cleared = true; await vue.nextTick()
|
||||
f.state.cleared = false; await vue.nextTick()
|
||||
assert.equal(hasClass(f.one('doc-tag-filter-trigger'), 'is-placeholder'), false)
|
||||
})
|
||||
|
||||
test(`${variant}: search, skeletons, empty results and paging stay controlled by the parent`, async t => {
|
||||
const f = fixture(variant); t.after(f.close)
|
||||
f.state.tags = []; f.state.loading = true; f.state.total = 0
|
||||
await f.open()
|
||||
assert.equal(all(f.root, el => el.type === 'skeleton').length, 8)
|
||||
assert.equal(f.elements('tag-empty-state').length, 0)
|
||||
await f.fire(all(f.root, el => el.type === 'input')[0]!, 'onInput', ' title ')
|
||||
assert.equal(f.state.search, 'title')
|
||||
f.state.loading = false; await vue.nextTick()
|
||||
assert.equal(textOf(f.one('tag-empty-state')), 'knowledgeBase.tagEmptyResult')
|
||||
f.state.tags = [{ id: 'a', name: 'Result', knowledge_count: 0, chunk_count: 0 }]
|
||||
f.state.hasMore = true; f.state.loadingMore = true; await vue.nextTick()
|
||||
assert.equal(textOf(f.one('tag-filter-panel__count')), '(1)')
|
||||
const button = all(f.one('tag-load-more'), el => el.type === 'button')[0]!
|
||||
assert.equal(button.props.loading, true)
|
||||
assert.equal(await f.fire(button), true)
|
||||
assert.equal(f.events.loadMore, 1)
|
||||
assert.equal(f.state.search, 'title')
|
||||
})
|
||||
|
||||
test(`${variant}: viewers can filter and managers can open management`, async t => {
|
||||
const f = fixture(variant); t.after(f.close)
|
||||
f.state.canManage = false; await f.open()
|
||||
assert.equal(f.elements('tag-manage-link').length, 0)
|
||||
await f.fire(f.elements('tag-filter-chip')[0]!)
|
||||
assert.deepEqual([...f.state.selectedIds], ['a'])
|
||||
f.state.canManage = true; await vue.nextTick()
|
||||
await f.fire(f.one('tag-manage-link'))
|
||||
assert.equal(f.events.manage, 1)
|
||||
assert.equal(all(f.root, el => el.type === 'overlay').length, 0)
|
||||
})
|
||||
}
|
||||
|
||||
test('external selection and tag pages update labels without dropping unloaded selections', async t => {
|
||||
const f = fixture('documents'); t.after(f.close)
|
||||
f.state.selectedIds = ['unloaded']; await vue.nextTick()
|
||||
assert.equal(textOf(f.one('doc-tag-filter-trigger__label')), 'knowledgeBase.allTags')
|
||||
assert.equal(f.one('doc-tag-filter-trigger').props.title, 'knowledgeBase.tagFilterTitle')
|
||||
await f.open(); await f.fire(f.elements('tag-filter-chip')[0]!)
|
||||
assert.deepEqual([...f.state.selectedIds], ['unloaded', 'a'])
|
||||
assert.equal(f.one('doc-tag-filter-trigger').props.title, 'Alpha')
|
||||
f.state.tags[0]!.name = 'Renamed'; await vue.nextTick()
|
||||
assert.equal(f.one('doc-tag-filter-trigger').props.title, 'Renamed')
|
||||
})
|
||||
@@ -0,0 +1,463 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
type FilterTag = { id: string; name: string; knowledge_count?: number; chunk_count?: number }
|
||||
const props = defineProps<{
|
||||
tags: FilterTag[]
|
||||
selectedIds: string[]
|
||||
total: number
|
||||
loading: boolean
|
||||
loadingMore: boolean
|
||||
hasMore: boolean
|
||||
canManage: boolean
|
||||
variant: 'documents' | 'faq'
|
||||
}>()
|
||||
const search = defineModel<string>('search', { required: true })
|
||||
const cleared = defineModel<boolean>('cleared', { required: true })
|
||||
const emit = defineEmits<{
|
||||
change: [ids: string[]]
|
||||
'load-more': []
|
||||
manage: []
|
||||
}>()
|
||||
const { t } = useI18n()
|
||||
const visible = ref(false)
|
||||
const hovered = ref(false)
|
||||
const tagMap = computed(() => new Map(props.tags.map(tag => [tag.id, tag])))
|
||||
const isPlaceholder = computed(() => props.selectedIds.length === 0 && cleared.value)
|
||||
const label = computed(() => {
|
||||
if (!props.selectedIds.length) return t(cleared.value ? 'knowledgeBase.tagFilterPlaceholder' : 'knowledgeBase.allTags')
|
||||
if (props.selectedIds.length === 1) return tagMap.value.get(props.selectedIds[0]!)?.name || t('knowledgeBase.allTags')
|
||||
return t('knowledgeBase.tagFilterMulti', { count: props.selectedIds.length })
|
||||
})
|
||||
const title = computed(() => {
|
||||
const names = props.selectedIds.map(id => tagMap.value.get(id)?.name).filter(Boolean)
|
||||
return names.length ? names.join('、') : t('knowledgeBase.tagFilterTitle')
|
||||
})
|
||||
const countOf = (tag: FilterTag) => (props.variant === 'documents' ? tag.knowledge_count : tag.chunk_count) || 0
|
||||
const toggle = (id: string) => {
|
||||
const next = new Set(props.selectedIds)
|
||||
if (next.has(id)) next.delete(id)
|
||||
else next.add(id)
|
||||
if (next.size) cleared.value = false
|
||||
emit('change', [...next])
|
||||
}
|
||||
const clear = () => {
|
||||
cleared.value = true
|
||||
emit('change', [])
|
||||
}
|
||||
const manage = () => {
|
||||
visible.value = false
|
||||
emit('manage')
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<t-popup v-model:visible="visible" trigger="click" placement="bottom-left"
|
||||
overlay-class-name="tag-filter-popup" :overlay-inner-style="{ padding: 0 }">
|
||||
<template #content>
|
||||
<div class="tag-filter-panel" :class="{ 'tag-filter-panel--documents': variant === 'documents' }" @click.stop>
|
||||
<div class="tag-filter-panel__header">
|
||||
<div class="tag-filter-panel__title">
|
||||
<span>{{ $t('knowledgeBase.tagFilterTitle') }}</span>
|
||||
<span class="tag-filter-panel__count">({{ total || tags.length }})</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="tag-search-bar">
|
||||
<t-input v-model.trim="search" size="small"
|
||||
:placeholder="$t('knowledgeBase.tagSearchPlaceholder')" clearable>
|
||||
<template #prefix-icon>
|
||||
<t-icon name="search" size="14px" />
|
||||
</template>
|
||||
</t-input>
|
||||
</div>
|
||||
<div class="tag-filter-panel__body">
|
||||
<template v-if="loading && !tags.length">
|
||||
<div class="tag-filter-chips">
|
||||
<div v-for="n in 8" :key="'skel-tag-' + n" class="tag-filter-chip-skeleton">
|
||||
<t-skeleton animation="gradient"
|
||||
:row-col="[{ width: '56px', height: '24px', type: 'rect' }]" />
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
<template v-else>
|
||||
<div class="tag-filter-chips">
|
||||
<button
|
||||
v-for="tag in tags"
|
||||
:key="tag.id"
|
||||
type="button"
|
||||
class="tag-filter-chip"
|
||||
:class="{ active: selectedIds.includes(tag.id) }"
|
||||
:title="`${tag.name} (${countOf(tag)})`"
|
||||
@click="toggle(tag.id)"
|
||||
>
|
||||
<span class="tag-filter-chip__label">{{ tag.name }}</span>
|
||||
<span class="tag-filter-chip__count">{{ countOf(tag) }}</span>
|
||||
</button>
|
||||
</div>
|
||||
<div v-if="!tags.length" class="tag-empty-state">
|
||||
{{ $t('knowledgeBase.tagEmptyResult') }}
|
||||
</div>
|
||||
<div v-if="hasMore" class="tag-load-more">
|
||||
<t-button variant="text" size="small" :loading="loadingMore"
|
||||
@click.stop="emit('load-more')">
|
||||
{{ $t('tenant.loadMore') }}
|
||||
</t-button>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
<div v-if="canManage" class="tag-filter-panel__footer">
|
||||
<t-button variant="text" size="small" class="tag-manage-link" @click="manage">
|
||||
{{ $t('knowledgeBase.tagManageLink') }}
|
||||
</t-button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
<div class="doc-filter-field" :class="{ 'doc-filter-field--documents': variant === 'documents' }">
|
||||
<button type="button" class="doc-tag-filter-trigger doc-filter-field__control"
|
||||
:class="{ open: visible, 'is-placeholder': isPlaceholder }"
|
||||
:aria-label="$t('knowledgeBase.tagFilterTitle')"
|
||||
:title="title"
|
||||
@mouseenter="hovered = true"
|
||||
@mouseleave="hovered = false">
|
||||
<span class="doc-tag-filter-trigger__prefix" aria-hidden="true">
|
||||
<t-icon name="discount" size="16px" />
|
||||
</span>
|
||||
<span class="doc-tag-filter-trigger__label">{{ label }}</span>
|
||||
<span class="doc-tag-filter-trigger__suffix">
|
||||
<span
|
||||
v-if="selectedIds.length > 0 && hovered"
|
||||
class="t-input__suffix t-input__suffix-icon t-input__clear"
|
||||
:aria-label="$t('common.clear')"
|
||||
@click.stop="clear"
|
||||
@mousedown.stop
|
||||
>
|
||||
<t-icon name="close-circle-filled" class="t-input__suffix-clear" />
|
||||
</span>
|
||||
<t-icon
|
||||
v-else
|
||||
name="chevron-down"
|
||||
size="16px"
|
||||
class="doc-tag-filter-trigger__caret"
|
||||
:class="{ open: visible }"
|
||||
/>
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
</t-popup>
|
||||
</template>
|
||||
|
||||
<style lang="less">
|
||||
.tag-filter-popup {
|
||||
z-index: 5500 !important;
|
||||
}
|
||||
|
||||
.tag-filter-popup .t-popup__content {
|
||||
padding: 0 !important;
|
||||
border-radius: var(--app-radius-md) !important;
|
||||
background: var(--td-bg-color-container) !important;
|
||||
border: 0.5px solid var(--td-component-stroke) !important;
|
||||
box-shadow:
|
||||
0 0 0 0.5px rgba(0, 0, 0, 0.03),
|
||||
0 2px 4px rgba(0, 0, 0, 0.04),
|
||||
0 8px 24px rgba(0, 0, 0, 0.1) !important;
|
||||
}
|
||||
</style>
|
||||
<style scoped lang="less">
|
||||
.doc-filter-field {
|
||||
width: 140px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.doc-tag-filter-trigger {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
box-sizing: border-box;
|
||||
width: 100%;
|
||||
height: 32px;
|
||||
padding: 0 8px;
|
||||
border: 1px solid transparent;
|
||||
border-radius: var(--td-radius-default);
|
||||
background: var(--td-bg-color-secondarycontainer);
|
||||
color: var(--td-text-color-primary);
|
||||
font-family: var(--app-font-family);
|
||||
font-size: var(--app-text-base);
|
||||
line-height: 1;
|
||||
cursor: pointer;
|
||||
transition: background var(--app-motion-base) ease, border-color var(--app-motion-base) ease;
|
||||
|
||||
&:hover,
|
||||
&.open {
|
||||
background: var(--td-bg-color-secondarycontainer);
|
||||
border-color: transparent;
|
||||
}
|
||||
|
||||
&.is-placeholder {
|
||||
color: var(--td-text-color-placeholder);
|
||||
}
|
||||
|
||||
&__prefix {
|
||||
flex-shrink: 0;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
margin-right: var(--td-comp-margin-s);
|
||||
color: var(--td-text-color-placeholder);
|
||||
}
|
||||
|
||||
&__label {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
&__suffix {
|
||||
flex-shrink: 0;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
margin-left: var(--td-comp-margin-s);
|
||||
}
|
||||
|
||||
&__caret {
|
||||
flex-shrink: 0;
|
||||
color: var(--td-text-color-placeholder);
|
||||
transition: transform var(--app-motion-base) ease, color var(--app-motion-base) ease;
|
||||
|
||||
&.open {
|
||||
color: var(--td-brand-color);
|
||||
transform: rotate(180deg);
|
||||
}
|
||||
}
|
||||
}
|
||||
.doc-filter-field--documents .doc-tag-filter-trigger__suffix {
|
||||
:deep(.t-input__suffix) {
|
||||
margin-left: 0;
|
||||
}
|
||||
:deep(.t-input__suffix-clear) {
|
||||
font-size: var(--app-text-xl);
|
||||
}
|
||||
}
|
||||
|
||||
.tag-filter-panel {
|
||||
width: 320px;
|
||||
max-width: min(320px, calc(100vw - 32px));
|
||||
max-height: min(70vh, 480px);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding: 12px 14px;
|
||||
box-sizing: border-box;
|
||||
font-size: var(--app-text-sm);
|
||||
color: var(--td-text-color-primary);
|
||||
}
|
||||
|
||||
.tag-filter-panel__header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.tag-filter-panel__title {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 6px;
|
||||
font-size: var(--app-text-base);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.tag-filter-panel__count {
|
||||
font-size: var(--app-text-sm);
|
||||
color: var(--td-text-color-placeholder);
|
||||
font-weight: 400;
|
||||
}
|
||||
|
||||
.tag-filter-panel .tag-search-bar {
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.tag-filter-panel__body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.tag-filter-chips {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.tag-filter-chip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
height: 24px;
|
||||
padding: 0 8px;
|
||||
border: 1px solid var(--td-component-stroke);
|
||||
border-radius: var(--app-radius-xs);
|
||||
background: transparent;
|
||||
color: var(--td-text-color-secondary);
|
||||
font-size: var(--app-text-xs);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.tag-filter-chip.active {
|
||||
border-color: color-mix(in srgb, var(--td-brand-color) 35%, var(--td-component-stroke));
|
||||
color: var(--td-brand-color);
|
||||
background-color: color-mix(in srgb, var(--td-brand-color) 6%, transparent);
|
||||
}
|
||||
|
||||
.tag-filter-chip__label {
|
||||
max-width: 120px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.tag-filter-chip__count {
|
||||
font-size: var(--app-text-2xs);
|
||||
color: var(--td-text-color-placeholder);
|
||||
}
|
||||
|
||||
.tag-filter-panel__footer {
|
||||
margin-top: 10px;
|
||||
padding-top: 10px;
|
||||
border-top: 1px solid var(--td-component-stroke);
|
||||
}
|
||||
|
||||
.tag-empty-state {
|
||||
text-align: center;
|
||||
padding: 10px 6px;
|
||||
color: var(--td-text-color-placeholder);
|
||||
font-size: var(--app-text-xs);
|
||||
}
|
||||
|
||||
.tag-load-more {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
padding-top: 2px;
|
||||
}
|
||||
.tag-filter-panel--documents .tag-filter-panel__header {
|
||||
padding: 0;
|
||||
color: var(--td-text-color-primary);
|
||||
}
|
||||
.tag-filter-panel--documents .tag-filter-panel__title {
|
||||
letter-spacing: 0.5px;
|
||||
}
|
||||
.tag-filter-panel--documents .tag-search-bar {
|
||||
padding: 0;
|
||||
}
|
||||
.tag-filter-panel--documents .tag-search-bar :deep(.t-input) {
|
||||
font-size: var(--app-text-md);
|
||||
background-color: var(--td-bg-color-secondarycontainer);
|
||||
border-color: transparent;
|
||||
border-radius: var(--app-radius-sm);
|
||||
box-shadow: none !important;
|
||||
}
|
||||
.tag-filter-panel--documents .tag-search-bar :deep(.t-input):hover,
|
||||
.tag-filter-panel--documents .tag-search-bar :deep(.t-input):focus,
|
||||
.tag-filter-panel--documents .tag-search-bar :deep(.t-input).t-is-focused {
|
||||
border-color: var(--td-component-border);
|
||||
background-color: var(--td-bg-color-container);
|
||||
box-shadow: none !important;
|
||||
}
|
||||
.tag-filter-panel--documents .tag-search-bar :deep(.t-input__inner) {
|
||||
font-size: var(--app-text-md);
|
||||
}
|
||||
.tag-filter-panel--documents .tag-search-bar :deep(.t-input__prefix-icon) {
|
||||
margin-right: 0;
|
||||
}
|
||||
.tag-filter-panel--documents .tag-filter-panel__body {
|
||||
overflow-x: hidden;
|
||||
scrollbar-width: thin;
|
||||
}
|
||||
.tag-filter-panel--documents .tag-filter-panel__body::-webkit-scrollbar {
|
||||
width: 4px;
|
||||
}
|
||||
.tag-filter-panel--documents .tag-filter-panel__body::-webkit-scrollbar-thumb {
|
||||
border-radius: 2px;
|
||||
background: var(--td-scrollbar-color);
|
||||
}
|
||||
.tag-filter-panel--documents .tag-filter-chips {
|
||||
align-items: flex-start;
|
||||
}
|
||||
.tag-filter-panel--documents .tag-filter-chip-skeleton {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.tag-filter-panel--documents .tag-filter-chip {
|
||||
box-sizing: border-box;
|
||||
max-width: 100%;
|
||||
font-family: var(--app-font-family);
|
||||
font-weight: 400;
|
||||
line-height: 24px;
|
||||
outline: none;
|
||||
transition: background var(--app-motion-fast) ease, color var(--app-motion-fast) ease, border-color var(--app-motion-fast) ease;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
.tag-filter-panel--documents .tag-filter-chip:hover:not(.active) {
|
||||
border-color: var(--td-component-border);
|
||||
background: var(--td-bg-color-secondarycontainer);
|
||||
color: var(--td-text-color-primary);
|
||||
}
|
||||
.tag-filter-panel--documents .tag-filter-chip:focus-visible {
|
||||
box-shadow: 0 0 0 2px color-mix(in srgb, var(--td-component-stroke) 60%, transparent);
|
||||
}
|
||||
.tag-filter-panel--documents .tag-filter-chip.active {
|
||||
font-weight: 500;
|
||||
}
|
||||
.tag-filter-panel--documents .tag-filter-chip.active .tag-filter-chip__count {
|
||||
color: color-mix(in srgb, var(--td-brand-color) 72%, var(--td-text-color-secondary));
|
||||
}
|
||||
.tag-filter-panel--documents .tag-filter-chip.active:hover {
|
||||
background-color: color-mix(in srgb, var(--td-brand-color) 10%, transparent);
|
||||
}
|
||||
.tag-filter-panel--documents .tag-filter-chip__label {
|
||||
min-width: 0;
|
||||
}
|
||||
.tag-filter-panel--documents .tag-filter-chip__count {
|
||||
flex-shrink: 0;
|
||||
font-weight: 400;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.tag-filter-panel--documents .tag-filter-chip__count::before {
|
||||
content: '·';
|
||||
margin-right: 2px;
|
||||
opacity: 0.65;
|
||||
}
|
||||
.tag-filter-panel--documents .tag-filter-panel__footer {
|
||||
display: flex;
|
||||
justify-content: flex-start;
|
||||
}
|
||||
.tag-filter-panel--documents .tag-filter-panel__footer :deep(.tag-manage-link.t-button) {
|
||||
padding: 0;
|
||||
height: auto;
|
||||
min-height: 0;
|
||||
font-size: var(--app-text-md);
|
||||
color: var(--td-text-color-secondary);
|
||||
border: none !important;
|
||||
background: transparent !important;
|
||||
box-shadow: none !important;
|
||||
transition: color var(--app-motion-fast) ease;
|
||||
}
|
||||
.tag-filter-panel--documents .tag-filter-panel__footer :deep(.tag-manage-link.t-button):hover,
|
||||
.tag-filter-panel--documents .tag-filter-panel__footer :deep(.tag-manage-link.t-button):focus-visible {
|
||||
color: var(--td-brand-color) !important;
|
||||
background: transparent !important;
|
||||
border-color: transparent !important;
|
||||
text-decoration: none;
|
||||
}
|
||||
.tag-filter-panel--documents .tag-load-more :deep(.t-button) {
|
||||
padding: 0;
|
||||
font-size: var(--app-text-sm);
|
||||
color: var(--td-text-color-placeholder);
|
||||
}
|
||||
.tag-filter-panel--documents .tag-empty-state {
|
||||
padding: 6px 0;
|
||||
font-size: var(--app-text-sm);
|
||||
}
|
||||
|
||||
</style>
|
||||
@@ -0,0 +1,154 @@
|
||||
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 { compileScript, parse } from '@vue/compiler-sfc'
|
||||
import * as vue from 'vue'
|
||||
|
||||
const source = readFileSync(new URL('./KnowledgeTagPicker.vue', import.meta.url), 'utf8')
|
||||
const { descriptor } = parse(source)
|
||||
const compiled = ts.transpileModule(compileScript(descriptor, { id: 'picker-test', inlineTemplate: true }).content, {
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 },
|
||||
}).outputText
|
||||
const translate = (key: string) => key
|
||||
type Host = { type: string; props: Record<string, any>; children: Host[]; text: string; parent?: Host }
|
||||
const node = (type: string): Host => ({ type, props: {}, children: [], text: '' })
|
||||
const renderer = vue.createRenderer<Host, Host>({
|
||||
createElement: node,
|
||||
createText: text => ({ ...node('#text'), text }),
|
||||
createComment: text => ({ ...node('#comment'), text }),
|
||||
patchProp: (el, key, _old, value) => { el.props[key] = value },
|
||||
setText: (el, text) => { el.text = text },
|
||||
setElementText: (el, text) => { el.children = []; el.text = text },
|
||||
parentNode: el => el.parent || null,
|
||||
nextSibling: el => el.parent?.children[el.parent.children.indexOf(el) + 1] || null,
|
||||
insert(el, parent, anchor) {
|
||||
if (el.parent) el.parent.children.splice(el.parent.children.indexOf(el), 1)
|
||||
el.parent = parent
|
||||
const index = anchor ? parent.children.indexOf(anchor) : -1
|
||||
parent.children.splice(index < 0 ? parent.children.length : index, 0, el)
|
||||
},
|
||||
remove(el) {
|
||||
el.parent?.children.splice(el.parent.children.indexOf(el), 1)
|
||||
el.parent = undefined
|
||||
},
|
||||
})
|
||||
const textOf = (el: Host): string => el.type === '#comment' ? '' : el.text + el.children.map(textOf).join('')
|
||||
const all = (el: Host, predicate: (node: Host) => boolean): Host[] => [
|
||||
...(predicate(el) ? [el] : []), ...el.children.flatMap(child => all(child, predicate)),
|
||||
]
|
||||
const hasClass = (el: Host, name: string) => String(el.props.class || '').split(' ').includes(name)
|
||||
|
||||
|
||||
async function fixture() {
|
||||
const calls: { create: unknown[][]; rename: unknown[][]; remove: unknown[][] } = { create: [], rename: [], remove: [] }
|
||||
let rows = [{ id: 'used', seq_id: 1, name: 'Used', knowledge_count: 2 }, { id: 'free', seq_id: 2, name: 'Free', knowledge_count: 0 }]
|
||||
const exports: { default?: vue.Component } = {}
|
||||
runInNewContext(compiled, { exports, setTimeout, clearTimeout, require(name: string) {
|
||||
if (name === 'vue') return vue
|
||||
if (name === 'vue-i18n') return { useI18n: () => ({ t: translate }) }
|
||||
if (name === 'tdesign-vue-next') return { MessagePlugin: { success() {}, error() {}, warning() {} } }
|
||||
if (name === '@/api/knowledge-base') return {
|
||||
listKnowledgeTags: async (_kb: string, params: { keyword?: string }) => {
|
||||
const filtered = rows.filter(r => !params.keyword || r.name.includes(params.keyword))
|
||||
return { data: { data: filtered.map(r => ({ ...r })), total: filtered.length } }
|
||||
},
|
||||
createKnowledgeBaseTag: async (...args: any[]) => {
|
||||
calls.create.push(args)
|
||||
const tag = { id: 'new', seq_id: 3, name: args[1].name, knowledge_count: 0 }
|
||||
rows.push(tag)
|
||||
return { data: tag }
|
||||
},
|
||||
updateKnowledgeBaseTag: async (...args: any[]) => { calls.rename.push(args); rows.find(r => r.id === args[1])!.name = args[2].name },
|
||||
deleteKnowledgeBaseTag: async (...args: any[]) => { calls.remove.push(args); rows = rows.filter(r => r.seq_id !== args[1]) },
|
||||
}
|
||||
throw new Error('Unexpected import: ' + name)
|
||||
} })
|
||||
const selectedIds = vue.ref<string[]>([])
|
||||
const changes: unknown[] = []
|
||||
const root = node('root')
|
||||
const app = renderer.createApp({ setup: () => () => vue.h(exports.default!, {
|
||||
kbId: 'kb', selectedIds: selectedIds.value,
|
||||
'onUpdate:selectedIds': (ids: string[]) => { selectedIds.value = ids },
|
||||
onChanged: (payload: unknown) => changes.push(payload),
|
||||
}) })
|
||||
app.config.globalProperties.$t = translate as typeof app.config.globalProperties.$t
|
||||
for (const [name, type] of [['t-input', 'input'], ['t-button', 'button'], ['t-checkbox', 'checkbox'], ['t-popconfirm', 'popconfirm'], ['t-tooltip', 'tooltip'], ['t-icon', 'icon'], ['t-loading', 'loading']]) {
|
||||
app.component(name!, vue.defineComponent({ setup: (_props, { slots }) => () => vue.h(type!, {}, slots.default?.()) }))
|
||||
}
|
||||
app.component('t-popup', vue.defineComponent({
|
||||
props: ['visible'], emits: ['visible-change'],
|
||||
setup: (props, { slots, emit }) => () => vue.h('popup', { onOpen: () => emit('visible-change', true) }, [slots.default?.(), props.visible ? slots.content?.() : null]),
|
||||
}))
|
||||
app.mount(root)
|
||||
const settle = async () => { for (let i = 0; i < 6; i++) await vue.nextTick() }
|
||||
await settle()
|
||||
const find = (predicate: (el: Host) => boolean) => { const el = all(root, predicate)[0]; assert.ok(el); return el }
|
||||
const fire = async (el: Host, event = 'onClick', value?: unknown) => { await el.props[event](value); await settle() }
|
||||
const search = async (value: string) => {
|
||||
await fire(find(el => el.type === 'input'), 'onUpdate:modelValue', value)
|
||||
await new Promise(resolve => setTimeout(resolve, 270))
|
||||
await settle()
|
||||
}
|
||||
return { root, calls, selectedIds, changes, find, fire, search, close: () => app.unmount() }
|
||||
}
|
||||
|
||||
test('search, create and select happen in one panel without losing previous selection', async t => {
|
||||
const f = await fixture(); t.after(f.close)
|
||||
await f.fire(f.find(el => el.type === 'checkbox'), 'onChange', true)
|
||||
assert.deepEqual([...f.selectedIds.value], ['used'])
|
||||
await f.search('New')
|
||||
await f.fire(f.find(el => hasClass(el, 'tag-picker-create')))
|
||||
assert.deepEqual(JSON.parse(JSON.stringify(f.calls.create)), [['kb', { name: 'New' }]])
|
||||
assert.deepEqual([...f.selectedIds.value], ['used', 'new'])
|
||||
assert.equal(f.changes.length, 1)
|
||||
})
|
||||
|
||||
test('rename saves in place without changing selection', async t => {
|
||||
const f = await fixture(); t.after(f.close)
|
||||
f.selectedIds.value = ['used']; await vue.nextTick()
|
||||
await f.fire(f.find(el => el.type === 'popup'), 'onOpen')
|
||||
await f.fire(f.find(el => el.type === 'button' && textOf(el) === 'knowledgeBase.tagEditAction'))
|
||||
const input = f.find(el => el.type === 'input' && el.props['aria-label'] === 'knowledgeBase.tagEditAction')
|
||||
await f.fire(input, 'onUpdate:modelValue', 'Renamed')
|
||||
await f.fire(f.find(el => el.type === 'button' && el.props['aria-label'] === 'common.save'))
|
||||
assert.deepEqual(JSON.parse(JSON.stringify(f.calls.rename)), [['kb', 'used', { name: 'Renamed' }]])
|
||||
assert.deepEqual([...f.selectedIds.value], ['used'])
|
||||
assert.ok(textOf(f.root).includes('Renamed'))
|
||||
})
|
||||
|
||||
test('selected tags move above unselected tags and search preserves selection', async t => {
|
||||
const f = await fixture(); t.after(f.close)
|
||||
const headings = () => all(f.root, el => hasClass(el, 'tag-picker-group-title')).map(textOf)
|
||||
const labels = () => all(f.root, el => el.type === 'checkbox').map(textOf)
|
||||
assert.deepEqual(headings(), ['knowledgeBase.tagPickerUnselected2'])
|
||||
await f.fire(f.find(el => el.type === 'checkbox' && textOf(el) === 'Free'), 'onChange', true)
|
||||
assert.deepEqual(headings(), ['knowledgeBase.tagPickerSelected1', 'knowledgeBase.tagPickerUnselected1'])
|
||||
assert.deepEqual(labels(), ['Free', 'Used'])
|
||||
await f.search('Used')
|
||||
assert.deepEqual(headings(), ['knowledgeBase.tagPickerUnselected1'])
|
||||
assert.deepEqual([...f.selectedIds.value], ['free'])
|
||||
await f.search('')
|
||||
assert.deepEqual(labels(), ['Free', 'Used'])
|
||||
await f.fire(f.find(el => el.type === 'checkbox' && textOf(el) === 'Used'), 'onChange', true)
|
||||
assert.deepEqual(headings(), ['knowledgeBase.tagPickerSelected2'])
|
||||
await f.fire(f.find(el => el.type === 'checkbox' && textOf(el) === 'Free'), 'onChange', false)
|
||||
assert.deepEqual(headings(), ['knowledgeBase.tagPickerSelected1', 'knowledgeBase.tagPickerUnselected1'])
|
||||
assert.deepEqual(labels(), ['Used', 'Free'])
|
||||
})
|
||||
|
||||
test('used tags cannot be deleted; unused deletion never requests cascading content removal', async t => {
|
||||
const f = await fixture(); t.after(f.close)
|
||||
await f.fire(f.find(el => el.type === 'popup'), 'onOpen')
|
||||
const deleteButtons = all(f.root, el => el.type === 'button' && textOf(el) === 'knowledgeBase.tagDeleteAction')
|
||||
assert.ok('disabled' in deleteButtons[0]!.props && deleteButtons[0]!.props.disabled !== false)
|
||||
assert.equal(all(f.root, el => el.type === 'popconfirm').length, 0)
|
||||
await f.fire(all(f.root, el => el.type === 'popup')[1]!, 'onOpen')
|
||||
assert.equal(all(f.root, el => el.type === 'popconfirm').length, 1)
|
||||
f.selectedIds.value = ['used', 'free']; await vue.nextTick()
|
||||
await f.fire(f.find(el => el.type === 'popconfirm'), 'onConfirm')
|
||||
assert.deepEqual(JSON.parse(JSON.stringify(f.calls.remove)), [['kb', 2]])
|
||||
assert.deepEqual([...f.selectedIds.value], ['used'])
|
||||
assert.equal(all(f.root, el => hasClass(el, 'tag-picker-row')).length, 1)
|
||||
})
|
||||
@@ -0,0 +1,210 @@
|
||||
<template>
|
||||
<div class="knowledge-tag-picker">
|
||||
<t-input v-model="query" :disabled="busy" :placeholder="$t('knowledgeBase.tagPickerSearch')" :maxlength="40" clearable>
|
||||
<template #prefix-icon><t-icon name="search" size="16px" /></template>
|
||||
</t-input>
|
||||
<div class="tag-picker-list" :aria-label="$t('knowledgeBase.columnTag')">
|
||||
<t-loading v-if="loading && !tags.length" size="small" />
|
||||
<template v-for="(tag, index) in orderedTags" :key="tag.id">
|
||||
<div v-if="index === 0 || index === selectedTags.length" class="tag-picker-group-title" role="heading" aria-level="3">
|
||||
<span>{{ $t(selectedIds.includes(tag.id) ? 'knowledgeBase.tagPickerSelected' : 'knowledgeBase.tagPickerUnselected') }}</span>
|
||||
<span class="tag-picker-group-count">{{ selectedIds.includes(tag.id) ? selectedTags.length : unselectedTags.length }}</span>
|
||||
</div>
|
||||
<div class="tag-picker-row">
|
||||
<template v-if="editingId === tag.id">
|
||||
<t-input v-model="editingName" autofocus :maxlength="40" size="small" :disabled="busy"
|
||||
:aria-label="$t('knowledgeBase.tagEditAction')" @enter="saveName(tag)"
|
||||
@keydown="(_v: string, ctx: { e: KeyboardEvent }) => { if (ctx.e.key === 'Escape') cancelEdit() }" />
|
||||
<t-button variant="text" shape="square" size="small" :loading="busy" :aria-label="$t('common.save')" @click="saveName(tag)"><t-icon name="check" size="14px" /></t-button>
|
||||
<t-button theme="default" variant="text" shape="square" size="small" :disabled="busy" :aria-label="$t('common.cancel')" @click="cancelEdit"><t-icon name="close" size="14px" /></t-button>
|
||||
</template>
|
||||
<template v-else>
|
||||
<t-checkbox :checked="selectedIds.includes(tag.id)" :disabled="busy" @change="toggle(tag.id)"><span :title="tag.name">{{ tag.name }}</span></t-checkbox>
|
||||
<t-popup attach="body" trigger="click" placement="bottom-right" :visible="menuTagId === tag.id"
|
||||
@visible-change="(visible: boolean) => { if (visible) menuTagId = tag.id; else if (menuTagId === tag.id) menuTagId = '' }">
|
||||
<button type="button" class="tag-picker-more" :class="{ 'is-open': menuTagId === tag.id }" :disabled="busy"
|
||||
:aria-label="`${tag.name} · ${$t('knowledgeBase.columnActions')}`" :aria-expanded="menuTagId === tag.id"><t-icon name="ellipsis" size="16px" /></button>
|
||||
<template #content>
|
||||
<div class="tag-picker-menu">
|
||||
<button type="button" @click="startEdit(tag)">{{ $t('knowledgeBase.tagEditAction') }}</button>
|
||||
<t-tooltip v-if="isUsed(tag)" :content="$t('knowledgeBase.tagPickerInUse')">
|
||||
<span><button type="button" disabled>{{ $t('knowledgeBase.tagDeleteAction') }}</button></span>
|
||||
</t-tooltip>
|
||||
<t-popconfirm v-else attach="body" :content="$t('knowledgeBase.tagPickerDeleteConfirm', { name: tag.name })"
|
||||
:confirm-btn="{ content: $t('common.delete'), theme: 'danger', loading: busy }"
|
||||
:cancel-btn="{ content: $t('common.cancel') }" @confirm="removeTag(tag)">
|
||||
<button type="button" class="tag-picker-delete" :disabled="busy">{{ $t('knowledgeBase.tagDeleteAction') }}</button>
|
||||
</t-popconfirm>
|
||||
</div>
|
||||
</template>
|
||||
</t-popup>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
<button v-if="canCreate && !loading" type="button" class="tag-picker-create" :disabled="busy" @click="createTag">
|
||||
<t-icon :name="busy ? 'loading' : 'add'" size="16px" />
|
||||
<span :title="query.trim()">{{ $t('knowledgeBase.tagCreateAction') }} “{{ query.trim() }}”</span>
|
||||
</button>
|
||||
<p v-if="!loading && !tags.length && !canCreate" class="tag-picker-empty">{{ $t(query.trim() ? 'knowledgeBase.tagEmptyResult' : 'knowledgeBase.noTags') }}</p>
|
||||
<t-button v-if="hasMore" variant="text" theme="default" size="small" :loading="loading" @click="load(false)">{{ $t('tenant.loadMore') }}</t-button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { MessagePlugin } from 'tdesign-vue-next';
|
||||
import { listKnowledgeTags, createKnowledgeBaseTag, updateKnowledgeBaseTag, deleteKnowledgeBaseTag } from '@/api/knowledge-base';
|
||||
|
||||
type Tag = { id: string; seq_id: number; name: string; knowledge_count?: number; chunk_count?: number };
|
||||
const props = defineProps<{ kbId: string; selectedIds: string[] }>();
|
||||
const emit = defineEmits<{
|
||||
'update:selectedIds': [ids: string[]];
|
||||
'busy-change': [busy: boolean];
|
||||
changed: [payload?: { deletedTagId?: string }];
|
||||
}>();
|
||||
const { t } = useI18n();
|
||||
const query = ref('');
|
||||
const tags = ref<Tag[]>([]);
|
||||
const loading = ref(false);
|
||||
const busy = ref(false);
|
||||
const page = ref(1);
|
||||
const hasMore = ref(false);
|
||||
const editingId = ref('');
|
||||
const menuTagId = ref('');
|
||||
const editingName = ref('');
|
||||
let requestVersion = 0;
|
||||
let debounce: ReturnType<typeof setTimeout> | undefined;
|
||||
const canCreate = computed(() => query.value.trim() && !tags.value.some(tag => tag.name === query.value.trim()));
|
||||
const selectedTagIds = computed(() => new Set(props.selectedIds));
|
||||
const selectedTags = computed(() => tags.value.filter(tag => selectedTagIds.value.has(tag.id)));
|
||||
const unselectedTags = computed(() => tags.value.filter(tag => !selectedTagIds.value.has(tag.id)));
|
||||
const orderedTags = computed(() => [...selectedTags.value, ...unselectedTags.value]);
|
||||
const isUsed = (tag: Tag) => !!(tag.knowledge_count || tag.chunk_count);
|
||||
const reportError = (error: any) => MessagePlugin.error(error?.message || t('common.operationFailed'));
|
||||
watch(busy, value => emit('busy-change', value), { flush: 'sync' });
|
||||
|
||||
async function load(reset = true) {
|
||||
if (!props.kbId || (!reset && loading.value)) return;
|
||||
const version = ++requestVersion;
|
||||
if (reset) { page.value = 1; tags.value = []; hasMore.value = false; }
|
||||
loading.value = true;
|
||||
try {
|
||||
const res: any = await listKnowledgeTags(props.kbId, { page: page.value, page_size: 50, keyword: query.value.trim() || undefined });
|
||||
if (version !== requestVersion) return;
|
||||
const rows = (res.data?.data || []).map((tag: Tag) => ({ ...tag, id: String(tag.id) }));
|
||||
tags.value = reset ? rows : [...tags.value, ...rows];
|
||||
hasMore.value = tags.value.length < (res.data?.total || 0);
|
||||
page.value++;
|
||||
} catch (error) { if (version === requestVersion) reportError(error); }
|
||||
finally { if (version === requestVersion) loading.value = false; }
|
||||
}
|
||||
watch(query, () => {
|
||||
clearTimeout(debounce);
|
||||
requestVersion++;
|
||||
loading.value = true;
|
||||
cancelEdit();
|
||||
menuTagId.value = '';
|
||||
debounce = setTimeout(() => { void load(); }, 250);
|
||||
});
|
||||
watch(() => props.kbId, () => { void load(); }, { immediate: true });
|
||||
onBeforeUnmount(() => { clearTimeout(debounce); requestVersion++; emit('busy-change', false); });
|
||||
|
||||
function toggle(id: string) {
|
||||
emit('update:selectedIds', props.selectedIds.includes(id) ? props.selectedIds.filter(value => value !== id) : [...props.selectedIds, id]);
|
||||
}
|
||||
function startEdit(tag: Tag) { menuTagId.value = ''; editingId.value = tag.id; editingName.value = tag.name; }
|
||||
function cancelEdit() { if (!busy.value) { editingId.value = ''; editingName.value = ''; } }
|
||||
async function createTag() {
|
||||
const name = query.value.trim();
|
||||
if (!name || busy.value || loading.value) return;
|
||||
busy.value = true;
|
||||
try {
|
||||
const res: any = await createKnowledgeBaseTag(props.kbId, { name });
|
||||
const tag = res.data || res;
|
||||
emit('update:selectedIds', [...new Set([...props.selectedIds, String(tag.id)])]);
|
||||
emit('changed');
|
||||
query.value = '';
|
||||
MessagePlugin.success(t('knowledgeBase.tagCreateSuccess'));
|
||||
} catch (error) { reportError(error); }
|
||||
finally { busy.value = false; }
|
||||
}
|
||||
async function saveName(tag: Tag) {
|
||||
const name = editingName.value.trim();
|
||||
if (busy.value) return;
|
||||
if (!name) { MessagePlugin.warning(t('knowledgeBase.tagNameRequired')); return; }
|
||||
if (name === tag.name) { cancelEdit(); return; }
|
||||
busy.value = true;
|
||||
try {
|
||||
await updateKnowledgeBaseTag(props.kbId, tag.id, { name });
|
||||
tag.name = name;
|
||||
editingId.value = '';
|
||||
emit('changed');
|
||||
MessagePlugin.success(t('knowledgeBase.tagEditSuccess'));
|
||||
} catch (error) { reportError(error); }
|
||||
finally { busy.value = false; }
|
||||
}
|
||||
async function removeTag(tag: Tag) {
|
||||
if (busy.value || isUsed(tag)) return;
|
||||
busy.value = true;
|
||||
try {
|
||||
// Do not force deletion: force also deletes the associated knowledge content.
|
||||
await deleteKnowledgeBaseTag(props.kbId, tag.seq_id);
|
||||
emit('update:selectedIds', props.selectedIds.filter(id => id !== tag.id));
|
||||
menuTagId.value = '';
|
||||
emit('changed', { deletedTagId: tag.id });
|
||||
await load();
|
||||
MessagePlugin.success(t('knowledgeBase.tagDeleteSuccess'));
|
||||
} catch (error) { reportError(error); }
|
||||
finally { busy.value = false; }
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
.knowledge-tag-picker { display: flex; flex-direction: column; gap: 8px; margin-top: 16px; }
|
||||
.tag-picker-list { max-height: min(280px, 40vh); overflow-y: auto; overflow-x: hidden; scrollbar-width: thin; scrollbar-gutter: stable; padding: 2px 4px 2px 0; }
|
||||
.tag-picker-group-title {
|
||||
display: flex; align-items: center; gap: 6px; padding: 5px 4px;
|
||||
color: var(--td-text-color-secondary); font-size: var(--app-text-xs); line-height: 18px;
|
||||
&:not(:first-child) { margin-top: 6px; padding-top: 10px; border-top: 1px solid var(--td-component-stroke); }
|
||||
}
|
||||
.tag-picker-group-count { color: var(--td-text-color-placeholder); font-variant-numeric: tabular-nums; }
|
||||
.tag-picker-row {
|
||||
display: flex; align-items: center; gap: 4px; min-width: 0; box-sizing: border-box; min-height: 34px; padding: 2px 4px; border-radius: var(--app-radius-xs);
|
||||
&:hover { background: var(--td-bg-color-container-hover); }
|
||||
> .t-checkbox { flex: 1; min-width: 0; margin: 0; }
|
||||
:deep(.t-checkbox__label) { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-weight: 400; }
|
||||
> .t-button, > .t-popup { flex-shrink: 0; }
|
||||
> .t-input__wrap { flex: 1; min-width: 0; }
|
||||
:deep(.t-button--theme-default) { color: var(--td-text-color-secondary); }
|
||||
:deep(.t-button--theme-default.t-is-disabled) { color: var(--td-text-color-disabled); }
|
||||
}
|
||||
.tag-picker-empty { padding: 12px 4px; margin: 0; font-size: var(--app-text-sm); color: var(--td-text-color-placeholder); }
|
||||
.tag-picker-more {
|
||||
display: flex; align-items: center; justify-content: center; width: 26px; height: 26px;
|
||||
padding: 0; border: 0; border-radius: var(--app-radius-xs); background: transparent;
|
||||
color: var(--td-text-color-placeholder); cursor: pointer; opacity: 0;
|
||||
&:hover, &.is-open { background: var(--td-bg-color-secondarycontainer); color: var(--td-text-color-primary); }
|
||||
}
|
||||
.tag-picker-row:hover .tag-picker-more, .tag-picker-row:focus-within .tag-picker-more, .tag-picker-more.is-open { opacity: 1; }
|
||||
.tag-picker-more:focus-visible, .tag-picker-create:focus-visible { outline: 2px solid var(--app-focus-border); outline-offset: 2px; }
|
||||
@media (hover: none) { .tag-picker-more { opacity: 1; } }
|
||||
.tag-picker-menu {
|
||||
min-width: 112px; display: flex; flex-direction: column; gap: 2px;
|
||||
button { width: 100%; display: block; border: 0; border-radius: var(--app-radius-xs); background: transparent; padding: 6px 10px;
|
||||
font: inherit; font-size: var(--app-text-base); font-weight: 400; line-height: 20px; text-align: left; color: var(--td-text-color-primary); cursor: pointer; }
|
||||
button:hover:enabled { background: var(--td-bg-color-container-hover); color: var(--td-brand-color); }
|
||||
button:disabled { color: var(--td-text-color-disabled); cursor: not-allowed; }
|
||||
.tag-picker-delete:hover:enabled { color: var(--td-error-color); }
|
||||
}
|
||||
.tag-picker-create {
|
||||
display: flex; align-items: center; gap: 8px; width: 100%; min-height: 36px;
|
||||
padding: 4px; border: 0; border-radius: var(--app-radius-xs); background: transparent;
|
||||
font: inherit; font-size: var(--app-text-md); text-align: left; color: var(--td-text-color-secondary); cursor: pointer;
|
||||
.t-icon { color: var(--td-brand-color); flex-shrink: 0; }
|
||||
span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
&:hover:enabled { background: var(--td-bg-color-container-hover); color: var(--td-text-color-primary); }
|
||||
&:disabled { cursor: wait; }
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,106 @@
|
||||
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 { compileScript, parse } from '@vue/compiler-sfc'
|
||||
import * as vue from 'vue'
|
||||
|
||||
const source = readFileSync(new URL('./KnowledgeTagPopover.vue', import.meta.url), 'utf8')
|
||||
const { descriptor } = parse(source)
|
||||
const compiled = ts.transpileModule(compileScript(descriptor, { id: 'tag-popover-test', inlineTemplate: true }).content, {
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 },
|
||||
}).outputText
|
||||
const translate = (key: string) => key
|
||||
type Host = { type: string; props: Record<string, any>; children: Host[]; text: string; parent?: Host }
|
||||
const node = (type: string): Host => ({ type, props: {}, children: [], text: '' })
|
||||
const renderer = vue.createRenderer<Host, Host>({
|
||||
createElement: node,
|
||||
createText: text => ({ ...node('#text'), text }),
|
||||
createComment: text => ({ ...node('#comment'), text }),
|
||||
patchProp: (el, key, _old, value) => { el.props[key] = value },
|
||||
setText: (el, text) => { el.text = text },
|
||||
setElementText: (el, text) => { el.children = []; el.text = text },
|
||||
parentNode: el => el.parent || null,
|
||||
nextSibling: el => el.parent?.children[el.parent.children.indexOf(el) + 1] || null,
|
||||
insert(el, parent, anchor) {
|
||||
if (el.parent) el.parent.children.splice(el.parent.children.indexOf(el), 1)
|
||||
el.parent = parent
|
||||
const index = anchor ? parent.children.indexOf(anchor) : -1
|
||||
parent.children.splice(index < 0 ? parent.children.length : index, 0, el)
|
||||
},
|
||||
remove(el) {
|
||||
el.parent?.children.splice(el.parent.children.indexOf(el), 1)
|
||||
el.parent = undefined
|
||||
},
|
||||
})
|
||||
const textOf = (el: Host): string => el.type === '#comment' ? '' : el.text + el.children.map(textOf).join('')
|
||||
const all = (el: Host, predicate: (node: Host) => boolean): Host[] => [
|
||||
...(predicate(el) ? [el] : []), ...el.children.flatMap(child => all(child, predicate)),
|
||||
]
|
||||
|
||||
|
||||
async function fixture(fail = false) {
|
||||
const state = vue.reactive({ visible: false, kbId: 'kb', knowledgeId: 'doc', tags: [{ id: 'a' }] })
|
||||
const requests: unknown[] = []
|
||||
let changes = 0
|
||||
const exports: { default?: vue.Component } = {}
|
||||
runInNewContext(compiled, { exports, require(name: string) {
|
||||
if (name === 'vue') return vue
|
||||
if (name === 'vue-i18n') return { useI18n: () => ({ t: translate }) }
|
||||
if (name === 'tdesign-vue-next') return { MessagePlugin: { success() {}, error() {} } }
|
||||
if (name === '@/api/knowledge-base') return { updateKnowledgeTagBatch: async (data: unknown) => {
|
||||
requests.push(JSON.parse(JSON.stringify(data)))
|
||||
if (fail) throw new Error('save failed')
|
||||
} }
|
||||
if (name === './KnowledgeTagPicker.vue') return { __esModule: true, default: vue.defineComponent({ props: ['selectedIds'], emits: ['update:selectedIds'], setup: (props, { emit }) => () => vue.h('picker', { selectedIds: props.selectedIds, 'onUpdate:selectedIds': (ids: string[]) => emit('update:selectedIds', ids) }) }) }
|
||||
throw new Error(name)
|
||||
} })
|
||||
const root = node('root')
|
||||
const app = renderer.createApp({ setup: () => () => vue.h(exports.default!, {
|
||||
...state, 'onUpdate:visible': (value: boolean) => { state.visible = value }, onChanged: () => { changes++ },
|
||||
}) })
|
||||
app.config.globalProperties.$t = translate as typeof app.config.globalProperties.$t
|
||||
app.component('t-popup', vue.defineComponent({
|
||||
props: ['visible'], setup: (props, { slots }) => () => vue.h('popup', {}, props.visible ? slots.content?.() : []),
|
||||
}))
|
||||
app.component('t-button', vue.defineComponent({ setup: (_props, { slots }) => () => vue.h('button', {}, slots.default?.()) }))
|
||||
app.mount(root)
|
||||
const settle = async () => { for (let i=0;i<5;i++) await vue.nextTick() }
|
||||
const find = (predicate: (el: Host) => boolean) => { const el = all(root,predicate)[0]; assert.ok(el); return el }
|
||||
const fire = async (el: Host, event = 'onClick', value?: unknown) => { await el.props[event](value); await settle() }
|
||||
state.visible = true; await settle()
|
||||
return { state, requests, changes: () => changes, root, find, fire, settle, close: () => app.unmount() }
|
||||
}
|
||||
|
||||
test('opening hydrates tags; refreshing the document preserves an open draft; cancel does not save', async t => {
|
||||
const f = await fixture(); t.after(f.close)
|
||||
const picker = f.find(el => el.type === 'picker')
|
||||
assert.deepEqual([...picker.props.selectedIds], ['a'])
|
||||
await f.fire(picker, 'onUpdate:selectedIds', ['a','b'])
|
||||
f.state.tags = [{ id:'other' }]; await f.settle()
|
||||
assert.deepEqual([...picker.props.selectedIds], ['a','b'])
|
||||
await f.fire(f.find(el => el.type === 'button' && textOf(el) === 'common.cancel'))
|
||||
assert.equal(f.state.visible, false)
|
||||
assert.equal(f.requests.length, 0)
|
||||
f.state.visible = true; await f.settle()
|
||||
assert.deepEqual([...f.find(el => el.type === 'picker').props.selectedIds], ['other'])
|
||||
})
|
||||
|
||||
test('confirm saves the target document and closes only after successful save', async t => {
|
||||
const f = await fixture(); t.after(f.close)
|
||||
await f.fire(f.find(el => el.type === 'picker'), 'onUpdate:selectedIds', ['b'])
|
||||
await f.fire(f.find(el => el.type === 'button' && textOf(el) === 'common.confirm'))
|
||||
assert.deepEqual(f.requests, [{ updates: { doc: ['b'] } }])
|
||||
assert.equal(f.state.visible, false)
|
||||
assert.equal(f.changes(), 1)
|
||||
})
|
||||
|
||||
test('a failed save preserves the popup and draft for retry', async t => {
|
||||
const f = await fixture(true); t.after(f.close)
|
||||
await f.fire(f.find(el => el.type === 'picker'), 'onUpdate:selectedIds', ['b'])
|
||||
await f.fire(f.find(el => el.type === 'button' && textOf(el) === 'common.confirm'))
|
||||
assert.equal(f.state.visible, true)
|
||||
assert.equal(f.changes(), 0)
|
||||
assert.deepEqual([...f.find(el => el.type === 'picker').props.selectedIds], ['b'])
|
||||
})
|
||||
@@ -0,0 +1,74 @@
|
||||
<template>
|
||||
<div class="knowledge-tag-anchor" @click.stop @mousedown.stop>
|
||||
<t-popup :visible="visible" :disabled="disabled" trigger="click" placement="bottom-left" attach="body"
|
||||
destroy-on-close overlay-class-name="knowledge-tag-popover" :overlay-inner-style="{ padding: '12px' }"
|
||||
@visible-change="changeVisible">
|
||||
<slot />
|
||||
<template #content>
|
||||
<section v-if="visible" class="tag-popover-panel" :aria-label="$t('knowledgeBase.tagEditDialogHeading')">
|
||||
<KnowledgeTagPicker :kb-id="kbId" :selected-ids="selectedIds" @update:selected-ids="selectedIds = $event"
|
||||
@busy-change="busy = $event" @changed="emit('changed', $event)" />
|
||||
<footer class="tag-popover-footer">
|
||||
<span>{{ $t('knowledgeBase.tagSelectedCount', { count: selectedIds.length }) }}</span>
|
||||
<t-button size="small" variant="text" theme="default" :disabled="busy || saving" @click="changeVisible(false)">{{ $t('common.cancel') }}</t-button>
|
||||
<t-button size="small" theme="primary" :disabled="busy" :loading="saving" @click="save">{{ $t('common.confirm') }}</t-button>
|
||||
</footer>
|
||||
</section>
|
||||
</template>
|
||||
</t-popup>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { MessagePlugin } from 'tdesign-vue-next';
|
||||
import { updateKnowledgeTagBatch } from '@/api/knowledge-base';
|
||||
import KnowledgeTagPicker from './KnowledgeTagPicker.vue';
|
||||
const props = defineProps<{
|
||||
kbId: string;
|
||||
knowledgeId: string;
|
||||
tags: { id: string }[];
|
||||
visible: boolean;
|
||||
disabled?: boolean;
|
||||
}>();
|
||||
const emit = defineEmits<{
|
||||
'update:visible': [visible: boolean];
|
||||
changed: [payload?: { deletedTagId?: string }];
|
||||
}>();
|
||||
const { t } = useI18n();
|
||||
const selectedIds = ref<string[]>([]);
|
||||
const busy = ref(false);
|
||||
const saving = ref(false);
|
||||
watch(() => props.visible, open => {
|
||||
if (open) selectedIds.value = props.tags.map(tag => tag.id);
|
||||
}, { immediate: true });
|
||||
function changeVisible(visible: boolean) {
|
||||
if (busy.value || saving.value || (visible && props.disabled)) return;
|
||||
emit('update:visible', visible);
|
||||
}
|
||||
async function save() {
|
||||
if (busy.value || saving.value) return;
|
||||
saving.value = true;
|
||||
try {
|
||||
await updateKnowledgeTagBatch({ updates: { [props.knowledgeId]: [...selectedIds.value] } });
|
||||
MessagePlugin.success(t('knowledgeBase.tagUpdateSuccess'));
|
||||
emit('update:visible', false);
|
||||
emit('changed');
|
||||
} catch (error: any) {
|
||||
MessagePlugin.error(error?.message || t('common.operationFailed'));
|
||||
} finally { saving.value = false; }
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
.knowledge-tag-anchor { min-width: 0; width: 100%; }
|
||||
.tag-popover-panel { width: min(300px, calc(100vw - 56px)); }
|
||||
.tag-popover-panel :deep(.knowledge-tag-picker) { margin-top: 0; }
|
||||
.tag-popover-panel :deep(.tag-picker-list) { max-height: min(240px, 40vh); }
|
||||
.tag-popover-footer {
|
||||
display: flex; align-items: center; gap: 6px; margin-top: 10px; padding-top: 10px;
|
||||
border-top: 1px solid var(--td-component-stroke);
|
||||
> span { flex: 1; font-size: var(--app-text-sm); color: var(--td-text-color-placeholder); }
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,80 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { readFileSync } from 'node:fs'
|
||||
|
||||
const dialog = readFileSync(new URL('./UploadConfirmDialog.vue', import.meta.url), 'utf8')
|
||||
const host = readFileSync(new URL('../../../components/UploadConfirmHost.vue', import.meta.url), 'utf8')
|
||||
const knowledgeBase = readFileSync(new URL('../KnowledgeBase.vue', import.meta.url), 'utf8')
|
||||
const platform = readFileSync(new URL('../../platform/index.vue', import.meta.url), 'utf8')
|
||||
|
||||
test('selects multiple document tags and returns them with the confirmation result', () => {
|
||||
assert.match(host, /:tag-ids="uploadConfirmStore\.tagIds"/)
|
||||
assert.match(dialog, /v-model="selectedTagIds"/)
|
||||
assert.match(dialog, /multiple/)
|
||||
assert.match(dialog, /listKnowledgeTags\(kbId, \{ page: 1, page_size: 1000 \}\)/)
|
||||
assert.match(dialog, /tagIds: \[\.\.\.selectedTagIds\.value\]/)
|
||||
})
|
||||
|
||||
test('uses confirmed tags for file and URL imports instead of reading the list filter at upload time', () => {
|
||||
assert.match(knowledgeBase, /const tagIds = result\.tagIds \|\| \[\]/)
|
||||
assert.match(knowledgeBase, /enqueueUploads\(files, \{[\s\S]*?\btagIds,[\s\S]*?\}\)/)
|
||||
assert.match(knowledgeBase, /executeUrlImport\(url, processConfig, tagIds\)/)
|
||||
assert.doesNotMatch(
|
||||
knowledgeBase,
|
||||
/const tagIdsToUpload = selectedTagIds\.value\.length > 0 \? \[\.\.\.selectedTagIds\.value\] : undefined/,
|
||||
)
|
||||
})
|
||||
|
||||
// Browsing a folder pre-fills the upload destination, so the dialog must show it
|
||||
// and the batch must use the folder the user confirmed there — never the sidebar
|
||||
// selection as it stands when the uploads actually start.
|
||||
test('takes the upload destination folder from the confirmation result', () => {
|
||||
assert.match(host, /:target-folder="uploadConfirmStore\.targetFolder"/)
|
||||
assert.match(host, /:folder-options="uploadConfirmStore\.folderOptions"/)
|
||||
assert.match(dialog, /class="destination-row"/)
|
||||
assert.match(dialog, /attach="body"/)
|
||||
assert.match(dialog, /overlay-class-name="upload-destination-popup"/)
|
||||
assert.match(dialog, /FolderPickerMenu/)
|
||||
assert.match(dialog, /onDestinationPicked/)
|
||||
assert.match(dialog, /targetFolder: localTargetFolder\.value/)
|
||||
assert.match(knowledgeBase, /targetFolder: result\.targetFolder \|\| ROOT_FOLDER_PATH/)
|
||||
assert.match(knowledgeBase, /targetFolder: selectedFolderPath\.value/)
|
||||
assert.match(knowledgeBase, /folderOptions: folderOptions\.value/)
|
||||
})
|
||||
|
||||
test('creates sub-folders from per-row actions without changing the selected destination', () => {
|
||||
const picker = readFileSync(new URL('./FolderPickerMenu.vue', import.meta.url), 'utf8')
|
||||
assert.match(picker, /startCreatingUnder/)
|
||||
assert.match(picker, /folder-picker__add/)
|
||||
assert.match(picker, /folder-picker__item--create/)
|
||||
assert.match(picker, /@keydown\.enter\.stop="commitNewFolder"/)
|
||||
assert.doesNotMatch(picker, /newFolderHintText/)
|
||||
assert.doesNotMatch(picker, /folder-picker__create-actions/)
|
||||
assert.doesNotMatch(picker, /newFolderParent/)
|
||||
assert.match(dialog, /pendingFolderPaths/)
|
||||
assert.match(dialog, /pickerFolderOptions/)
|
||||
assert.match(dialog, /@create="onDestinationCreated"/)
|
||||
})
|
||||
|
||||
test('calls out directory uploads via relative paths in the file list', () => {
|
||||
assert.match(dialog, /fileRelativeDir/)
|
||||
assert.doesNotMatch(dialog, /folder-upload-banner/)
|
||||
})
|
||||
|
||||
test('routes global knowledge file drops through the upload confirmation flow', () => {
|
||||
assert.match(platform, /weknora:knowledge-file-drop/)
|
||||
assert.match(knowledgeBase, /handleKnowledgeFileDrop/)
|
||||
assert.match(knowledgeBase, /handleUploadSourceFiles\(files\)/)
|
||||
})
|
||||
|
||||
test('uses section navigation with inline chunking controls and advanced options grouped', () => {
|
||||
assert.match(dialog, /v-model="uiState\.chunkingConfig\.strategy"/)
|
||||
assert.match(dialog, /v-model="uiState\.chunkingConfig\.chunkSize"/)
|
||||
assert.match(dialog, /v-model="uiState\.chunkingConfig\.chunkOverlap"/)
|
||||
assert.match(dialog, /chunkingMoreOpen/)
|
||||
assert.match(dialog, /activeSection === 'graph'/)
|
||||
assert.match(dialog, /class="files-panel"/)
|
||||
assert.match(dialog, /statusFull/)
|
||||
assert.match(dialog, /data-section="multimodal"/)
|
||||
assert.doesNotMatch(dialog, /<KBChunkingSettings/)
|
||||
})
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,144 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { createRequire } from 'node:module'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { runInNewContext } from 'node:vm'
|
||||
import test from 'node:test'
|
||||
import { compileScript, parse } from '@vue/compiler-sfc'
|
||||
import ts from 'typescript'
|
||||
import { createRenderer, h } from 'vue'
|
||||
import * as imageProcessingConfig from '../../../utils/imageProcessingConfig'
|
||||
|
||||
const require = createRequire(import.meta.url)
|
||||
const filename = fileURLToPath(new URL('./UploadConfirmDialog.vue', import.meta.url))
|
||||
const { descriptor } = parse(readFileSync(filename, 'utf8'), { filename })
|
||||
const script = compileScript(descriptor, { id: 'upload-image-vector-test' }).content
|
||||
.replace('__expose();', '')
|
||||
.replace('return __returned__', '__expose(__returned__); return __returned__')
|
||||
const compiled = ts.transpileModule(script, {
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 },
|
||||
}).outputText
|
||||
|
||||
function fixture(kbInfo: any) {
|
||||
const exports: any = {}
|
||||
runInNewContext(compiled, {
|
||||
exports, console,
|
||||
require(name: string) {
|
||||
if (name === 'vue') return require('vue')
|
||||
if (name === 'vue-i18n') return { useI18n: () => ({ t: (key: string) => key, te: () => false }) }
|
||||
if (name === '@/stores/chatResources') return { useChatResourcesStore: () => ({}) }
|
||||
if (name === '@/stores/editorResources') return { useEditorResourcesStore: () => ({}) }
|
||||
if (name === '@/stores/ui') return { useUIStore: () => ({}) }
|
||||
if (name === '@/api/knowledge-base') return { mergeImageActions: () => ({ ocr: { on: [] } }) }
|
||||
if (name === '@/utils/imageProcessingConfig') return imageProcessingConfig
|
||||
return { default: {} }
|
||||
},
|
||||
})
|
||||
exports.default.render = () => null
|
||||
const renderer = createRenderer<any, any>({
|
||||
createElement: () => ({}), createText: () => ({}), createComment: () => ({}),
|
||||
insert() {}, remove() {}, setElementText() {}, setText() {}, patchProp() {},
|
||||
parentNode: () => null, nextSibling: () => null,
|
||||
})
|
||||
let vm: any
|
||||
const app = renderer.createApp({ setup: () => () => h(exports.default, { visible: false, kbInfo, ref: (value: any) => { vm = value } }) })
|
||||
app.mount({})
|
||||
vm.initFromKbInfo(kbInfo)
|
||||
return { vm, dispose: () => app.unmount() }
|
||||
}
|
||||
|
||||
for (const enabled of [false, true]) {
|
||||
test(`upload inherits ${enabled} and submits the explicit opposite without changing the KB`, () => {
|
||||
const kb = { embedding_model_id: 'shared-embedding', image_processing_config: { image_vector_enabled: enabled } }
|
||||
const f = fixture(kb)
|
||||
try {
|
||||
assert.equal(f.vm.uiState.imageVectorEnabled, enabled)
|
||||
f.vm.uiState.imageVectorEnabled = !enabled
|
||||
const payload = JSON.parse(JSON.stringify(f.vm.buildProcessOverrides()))
|
||||
assert.equal(payload.image_vector_enabled, !enabled)
|
||||
assert.equal(kb.image_processing_config.image_vector_enabled, enabled)
|
||||
assert.equal('embedding_model_id' in payload, false)
|
||||
} finally { f.dispose() }
|
||||
})
|
||||
test(`reparse restores an explicit ${enabled} over the KB default`, () => {
|
||||
const f = fixture({ image_processing_config: { image_vector_enabled: !enabled } })
|
||||
try {
|
||||
f.vm.applyOverridesToState({ image_vector_enabled: enabled })
|
||||
assert.equal(f.vm.uiState.imageVectorEnabled, enabled)
|
||||
assert.equal(f.vm.buildProcessOverrides().image_vector_enabled, enabled)
|
||||
} finally { f.dispose() }
|
||||
})
|
||||
}
|
||||
|
||||
test('old documents inherit the KB value and old KBs default off', () => {
|
||||
const f = fixture({ image_processing_config: { image_vector_enabled: true } })
|
||||
try {
|
||||
f.vm.applyOverridesToState({ summary_enabled: false })
|
||||
assert.equal(f.vm.uiState.imageVectorEnabled, true)
|
||||
f.vm.initFromKbInfo({})
|
||||
assert.equal(f.vm.uiState.imageVectorEnabled, false)
|
||||
} finally { f.dispose() }
|
||||
})
|
||||
|
||||
test('image capability warning uses the KB embedding model and tolerates shared models absent from the list', () => {
|
||||
const f = fixture({ embedding_model_id: 'embedding' })
|
||||
try {
|
||||
assert.equal(f.vm.embeddingTakesImages, true)
|
||||
f.vm.allModels = [{ id: 'embedding', capabilities: { input: ['text'] } }]
|
||||
assert.equal(f.vm.embeddingTakesImages, false)
|
||||
f.vm.allModels = [{ id: 'embedding', capabilities: { input: ['text', 'image'] } }]
|
||||
assert.equal(f.vm.embeddingTakesImages, true)
|
||||
} finally { f.dispose() }
|
||||
})
|
||||
|
||||
for (const pipelineId of ['default', 'smartocr', 'caption_ocr', 'ob_cap_ocr']) {
|
||||
for (const params of [undefined, {}, { 'default.caption.thinking_enabled': false }]) {
|
||||
test(`reparse replaces KB parameters with document ${pipelineId} parameters ${JSON.stringify(params)}`, () => {
|
||||
const kb = {
|
||||
vlm_config: { enabled: true, model_id: 'vlm' },
|
||||
image_processing_config: { image_pipeline: 'default', image_pipeline_params: { 'default.caption_enabled': false, 'default.caption.thinking_enabled': true } },
|
||||
}
|
||||
const f = fixture(kb)
|
||||
try {
|
||||
f.vm.applyOverridesToState({ image_pipeline: pipelineId, image_pipeline_params: params })
|
||||
const result = JSON.parse(JSON.stringify(f.vm.buildProcessOverrides()))
|
||||
assert.equal(result.image_pipeline, imageProcessingConfig.normalizeImagePipelineId(pipelineId))
|
||||
assert.deepEqual(result.image_pipeline_params ?? {}, params ?? {})
|
||||
assert.deepEqual(kb.image_processing_config.image_pipeline_params, { 'default.caption_enabled': false, 'default.caption.thinking_enabled': true })
|
||||
} finally { f.dispose() }
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
for (const kbPipeline of ['default', 'smartocr']) {
|
||||
for (const attrsEnabled of [false, true]) {
|
||||
test(`legacy reparse override ${attrsEnabled} only retains parameters from ${kbPipeline} when the pipeline matches`, () => {
|
||||
const params = { 'default.caption.thinking_enabled': true }
|
||||
const f = fixture({
|
||||
vlm_config: { enabled: true, model_id: 'vlm' },
|
||||
image_processing_config: { image_pipeline: kbPipeline, image_pipeline_params: params },
|
||||
})
|
||||
try {
|
||||
f.vm.applyOverridesToState({ image_attrs_enabled: attrsEnabled })
|
||||
const result = JSON.parse(JSON.stringify(f.vm.buildProcessOverrides()))
|
||||
const pipeline = attrsEnabled ? 'smartocr' : 'default'
|
||||
assert.equal(result.image_pipeline, pipeline)
|
||||
assert.deepEqual(result.image_pipeline_params ?? {}, kbPipeline === pipeline ? params : {})
|
||||
} finally { f.dispose() }
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
test('reparse inherits KB parameters when the document has no pipeline selection', () => {
|
||||
const params = { 'default.caption_enabled': false }
|
||||
const f = fixture({
|
||||
vlm_config: { enabled: true, model_id: 'vlm' },
|
||||
image_processing_config: { image_pipeline: 'default', image_pipeline_params: params },
|
||||
})
|
||||
try {
|
||||
for (const overrides of [undefined, { summary_enabled: false }, { image_pipeline_params: { 'default.caption_enabled': true } }]) {
|
||||
f.vm.applyOverridesToState(overrides)
|
||||
assert.deepEqual(JSON.parse(JSON.stringify(f.vm.buildProcessOverrides().image_pipeline_params)), params)
|
||||
}
|
||||
} finally { f.dispose() }
|
||||
})
|
||||
@@ -0,0 +1,36 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
|
||||
import {
|
||||
DEFAULT_DOCUMENT_SORT,
|
||||
DOCUMENT_SORT_OPTIONS,
|
||||
getDocumentSortOption,
|
||||
getDocumentSortParams,
|
||||
} from './documentSorting';
|
||||
|
||||
test('文档排序默认使用创建时间倒序', () => {
|
||||
assert.equal(DEFAULT_DOCUMENT_SORT, 'created_desc');
|
||||
assert.deepEqual(getDocumentSortParams(DEFAULT_DOCUMENT_SORT), {
|
||||
sort_by: 'created_at',
|
||||
sort_order: 'desc',
|
||||
});
|
||||
});
|
||||
|
||||
test('文档排序提供三组共六个选项并映射到服务端白名单参数', () => {
|
||||
assert.equal(DOCUMENT_SORT_OPTIONS.length, 6);
|
||||
assert.deepEqual(
|
||||
DOCUMENT_SORT_OPTIONS.map(({ value, sortBy, sortOrder }) => [value, sortBy, sortOrder]),
|
||||
[
|
||||
['updated_desc', 'updated_at', 'desc'],
|
||||
['updated_asc', 'updated_at', 'asc'],
|
||||
['created_desc', 'created_at', 'desc'],
|
||||
['created_asc', 'created_at', 'asc'],
|
||||
['name_asc', 'file_name', 'asc'],
|
||||
['name_desc', 'file_name', 'desc'],
|
||||
],
|
||||
);
|
||||
});
|
||||
|
||||
test('未知排序值会安全回退到默认选项', () => {
|
||||
assert.equal(getDocumentSortOption('invalid' as never).value, DEFAULT_DOCUMENT_SORT);
|
||||
});
|
||||
@@ -0,0 +1,90 @@
|
||||
import type {
|
||||
KnowledgeListSortField,
|
||||
KnowledgeListSortOrder,
|
||||
} from '@/api/knowledge-base';
|
||||
|
||||
export type DocumentSortValue =
|
||||
| 'updated_desc'
|
||||
| 'updated_asc'
|
||||
| 'created_desc'
|
||||
| 'created_asc'
|
||||
| 'name_asc'
|
||||
| 'name_desc';
|
||||
|
||||
export interface DocumentSortOption {
|
||||
value: DocumentSortValue;
|
||||
sortBy: KnowledgeListSortField;
|
||||
sortOrder: KnowledgeListSortOrder;
|
||||
groupKey: 'updatedTime' | 'createdTime' | 'fileName';
|
||||
labelKey:
|
||||
| 'recentlyUpdated'
|
||||
| 'earliestUpdated'
|
||||
| 'newestCreated'
|
||||
| 'earliestCreated'
|
||||
| 'nameAscending'
|
||||
| 'nameDescending';
|
||||
}
|
||||
|
||||
export const DEFAULT_DOCUMENT_SORT: DocumentSortValue = 'created_desc';
|
||||
|
||||
export const DOCUMENT_SORT_OPTIONS: readonly DocumentSortOption[] = [
|
||||
{
|
||||
value: 'updated_desc',
|
||||
sortBy: 'updated_at',
|
||||
sortOrder: 'desc',
|
||||
groupKey: 'updatedTime',
|
||||
labelKey: 'recentlyUpdated',
|
||||
},
|
||||
{
|
||||
value: 'updated_asc',
|
||||
sortBy: 'updated_at',
|
||||
sortOrder: 'asc',
|
||||
groupKey: 'updatedTime',
|
||||
labelKey: 'earliestUpdated',
|
||||
},
|
||||
{
|
||||
value: 'created_desc',
|
||||
sortBy: 'created_at',
|
||||
sortOrder: 'desc',
|
||||
groupKey: 'createdTime',
|
||||
labelKey: 'newestCreated',
|
||||
},
|
||||
{
|
||||
value: 'created_asc',
|
||||
sortBy: 'created_at',
|
||||
sortOrder: 'asc',
|
||||
groupKey: 'createdTime',
|
||||
labelKey: 'earliestCreated',
|
||||
},
|
||||
{
|
||||
value: 'name_asc',
|
||||
sortBy: 'file_name',
|
||||
sortOrder: 'asc',
|
||||
groupKey: 'fileName',
|
||||
labelKey: 'nameAscending',
|
||||
},
|
||||
{
|
||||
value: 'name_desc',
|
||||
sortBy: 'file_name',
|
||||
sortOrder: 'desc',
|
||||
groupKey: 'fileName',
|
||||
labelKey: 'nameDescending',
|
||||
},
|
||||
];
|
||||
|
||||
export function getDocumentSortOption(value: DocumentSortValue): DocumentSortOption {
|
||||
return DOCUMENT_SORT_OPTIONS.find((option) => option.value === value)
|
||||
?? DOCUMENT_SORT_OPTIONS.find((option) => option.value === DEFAULT_DOCUMENT_SORT)
|
||||
?? DOCUMENT_SORT_OPTIONS[0];
|
||||
}
|
||||
|
||||
export function getDocumentSortParams(value: DocumentSortValue): {
|
||||
sort_by: KnowledgeListSortField;
|
||||
sort_order: KnowledgeListSortOrder;
|
||||
} {
|
||||
const option = getDocumentSortOption(value);
|
||||
return {
|
||||
sort_by: option.sortBy,
|
||||
sort_order: option.sortOrder,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,280 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import {
|
||||
buildFolderRows,
|
||||
buildUploadFileName,
|
||||
canMoveFolderTo,
|
||||
childFolders,
|
||||
folderAncestorPaths,
|
||||
folderBreadcrumbs,
|
||||
folderDocumentCounts,
|
||||
folderOptionFromPath,
|
||||
folderPathExists,
|
||||
isFilteringDocuments,
|
||||
isFolderUpload,
|
||||
joinFolderPath,
|
||||
MAX_FOLDER_DEPTH,
|
||||
MAX_FOLDER_PATH_LENGTH,
|
||||
MAX_FOLDER_SEGMENT_LENGTH,
|
||||
normalizeFolderPath,
|
||||
ROOT_FOLDER_PATH,
|
||||
sortFolderOptions,
|
||||
} from './folderTree.ts'
|
||||
|
||||
const folders = [
|
||||
{
|
||||
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 },
|
||||
]
|
||||
|
||||
const tree = { root_document_count: 2, total_document_count: 7, folders }
|
||||
|
||||
test('a plain single-file upload into the root sends no path-qualified name', () => {
|
||||
assert.equal(buildUploadFileName({ name: 'report.pdf' }, ROOT_FOLDER_PATH), 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' }, ''),
|
||||
'handbook/onboarding/day-one.md',
|
||||
)
|
||||
assert.equal(
|
||||
buildUploadFileName({ name: 'README.md', webkitRelativePath: 'handbook/README.md' }, ''),
|
||||
'handbook/README.md',
|
||||
)
|
||||
})
|
||||
|
||||
test('files land in the destination folder confirmed for the batch', () => {
|
||||
assert.equal(
|
||||
buildUploadFileName({ name: 'report.pdf' }, 'handbook/policies'),
|
||||
'handbook/policies/report.pdf',
|
||||
)
|
||||
})
|
||||
|
||||
test('a folder upload into a destination 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' },
|
||||
])
|
||||
// The root row needs no crumbs of its own.
|
||||
assert.deepEqual(folderBreadcrumbs(ROOT_FOLDER_PATH), [])
|
||||
})
|
||||
|
||||
test('ancestor paths always include the root so the tree opens down to the selection', () => {
|
||||
assert.deepEqual(folderAncestorPaths('a/b/c'), ['', 'a', 'a/b', 'a/b/c'])
|
||||
assert.deepEqual(folderAncestorPaths(ROOT_FOLDER_PATH), [''])
|
||||
})
|
||||
|
||||
test('the root always exists, other folders are looked up at any depth', () => {
|
||||
assert.equal(folderPathExists(folders, ROOT_FOLDER_PATH), true)
|
||||
assert.equal(folderPathExists([], ROOT_FOLDER_PATH), true)
|
||||
assert.equal(folderPathExists(folders, 'handbook/onboarding/day-one'), true)
|
||||
assert.equal(folderPathExists(folders, 'handbook/policies'), false)
|
||||
})
|
||||
|
||||
test('the root is the only row when it is collapsed', () => {
|
||||
const rows = buildFolderRows(tree, new Set())
|
||||
assert.equal(rows.length, 1)
|
||||
assert.equal(rows[0].kind, 'root')
|
||||
assert.equal(rows[0].path, ROOT_FOLDER_PATH)
|
||||
assert.equal(rows[0].hasChildren, true)
|
||||
})
|
||||
|
||||
test('top-level folders are children of the root, not its siblings', () => {
|
||||
const rows = buildFolderRows(tree, new Set([ROOT_FOLDER_PATH]))
|
||||
assert.deepEqual(
|
||||
rows.map((row) => [row.path, row.depth]),
|
||||
[
|
||||
['', 0],
|
||||
['handbook', 1],
|
||||
['design', 1],
|
||||
],
|
||||
)
|
||||
})
|
||||
|
||||
test('expanding nested folders indents each level one step deeper', () => {
|
||||
const rows = buildFolderRows(tree, new Set([ROOT_FOLDER_PATH, 'handbook', 'handbook/onboarding']))
|
||||
assert.deepEqual(
|
||||
rows.map((row) => [row.path, row.depth]),
|
||||
[
|
||||
['', 0],
|
||||
['handbook', 1],
|
||||
['handbook/onboarding', 2],
|
||||
['handbook/onboarding/day-one', 3],
|
||||
['design', 1],
|
||||
],
|
||||
)
|
||||
})
|
||||
|
||||
test('expanding a folder whose parent is collapsed keeps it hidden', () => {
|
||||
const rows = buildFolderRows(tree, new Set([ROOT_FOLDER_PATH, 'handbook/onboarding']))
|
||||
assert.deepEqual(rows.map((row) => row.path), ['', 'handbook', 'design'])
|
||||
})
|
||||
|
||||
test('a knowledge base without folders shows a root row with no toggle', () => {
|
||||
const rows = buildFolderRows({ root_document_count: 3, total_document_count: 3, folders: [] }, new Set([ROOT_FOLDER_PATH]))
|
||||
assert.equal(rows.length, 1)
|
||||
assert.equal(rows[0].hasChildren, false)
|
||||
})
|
||||
|
||||
test('an unloaded tree still yields a root row so the sidebar never renders empty', () => {
|
||||
const rows = buildFolderRows(null, new Set([ROOT_FOLDER_PATH]))
|
||||
assert.deepEqual(rows.map((row) => [row.kind, row.totalCount]), [['root', 0]])
|
||||
})
|
||||
|
||||
test('tree rows carry the recursive total, which is how much a folder contains', () => {
|
||||
const [root, handbook] = buildFolderRows(tree, new Set([ROOT_FOLDER_PATH]))
|
||||
assert.equal(root.totalCount, 7)
|
||||
assert.equal(handbook.totalCount, 4)
|
||||
assert.equal(handbook.documentCount, 1)
|
||||
})
|
||||
|
||||
// The breadcrumb and the empty state both report the folder's size, which is the
|
||||
// recursive total once connector-produced trees nest. `direct` stays available so
|
||||
// a caller can tell an empty folder from one whose documents live below it.
|
||||
test('folder counts separate a folder from its whole subtree', () => {
|
||||
assert.deepEqual(folderDocumentCounts(tree, ROOT_FOLDER_PATH), { direct: 2, total: 7 })
|
||||
assert.deepEqual(folderDocumentCounts(tree, 'handbook'), { direct: 1, total: 4 })
|
||||
assert.deepEqual(folderDocumentCounts(tree, 'handbook/onboarding'), { direct: 2, total: 3 })
|
||||
assert.deepEqual(folderDocumentCounts(tree, 'handbook/onboarding/day-one'), { direct: 1, total: 1 })
|
||||
|
||||
// A path that is no longer in the tree and an unloaded tree both leave the
|
||||
// caller to fall back to the document list it did load.
|
||||
assert.equal(folderDocumentCounts(tree, 'handbook/gone'), null)
|
||||
assert.equal(folderDocumentCounts(null, ROOT_FOLDER_PATH), null)
|
||||
assert.equal(folderDocumentCounts(null, 'handbook'), null)
|
||||
})
|
||||
|
||||
// The regression this guards: the deployed DingTalk tree has a folder whose
|
||||
// documents all sit one level down, so its direct count is 0. Reading that as
|
||||
// the folder's size made the sidebar and the empty state claim it was empty.
|
||||
test('a folder that only groups sub-folders still reports a total', () => {
|
||||
const grouped = {
|
||||
root_document_count: 0,
|
||||
total_document_count: 5,
|
||||
folders: [{
|
||||
path: '天诛渗透攻防',
|
||||
name: '天诛渗透攻防',
|
||||
document_count: 0,
|
||||
total_count: 5,
|
||||
children: [
|
||||
{ path: '天诛渗透攻防/FAQ', name: 'FAQ', document_count: 2, total_count: 2 },
|
||||
{ path: '天诛渗透攻防/售后', name: '售后', document_count: 2, total_count: 2 },
|
||||
{ path: '天诛渗透攻防/2024使用培训视频', name: '2024使用培训视频', document_count: 1, total_count: 1 },
|
||||
],
|
||||
}],
|
||||
}
|
||||
assert.deepEqual(folderDocumentCounts(grouped, '天诛渗透攻防'), { direct: 0, total: 5 })
|
||||
const counts = folderDocumentCounts(grouped, '天诛渗透攻防')!
|
||||
assert.equal(counts.total - counts.direct, 5, 'all five documents are below the folder')
|
||||
})
|
||||
|
||||
// Browsing a folder shows its own sub-folders as list entries, which is what
|
||||
// lets a document uploaded on its own simply sit at the top level next to the
|
||||
// folders instead of needing a mode switch to be found.
|
||||
test('the list shows the direct sub-folders of the browsed folder', () => {
|
||||
assert.deepEqual(
|
||||
childFolders(tree, ROOT_FOLDER_PATH).map((node) => node.path),
|
||||
['handbook', 'design'],
|
||||
)
|
||||
assert.deepEqual(
|
||||
childFolders(tree, 'handbook').map((node) => node.path),
|
||||
['handbook/onboarding'],
|
||||
)
|
||||
// A leaf folder and an unknown path both have nothing to descend into.
|
||||
assert.deepEqual(childFolders(tree, 'design'), [])
|
||||
assert.deepEqual(childFolders(tree, 'nope'), [])
|
||||
assert.deepEqual(childFolders(null, ROOT_FOLDER_PATH), [])
|
||||
})
|
||||
|
||||
// The browse/search distinction replaces the scope switch: it is derived from
|
||||
// what the user is already doing rather than from a control they must interpret.
|
||||
test('any active filter turns browsing into a subtree search', () => {
|
||||
assert.equal(isFilteringDocuments({}), false)
|
||||
assert.equal(isFilteringDocuments({ keyword: ' ' }), false, 'whitespace is not a search')
|
||||
assert.equal(isFilteringDocuments({ timeRange: [] }), false)
|
||||
assert.equal(isFilteringDocuments({ timeRange: ['', ''] }), false)
|
||||
|
||||
assert.equal(isFilteringDocuments({ keyword: 'spec' }), true)
|
||||
assert.equal(isFilteringDocuments({ tagIds: ['t1'] }), true)
|
||||
assert.equal(isFilteringDocuments({ fileType: 'pdf' }), true)
|
||||
assert.equal(isFilteringDocuments({ parseStatus: 'failed' }), true)
|
||||
assert.equal(isFilteringDocuments({ source: 'web' }), true)
|
||||
assert.equal(isFilteringDocuments({ timeRange: ['2026-01-01', ''] }), true)
|
||||
})
|
||||
|
||||
test('folder paths typed by the user are canonicalized like the server does', () => {
|
||||
assert.equal(normalizeFolderPath(' docs / spec '), 'docs/spec')
|
||||
assert.equal(normalizeFolderPath('docs//spec/'), 'docs/spec')
|
||||
assert.equal(normalizeFolderPath('../../docs'), 'docs')
|
||||
assert.equal(normalizeFolderPath('docs\\spec'), 'docs/spec')
|
||||
assert.equal(normalizeFolderPath('///'), '')
|
||||
assert.equal(joinFolderPath('handbook', 'policies '), 'handbook/policies')
|
||||
assert.equal(joinFolderPath('', 'handbook'), 'handbook')
|
||||
})
|
||||
|
||||
test('folder paths typed by the user respect the same depth and length caps as the server', () => {
|
||||
const deep = `${'a/'.repeat(MAX_FOLDER_DEPTH + 5)}a`
|
||||
const normalizedDeep = normalizeFolderPath(deep)
|
||||
assert.equal(normalizedDeep.split('/').filter(Boolean).length, MAX_FOLDER_DEPTH)
|
||||
|
||||
const longSegment = 'x'.repeat(MAX_FOLDER_SEGMENT_LENGTH + 50)
|
||||
assert.equal(normalizeFolderPath(longSegment).length, MAX_FOLDER_SEGMENT_LENGTH)
|
||||
|
||||
const wide = 'y'.repeat(100).concat('/').repeat(12).slice(0, -1)
|
||||
assert.ok(normalizeFolderPath(wide).length <= MAX_FOLDER_PATH_LENGTH)
|
||||
})
|
||||
|
||||
// Moving a folder into its own subtree would make that subtree unreachable.
|
||||
test('a folder cannot be moved inside itself', () => {
|
||||
assert.equal(canMoveFolderTo('docs', 'handbook'), true)
|
||||
assert.equal(canMoveFolderTo('docs', 'docsets'), true, 'a shared prefix is not containment')
|
||||
assert.equal(canMoveFolderTo('docs', 'docs/spec'), false)
|
||||
assert.equal(canMoveFolderTo('docs', 'docs'), false)
|
||||
assert.equal(canMoveFolderTo('docs', ''), false)
|
||||
assert.equal(canMoveFolderTo('', 'docs'), false)
|
||||
})
|
||||
|
||||
test('folderOptionFromPath derives picker row metadata from a canonical path', () => {
|
||||
assert.deepEqual(folderOptionFromPath('handbook/onboarding'), {
|
||||
path: 'handbook/onboarding',
|
||||
name: 'onboarding',
|
||||
depth: 1,
|
||||
})
|
||||
assert.deepEqual(
|
||||
sortFolderOptions([
|
||||
{ path: 'handbook/onboarding' },
|
||||
{ path: 'handbook' },
|
||||
{ path: 'archive' },
|
||||
]).map((row) => row.path),
|
||||
['archive', 'handbook', 'handbook/onboarding'],
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,307 @@
|
||||
import type { KnowledgeFolderNode, KnowledgeFolderTree } from '@/api/knowledge-base/index'
|
||||
|
||||
/**
|
||||
* Pure helpers behind the knowledge base folder sidebar.
|
||||
*
|
||||
* A folder selection is just a path, where the empty string is the knowledge
|
||||
* base root. The root is a real node of the tree — every top-level folder is
|
||||
* its child — so there is no separate "all documents" pseudo-row: what the root
|
||||
* row lists is decided by the same recursive switch as any other folder.
|
||||
*/
|
||||
export const ROOT_FOLDER_PATH = ''
|
||||
|
||||
/** Keep in sync with types.MaxKnowledgeFolderDepth on the server. */
|
||||
export const MAX_FOLDER_DEPTH = 16
|
||||
/** Keep in sync with types.MaxKnowledgeFolderSegmentLength on the server. */
|
||||
export const MAX_FOLDER_SEGMENT_LENGTH = 128
|
||||
/** Keep in sync with types.MaxKnowledgeFolderPathLength on the server. */
|
||||
export const MAX_FOLDER_PATH_LENGTH = 1024
|
||||
|
||||
/** Minimal shape of the browser File objects the upload flow deals with. */
|
||||
export type UploadFileLike = {
|
||||
name: string
|
||||
webkitRelativePath?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* A folder listed as a row or card in the document list. It is the subset of a
|
||||
* tree node the list needs: the path to navigate to and the two counts.
|
||||
*/
|
||||
export type FolderEntry = Pick<
|
||||
KnowledgeFolderNode,
|
||||
'path' | 'name' | 'document_count' | 'total_count'
|
||||
>
|
||||
|
||||
/**
|
||||
* One rendered row of the flattened tree. The root row carries the knowledge
|
||||
* base totals; the component supplies its label.
|
||||
*/
|
||||
export type FolderRow = {
|
||||
kind: 'root' | 'folder'
|
||||
path: string
|
||||
name: string
|
||||
depth: number
|
||||
/** Documents stored directly in this folder. */
|
||||
documentCount: number
|
||||
/** Documents in this folder plus every descendant folder. */
|
||||
totalCount: number
|
||||
hasChildren: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 destination folder
|
||||
* chosen for the batch and the browser's webkitRelativePath, whose picked
|
||||
* directory becomes a folder under that destination.
|
||||
*
|
||||
* Returns undefined for a plain single-file upload into the root so that request
|
||||
* stays byte-identical to the pre-folder behaviour.
|
||||
*/
|
||||
export function buildUploadFileName(
|
||||
file: UploadFileLike,
|
||||
targetFolder: string,
|
||||
): string | undefined {
|
||||
const segments: string[] = []
|
||||
if (targetFolder) segments.push(targetFolder)
|
||||
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.
|
||||
* The root has no crumbs of its own — callers render it as the leading item.
|
||||
*/
|
||||
export function folderBreadcrumbs(path: string): 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 root, the path itself and every folder in between, used to keep the
|
||||
* selected folder reachable by expanding the rows above it.
|
||||
*/
|
||||
export function folderAncestorPaths(path: string): string[] {
|
||||
const paths = [ROOT_FOLDER_PATH]
|
||||
if (!path) return paths
|
||||
const segments = path.split('/')
|
||||
segments.forEach((_, index) => paths.push(segments.slice(0, index + 1).join('/')))
|
||||
return paths
|
||||
}
|
||||
|
||||
/** Depth-first search for a folder path in the tree. The root always exists. */
|
||||
export function folderPathExists(folders: KnowledgeFolderNode[], path: string): boolean {
|
||||
if (path === ROOT_FOLDER_PATH) return true
|
||||
return folders.some((node) => node.path === path || folderPathExists(node.children || [], path))
|
||||
}
|
||||
|
||||
function flattenFolders(
|
||||
folders: KnowledgeFolderNode[],
|
||||
expanded: Set<string>,
|
||||
depth: number,
|
||||
): FolderRow[] {
|
||||
const rows: FolderRow[] = []
|
||||
folders.forEach((node) => {
|
||||
const hasChildren = !!node.children?.length
|
||||
rows.push({
|
||||
kind: 'folder',
|
||||
path: node.path,
|
||||
name: node.name,
|
||||
depth,
|
||||
documentCount: node.document_count,
|
||||
totalCount: node.total_count,
|
||||
hasChildren,
|
||||
})
|
||||
if (hasChildren && expanded.has(node.path)) {
|
||||
rows.push(...flattenFolders(node.children!, expanded, depth + 1))
|
||||
}
|
||||
})
|
||||
return rows
|
||||
}
|
||||
|
||||
/**
|
||||
* Flatten the tree into the visible rows: the root first, then the folders
|
||||
* nested beneath it, honouring the expanded set at every level.
|
||||
*/
|
||||
export function buildFolderRows(
|
||||
tree: KnowledgeFolderTree | null,
|
||||
expanded: Set<string>,
|
||||
): FolderRow[] {
|
||||
const folders = tree?.folders ?? []
|
||||
const root: FolderRow = {
|
||||
kind: 'root',
|
||||
path: ROOT_FOLDER_PATH,
|
||||
name: '',
|
||||
depth: 0,
|
||||
documentCount: tree?.root_document_count ?? 0,
|
||||
totalCount: tree?.total_document_count ?? 0,
|
||||
hasChildren: folders.length > 0,
|
||||
}
|
||||
if (!root.hasChildren || !expanded.has(ROOT_FOLDER_PATH)) return [root]
|
||||
return [root, ...flattenFolders(folders, expanded, 1)]
|
||||
}
|
||||
|
||||
/** Depth-first lookup of one folder node anywhere in the tree. */
|
||||
function findFolderNode(
|
||||
folders: KnowledgeFolderNode[],
|
||||
path: string,
|
||||
): KnowledgeFolderNode | undefined {
|
||||
for (const node of folders) {
|
||||
if (node.path === path) return node
|
||||
const found = findFolderNode(node.children || [], path)
|
||||
if (found) return found
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Direct sub-folders of a folder: the rows the sidebar tree renders underneath
|
||||
* it. The root's children are the top-level folders.
|
||||
*/
|
||||
export function childFolders(
|
||||
tree: KnowledgeFolderTree | null,
|
||||
path: string,
|
||||
): KnowledgeFolderNode[] {
|
||||
const folders = tree?.folders ?? []
|
||||
if (path === ROOT_FOLDER_PATH) return folders
|
||||
return findFolderNode(folders, path)?.children ?? []
|
||||
}
|
||||
|
||||
/**
|
||||
* How many documents a folder holds: the ones stored directly in it, and the
|
||||
* ones in its whole subtree. Returns null when the tree is unavailable or the
|
||||
* path is not in it, so callers can fall back to the loaded document list.
|
||||
*
|
||||
* The two numbers differ as soon as folders nest: a parent that only groups
|
||||
* sub-folders has 0 direct documents but a non-zero total, and showing the
|
||||
* direct count there reads as "empty".
|
||||
*/
|
||||
export function folderDocumentCounts(
|
||||
tree: KnowledgeFolderTree | null,
|
||||
path: string,
|
||||
): { direct: number; total: number } | null {
|
||||
if (!tree) return null
|
||||
if (path === ROOT_FOLDER_PATH) {
|
||||
return { direct: tree.root_document_count ?? 0, total: tree.total_document_count ?? 0 }
|
||||
}
|
||||
const node = findFolderNode(tree.folders ?? [], path)
|
||||
if (!node) return null
|
||||
return { direct: node.document_count ?? 0, total: node.total_count ?? 0 }
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the document list is filtering rather than browsing.
|
||||
*
|
||||
* This is the single input that decides how a folder selection is read, and it
|
||||
* comes from what the user is already doing instead of from a mode switch they
|
||||
* have to understand:
|
||||
*
|
||||
* - Browsing (no filter active) lists the selected folder's own contents — its
|
||||
* sub-folders as entries plus the documents directly inside it, the way a file
|
||||
* manager does. A document uploaded on its own therefore sits at the top level
|
||||
* next to the folders, which is exactly where it belongs.
|
||||
* - Filtering searches the selected folder and everything below it, returning a
|
||||
* flat result set, because a search that stopped at one level would hide
|
||||
* matches for no good reason.
|
||||
*/
|
||||
export function isFilteringDocuments(filters: {
|
||||
keyword?: string
|
||||
tagIds?: string[]
|
||||
fileType?: string
|
||||
parseStatus?: string
|
||||
source?: string
|
||||
timeRange?: string[]
|
||||
}): boolean {
|
||||
return !!(
|
||||
filters.keyword?.trim() ||
|
||||
filters.tagIds?.length ||
|
||||
filters.fileType ||
|
||||
filters.parseStatus ||
|
||||
filters.source ||
|
||||
filters.timeRange?.filter(Boolean).length
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Canonicalize a user-typed folder path the same way the server does, so the
|
||||
* move dialog can preview and compare the destination it is about to send.
|
||||
*/
|
||||
export function normalizeFolderPath(path: string): string {
|
||||
const segments: string[] = []
|
||||
for (const raw of path.replace(/\\/g, '/').split('/')) {
|
||||
let segment = raw.trim().replace(/[. ]+$/, '')
|
||||
if (!segment || segment === '.' || segment === '..') continue
|
||||
if (segment.length > MAX_FOLDER_SEGMENT_LENGTH) {
|
||||
segment = segment.slice(0, MAX_FOLDER_SEGMENT_LENGTH).trim()
|
||||
}
|
||||
if (!segment) continue
|
||||
segments.push(segment)
|
||||
if (segments.length >= MAX_FOLDER_DEPTH) break
|
||||
}
|
||||
let normalized = segments.join('/')
|
||||
while (normalized.length > MAX_FOLDER_PATH_LENGTH && segments.length > 0) {
|
||||
segments.pop()
|
||||
normalized = segments.join('/')
|
||||
}
|
||||
return normalized
|
||||
}
|
||||
|
||||
/** Destination path for a new sub-folder of `parent`. */
|
||||
export function joinFolderPath(parent: string, name: string): string {
|
||||
return normalizeFolderPath(parent ? `${parent}/${name}` : name)
|
||||
}
|
||||
|
||||
/** Flat picker row for a canonical folder path (used for optimistic create rows). */
|
||||
export function folderOptionFromPath(path: string): { path: string; name: string; depth: number } {
|
||||
const segments = path.split('/').filter(Boolean)
|
||||
return {
|
||||
path,
|
||||
name: segments[segments.length - 1] || path,
|
||||
depth: Math.max(segments.length - 1, 0),
|
||||
}
|
||||
}
|
||||
|
||||
/** Sort folder picker rows in tree order (parent before child, siblings lexicographic). */
|
||||
export function sortFolderOptions<T extends { path: string }>(options: T[]): T[] {
|
||||
return [...options].sort((a, b) => {
|
||||
const aParts = a.path.split('/').filter(Boolean)
|
||||
const bParts = b.path.split('/').filter(Boolean)
|
||||
const max = Math.max(aParts.length, bParts.length)
|
||||
for (let i = 0; i < max; i += 1) {
|
||||
const aSeg = aParts[i]
|
||||
const bSeg = bParts[i]
|
||||
if (aSeg === undefined) return -1
|
||||
if (bSeg === undefined) return 1
|
||||
const cmp = aSeg.localeCompare(bSeg)
|
||||
if (cmp !== 0) return cmp
|
||||
}
|
||||
return 0
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a folder can be renamed/moved to `to`: a folder cannot land inside its
|
||||
* own subtree, which would make that subtree unreachable.
|
||||
*/
|
||||
export function canMoveFolderTo(from: string, to: string): boolean {
|
||||
const source = normalizeFolderPath(from)
|
||||
const target = normalizeFolderPath(to)
|
||||
if (!source || !target) return false
|
||||
if (target === source) return false
|
||||
return !target.startsWith(`${source}/`)
|
||||
}
|
||||
@@ -0,0 +1,411 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { MessagePlugin } from 'tdesign-vue-next'
|
||||
import { listKnowledgeFiles } from '@/api/knowledge-base'
|
||||
|
||||
// GallerySourcePicker is the "filter by source document" panel of the image
|
||||
// gallery, rendered inside the toolbar popup next to the filter and sort
|
||||
// panels: a keyword-searchable checkbox list of the knowledge base's
|
||||
// documents, newest uploads first, loaded page by page as it scrolls. Like the
|
||||
// filter panel, every tick applies at once (an empty selection clears the
|
||||
// restriction).
|
||||
//
|
||||
// Overflow guards: a KB with a huge document count must neither flood the
|
||||
// panel nor produce an unbounded gallery query. Without a keyword only the
|
||||
// most recent RECENT_WINDOW documents are listed; a keyword hit list beyond
|
||||
// SAFE_HITS cannot be select-all-ed (the user is asked to narrow the
|
||||
// keyword), which also keeps one select-all fetch within the backend's
|
||||
// page_size ceiling — the same 1000 the POST /images body cap enforces.
|
||||
const props = defineProps<{
|
||||
kbId: string
|
||||
visible: boolean
|
||||
selected: string[]
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'update:selected', knowledgeIds: string[]): void
|
||||
}>()
|
||||
|
||||
const NS = 'knowledgeEditor.wikiBrowser.gallery'
|
||||
const { t } = useI18n()
|
||||
|
||||
const PAGE_SIZE = 30
|
||||
const RECENT_WINDOW = 500
|
||||
const SAFE_HITS = 1000
|
||||
const SEARCH_DEBOUNCE_MS = 300
|
||||
const LOAD_AHEAD_PX = 80
|
||||
|
||||
const keyword = ref('')
|
||||
const page = ref(0)
|
||||
const total = ref(0)
|
||||
const loading = ref(false)
|
||||
const bulkLoading = ref(false)
|
||||
// Documents loaded so far for the current keyword.
|
||||
const docs = ref<Array<{ id: string; file_name: string; created_at: string }>>([])
|
||||
const listEl = ref<HTMLElement | null>(null)
|
||||
|
||||
const selectedSet = computed(() => new Set(props.selected))
|
||||
|
||||
// How many documents the listing actually offers: the raw total, capped to
|
||||
// the window the overflow guards allow for the current search state.
|
||||
const shownTotal = computed(() => {
|
||||
if (keyword.value.trim()) return Math.min(total.value, SAFE_HITS)
|
||||
return Math.min(total.value, RECENT_WINDOW)
|
||||
})
|
||||
const overflown = computed(() => total.value > shownTotal.value)
|
||||
const hasMore = computed(() => docs.value.length < shownTotal.value)
|
||||
// Select-all needs the full hit list in one fetch, so it is only offered
|
||||
// while the current listing is fully enumerable.
|
||||
const canSelectAll = computed(() => !overflown.value && shownTotal.value > 0)
|
||||
|
||||
const loadedAllSelected = computed(
|
||||
() => docs.value.length > 0 && docs.value.every((d) => selectedSet.value.has(d.id)),
|
||||
)
|
||||
const loadedSomeSelected = computed(() => docs.value.some((d) => selectedSet.value.has(d.id)))
|
||||
|
||||
// Bumped by every keyword change, so a response for an older search state
|
||||
// (page fetch or select-all) is dropped.
|
||||
let fetchToken = 0
|
||||
async function loadPage(reset: boolean) {
|
||||
if (!props.kbId) return
|
||||
if (reset) {
|
||||
fetchToken++
|
||||
page.value = 0
|
||||
docs.value = []
|
||||
total.value = 0
|
||||
listEl.value?.scrollTo({ top: 0 })
|
||||
}
|
||||
const token = fetchToken
|
||||
const nextPage = page.value + 1
|
||||
loading.value = true
|
||||
try {
|
||||
const res: any = await listKnowledgeFiles(props.kbId, {
|
||||
page: nextPage,
|
||||
page_size: PAGE_SIZE,
|
||||
keyword: keyword.value.trim() || undefined,
|
||||
sort_by: 'created_at',
|
||||
sort_order: 'desc',
|
||||
})
|
||||
if (token !== fetchToken) return
|
||||
const known = new Set(docs.value.map((d) => d.id))
|
||||
const items: any[] = res?.data ?? []
|
||||
for (const it of items) {
|
||||
const id = String(it.id)
|
||||
if (known.has(id)) continue
|
||||
docs.value.push({ id, file_name: it.file_name || it.title || id, created_at: it.created_at || '' })
|
||||
}
|
||||
page.value = nextPage
|
||||
total.value = items.length ? Number(res?.total) || 0 : docs.value.length
|
||||
} catch (_) {
|
||||
if (token === fetchToken && reset) total.value = 0
|
||||
} finally {
|
||||
if (token === fetchToken) loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function onListScroll() {
|
||||
const el = listEl.value
|
||||
if (!el || loading.value || !hasMore.value) return
|
||||
if (el.scrollTop + el.clientHeight >= el.scrollHeight - LOAD_AHEAD_PX) void loadPage(false)
|
||||
}
|
||||
|
||||
let searchTimer: ReturnType<typeof setTimeout> | undefined
|
||||
function cancelSearch() {
|
||||
if (searchTimer) clearTimeout(searchTimer)
|
||||
searchTimer = undefined
|
||||
}
|
||||
|
||||
watch(
|
||||
() => props.visible,
|
||||
(open) => {
|
||||
cancelSearch()
|
||||
if (!open) return
|
||||
keyword.value = ''
|
||||
void loadPage(true)
|
||||
},
|
||||
{ immediate: true },
|
||||
)
|
||||
|
||||
function onKeywordChange(value: string) {
|
||||
keyword.value = value
|
||||
cancelSearch()
|
||||
searchTimer = setTimeout(() => void loadPage(true), SEARCH_DEBOUNCE_MS)
|
||||
}
|
||||
|
||||
function commit(next: Set<string>): boolean {
|
||||
if (next.size > SAFE_HITS) {
|
||||
MessagePlugin.warning(t(`${NS}.sourceFilterTooMany`))
|
||||
return false
|
||||
}
|
||||
emit('update:selected', Array.from(next))
|
||||
return true
|
||||
}
|
||||
|
||||
function toggle(id: string, checked: boolean) {
|
||||
const next = new Set(props.selected)
|
||||
if (checked) next.add(id)
|
||||
else next.delete(id)
|
||||
commit(next)
|
||||
}
|
||||
|
||||
// Header checkbox, across every hit of the current search (the guards above
|
||||
// keep one fetch within the backend's page_size ceiling): drops the hits when
|
||||
// all of them are already selected, adds them otherwise. Merged into the
|
||||
// selection so earlier keywords survive.
|
||||
async function onToggleAll() {
|
||||
if (!canSelectAll.value || bulkLoading.value) return
|
||||
const token = fetchToken
|
||||
bulkLoading.value = true
|
||||
try {
|
||||
const res: any = await listKnowledgeFiles(props.kbId, {
|
||||
page: 1,
|
||||
page_size: SAFE_HITS,
|
||||
keyword: keyword.value.trim() || undefined,
|
||||
sort_by: 'created_at',
|
||||
sort_order: 'desc',
|
||||
})
|
||||
if (token !== fetchToken) return
|
||||
const ids: string[] = (res?.data ?? []).map((it: any) => String(it.id))
|
||||
if (!ids.length) return
|
||||
const next = new Set(props.selected)
|
||||
if (ids.every((id) => next.has(id))) {
|
||||
for (const id of ids) next.delete(id)
|
||||
} else {
|
||||
for (const id of ids) next.add(id)
|
||||
}
|
||||
commit(next)
|
||||
} catch (_) {
|
||||
// keep the selection untouched on failure
|
||||
} finally {
|
||||
bulkLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function onClear() {
|
||||
emit('update:selected', [])
|
||||
}
|
||||
|
||||
const pad = (n: number) => String(n).padStart(2, '0')
|
||||
|
||||
function formatDate(raw: string): string {
|
||||
if (!raw) return ''
|
||||
const d = new Date(raw)
|
||||
if (Number.isNaN(d.getTime())) return raw
|
||||
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`
|
||||
}
|
||||
|
||||
function formatTime(raw: string): string {
|
||||
if (!raw) return ''
|
||||
const d = new Date(raw)
|
||||
if (Number.isNaN(d.getTime())) return raw
|
||||
return `${formatDate(raw)} ${pad(d.getHours())}:${pad(d.getMinutes())}`
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="gsp-panel" :aria-label="t(`${NS}.sourceFilterTitle`)">
|
||||
<header class="gsp-panel__header">
|
||||
<strong>{{ t(`${NS}.sourceFilterTitle`) }}</strong>
|
||||
<button type="button" :disabled="!props.selected.length" @click="onClear">
|
||||
{{ t(`${NS}.sourceFilterClear`) }}
|
||||
</button>
|
||||
</header>
|
||||
<div class="gsp-panel__hint">{{ t(`${NS}.sourceFilterSubtitle`) }}</div>
|
||||
|
||||
<t-input
|
||||
:value="keyword"
|
||||
clearable
|
||||
:placeholder="t(`${NS}.sourceFilterSearch`)"
|
||||
:aria-label="t(`${NS}.sourceFilterSearch`)"
|
||||
class="gsp-search"
|
||||
@change="(v: string) => onKeywordChange(String(v ?? ''))"
|
||||
>
|
||||
<template #prefix-icon><t-icon name="search" size="16px" /></template>
|
||||
</t-input>
|
||||
|
||||
<div v-if="overflown" class="gsp-overflow-hint" role="status">
|
||||
<t-icon name="info-circle" size="14px" />
|
||||
<span>
|
||||
{{
|
||||
keyword.trim()
|
||||
? t(`${NS}.sourceFilterOverflowHits`, { total: total, cap: shownTotal })
|
||||
: t(`${NS}.sourceFilterOverflowRecent`, { cap: shownTotal })
|
||||
}}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="gsp-bar">
|
||||
<t-checkbox
|
||||
:checked="loadedAllSelected"
|
||||
:indeterminate="loadedSomeSelected && !loadedAllSelected"
|
||||
:disabled="!canSelectAll || bulkLoading"
|
||||
:title="canSelectAll ? t(`${NS}.sourceFilterSelectAll`) : undefined"
|
||||
@change="onToggleAll"
|
||||
>
|
||||
{{ t('common.selectAll') }}
|
||||
</t-checkbox>
|
||||
<span class="gsp-bar__count">{{ t(`${NS}.sourceFilterSelected`, { count: props.selected.length }) }}</span>
|
||||
</div>
|
||||
|
||||
<div ref="listEl" class="gsp-list" @scroll.passive="onListScroll">
|
||||
<div
|
||||
v-for="d in docs"
|
||||
:key="d.id"
|
||||
class="gsp-item"
|
||||
:class="{ 'is-selected': selectedSet.has(d.id) }"
|
||||
:title="`${d.file_name}${d.created_at ? ' · ' + formatTime(d.created_at) : ''}`"
|
||||
@click="toggle(d.id, !selectedSet.has(d.id))"
|
||||
>
|
||||
<span class="gsp-item__check" @click.stop>
|
||||
<t-checkbox
|
||||
:checked="selectedSet.has(d.id)"
|
||||
@change="(checked: boolean) => toggle(d.id, checked)"
|
||||
/>
|
||||
</span>
|
||||
<span class="gsp-item__name">{{ d.file_name }}</span>
|
||||
<span class="gsp-item__time">{{ formatDate(d.created_at) }}</span>
|
||||
</div>
|
||||
<div v-if="loading || bulkLoading" class="gsp-list__status">
|
||||
<t-loading size="small" />
|
||||
</div>
|
||||
<div v-else-if="!docs.length" class="gsp-list__status">
|
||||
{{ t(`${NS}.sourceFilterEmpty`) }}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped lang="less">
|
||||
// Same frame and type scale as the gallery's filter panel.
|
||||
.gsp-panel {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
width: 360px;
|
||||
max-width: calc(100vw - 32px);
|
||||
padding: 16px;
|
||||
box-sizing: border-box;
|
||||
color: var(--td-text-color-primary);
|
||||
font-size: var(--app-text-md);
|
||||
|
||||
&__header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
|
||||
strong {
|
||||
font-size: var(--app-text-base);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
button {
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: var(--td-text-color-secondary);
|
||||
font: inherit;
|
||||
font-size: var(--app-text-sm);
|
||||
cursor: pointer;
|
||||
|
||||
&:hover:not(:disabled) { color: var(--td-brand-color); }
|
||||
&:disabled { color: var(--td-text-color-disabled); cursor: default; }
|
||||
}
|
||||
}
|
||||
|
||||
&__hint {
|
||||
margin: 2px 0 12px;
|
||||
color: var(--td-text-color-placeholder);
|
||||
font-size: var(--app-text-xs);
|
||||
line-height: 17px;
|
||||
}
|
||||
}
|
||||
|
||||
.gsp-search :deep(.t-input) {
|
||||
border-color: var(--td-component-stroke);
|
||||
border-radius: var(--app-radius-md);
|
||||
font-size: var(--app-text-md);
|
||||
}
|
||||
|
||||
.gsp-overflow-hint {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 6px;
|
||||
margin-top: 8px;
|
||||
color: var(--td-warning-color);
|
||||
font-size: var(--app-text-xs);
|
||||
line-height: 17px;
|
||||
|
||||
.t-icon {
|
||||
flex-shrink: 0;
|
||||
margin-top: 2px;
|
||||
}
|
||||
}
|
||||
|
||||
.gsp-bar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
margin-top: 12px;
|
||||
padding: 0 8px 8px;
|
||||
border-bottom: 1px solid var(--td-component-stroke);
|
||||
|
||||
&__count {
|
||||
color: var(--td-text-color-placeholder);
|
||||
font-size: var(--app-text-sm);
|
||||
font-variant-numeric: tabular-nums;
|
||||
white-space: nowrap;
|
||||
}
|
||||
}
|
||||
|
||||
.gsp-list {
|
||||
max-height: 288px;
|
||||
min-height: 96px;
|
||||
margin: 4px -8px 0;
|
||||
padding: 0 8px;
|
||||
overflow-y: auto;
|
||||
|
||||
&__status {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
padding: 16px 0;
|
||||
color: var(--td-text-color-placeholder);
|
||||
font-size: var(--app-text-sm);
|
||||
}
|
||||
}
|
||||
|
||||
.gsp-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
height: 32px;
|
||||
padding: 0 8px;
|
||||
border-radius: var(--app-radius-sm);
|
||||
cursor: pointer;
|
||||
transition: background-color var(--app-motion-fast) ease;
|
||||
|
||||
&:hover { background: var(--td-bg-color-secondarycontainer); }
|
||||
|
||||
&__check {
|
||||
display: flex;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
&__name {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
&__time {
|
||||
flex-shrink: 0;
|
||||
color: var(--td-text-color-placeholder);
|
||||
font-size: var(--app-text-xs);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
&.is-selected .gsp-item__name { color: var(--td-brand-color); }
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,980 @@
|
||||
<script setup lang="ts">
|
||||
import { fmtBeijingTime } from '@/utils/datetime'
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, ref, useId, watch } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import type { ImageAsset } from '@/api/image-gallery'
|
||||
import { copyWithToast } from '@/utils/clipboard'
|
||||
import { renderDocumentPreviewMarkdown } from '@/utils/documentPreviewMarkdown'
|
||||
|
||||
export interface GalleryAttrRow {
|
||||
key: string
|
||||
label: string
|
||||
value: string
|
||||
}
|
||||
|
||||
const props = defineProps<{
|
||||
/** The loaded images; the viewer walks them in order. */
|
||||
items: ImageAsset[]
|
||||
index: number
|
||||
total: number
|
||||
/** More images are being fetched; navigation waits for them. */
|
||||
loading: boolean
|
||||
thumbUrls: Record<string, string>
|
||||
resolveSrc: (url: string) => Promise<string>
|
||||
attrRows: (img: ImageAsset) => GalleryAttrRow[]
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'close'): void
|
||||
(e: 'select', index: number): void
|
||||
/** Step past the loaded edge; the gallery loads more images. */
|
||||
(e: 'load-more'): void
|
||||
(e: 'open-source', knowledgeId: string): void
|
||||
}>()
|
||||
|
||||
const NS = 'knowledgeEditor.wikiBrowser.gallery'
|
||||
const { t, locale } = useI18n()
|
||||
|
||||
const current = computed<ImageAsset | null>(() => props.items[props.index] ?? null)
|
||||
const position = computed(() => props.index + 1)
|
||||
const hasPrev = computed(() => position.value > 1)
|
||||
const hasNext = computed(() => position.value < props.total)
|
||||
|
||||
function prev(): void {
|
||||
if (props.loading || !hasPrev.value) return
|
||||
emit('select', props.index - 1)
|
||||
}
|
||||
|
||||
function next(): void {
|
||||
if (props.loading || !hasNext.value) return
|
||||
if (props.index < props.items.length - 1) emit('select', props.index + 1)
|
||||
else emit('load-more')
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Zoom, pan and rotation. Scale 1 is "fit to the stage"; the translation is
|
||||
// kept relative to the stage centre so zooming can anchor on the cursor.
|
||||
// ---------------------------------------------------------------------------
|
||||
const MIN_SCALE = 0.2
|
||||
const MAX_SCALE = 8
|
||||
const scale = ref(1)
|
||||
const rotation = ref(0)
|
||||
const tx = ref(0)
|
||||
const ty = ref(0)
|
||||
const dragging = ref(false)
|
||||
|
||||
function resetView(): void {
|
||||
scale.value = 1
|
||||
rotation.value = 0
|
||||
tx.value = 0
|
||||
ty.value = 0
|
||||
}
|
||||
|
||||
function zoomTo(target: number, anchor?: { x: number; y: number }): void {
|
||||
const next = Math.min(MAX_SCALE, Math.max(MIN_SCALE, target))
|
||||
const k = next / scale.value
|
||||
const ax = anchor?.x ?? 0
|
||||
const ay = anchor?.y ?? 0
|
||||
tx.value = ax - (ax - tx.value) * k
|
||||
ty.value = ay - (ay - ty.value) * k
|
||||
scale.value = next
|
||||
// Nothing to pan once the image fits again; re-centre it.
|
||||
if (next <= fitScale()) {
|
||||
tx.value = 0
|
||||
ty.value = 0
|
||||
}
|
||||
}
|
||||
|
||||
/** The scale at which the (possibly rotated) image fits the stage. */
|
||||
function fitScale(): number {
|
||||
const img = imgEl.value
|
||||
const stage = stageEl.value
|
||||
if (!img || !stage || rotation.value % 180 === 0) return 1
|
||||
const w = img.clientWidth
|
||||
const h = img.clientHeight
|
||||
if (!w || !h) return 1
|
||||
const style = getComputedStyle(stage)
|
||||
const boxW = stage.clientWidth - parseFloat(style.paddingLeft) - parseFloat(style.paddingRight)
|
||||
const boxH = stage.clientHeight - parseFloat(style.paddingTop) - parseFloat(style.paddingBottom)
|
||||
return Math.min(1, boxW / h, boxH / w)
|
||||
}
|
||||
|
||||
/** The scale at which one image pixel is one screen pixel. */
|
||||
function actualScale(): number {
|
||||
const img = imgEl.value
|
||||
if (!img || !natural.value || !img.clientWidth) return 1
|
||||
return natural.value.w / img.clientWidth
|
||||
}
|
||||
|
||||
function anchorOf(e: { clientX: number; clientY: number }): { x: number; y: number } {
|
||||
const rect = stageEl.value?.getBoundingClientRect()
|
||||
if (!rect) return { x: 0, y: 0 }
|
||||
return { x: e.clientX - rect.left - rect.width / 2, y: e.clientY - rect.top - rect.height / 2 }
|
||||
}
|
||||
|
||||
const zoomIn = () => zoomTo(scale.value * 1.25)
|
||||
const zoomOut = () => zoomTo(scale.value / 1.25)
|
||||
const zoomActual = () => zoomTo(actualScale())
|
||||
|
||||
function rotate(): void {
|
||||
rotation.value = (rotation.value + 90) % 360
|
||||
tx.value = 0
|
||||
ty.value = 0
|
||||
scale.value = fitScale()
|
||||
}
|
||||
|
||||
function onWheel(e: WheelEvent): void {
|
||||
if (!loaded.value) return
|
||||
zoomTo(scale.value * Math.exp(-e.deltaY * 0.002), anchorOf(e))
|
||||
}
|
||||
|
||||
function onDblClick(e: MouseEvent): void {
|
||||
if (!loaded.value) return
|
||||
if (Math.abs(scale.value - fitScale()) > 0.01) {
|
||||
resetView()
|
||||
scale.value = fitScale()
|
||||
} else {
|
||||
zoomTo(Math.max(2, actualScale()), anchorOf(e))
|
||||
}
|
||||
}
|
||||
|
||||
let dragStart: { x: number; y: number; tx: number; ty: number } | null = null
|
||||
|
||||
function onPointerDown(e: PointerEvent): void {
|
||||
if (e.button !== 0 || !loaded.value || scale.value <= fitScale()) return
|
||||
dragStart = { x: e.clientX, y: e.clientY, tx: tx.value, ty: ty.value }
|
||||
dragging.value = true
|
||||
;(e.currentTarget as HTMLElement).setPointerCapture(e.pointerId)
|
||||
}
|
||||
|
||||
function onPointerMove(e: PointerEvent): void {
|
||||
if (!dragStart) return
|
||||
tx.value = dragStart.tx + e.clientX - dragStart.x
|
||||
ty.value = dragStart.ty + e.clientY - dragStart.y
|
||||
}
|
||||
|
||||
function onPointerUp(): void {
|
||||
dragStart = null
|
||||
dragging.value = false
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Source resolution. The <img> is rendered only once a displayable source is
|
||||
// in hand: a raw storage handle would fire the error handler and mask the
|
||||
// image that is still being fetched. The token keeps a slow fetch from
|
||||
// overwriting a faster one that navigated past it.
|
||||
// ---------------------------------------------------------------------------
|
||||
const src = ref('')
|
||||
const loaded = ref(false)
|
||||
const failed = ref(false)
|
||||
const natural = ref<{ w: number; h: number } | null>(null)
|
||||
let srcToken = 0
|
||||
|
||||
watch(
|
||||
() => current.value?.url,
|
||||
async (url) => {
|
||||
const token = ++srcToken
|
||||
resetView()
|
||||
src.value = ''
|
||||
loaded.value = false
|
||||
failed.value = false
|
||||
natural.value = null
|
||||
if (!url) return
|
||||
const resolved = await props.resolveSrc(url)
|
||||
if (token !== srcToken) return
|
||||
src.value = resolved
|
||||
},
|
||||
{ immediate: true },
|
||||
)
|
||||
|
||||
const imgEl = ref<HTMLImageElement | null>(null)
|
||||
const stageEl = ref<HTMLElement | null>(null)
|
||||
|
||||
function onImgLoad(): void {
|
||||
loaded.value = true
|
||||
const el = imgEl.value
|
||||
if (el) natural.value = { w: el.naturalWidth, h: el.naturalHeight }
|
||||
}
|
||||
|
||||
function onImgError(): void {
|
||||
failed.value = true
|
||||
}
|
||||
|
||||
const canPan = computed(() => loaded.value && scale.value > 1)
|
||||
const zoomPercent = computed(() => `${Math.round(scale.value * 100)}%`)
|
||||
const imgStyle = computed(() => ({
|
||||
transform: `translate(${tx.value}px, ${ty.value}px) rotate(${rotation.value}deg) scale(${scale.value})`,
|
||||
}))
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Actions
|
||||
// ---------------------------------------------------------------------------
|
||||
const EXT_BY_TYPE: Record<string, string> = {
|
||||
'image/png': 'png',
|
||||
'image/jpeg': 'jpg',
|
||||
'image/gif': 'gif',
|
||||
'image/webp': 'webp',
|
||||
'image/svg+xml': 'svg',
|
||||
'image/bmp': 'bmp',
|
||||
}
|
||||
|
||||
function downloadName(img: ImageAsset, type: string): string {
|
||||
const base = (img.source_name || 'image').replace(/\.[^./\\]+$/, '').replace(/[\\/:*?"<>|]+/g, '_')
|
||||
const fromUrl = /\.([a-z0-9]{2,5})(?:$|[?#])/i.exec(img.url)?.[1]
|
||||
const ext = EXT_BY_TYPE[type] || fromUrl || 'png'
|
||||
return `${base}-${position.value}.${ext}`
|
||||
}
|
||||
|
||||
async function download(): Promise<void> {
|
||||
const img = current.value
|
||||
if (!img || !src.value) return
|
||||
try {
|
||||
const blob = await (await fetch(src.value)).blob()
|
||||
const url = URL.createObjectURL(blob)
|
||||
const a = document.createElement('a')
|
||||
a.href = url
|
||||
a.download = downloadName(img, blob.type)
|
||||
a.click()
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1000)
|
||||
} catch {
|
||||
// A cross-origin image the browser may not read back: let it open instead.
|
||||
openOriginal()
|
||||
}
|
||||
}
|
||||
|
||||
function openOriginal(): void {
|
||||
if (src.value) window.open(src.value, '_blank', 'noopener')
|
||||
}
|
||||
|
||||
const copyText = (text: string) => copyWithToast(text, 'common.copySuccess')
|
||||
|
||||
// The info panel is a per-viewer preference; storage may be unavailable.
|
||||
const INFO_KEY = 'weknora_gallery_viewer_info'
|
||||
function readInfoPref(): boolean {
|
||||
try {
|
||||
return localStorage.getItem(INFO_KEY) !== '0'
|
||||
} catch {
|
||||
return true
|
||||
}
|
||||
}
|
||||
const showInfo = ref(readInfoPref())
|
||||
function toggleInfo(): void {
|
||||
showInfo.value = !showInfo.value
|
||||
try {
|
||||
localStorage.setItem(INFO_KEY, showInfo.value ? '1' : '0')
|
||||
} catch {
|
||||
// Not remembered this time; the toggle itself still works.
|
||||
}
|
||||
}
|
||||
|
||||
const attrs = computed(() => (current.value ? props.attrRows(current.value) : []))
|
||||
const captionHtml = computed(() => renderDocumentPreviewMarkdown(current.value?.caption || ''))
|
||||
const ocrHtml = computed(() => renderDocumentPreviewMarkdown(current.value?.ocr_text || ''))
|
||||
const sectionId = useId()
|
||||
const captionExpanded = ref(true)
|
||||
const ocrExpanded = ref(true)
|
||||
watch(() => current.value?.id, () => {
|
||||
captionExpanded.value = true
|
||||
ocrExpanded.value = true
|
||||
})
|
||||
|
||||
function formatTime(iso: string): string {
|
||||
if (!iso) return ''
|
||||
const d = new Date(iso)
|
||||
return fmtBeijingTime(d) || iso
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Filmstrip: keep the current thumbnail in view as the viewer moves.
|
||||
// ---------------------------------------------------------------------------
|
||||
const stripEl = ref<HTMLElement | null>(null)
|
||||
watch(
|
||||
() => [props.index, props.items] as const,
|
||||
async () => {
|
||||
await nextTick()
|
||||
const el = stripEl.value?.querySelector<HTMLElement>('.igv-strip__item.is-current')
|
||||
el?.scrollIntoView({ block: 'nearest', inline: 'center', behavior: 'smooth' })
|
||||
},
|
||||
{ immediate: true },
|
||||
)
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Keyboard. Bound on window while the viewer is mounted: the overlay itself is
|
||||
// never focused, so a listener on it would never hear a key.
|
||||
// ---------------------------------------------------------------------------
|
||||
function onKey(e: KeyboardEvent): void {
|
||||
if (e.defaultPrevented || e.metaKey || e.ctrlKey || e.altKey) return
|
||||
const target = e.target as HTMLElement | null
|
||||
if (target?.closest?.('input, textarea, select, [contenteditable="true"]')) return
|
||||
const actions: Record<string, () => void> = {
|
||||
Escape: () => emit('close'),
|
||||
ArrowLeft: prev,
|
||||
ArrowRight: next,
|
||||
'+': zoomIn,
|
||||
'=': zoomIn,
|
||||
'-': zoomOut,
|
||||
'0': () => resetView(),
|
||||
r: rotate,
|
||||
i: toggleInfo,
|
||||
}
|
||||
const action = actions[e.key]
|
||||
if (!action) return
|
||||
e.preventDefault()
|
||||
action()
|
||||
}
|
||||
|
||||
onMounted(() => window.addEventListener('keydown', onKey))
|
||||
onBeforeUnmount(() => window.removeEventListener('keydown', onKey))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Teleport to="body">
|
||||
<div class="igv" :class="{ 'has-info': showInfo }" role="dialog" aria-modal="true" :aria-label="current?.caption || t(`${NS}.title`)">
|
||||
<div class="igv-main">
|
||||
<header class="igv-topbar">
|
||||
<div class="igv-topbar__title">
|
||||
<span class="igv-counter">{{ position }} / {{ total }}</span>
|
||||
<span class="igv-name" :title="current?.source_name">{{ current?.source_name || current?.knowledge_id }}</span>
|
||||
</div>
|
||||
<div class="igv-tools">
|
||||
<t-tooltip :content="t(`${NS}.zoomOut`)">
|
||||
<button type="button" class="igv-tool" :disabled="!loaded" :aria-label="t(`${NS}.zoomOut`)" @click="zoomOut">
|
||||
<t-icon name="zoom-out" />
|
||||
</button>
|
||||
</t-tooltip>
|
||||
<t-tooltip :content="t(`${NS}.zoomReset`)">
|
||||
<button type="button" class="igv-tool igv-tool--text" :disabled="!loaded" @click="resetView">{{ zoomPercent }}</button>
|
||||
</t-tooltip>
|
||||
<t-tooltip :content="t(`${NS}.zoomIn`)">
|
||||
<button type="button" class="igv-tool" :disabled="!loaded" :aria-label="t(`${NS}.zoomIn`)" @click="zoomIn">
|
||||
<t-icon name="zoom-in" />
|
||||
</button>
|
||||
</t-tooltip>
|
||||
<t-tooltip :content="t(`${NS}.actualSize`)">
|
||||
<button type="button" class="igv-tool igv-tool--text" :disabled="!loaded" @click="zoomActual">1:1</button>
|
||||
</t-tooltip>
|
||||
<t-tooltip :content="t(`${NS}.rotate`)">
|
||||
<button type="button" class="igv-tool" :disabled="!loaded" :aria-label="t(`${NS}.rotate`)" @click="rotate">
|
||||
<t-icon name="rotation" />
|
||||
</button>
|
||||
</t-tooltip>
|
||||
<span class="igv-tools__sep" />
|
||||
<t-tooltip :content="t(`${NS}.download`)">
|
||||
<button type="button" class="igv-tool" :disabled="!src" :aria-label="t(`${NS}.download`)" @click="download">
|
||||
<t-icon name="download" />
|
||||
</button>
|
||||
</t-tooltip>
|
||||
<t-tooltip :content="t(`${NS}.openOriginal`)">
|
||||
<button type="button" class="igv-tool" :disabled="!src" :aria-label="t(`${NS}.openOriginal`)" @click="openOriginal">
|
||||
<t-icon name="jump" />
|
||||
</button>
|
||||
</t-tooltip>
|
||||
<t-tooltip :content="t(`${NS}.toggleInfo`)">
|
||||
<button type="button" class="igv-tool" :class="{ 'is-on': showInfo }" :aria-pressed="showInfo" :aria-label="t(`${NS}.toggleInfo`)" @click="toggleInfo">
|
||||
<t-icon name="info-circle" />
|
||||
</button>
|
||||
</t-tooltip>
|
||||
<span class="igv-tools__sep" />
|
||||
<t-tooltip :content="t(`${NS}.viewerClose`)">
|
||||
<button type="button" class="igv-tool" :aria-label="t(`${NS}.viewerClose`)" @click="emit('close')">
|
||||
<t-icon name="close" />
|
||||
</button>
|
||||
</t-tooltip>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div
|
||||
ref="stageEl"
|
||||
class="igv-stage"
|
||||
:class="{ 'can-pan': canPan, 'is-dragging': dragging }"
|
||||
@wheel.prevent="onWheel"
|
||||
@dblclick="onDblClick"
|
||||
@pointerdown="onPointerDown"
|
||||
@pointermove="onPointerMove"
|
||||
@pointerup="onPointerUp"
|
||||
@pointercancel="onPointerUp"
|
||||
@click.self="emit('close')"
|
||||
>
|
||||
<img
|
||||
v-if="src && !failed"
|
||||
ref="imgEl"
|
||||
:src="src"
|
||||
:alt="current?.caption"
|
||||
class="igv-image"
|
||||
:class="{ 'is-loaded': loaded }"
|
||||
:style="imgStyle"
|
||||
draggable="false"
|
||||
@load="onImgLoad"
|
||||
@error="onImgError"
|
||||
/>
|
||||
<div v-if="failed" class="igv-state">
|
||||
<t-icon name="image-error" size="32px" />
|
||||
<span>{{ t(`${NS}.imageLoadError`) }}</span>
|
||||
</div>
|
||||
<t-loading v-else-if="!loaded || loading" class="igv-state" size="medium" />
|
||||
|
||||
<button type="button" class="igv-nav igv-nav--prev" :disabled="!hasPrev || loading" :aria-label="t(`${NS}.prev`)" @click.stop="prev">
|
||||
<t-icon name="chevron-left" size="24px" />
|
||||
</button>
|
||||
<button type="button" class="igv-nav igv-nav--next" :disabled="!hasNext || loading" :aria-label="t(`${NS}.next`)" @click.stop="next">
|
||||
<t-icon name="chevron-right" size="24px" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div v-if="items.length > 1" ref="stripEl" class="igv-strip">
|
||||
<button
|
||||
v-for="(img, i) in items"
|
||||
:key="img.id"
|
||||
type="button"
|
||||
class="igv-strip__item"
|
||||
:class="{ 'is-current': i === index }"
|
||||
:aria-label="img.caption || String(i + 1)"
|
||||
@click="emit('select', i)"
|
||||
>
|
||||
<img v-if="thumbUrls[img.id]" :src="thumbUrls[img.id]" alt="" draggable="false" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<aside v-if="showInfo && current" class="igv-info">
|
||||
<div class="igv-info__content">
|
||||
<section class="igv-section" :class="{ 'is-collapsed': !captionExpanded }">
|
||||
<div class="igv-section__head">
|
||||
<h3>
|
||||
<button
|
||||
type="button"
|
||||
class="igv-section__toggle"
|
||||
:aria-expanded="captionExpanded"
|
||||
:aria-controls="`${sectionId}-caption`"
|
||||
@click="captionExpanded = !captionExpanded"
|
||||
>
|
||||
<span>{{ t(`${NS}.caption`) }}</span>
|
||||
<t-icon :name="captionExpanded ? 'chevron-down' : 'chevron-right'" size="14px" aria-hidden="true" />
|
||||
</button>
|
||||
</h3>
|
||||
<button v-if="current.caption" type="button" class="igv-copy" :title="t(`${NS}.copy`)" :aria-label="`${t(`${NS}.copy`)} ${t(`${NS}.caption`)}`" @click="copyText(current.caption)">
|
||||
<t-icon name="file-copy" size="14px" aria-hidden="true" />
|
||||
</button>
|
||||
</div>
|
||||
<div v-show="captionExpanded" :id="`${sectionId}-caption`">
|
||||
<div v-if="current.caption" class="igv-markdown" v-html="captionHtml" />
|
||||
<p v-else class="igv-text is-muted">{{ t(`${NS}.noCaption`) }}</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="igv-section" :class="{ 'is-collapsed': !ocrExpanded }">
|
||||
<div class="igv-section__head">
|
||||
<h3>
|
||||
<button
|
||||
type="button"
|
||||
class="igv-section__toggle"
|
||||
:aria-expanded="ocrExpanded"
|
||||
:aria-controls="`${sectionId}-ocr`"
|
||||
@click="ocrExpanded = !ocrExpanded"
|
||||
>
|
||||
<span>{{ t(`${NS}.ocr`) }}</span>
|
||||
<t-icon :name="ocrExpanded ? 'chevron-down' : 'chevron-right'" size="14px" aria-hidden="true" />
|
||||
</button>
|
||||
</h3>
|
||||
<button v-if="current.ocr_text" type="button" class="igv-copy" :title="t(`${NS}.copy`)" :aria-label="`${t(`${NS}.copy`)} ${t(`${NS}.ocr`)}`" @click="copyText(current.ocr_text)">
|
||||
<t-icon name="file-copy" size="14px" aria-hidden="true" />
|
||||
</button>
|
||||
</div>
|
||||
<div v-show="ocrExpanded" :id="`${sectionId}-ocr`">
|
||||
<div v-if="current.ocr_text" class="igv-markdown" v-html="ocrHtml" />
|
||||
<p v-else class="igv-text is-muted">{{ t(`${NS}.noOcr`) }}</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section v-if="attrs.length" class="igv-section">
|
||||
<div class="igv-section__head"><h3>{{ t(`${NS}.attributes`) }}</h3></div>
|
||||
<dl class="igv-props">
|
||||
<template v-for="a in attrs" :key="a.key">
|
||||
<dt>{{ a.label }}</dt>
|
||||
<dd>{{ a.value }}</dd>
|
||||
</template>
|
||||
</dl>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<section class="igv-section igv-info__details">
|
||||
<div class="igv-section__head"><h3>{{ t(`${NS}.details`) }}</h3></div>
|
||||
<dl class="igv-props">
|
||||
<dt>{{ t(`${NS}.source`) }}</dt>
|
||||
<dd>
|
||||
<button type="button" class="igv-source" :title="t(`${NS}.openSource`)" @click="emit('open-source', current.knowledge_id)">
|
||||
<t-icon name="file" size="14px" />
|
||||
<span>{{ current.source_name || current.knowledge_id }}</span>
|
||||
</button>
|
||||
</dd>
|
||||
<template v-if="natural">
|
||||
<dt>{{ t(`${NS}.dimensions`) }}</dt>
|
||||
<dd>{{ natural.w }} × {{ natural.h }}</dd>
|
||||
</template>
|
||||
<dt>{{ t(`${NS}.status`) }}</dt>
|
||||
<dd>
|
||||
<t-tag size="small" variant="light" :theme="current.is_enabled ? 'success' : 'default'">
|
||||
{{ t(`${NS}.attr.builtin_is_enabled_value_${current.is_enabled ? 'true' : 'false'}`) }}
|
||||
</t-tag>
|
||||
</dd>
|
||||
<template v-if="current.created_at">
|
||||
<dt>{{ t(`${NS}.attr.builtin_created_at`) }}</dt>
|
||||
<dd>{{ formatTime(current.created_at) }}</dd>
|
||||
</template>
|
||||
</dl>
|
||||
</section>
|
||||
</aside>
|
||||
</div>
|
||||
</Teleport>
|
||||
</template>
|
||||
|
||||
<style scoped lang="less">
|
||||
// The stage is always dark, whatever the app theme: images read best on a
|
||||
// neutral dark ground, and the controls over it are sized for that.
|
||||
.igv {
|
||||
--igv-stage-bg: #111214;
|
||||
--igv-chrome-fg: rgb(255 255 255 / 86%);
|
||||
--igv-chrome-muted: rgb(255 255 255 / 55%);
|
||||
--igv-chrome-hover: rgb(255 255 255 / 12%);
|
||||
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: var(--z-drawer);
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
background: var(--igv-stage-bg);
|
||||
color: var(--igv-chrome-fg);
|
||||
|
||||
&.has-info {
|
||||
grid-template-columns: minmax(0, 1fr) 360px;
|
||||
}
|
||||
}
|
||||
|
||||
.igv-main {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.igv-topbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
height: 52px;
|
||||
padding: 0 12px 0 20px;
|
||||
flex-shrink: 0;
|
||||
|
||||
&__title {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 12px;
|
||||
min-width: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.igv-counter {
|
||||
font-size: var(--app-text-md);
|
||||
font-variant-numeric: tabular-nums;
|
||||
color: var(--igv-chrome-muted);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.igv-name {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
font-size: var(--app-text-base);
|
||||
}
|
||||
|
||||
.igv-tools {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
flex-shrink: 0;
|
||||
|
||||
&__sep {
|
||||
width: 1px;
|
||||
height: 18px;
|
||||
margin: 0 6px;
|
||||
background: rgb(255 255 255 / 16%);
|
||||
}
|
||||
}
|
||||
|
||||
.igv-tool {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-width: 32px;
|
||||
height: 32px;
|
||||
padding: 0 6px;
|
||||
border: 0;
|
||||
border-radius: var(--app-radius-sm);
|
||||
background: transparent;
|
||||
color: var(--igv-chrome-fg);
|
||||
font: inherit;
|
||||
font-size: var(--app-text-xl);
|
||||
cursor: pointer;
|
||||
transition: background-color var(--app-motion-fast) ease;
|
||||
|
||||
&--text {
|
||||
min-width: 48px;
|
||||
font-size: var(--app-text-sm);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
&:hover:not(:disabled),
|
||||
&.is-on {
|
||||
background: var(--igv-chrome-hover);
|
||||
}
|
||||
|
||||
&:disabled {
|
||||
opacity: 0.35;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
&:focus-visible {
|
||||
outline: 2px solid var(--app-focus-border);
|
||||
outline-offset: 1px;
|
||||
}
|
||||
}
|
||||
|
||||
.igv-stage {
|
||||
position: relative;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
overflow: hidden;
|
||||
padding: 16px 72px;
|
||||
user-select: none;
|
||||
touch-action: none;
|
||||
|
||||
&.can-pan { cursor: grab; }
|
||||
&.is-dragging { cursor: grabbing; }
|
||||
}
|
||||
|
||||
.igv-image {
|
||||
max-width: 100%;
|
||||
max-height: 100%;
|
||||
object-fit: contain;
|
||||
opacity: 0;
|
||||
transition: transform var(--app-motion-fast) ease, opacity var(--app-motion-fast) ease;
|
||||
will-change: transform;
|
||||
|
||||
&.is-loaded { opacity: 1; }
|
||||
|
||||
.is-dragging & { transition: opacity var(--app-motion-fast) ease; }
|
||||
}
|
||||
|
||||
.igv-state {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
color: var(--igv-chrome-muted);
|
||||
font-size: var(--app-text-md);
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.igv-nav {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
margin-top: -22px;
|
||||
border: 0;
|
||||
border-radius: var(--app-radius-pill);
|
||||
background: rgb(255 255 255 / 10%);
|
||||
color: var(--igv-chrome-fg);
|
||||
cursor: pointer;
|
||||
transition: background-color var(--app-motion-fast) ease, opacity var(--app-motion-fast) ease;
|
||||
|
||||
&--prev { left: 16px; }
|
||||
&--next { right: 16px; }
|
||||
|
||||
&:hover:not(:disabled) { background: rgb(255 255 255 / 20%); }
|
||||
&:disabled { opacity: 0.2; cursor: default; }
|
||||
&:focus-visible { outline: 2px solid var(--app-focus-border); outline-offset: 2px; }
|
||||
}
|
||||
|
||||
.igv-strip {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
flex-shrink: 0;
|
||||
padding: 10px 20px 14px;
|
||||
overflow-x: auto;
|
||||
scrollbar-width: thin;
|
||||
scrollbar-color: rgb(255 255 255 / 20%) transparent;
|
||||
|
||||
&__item {
|
||||
flex: 0 0 auto;
|
||||
width: 56px;
|
||||
height: 42px;
|
||||
padding: 0;
|
||||
border: 2px solid transparent;
|
||||
border-radius: var(--app-radius-xs);
|
||||
overflow: hidden;
|
||||
background: rgb(255 255 255 / 8%);
|
||||
opacity: 0.5;
|
||||
cursor: pointer;
|
||||
transition: opacity var(--app-motion-fast) ease, border-color var(--app-motion-fast) ease;
|
||||
|
||||
img {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
&:hover { opacity: 0.85; }
|
||||
|
||||
&.is-current {
|
||||
opacity: 1;
|
||||
border-color: var(--td-brand-color);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.igv-info {
|
||||
--igv-info-padding-x: 16px;
|
||||
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
background: var(--td-bg-color-container);
|
||||
color: var(--td-text-color-primary);
|
||||
border-left: 1px solid var(--td-component-stroke);
|
||||
text-align: left;
|
||||
|
||||
&__content {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
padding: 0 var(--igv-info-padding-x) 20px;
|
||||
scrollbar-width: thin;
|
||||
|
||||
> .igv-section + .igv-section { padding-top: 0; }
|
||||
|
||||
// Each section bounds its sticky header, so the next title takes over.
|
||||
> .igv-section > .igv-section__head {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 1;
|
||||
margin: 0 calc(-1 * var(--igv-info-padding-x));
|
||||
padding: 16px var(--igv-info-padding-x) 12px;
|
||||
background: var(--td-bg-color-container);
|
||||
}
|
||||
}
|
||||
|
||||
&__details {
|
||||
flex: 0 0 auto;
|
||||
box-sizing: border-box;
|
||||
max-height: 50%;
|
||||
overflow-y: auto;
|
||||
padding: 16px var(--igv-info-padding-x) 20px;
|
||||
border-top: 1px solid var(--td-component-stroke);
|
||||
scrollbar-width: thin;
|
||||
}
|
||||
}
|
||||
|
||||
.igv-section {
|
||||
& + & {
|
||||
margin-top: 20px;
|
||||
padding-top: 16px;
|
||||
border-top: 1px solid var(--td-component-stroke);
|
||||
}
|
||||
|
||||
&__head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
min-height: 24px;
|
||||
margin-bottom: 12px;
|
||||
|
||||
h3 {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
gap: 8px;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
font-size: var(--app-text-md);
|
||||
font-weight: 600;
|
||||
line-height: 24px;
|
||||
color: var(--td-text-color-primary);
|
||||
|
||||
&::before {
|
||||
content: '';
|
||||
flex-shrink: 0;
|
||||
width: 3px;
|
||||
height: 14px;
|
||||
border-radius: 2px;
|
||||
background: var(--td-brand-color);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
&.is-collapsed > &__head { margin-bottom: 0; }
|
||||
|
||||
&__toggle {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
gap: 8px;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
border-radius: var(--app-radius-xs);
|
||||
background: transparent;
|
||||
color: inherit;
|
||||
font: inherit;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
|
||||
.t-icon { flex-shrink: 0; color: var(--td-text-color-secondary); }
|
||||
&:hover { color: var(--td-brand-color); }
|
||||
&:focus-visible { outline: 2px solid var(--app-focus-border); outline-offset: 2px; }
|
||||
}
|
||||
}
|
||||
|
||||
.igv-copy {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex-shrink: 0;
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
border-radius: var(--app-radius-xs);
|
||||
background: transparent;
|
||||
color: var(--td-text-color-secondary);
|
||||
font: inherit;
|
||||
font-size: var(--app-text-sm);
|
||||
cursor: pointer;
|
||||
|
||||
&:hover {
|
||||
color: var(--td-brand-color);
|
||||
background: var(--td-bg-color-container-hover);
|
||||
}
|
||||
|
||||
&:focus-visible { outline: 2px solid var(--app-focus-border); outline-offset: 2px; }
|
||||
}
|
||||
|
||||
.igv-text {
|
||||
margin: 0;
|
||||
font-size: var(--app-text-md);
|
||||
line-height: 1.7;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
|
||||
&.is-muted { color: var(--td-text-color-placeholder); }
|
||||
}
|
||||
|
||||
.igv-markdown {
|
||||
font-size: var(--app-text-md);
|
||||
line-height: 1.75;
|
||||
overflow-wrap: anywhere;
|
||||
|
||||
:deep(> :first-child) { margin-top: 0; }
|
||||
:deep(> :last-child) { margin-bottom: 0; }
|
||||
:deep(p) { margin: 0 0 10px; }
|
||||
:deep(h1), :deep(h2), :deep(h3), :deep(h4), :deep(h5), :deep(h6) {
|
||||
margin: 16px 0 8px;
|
||||
font-size: inherit;
|
||||
font-weight: 600;
|
||||
line-height: 1.5;
|
||||
}
|
||||
:deep(ul), :deep(ol) { margin: 8px 0 12px; padding-left: 20px; }
|
||||
:deep(li) { margin: 4px 0; }
|
||||
:deep(li > p) { margin: 0 0 4px; }
|
||||
:deep(li > ul), :deep(li > ol) { margin: 4px 0; }
|
||||
:deep(strong) { font-weight: 600; }
|
||||
:deep(a) { color: var(--td-brand-color); text-decoration: underline; }
|
||||
:deep(blockquote) {
|
||||
margin: 10px 0;
|
||||
padding-left: 12px;
|
||||
border-left: 3px solid var(--td-component-stroke);
|
||||
color: var(--td-text-color-secondary);
|
||||
}
|
||||
:deep(code) {
|
||||
padding: 2px 4px;
|
||||
border-radius: var(--app-radius-xs);
|
||||
background: var(--td-bg-color-secondarycontainer);
|
||||
font-size: 0.9em;
|
||||
}
|
||||
:deep(pre) {
|
||||
margin: 10px 0;
|
||||
padding: 10px;
|
||||
overflow-x: auto;
|
||||
border-radius: var(--app-radius-sm);
|
||||
background: var(--td-bg-color-secondarycontainer);
|
||||
line-height: 1.6;
|
||||
}
|
||||
:deep(pre code) { padding: 0; background: transparent; }
|
||||
:deep(img) { max-width: 100%; height: auto; }
|
||||
:deep(table) { display: block; max-width: 100%; overflow-x: auto; border-collapse: collapse; }
|
||||
:deep(th), :deep(td) { padding: 6px 8px; border: 1px solid var(--td-component-stroke); }
|
||||
:deep(hr) { margin: 16px 0; border: 0; border-top: 1px solid var(--td-component-stroke); }
|
||||
}
|
||||
|
||||
.igv-props {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) minmax(0, 2fr);
|
||||
gap: 8px 16px;
|
||||
margin: 0;
|
||||
font-size: var(--app-text-md);
|
||||
line-height: 22px;
|
||||
|
||||
dt { color: var(--td-text-color-secondary); overflow-wrap: anywhere; }
|
||||
dd {
|
||||
margin: 0;
|
||||
min-width: 0;
|
||||
text-align: left;
|
||||
word-break: break-word;
|
||||
}
|
||||
}
|
||||
|
||||
.igv-source {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
max-width: 100%;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: var(--td-brand-color);
|
||||
font: inherit;
|
||||
cursor: pointer;
|
||||
|
||||
span {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
&:hover span { text-decoration: underline; }
|
||||
}
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.igv.has-info { grid-template-columns: minmax(0, 1fr); grid-template-rows: minmax(0, 1fr) 40%; }
|
||||
.igv-info { border-left: 0; border-top: 1px solid var(--td-component-stroke); }
|
||||
.igv-stage { padding: 12px 56px; }
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,289 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import test from 'node:test'
|
||||
import vm from 'node:vm'
|
||||
import ts from 'typescript'
|
||||
import * as vue from 'vue'
|
||||
import type { ImageAsset, ImageListParams, ImageListResult } from '@/api/image-gallery'
|
||||
|
||||
// Exercise the component's actual loading and viewer logic with deferred API
|
||||
// responses so races and retries are deterministic, without a live backend.
|
||||
const source = readFileSync(new URL('./ImageGallery.vue', import.meta.url), 'utf8')
|
||||
.split('<script setup lang="ts">')[1].split('</script>')[0]
|
||||
const compiled = ts.transpileModule(`${source}\nexport {
|
||||
items, page, total, loading, error, keyword, hasMore, viewerIndex, viewerOpen,
|
||||
reload, loadMore, openViewer, onViewerLoadMore, initGallery,
|
||||
resolveImageSrc, thumbUrls,
|
||||
}`, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } }).outputText
|
||||
|
||||
function setup(proxyImages = false) {
|
||||
const calls: Array<{
|
||||
kb: string; params: ImageListParams
|
||||
resolve: (value: ImageListResult) => void; reject: (reason: Error) => void
|
||||
}> = []
|
||||
const imageCalls: Array<{
|
||||
url: string; signal?: AbortSignal
|
||||
resolve: (response: { ok: boolean; blob: () => Promise<Blob> }) => void
|
||||
reject: (reason: Error) => void
|
||||
}> = []
|
||||
const created: string[] = []
|
||||
const revoked: string[] = []
|
||||
const unmountHooks: Array<() => void> = []
|
||||
const props = vue.reactive({ knowledgeBaseId: 'kb-1' })
|
||||
const modules: Record<string, unknown> = {
|
||||
vue: { ...vue, onMounted() {}, onBeforeUnmount: (hook: () => void) => unmountHooks.push(hook), watch() {} },
|
||||
'vue-i18n': { useI18n: () => ({ t: (key: string) => key, te: () => false }) },
|
||||
'@/api/image-gallery': {
|
||||
listGalleryImages: (kb: string, params: ImageListParams) => new Promise((resolve, reject) => {
|
||||
calls.push({ kb, params, resolve, reject })
|
||||
}),
|
||||
fetchGalleryConfig: async () => ({ attributes: [], attribute_sources: [], mode: 'all', status: {} }),
|
||||
},
|
||||
'@/api/auth': { updateMyPreferences: async () => {} },
|
||||
'./galleryImageSrc': {
|
||||
galleryImageRequest: (url: string, kb: string) => proxyImages && url.startsWith('local://')
|
||||
? { url: `/kb/${kb}/${url}`, headers: { Authorization: 'test-token' } }
|
||||
: null,
|
||||
},
|
||||
}
|
||||
const state: any = {}
|
||||
vm.runInNewContext(compiled, {
|
||||
exports: state, defineProps: () => props, defineEmits: () => () => {},
|
||||
setTimeout, clearTimeout, console, Error, AbortController,
|
||||
fetch: (url: string, options: RequestInit) => new Promise((resolve, reject) => {
|
||||
imageCalls.push({ url, signal: options.signal ?? undefined, resolve, reject })
|
||||
}),
|
||||
URL: {
|
||||
createObjectURL: () => {
|
||||
const url = `blob:gallery-${created.length + 1}`
|
||||
created.push(url)
|
||||
return url
|
||||
},
|
||||
revokeObjectURL: (url: string) => revoked.push(url),
|
||||
},
|
||||
require: (id: string) => {
|
||||
assert.ok(id in modules, `unexpected import ${id}`)
|
||||
return modules[id]
|
||||
},
|
||||
})
|
||||
const respond = (index: number, ids: string[], total = 60) => calls[index].resolve({
|
||||
items: ids.map(id => ({ id, url: `https://example.com/${id}.png` }) as ImageAsset),
|
||||
total, page: calls[index].params.page!, pageSize: 24,
|
||||
})
|
||||
const ids = () => Array.from(state.items.value, (img: ImageAsset) => img.id)
|
||||
const respondImage = (index: number) => imageCalls[index].resolve({ ok: true, blob: async () => new Blob(['image']) })
|
||||
const unmount = () => unmountHooks.forEach(hook => hook())
|
||||
return { state, calls, props, respond, ids, imageCalls, respondImage, created, revoked, unmount }
|
||||
}
|
||||
|
||||
const settleImages = () => new Promise<void>(resolve => setImmediate(resolve))
|
||||
|
||||
test('scroll appends unique images, serializes requests, and stops at the total', async () => {
|
||||
const { state, calls, respond, ids } = setup()
|
||||
const first = state.reload()
|
||||
respond(0, ['a', 'b'])
|
||||
await first
|
||||
const next = state.loadMore()
|
||||
assert.equal(await state.loadMore(), false)
|
||||
assert.equal(calls.length, 2)
|
||||
assert.equal(calls[1].params.page, 2)
|
||||
respond(1, ['b', 'c'], 48)
|
||||
await next
|
||||
assert.deepEqual(ids(), ['a', 'b', 'c'])
|
||||
assert.equal(state.hasMore.value, false)
|
||||
assert.equal(await state.loadMore(), false)
|
||||
})
|
||||
|
||||
test('append failures retain cards and retry the same page', async () => {
|
||||
const { state, calls, respond, ids } = setup()
|
||||
const first = state.reload()
|
||||
respond(0, ['a'])
|
||||
await first
|
||||
const next = state.loadMore()
|
||||
calls[1].reject(new Error('offline'))
|
||||
assert.equal(await next, false)
|
||||
assert.deepEqual(ids(), ['a'])
|
||||
assert.equal(state.page.value, 1)
|
||||
assert.equal(state.error.value, 'offline')
|
||||
const retry = state.loadMore()
|
||||
assert.equal(calls[2].params.page, 2)
|
||||
respond(2, ['b'])
|
||||
await retry
|
||||
assert.deepEqual(ids(), ['a', 'b'])
|
||||
assert.equal(state.error.value, '')
|
||||
})
|
||||
|
||||
test('a new search discards an older append and resets the viewer', async () => {
|
||||
const { state, calls, respond, ids } = setup()
|
||||
const first = state.reload()
|
||||
respond(0, ['a'])
|
||||
await first
|
||||
state.openViewer(0)
|
||||
const older = state.onViewerLoadMore()
|
||||
state.keyword.value = 'new search'
|
||||
const fresh = state.reload()
|
||||
assert.equal(state.viewerOpen.value, false)
|
||||
assert.equal(calls[2].params.keyword, 'new search')
|
||||
respond(2, ['new'], 1)
|
||||
await fresh
|
||||
respond(1, ['old'])
|
||||
await older
|
||||
assert.deepEqual(ids(), ['new'])
|
||||
assert.equal(state.total.value, 1)
|
||||
})
|
||||
|
||||
test('viewer loads past the last card without dropping previous images', async () => {
|
||||
const { state, respond, ids } = setup()
|
||||
const first = state.reload()
|
||||
respond(0, ['a', 'b'])
|
||||
await first
|
||||
state.openViewer(1)
|
||||
const step = state.onViewerLoadMore()
|
||||
respond(1, ['c', 'd'])
|
||||
await step
|
||||
assert.deepEqual(ids(), ['a', 'b', 'c', 'd'])
|
||||
assert.equal(state.viewerIndex.value, 2)
|
||||
assert.equal(state.viewerOpen.value, true)
|
||||
})
|
||||
|
||||
test('switching knowledge bases invalidates the previous request immediately', async () => {
|
||||
const { state, props, calls, respond, ids } = setup()
|
||||
const old = state.reload()
|
||||
props.knowledgeBaseId = 'kb-2'
|
||||
const fresh = state.initGallery()
|
||||
respond(0, ['old'])
|
||||
await old
|
||||
await vue.nextTick()
|
||||
assert.deepEqual(ids(), [])
|
||||
assert.equal(calls[1].kb, 'kb-2')
|
||||
respond(1, ['new'], 1)
|
||||
await fresh
|
||||
assert.deepEqual(ids(), ['new'])
|
||||
})
|
||||
|
||||
test('an empty batch stops automatic loading even if the total is stale', async () => {
|
||||
const { state, respond, calls } = setup()
|
||||
const first = state.reload()
|
||||
respond(0, ['a'])
|
||||
await first
|
||||
const next = state.loadMore()
|
||||
respond(1, [], 100)
|
||||
await next
|
||||
assert.equal(state.hasMore.value, false)
|
||||
assert.equal(await state.loadMore(), false)
|
||||
assert.equal(calls.length, 2)
|
||||
})
|
||||
|
||||
test('proxied images share a request and cached URL, then release it on unmount', async () => {
|
||||
const { state, imageCalls, respondImage, created, revoked, unmount } = setup(true)
|
||||
const first = state.resolveImageSrc('local://image')
|
||||
assert.equal(state.resolveImageSrc('local://image'), first)
|
||||
assert.equal(imageCalls.length, 1)
|
||||
respondImage(0)
|
||||
const url = await first
|
||||
assert.equal(await state.resolveImageSrc('local://image'), url)
|
||||
assert.equal(imageCalls.length, 1)
|
||||
assert.deepEqual(created, [url])
|
||||
unmount()
|
||||
assert.deepEqual(revoked, [url])
|
||||
const late = state.resolveImageSrc('local://image')
|
||||
assert.equal(imageCalls.length, 1)
|
||||
assert.equal(await late, 'local://image')
|
||||
})
|
||||
|
||||
test('unmount aborts a thumbnail fetch and ignores a response that arrives anyway', async () => {
|
||||
const { state, calls, imageCalls, created, revoked, unmount } = setup(true)
|
||||
const listing = state.reload()
|
||||
calls[0].resolve({ items: [{ id: 'a', url: 'local://image' } as ImageAsset], total: 1, page: 1, pageSize: 24 })
|
||||
await listing
|
||||
const pending = state.resolveImageSrc('local://image')
|
||||
unmount()
|
||||
assert.equal(imageCalls[0].signal?.aborted, true)
|
||||
let bodyReads = 0
|
||||
imageCalls[0].resolve({ ok: true, blob: async () => { bodyReads++; return new Blob(['image']) } })
|
||||
assert.equal(await pending, 'local://image')
|
||||
assert.equal(bodyReads, 0)
|
||||
assert.deepEqual(created, [])
|
||||
assert.deepEqual(revoked, [])
|
||||
assert.deepEqual(Object.keys(state.thumbUrls.value), [])
|
||||
})
|
||||
|
||||
test('unmount during response body reading prevents late Blob URL creation', async () => {
|
||||
const { state, imageCalls, created, unmount } = setup(true)
|
||||
const pending = state.resolveImageSrc('local://image')
|
||||
let finishBody!: (blob: Blob) => void
|
||||
const body = new Promise<Blob>(resolve => { finishBody = resolve })
|
||||
let bodyReads = 0
|
||||
imageCalls[0].resolve({ ok: true, blob: () => { bodyReads++; return body } })
|
||||
await settleImages()
|
||||
assert.equal(bodyReads, 1)
|
||||
unmount()
|
||||
finishBody(new Blob(['image']))
|
||||
assert.equal(await pending, 'local://image')
|
||||
assert.deepEqual(created, [])
|
||||
})
|
||||
|
||||
test('reload cancels old image requests without removing a replacement for the same URL', async () => {
|
||||
const { state, imageCalls, respondImage, respond, created, unmount } = setup(true)
|
||||
const old = state.resolveImageSrc('local://image')
|
||||
const listing = state.reload()
|
||||
assert.equal(imageCalls[0].signal?.aborted, true)
|
||||
const fresh = state.resolveImageSrc('local://image')
|
||||
assert.equal(imageCalls.length, 2)
|
||||
assert.equal(imageCalls[1].signal?.aborted, false)
|
||||
respondImage(0)
|
||||
assert.equal(await old, 'local://image')
|
||||
assert.equal(state.resolveImageSrc('local://image'), fresh)
|
||||
assert.equal(imageCalls.length, 2)
|
||||
respond(0, [], 0)
|
||||
await listing
|
||||
respondImage(1)
|
||||
assert.equal(await fresh, 'blob:gallery-1')
|
||||
assert.deepEqual(created, ['blob:gallery-1'])
|
||||
unmount()
|
||||
})
|
||||
|
||||
test('switching knowledge bases releases cached URLs and starts new scoped image requests', async () => {
|
||||
const { state, props, imageCalls, respondImage, respond, created, revoked, unmount } = setup(true)
|
||||
const cached = state.resolveImageSrc('local://cached')
|
||||
respondImage(0)
|
||||
await cached
|
||||
const old = state.resolveImageSrc('local://pending')
|
||||
props.knowledgeBaseId = 'kb-2'
|
||||
const listing = state.initGallery()
|
||||
assert.equal(imageCalls[1].signal?.aborted, true)
|
||||
assert.deepEqual(revoked, ['blob:gallery-1'])
|
||||
await settleImages()
|
||||
respond(0, [], 0)
|
||||
await listing
|
||||
const fresh = state.resolveImageSrc('local://pending')
|
||||
assert.equal(imageCalls[2].url, '/kb/kb-2/local://pending')
|
||||
respondImage(1)
|
||||
assert.equal(await old, 'local://pending')
|
||||
assert.equal(state.resolveImageSrc('local://pending'), fresh)
|
||||
respondImage(2)
|
||||
await fresh
|
||||
const refetch = state.resolveImageSrc('local://cached')
|
||||
assert.equal(imageCalls[3].url, '/kb/kb-2/local://cached')
|
||||
respondImage(3)
|
||||
await refetch
|
||||
assert.deepEqual(created, ['blob:gallery-1', 'blob:gallery-2', 'blob:gallery-3'])
|
||||
unmount()
|
||||
})
|
||||
|
||||
test('HTTP and network failures allow retry, and ordinary URLs skip the proxy', async () => {
|
||||
const { state, imageCalls, respondImage, unmount } = setup(true)
|
||||
const raw = 'local://image'
|
||||
const failedHTTP = state.resolveImageSrc(raw)
|
||||
imageCalls[0].resolve({ ok: false, blob: async () => { throw new Error('must not read') } })
|
||||
assert.equal(await failedHTTP, raw)
|
||||
const failedNetwork = state.resolveImageSrc(raw)
|
||||
imageCalls[1].reject(new Error('offline'))
|
||||
assert.equal(await failedNetwork, raw)
|
||||
const success = state.resolveImageSrc(raw)
|
||||
respondImage(2)
|
||||
assert.equal(await success, 'blob:gallery-1')
|
||||
assert.equal(await state.resolveImageSrc('https://example.com/image.png'), 'https://example.com/image.png')
|
||||
assert.equal(imageCalls.length, 3)
|
||||
unmount()
|
||||
})
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,26 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import { galleryImageRequest } from './galleryImageSrc.ts'
|
||||
|
||||
const KB_PROXY = '/api/v1/knowledge-bases/kb-1/files?file_path='
|
||||
|
||||
// The default local storage writes local:// handles; they, and every other
|
||||
// storage scheme, must reach the knowledge-base proxy instead of <img src>.
|
||||
for (const url of [
|
||||
'local://10001/exports/a.png',
|
||||
'minio://bucket/a.png',
|
||||
'cos://bucket/a.png',
|
||||
's3://bucket/a.png',
|
||||
'resource://AbCdEfGhIjKlMnOpQrStUv',
|
||||
'storage://backend-1/local://10001/a.png',
|
||||
]) {
|
||||
test(`${url.split('://')[0]}:// images load through the knowledge-base file proxy`, () => {
|
||||
assert.equal(galleryImageRequest(url, 'kb-1')?.url, `${KB_PROXY}${encodeURIComponent(url)}`)
|
||||
})
|
||||
}
|
||||
|
||||
test('browser-renderable URLs are used as is', () => {
|
||||
assert.equal(galleryImageRequest('https://cdn.example.com/a.png', 'kb-1'), null)
|
||||
assert.equal(galleryImageRequest('', 'kb-1'), null)
|
||||
})
|
||||
@@ -0,0 +1,21 @@
|
||||
import {
|
||||
buildProtectedFileRequest,
|
||||
isProviderFileURL,
|
||||
resolveProtectedFileAccess,
|
||||
type ProtectedFileRequest,
|
||||
} from '../../../utils/protectedFileAccess.ts'
|
||||
|
||||
/**
|
||||
* The proxy request that loads one gallery image, or null when the browser can
|
||||
* render the URL as is.
|
||||
*
|
||||
* Stored images are storage handles (local://, minio://, cos://, s3://,
|
||||
* storage://<backend>/..., resource://) that no browser can open; they go
|
||||
* through the knowledge-base file proxy, which is also what authorises a
|
||||
* viewer of a KB shared from another tenant. The scheme list is the one
|
||||
* protectedFileAccess owns, so the gallery cannot drift from chat and wiki.
|
||||
*/
|
||||
export function galleryImageRequest(rawUrl: string, kbId: string): ProtectedFileRequest | null {
|
||||
if (!rawUrl || !isProviderFileURL(rawUrl)) return null
|
||||
return buildProtectedFileRequest(rawUrl, resolveProtectedFileAccess({ mode: 'knowledgeBase', kbId }))
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import {
|
||||
mergeAllScopeKnowledgeBases,
|
||||
isSharedKbEditable,
|
||||
type OwnedKnowledgeBase,
|
||||
type SharedKnowledgeBaseLike,
|
||||
type MergedKnowledgeBase,
|
||||
} from './kbListMerge.ts'
|
||||
|
||||
const ME = 'user-me'
|
||||
|
||||
function owned(id: string, extra: Partial<OwnedKnowledgeBase> = {}): OwnedKnowledgeBase {
|
||||
return { id, creator_id: ME, ...extra }
|
||||
}
|
||||
|
||||
function shared(
|
||||
kbId: string,
|
||||
permission: string,
|
||||
extra: Partial<SharedKnowledgeBaseLike> = {},
|
||||
): SharedKnowledgeBaseLike {
|
||||
return {
|
||||
knowledge_base: { id: kbId },
|
||||
permission,
|
||||
shared_at: '2026-01-01T00:00:00Z',
|
||||
share_id: `share-${kbId}-${permission}`,
|
||||
org_name: 'Org',
|
||||
...extra,
|
||||
}
|
||||
}
|
||||
|
||||
// Render keys must be unique — duplicate `:key` values are exactly what
|
||||
// blanks the list in #795.
|
||||
function keys(list: MergedKnowledgeBase[]): string[] {
|
||||
return list.map((kb) => kb.id)
|
||||
}
|
||||
|
||||
function hasUniqueKeys(list: MergedKnowledgeBase[]): boolean {
|
||||
return new Set(keys(list)).size === list.length
|
||||
}
|
||||
|
||||
test('renders an empty list when there are no knowledge bases', () => {
|
||||
assert.deepEqual(mergeAllScopeKnowledgeBases([], [], ME), [])
|
||||
})
|
||||
|
||||
test('keeps a single owned KB (the case that always worked)', () => {
|
||||
const result = mergeAllScopeKnowledgeBases([owned('a')], [], ME)
|
||||
assert.deepEqual(keys(result), ['a'])
|
||||
assert.equal(result[0].isMine, true)
|
||||
})
|
||||
|
||||
test('renders every owned KB once when there are two or more (#795 regression)', () => {
|
||||
const result = mergeAllScopeKnowledgeBases([owned('a'), owned('b'), owned('c')], [], ME)
|
||||
assert.deepEqual(keys(result), ['a', 'b', 'c'])
|
||||
assert.ok(hasUniqueKeys(result))
|
||||
})
|
||||
|
||||
test('does not emit a KB twice when it is both owned and shared back', () => {
|
||||
// Without de-dup this yields two entries keyed "a" -> duplicate Vue key
|
||||
// -> blank list. Owned must win.
|
||||
const result = mergeAllScopeKnowledgeBases([owned('a'), owned('b')], [shared('a', 'viewer')], ME)
|
||||
assert.deepEqual(keys(result), ['a', 'b'])
|
||||
assert.ok(hasUniqueKeys(result))
|
||||
const a = result.find((kb) => kb.id === 'a')!
|
||||
assert.equal(a.isMine, true)
|
||||
})
|
||||
|
||||
test('renders exactly one card per KB when several owned KBs are also shared back', () => {
|
||||
// Pre-fix this returned 4 rows (2 owned + 2 shared dups) with colliding
|
||||
// keys, which is what blanked the page once there were ≥2 KBs.
|
||||
const result = mergeAllScopeKnowledgeBases(
|
||||
[owned('a'), owned('b')],
|
||||
[shared('a', 'viewer'), shared('b', 'editor')],
|
||||
ME,
|
||||
)
|
||||
assert.equal(result.length, 2)
|
||||
assert.deepEqual([...keys(result)].sort(), ['a', 'b'])
|
||||
assert.ok(hasUniqueKeys(result))
|
||||
})
|
||||
|
||||
test('collapses the same KB shared through multiple orgs into one card', () => {
|
||||
// Two distinct shares (different share_id) but the same knowledge_base.id
|
||||
// — the real-world trigger for duplicate keys once there are ≥2 rows.
|
||||
const result = mergeAllScopeKnowledgeBases(
|
||||
[],
|
||||
[
|
||||
shared('x', 'viewer', { org_name: 'Org A', share_id: 'share-x-A' }),
|
||||
shared('x', 'editor', { org_name: 'Org B', share_id: 'share-x-B' }),
|
||||
],
|
||||
ME,
|
||||
)
|
||||
assert.deepEqual(keys(result), ['x'])
|
||||
assert.ok(hasUniqueKeys(result))
|
||||
})
|
||||
|
||||
test('keeps the most-privileged permission when collapsing duplicate shares', () => {
|
||||
const result = mergeAllScopeKnowledgeBases(
|
||||
[],
|
||||
[
|
||||
shared('x', 'viewer', { share_id: 's1' }),
|
||||
shared('x', 'admin', { share_id: 's2' }),
|
||||
shared('x', 'editor', { share_id: 's3' }),
|
||||
],
|
||||
ME,
|
||||
)
|
||||
assert.equal(result.length, 1)
|
||||
assert.equal((result[0] as { permission: string }).permission, 'admin')
|
||||
})
|
||||
|
||||
test('guarantees unique keys across a mixed owned + shared set', () => {
|
||||
const result = mergeAllScopeKnowledgeBases(
|
||||
[owned('a'), owned('b', { creator_id: 'someone-else' })],
|
||||
[
|
||||
shared('a', 'editor'), // overlaps owned -> dropped
|
||||
shared('c', 'viewer'),
|
||||
shared('c', 'admin', { share_id: 'share-c-2' }), // duplicate share -> collapsed
|
||||
shared('d', 'editor'),
|
||||
],
|
||||
ME,
|
||||
)
|
||||
assert.ok(hasUniqueKeys(result))
|
||||
assert.deepEqual(new Set(keys(result)), new Set(['a', 'b', 'c', 'd']))
|
||||
})
|
||||
|
||||
test('orders pinned (newest first) → own → teammate → shared(editable first)', () => {
|
||||
const result = mergeAllScopeKnowledgeBases(
|
||||
[
|
||||
owned('mine'),
|
||||
owned('teammate', { creator_id: 'someone-else' }),
|
||||
owned('pin-old', { is_pinned: true, pinned_at: '2026-01-01T00:00:00Z' }),
|
||||
owned('pin-new', { is_pinned: true, pinned_at: '2026-02-01T00:00:00Z' }),
|
||||
],
|
||||
[shared('view-only', 'viewer'), shared('editable', 'editor')],
|
||||
ME,
|
||||
)
|
||||
assert.deepEqual(keys(result), [
|
||||
'pin-new',
|
||||
'pin-old',
|
||||
'mine',
|
||||
'teammate',
|
||||
'editable',
|
||||
'view-only',
|
||||
])
|
||||
})
|
||||
|
||||
test('drops shared rows whose knowledge_base is null', () => {
|
||||
const result = mergeAllScopeKnowledgeBases(
|
||||
[owned('a')],
|
||||
[{ knowledge_base: null, permission: 'viewer', shared_at: '', share_id: 's' }],
|
||||
ME,
|
||||
)
|
||||
assert.deepEqual(keys(result), ['a'])
|
||||
})
|
||||
|
||||
test('isSharedKbEditable treats admin/editor as editable, others read-only', () => {
|
||||
assert.equal(isSharedKbEditable('admin'), true)
|
||||
assert.equal(isSharedKbEditable('editor'), true)
|
||||
assert.equal(isSharedKbEditable('viewer'), false)
|
||||
assert.equal(isSharedKbEditable(undefined), false)
|
||||
})
|
||||
@@ -0,0 +1,155 @@
|
||||
// Pure helpers backing the "All" scope of the knowledge-base list.
|
||||
//
|
||||
// The list template renders every card with `:key="kb.id"`. Vue requires
|
||||
// `v-for` keys to be unique within a list — duplicate keys corrupt the
|
||||
// virtual-DOM patch and the list renders empty or partial. The same
|
||||
// knowledge base can legitimately show up more than once in the source
|
||||
// data:
|
||||
//
|
||||
// 1. A KB the caller owns can also be shared back to them (e.g. they
|
||||
// belong to an org the KB was shared into), so it appears in both the
|
||||
// owned list and `sharedKnowledgeBases`.
|
||||
// 2. The very same KB can be shared into the caller's view through more
|
||||
// than one organization. Each share is a distinct row (its own
|
||||
// `share_id`) but carries the identical `knowledge_base.id`.
|
||||
//
|
||||
// Either case yields two entries with the same `kb.id` once there are ≥2
|
||||
// knowledge bases, which is the #795 symptom: a single KB renders fine
|
||||
// (no collision) while two or more blank the page. De-duplicating by KB
|
||||
// id here keeps the keys unique. Owned rows win over shared ones, and
|
||||
// among multiple shares of the same KB we keep the most-privileged
|
||||
// permission so the card stays as capable as the caller's best grant.
|
||||
|
||||
export interface OwnedKnowledgeBase {
|
||||
id: string;
|
||||
is_pinned?: boolean;
|
||||
pinned_at?: string;
|
||||
created_at?: string;
|
||||
creator_id?: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface SharedKnowledgeBaseLike {
|
||||
knowledge_base: {
|
||||
id: string;
|
||||
knowledge_count?: number;
|
||||
chunk_count?: number;
|
||||
[key: string]: unknown;
|
||||
} | null;
|
||||
permission: string;
|
||||
shared_at: string;
|
||||
share_id: string;
|
||||
org_name?: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export type MergedOwnedKnowledgeBase = OwnedKnowledgeBase & { isMine: true };
|
||||
export type MergedSharedKnowledgeBase = Record<string, unknown> & {
|
||||
id: string;
|
||||
isMine: false;
|
||||
permission: string;
|
||||
shared_at: string;
|
||||
share_id: string;
|
||||
org_name?: string;
|
||||
};
|
||||
export type MergedKnowledgeBase =
|
||||
| MergedOwnedKnowledgeBase
|
||||
| MergedSharedKnowledgeBase;
|
||||
|
||||
// Permissions that grant write access. Mirrors EDITABLE_PERMS in
|
||||
// KnowledgeBaseList.vue — kept local so this module stays free of any
|
||||
// component/store imports and remains trivially unit-testable.
|
||||
const EDITABLE_PERMS = new Set(['admin', 'editor']);
|
||||
|
||||
export function isSharedKbEditable(perm: string | undefined): boolean {
|
||||
return !!perm && EDITABLE_PERMS.has(perm);
|
||||
}
|
||||
|
||||
// Higher rank = more privileged. Unknown permissions rank lowest so they
|
||||
// never shadow a real grant when collapsing duplicate shares.
|
||||
const PERMISSION_RANK: Record<string, number> = { admin: 3, editor: 2, viewer: 1 };
|
||||
|
||||
function permissionRank(perm: string | undefined): number {
|
||||
return (perm && PERMISSION_RANK[perm]) || 0;
|
||||
}
|
||||
|
||||
function isMyKb(kb: { creator_id?: string }, currentUserId: string | undefined): boolean {
|
||||
return !!(kb.creator_id && currentUserId && kb.creator_id === currentUserId);
|
||||
}
|
||||
|
||||
function pinnedTime(kb: OwnedKnowledgeBase): number {
|
||||
return kb.pinned_at ? Date.parse(kb.pinned_at) : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the de-duplicated, ordered list rendered by the "All" scope.
|
||||
*
|
||||
* Ordering (unchanged from the previous inline logic):
|
||||
* 1. pinned KBs (any creator the caller pinned), newest pin first
|
||||
* 2. the caller's own non-pinned KBs
|
||||
* 3. teammate non-pinned KBs (own tenant, someone else created)
|
||||
* 4. shared KBs, editable grants before view-only
|
||||
*
|
||||
* On top of that, every entry is unique by knowledge-base id: owned rows
|
||||
* win over shared duplicates, and repeated shares of one KB collapse to
|
||||
* the most-privileged permission.
|
||||
*/
|
||||
export function mergeAllScopeKnowledgeBases(
|
||||
owned: OwnedKnowledgeBase[],
|
||||
shared: SharedKnowledgeBaseLike[],
|
||||
currentUserId: string | undefined,
|
||||
): MergedKnowledgeBase[] {
|
||||
const result: MergedKnowledgeBase[] = [];
|
||||
|
||||
const pinned: OwnedKnowledgeBase[] = [];
|
||||
const ownMine: OwnedKnowledgeBase[] = [];
|
||||
const teammateMine: OwnedKnowledgeBase[] = [];
|
||||
const ownedIds = new Set<string>();
|
||||
for (const kb of owned) {
|
||||
ownedIds.add(kb.id);
|
||||
if (kb.is_pinned) pinned.push(kb);
|
||||
else if (isMyKb(kb, currentUserId)) ownMine.push(kb);
|
||||
else teammateMine.push(kb);
|
||||
}
|
||||
pinned.sort((a, b) => pinnedTime(b) - pinnedTime(a));
|
||||
|
||||
for (const kb of pinned) result.push({ ...kb, isMine: true as const });
|
||||
for (const kb of ownMine) result.push({ ...kb, isMine: true as const });
|
||||
for (const kb of teammateMine) result.push({ ...kb, isMine: true as const });
|
||||
|
||||
// Collapse the shared rows by KB id, keeping the most-privileged grant,
|
||||
// and drop any KB the caller already owns. This is what guarantees a
|
||||
// unique `:key` per rendered card.
|
||||
const dedupedShared = new Map<string, SharedKnowledgeBaseLike>();
|
||||
for (const entry of shared) {
|
||||
const kb = entry?.knowledge_base;
|
||||
if (!kb) continue;
|
||||
if (ownedIds.has(kb.id)) continue;
|
||||
const existing = dedupedShared.get(kb.id);
|
||||
if (!existing || permissionRank(entry.permission) > permissionRank(existing.permission)) {
|
||||
dedupedShared.set(kb.id, entry);
|
||||
}
|
||||
}
|
||||
|
||||
const sortedShared = [...dedupedShared.values()].sort((a, b) => {
|
||||
const aE = isSharedKbEditable(a.permission) ? 0 : 1;
|
||||
const bE = isSharedKbEditable(b.permission) ? 0 : 1;
|
||||
return aE - bE;
|
||||
});
|
||||
|
||||
for (const shared of sortedShared) {
|
||||
const kb = shared.knowledge_base!;
|
||||
result.push({
|
||||
...kb,
|
||||
isMine: false as const,
|
||||
permission: shared.permission,
|
||||
shared_at: shared.shared_at,
|
||||
share_id: shared.share_id,
|
||||
org_name: shared.org_name,
|
||||
knowledge_count: kb.knowledge_count,
|
||||
chunk_count: kb.chunk_count,
|
||||
} as MergedSharedKnowledgeBase);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
|
||||
import { isBatchDownloadableKnowledge, resolveKnowledgeDownloadFileName } from './knowledgeDownloadFileName.ts';
|
||||
|
||||
test('prefers the original filename over the extensionless display name', () => {
|
||||
assert.equal(resolveKnowledgeDownloadFileName({
|
||||
id: 'knowledge-1',
|
||||
original_file_name: 'quarterly-report.pdf',
|
||||
file_name: 'quarterly-report',
|
||||
type: 'file',
|
||||
}), 'quarterly-report.pdf');
|
||||
});
|
||||
|
||||
test('falls back to the backend filename when no original filename is present', () => {
|
||||
assert.equal(resolveKnowledgeDownloadFileName({
|
||||
id: 'knowledge-2',
|
||||
file_name: 'notes.txt',
|
||||
type: 'file',
|
||||
}), 'notes.txt');
|
||||
});
|
||||
|
||||
test('batch download skips web pages without an original file', () => {
|
||||
assert.equal(isBatchDownloadableKnowledge({ type: 'manual' }), true);
|
||||
assert.equal(isBatchDownloadableKnowledge({ type: 'file', file_path: 'stored' }), true);
|
||||
assert.equal(isBatchDownloadableKnowledge({ type: 'url' }), false);
|
||||
assert.equal(isBatchDownloadableKnowledge({ type: 'url', file_path: 'snapshot.html' }), true);
|
||||
assert.equal(isBatchDownloadableKnowledge(undefined), false);
|
||||
});
|
||||
|
||||
test('adds the markdown extension to manual documents exactly once', () => {
|
||||
assert.equal(resolveKnowledgeDownloadFileName({
|
||||
id: 'knowledge-3',
|
||||
title: 'meeting-notes',
|
||||
type: 'manual',
|
||||
}), 'meeting-notes.md');
|
||||
assert.equal(resolveKnowledgeDownloadFileName({
|
||||
id: 'knowledge-4',
|
||||
title: 'meeting-notes.md',
|
||||
type: 'manual',
|
||||
}), 'meeting-notes.md');
|
||||
});
|
||||
@@ -0,0 +1,21 @@
|
||||
export interface KnowledgeDownloadItem {
|
||||
id: string;
|
||||
original_file_name?: string;
|
||||
file_name?: string;
|
||||
title?: string;
|
||||
type?: string;
|
||||
}
|
||||
|
||||
export function resolveKnowledgeDownloadFileName(item: KnowledgeDownloadItem): string {
|
||||
const baseName = item.original_file_name || item.file_name || item.title || item.id;
|
||||
if (item.type === 'manual' && !baseName.toLowerCase().endsWith('.md')) {
|
||||
return `${baseName}.md`;
|
||||
}
|
||||
return baseName;
|
||||
}
|
||||
|
||||
export function isBatchDownloadableKnowledge(item?: { type?: string; file_path?: string } | null): boolean {
|
||||
if (!item) return false;
|
||||
if (item.type === 'manual') return true;
|
||||
return Boolean(item.file_path);
|
||||
}
|
||||
@@ -0,0 +1,495 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { createRequire } from 'node:module'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { runInNewContext } from 'node:vm'
|
||||
import test from 'node:test'
|
||||
import { compileScript, parse } from '@vue/compiler-sfc'
|
||||
import ts from 'typescript'
|
||||
import { createRenderer, h, nextTick, reactive, ref } from 'vue'
|
||||
|
||||
const require = createRequire(import.meta.url)
|
||||
const filename = fileURLToPath(new URL('./DataSourceEditorDialog.vue', import.meta.url))
|
||||
const { descriptor } = parse(readFileSync(filename, 'utf8'), { filename })
|
||||
const script = compileScript(descriptor, { id: 'datasource-editor-test' }).content
|
||||
.replace('__expose();', '')
|
||||
.replace('return __returned__', '__expose(__returned__); return __returned__')
|
||||
const compiled = ts.transpileModule(script, {
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 },
|
||||
}).outputText
|
||||
|
||||
// Lets un-awaited API calls (e.g. loadResources fired by nextStep) settle.
|
||||
const flush = async () => {
|
||||
await new Promise(resolve => setImmediate(resolve))
|
||||
await nextTick()
|
||||
}
|
||||
|
||||
async function fixture({
|
||||
configured = true,
|
||||
create = false,
|
||||
type = 'gitlab',
|
||||
settings = { projects: [{ project_id: '123', paths: [] }] },
|
||||
resources = [],
|
||||
dataSource = null,
|
||||
}: {
|
||||
configured?: boolean
|
||||
create?: boolean
|
||||
type?: string
|
||||
settings?: Record<string, unknown>
|
||||
resources?: any[]
|
||||
dataSource?: any
|
||||
} = {}) {
|
||||
const calls: Array<{ method: string; args: any[] }> = []
|
||||
const warnings: string[] = []
|
||||
let storedToken = configured ? 'expired-token' : ''
|
||||
const api = {
|
||||
async validateCredentials(type: string, credentials: Record<string, string>) {
|
||||
calls.push({ method: 'validateCredentials', args: [type, { ...credentials }] })
|
||||
if (type !== 'confluence' && credentials.access_token !== 'rotated-token') throw new Error('gitlab API /user: status 401')
|
||||
},
|
||||
async validateConnection(id: string) {
|
||||
calls.push({ method: 'validateConnection', args: [id] })
|
||||
if (storedToken !== 'rotated-token') throw new Error('gitlab API /user: status 401')
|
||||
},
|
||||
async updateDataSource(id: string, data: any) {
|
||||
calls.push({ method: 'updateDataSource', args: [id, JSON.parse(JSON.stringify(data))] })
|
||||
// The main update endpoint deliberately preserves stored credentials.
|
||||
},
|
||||
async putDataSourceCredentials(id: string, credentials: Record<string, string>) {
|
||||
calls.push({ method: 'putDataSourceCredentials', args: [id, { ...credentials }] })
|
||||
storedToken = credentials.access_token
|
||||
},
|
||||
async createDataSource(data: any) {
|
||||
calls.push({ method: 'createDataSource', args: [JSON.parse(JSON.stringify(data))] })
|
||||
return { data: { id: 'source-temp' } }
|
||||
},
|
||||
// Lazy picker: the first call lists roots, later calls list one level.
|
||||
async listResources(id: string, parentId?: string) {
|
||||
calls.push({ method: 'listResources', args: [id, parentId] })
|
||||
return { data: resources.filter(r => (parentId ? r.parent_id === parentId : !r.parent_id)) }
|
||||
},
|
||||
async resolveResourceAncestors(id: string, ids: string[]) {
|
||||
calls.push({ method: 'resolveResourceAncestors', args: [id, ids] })
|
||||
return { data: { ancestors: [] } }
|
||||
},
|
||||
}
|
||||
const props = reactive({
|
||||
visible: false, kbId: 'kb-one',
|
||||
dataSource: create ? null : dataSource || {
|
||||
id: 'source-one', name: 'GitLab', type,
|
||||
credentials: { credentials: { configured } },
|
||||
config: { resource_ids: [], settings },
|
||||
sync_schedule: '0 0 */6 * * *', sync_mode: 'incremental',
|
||||
conflict_strategy: 'overwrite', sync_deletions: true,
|
||||
},
|
||||
})
|
||||
const exports: any = {}
|
||||
runInNewContext(compiled, {
|
||||
exports,
|
||||
require(name: string) {
|
||||
if (name === 'vue') return require('vue')
|
||||
if (name === 'vue-i18n') return { useI18n: () => ({ t: (key: string) => key }) }
|
||||
if (name === 'tdesign-vue-next') return { MessagePlugin: { warning(msg: string) { warnings.push(msg) }, success() {}, error() {} } }
|
||||
if (name === '@/api/datasource') return api
|
||||
return { default: {} }
|
||||
},
|
||||
URL, console,
|
||||
})
|
||||
const component = exports.default
|
||||
component.render = () => null
|
||||
const renderer = createRenderer<any, any>({
|
||||
createElement: () => ({}), createText: () => ({}), createComment: () => ({}),
|
||||
insert() {}, remove() {}, setElementText() {}, setText() {}, patchProp() {},
|
||||
parentNode: () => null, nextSibling: () => null,
|
||||
})
|
||||
const instance = ref<any>()
|
||||
const app = renderer.createApp({ render: () => h(component, { ...props, ref: instance }) })
|
||||
app.mount({})
|
||||
props.visible = true
|
||||
await nextTick()
|
||||
const vm = instance.value
|
||||
async function replace(token = 'rotated-token') {
|
||||
vm.enterReplaceCredentials()
|
||||
vm.form.config.credentials = { base_url: 'https://gitlab.example.com', access_token: token }
|
||||
await nextTick()
|
||||
}
|
||||
return { vm, calls, warnings, replace, storedToken: () => storedToken, close: () => app.unmount() }
|
||||
}
|
||||
|
||||
test('rotated GitLab credentials are tested without updating the saved data source', async () => {
|
||||
const f = await fixture()
|
||||
try {
|
||||
await f.replace()
|
||||
await f.vm.testConnection()
|
||||
assert.equal(f.vm.testResult, 'success')
|
||||
assert.deepEqual(f.calls, [{ method: 'validateCredentials', args: ['gitlab', {
|
||||
base_url: 'https://gitlab.example.com', access_token: 'rotated-token',
|
||||
}] }])
|
||||
assert.equal(f.storedToken(), 'expired-token')
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
test('Next tests the replacement and final save commits credentials before settings', async () => {
|
||||
const f = await fixture()
|
||||
try {
|
||||
await f.replace()
|
||||
await f.vm.nextStep()
|
||||
assert.equal(f.vm.step, 2)
|
||||
await f.vm.nextStep()
|
||||
assert.equal(f.vm.step, 3)
|
||||
await f.vm.handleSubmit()
|
||||
assert.deepEqual(f.calls.map(call => call.method), [
|
||||
'validateCredentials', 'putDataSourceCredentials', 'updateDataSource',
|
||||
])
|
||||
assert.equal(f.storedToken(), 'rotated-token')
|
||||
assert.deepEqual(f.calls[2].args[1].config.credentials, {})
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
test('invalid replacement stays on the credentials step and can be corrected', async () => {
|
||||
const f = await fixture()
|
||||
try {
|
||||
await f.replace('invalid-token')
|
||||
await f.vm.nextStep()
|
||||
assert.equal(f.vm.step, 1)
|
||||
assert.equal(f.vm.testResult, 'error')
|
||||
assert.match(f.vm.testErrorMsg, /401/)
|
||||
assert.equal(f.storedToken(), 'expired-token')
|
||||
await f.replace()
|
||||
await f.vm.nextStep()
|
||||
assert.equal(f.vm.step, 2)
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
test('testing unchanged credentials still validates the stored token', async () => {
|
||||
const f = await fixture()
|
||||
try {
|
||||
await f.vm.testConnection()
|
||||
assert.equal(f.vm.testResult, 'error')
|
||||
assert.deepEqual(f.calls.map(call => call.method), ['updateDataSource', 'validateConnection'])
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
test('an existing data source with no saved credentials tests the entered token', async () => {
|
||||
const f = await fixture({ configured: false })
|
||||
try {
|
||||
await f.replace()
|
||||
await f.vm.testConnection()
|
||||
assert.equal(f.vm.testResult, 'success')
|
||||
assert.deepEqual(f.calls.map(call => call.method), ['validateCredentials'])
|
||||
assert.equal(f.storedToken(), '')
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
test('new GitLab data sources continue to test credentials without persistence', async () => {
|
||||
const f = await fixture({ create: true })
|
||||
try {
|
||||
f.vm.selectType(f.vm.connectorDefs.find((def: any) => def.type === 'gitlab'))
|
||||
await f.replace()
|
||||
await f.vm.testConnection()
|
||||
assert.equal(f.vm.testResult, 'success')
|
||||
assert.deepEqual(f.calls.map(call => call.method), ['validateCredentials'])
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
const seafileRepoA = '0f1e2d3c-4b5a-4968-8776-655443322110'
|
||||
const seafileRepoB = 'ffffffff-0000-4000-8000-000000000001'
|
||||
|
||||
// A lazy Seafile tree: two libraries, one with a folder that holds a file.
|
||||
const seafileResources = [
|
||||
{ external_id: `${seafileRepoA}:/`, name: 'Docs', type: 'library', has_children: true },
|
||||
{ external_id: `${seafileRepoB}:/`, name: 'Design', type: 'library', has_children: true },
|
||||
{ external_id: `${seafileRepoA}:/guides`, name: 'guides', type: 'directory', parent_id: `${seafileRepoA}:/`, has_children: true },
|
||||
{ external_id: `${seafileRepoA}:/guides/a.pdf`, name: 'a.pdf', type: 'file', parent_id: `${seafileRepoA}:/guides`, has_children: false },
|
||||
]
|
||||
|
||||
// Opens a new Seafile data source on the picker step with the roots listed.
|
||||
async function seafileFixture(resources = seafileResources) {
|
||||
const f = await fixture({ create: true, resources })
|
||||
f.vm.selectType(f.vm.connectorDefs.find((def: any) => def.type === 'seafile'))
|
||||
f.vm.form.config.credentials = { base_url: 'https://seafile.example.com', api_token: 'rotated-token' }
|
||||
f.vm.testResult = 'success'
|
||||
await f.vm.nextStep()
|
||||
await flush()
|
||||
return f
|
||||
}
|
||||
|
||||
test('Seafile picker lists libraries lazily and shows the library icon', async () => {
|
||||
const f = await seafileFixture()
|
||||
try {
|
||||
assert.equal(f.vm.step, 2)
|
||||
assert.deepEqual(f.calls.map(call => call.method), ['createDataSource', 'listResources'])
|
||||
assert.deepEqual([...f.vm.resources].map((r: any) => r.external_id), [`${seafileRepoA}:/`, `${seafileRepoB}:/`])
|
||||
assert.equal(f.vm.resourceIconName(f.vm.resources[0]), 'root-list')
|
||||
assert.equal(f.vm.resourceTypeLabel('library'), 'datasource.resourceType.library')
|
||||
await f.vm.ensureChildrenLoaded(`${seafileRepoA}:/`)
|
||||
await f.vm.ensureChildrenLoaded(`${seafileRepoA}:/guides`)
|
||||
assert.equal(f.vm.resourceIconName(f.vm.resources.find((r: any) => r.name === 'guides')), 'folder')
|
||||
assert.equal(f.vm.resourceIconName(f.vm.resources.find((r: any) => r.name === 'a.pdf')), 'file')
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
test('Seafile selection stays within one library until it is cleared', async () => {
|
||||
const f = await seafileFixture()
|
||||
try {
|
||||
await f.vm.ensureChildrenLoaded(`${seafileRepoA}:/`)
|
||||
await f.vm.ensureChildrenLoaded(`${seafileRepoA}:/guides`)
|
||||
f.vm.toggleResource(`${seafileRepoA}:/guides/a.pdf`)
|
||||
f.vm.toggleResource(`${seafileRepoB}:/`)
|
||||
assert.deepEqual([...f.vm.selectedResourceIds], [`${seafileRepoA}:/guides/a.pdf`])
|
||||
assert.deepEqual(f.warnings, ['datasource.seafile.singleLibraryOnly'])
|
||||
// Clearing library A first lets the user pick library B before saving.
|
||||
f.vm.toggleResource(`${seafileRepoA}:/guides/a.pdf`)
|
||||
f.vm.toggleResource(`${seafileRepoB}:/`)
|
||||
assert.deepEqual([...f.vm.selectedResourceIds], [`${seafileRepoB}:/`])
|
||||
assert.equal(f.warnings.length, 1)
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
test('Seafile requires a selection before the strategy step', async () => {
|
||||
const f = await seafileFixture()
|
||||
try {
|
||||
await f.vm.nextStep()
|
||||
assert.equal(f.vm.step, 2)
|
||||
assert.deepEqual(f.warnings, ['datasource.seafile.selectionRequired'])
|
||||
f.vm.toggleResource(`${seafileRepoA}:/`)
|
||||
await f.vm.nextStep()
|
||||
assert.equal(f.vm.step, 3)
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
test('a vanished saved Seafile selection is cleared by unchecking its library', async () => {
|
||||
const f = await fixture({ resources: seafileResources, dataSource: {
|
||||
id: 'source-one', name: 'Seafile', type: 'seafile',
|
||||
credentials: { credentials: { configured: true } },
|
||||
config: { resource_ids: [`${seafileRepoA}:/guides/vanished.pdf`], settings: {} },
|
||||
sync_schedule: '0 0 */6 * * *', sync_mode: 'incremental',
|
||||
conflict_strategy: 'overwrite', sync_deletions: true,
|
||||
} })
|
||||
try {
|
||||
await f.vm.nextStep()
|
||||
await flush()
|
||||
assert.equal(f.vm.step, 2)
|
||||
assert.deepEqual([...f.vm.selectedResourceIds], [`${seafileRepoA}:/guides/vanished.pdf`])
|
||||
// The stale path is invisible, so library B is refused until A is cleared.
|
||||
f.vm.toggleResource(`${seafileRepoB}:/`)
|
||||
assert.deepEqual(f.warnings, ['datasource.seafile.singleLibraryOnly'])
|
||||
// Checking then unchecking library A sweeps the stale path with it.
|
||||
f.vm.toggleResource(`${seafileRepoA}:/`)
|
||||
f.vm.toggleResource(`${seafileRepoA}:/`)
|
||||
assert.deepEqual([...f.vm.selectedResourceIds], [])
|
||||
f.vm.toggleResource(`${seafileRepoB}:/`)
|
||||
assert.deepEqual([...f.vm.selectedResourceIds], [`${seafileRepoB}:/`])
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
test('the single-library guard leaves Feishu and Lark Drive selections alone', async () => {
|
||||
for (const type of ['feishu_drive', 'lark_drive']) {
|
||||
const f = await fixture({ create: true })
|
||||
try {
|
||||
f.vm.selectType(f.vm.connectorDefs.find((def: any) => def.type === type))
|
||||
// Drive IDs are "folderToken:fileToken"; roots under two folders must
|
||||
// both stay selectable.
|
||||
f.vm.resources = [
|
||||
{ external_id: 'folderA:fileA', name: 'A', type: 'file', has_children: false },
|
||||
{ external_id: 'folderB:fileB', name: 'B', type: 'file', has_children: false },
|
||||
]
|
||||
await nextTick()
|
||||
f.vm.toggleResource('folderA:fileA')
|
||||
f.vm.toggleResource('folderB:fileB')
|
||||
assert.deepEqual([...f.vm.selectedResourceIds].sort(), ['folderA:fileA', 'folderB:fileB'], type)
|
||||
assert.deepEqual(f.warnings, [], type)
|
||||
} finally { f.close() }
|
||||
}
|
||||
})
|
||||
|
||||
test('a new Yuque data source adopts the TOC folder layout, but not the filter', async () => {
|
||||
const f = await fixture({ create: true })
|
||||
try {
|
||||
assert.equal(f.vm.form.config.settings.folder_mode, undefined)
|
||||
f.vm.selectType(f.vm.connectorDefs.find((def: any) => def.type === 'yuque'))
|
||||
assert.equal(f.vm.form.config.settings.folder_mode, 'toc')
|
||||
// The layout is a presentation choice; toc_only decides what may enter the
|
||||
// knowledge base, so a new source is deliberately left without it.
|
||||
assert.equal(f.vm.form.config.settings.toc_only, undefined)
|
||||
assert.equal(f.vm.yuqueTOCOnly, false)
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
test('an existing Yuque data source reports its admission filter', async () => {
|
||||
const f = await fixture({ type: 'yuque', settings: { folder_mode: 'toc', toc_only: true } })
|
||||
try {
|
||||
assert.equal(f.vm.yuqueTOCOnly, true)
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
test('an existing Yuque data source is never switched to the TOC layout', async () => {
|
||||
const f = await fixture({ type: 'yuque', settings: {} })
|
||||
try {
|
||||
// Opening a source created before this control existed must not inject
|
||||
// folder_mode: the connector default (flat) has to stand, otherwise editing
|
||||
// an unrelated field would silently re-file the whole knowledge base.
|
||||
assert.equal(f.vm.form.config.settings.folder_mode, undefined)
|
||||
assert.equal(f.vm.yuqueFolderMode, 'none')
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
test('an existing Yuque data source on the TOC layout reports it', async () => {
|
||||
const f = await fixture({ type: 'yuque', settings: { folder_mode: 'toc' } })
|
||||
try {
|
||||
assert.equal(f.vm.yuqueFolderMode, 'toc')
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
test('a DingTalk data source reports the uploaded-file switch, defaulting to off', async () => {
|
||||
const off = await fixture({ type: 'dingtalk', settings: {} })
|
||||
try {
|
||||
// The connector treats a missing key as false, so an existing source that
|
||||
// predates this control must render as off — and stay untouched.
|
||||
assert.equal(off.vm.dingtalkIncludeUploadedFiles, false)
|
||||
assert.equal(off.vm.form.config.settings.include_uploaded_files, undefined)
|
||||
} finally { off.close() }
|
||||
|
||||
const on = await fixture({ type: 'dingtalk', settings: { include_uploaded_files: true } })
|
||||
try {
|
||||
assert.equal(on.vm.dingtalkIncludeUploadedFiles, true)
|
||||
} finally { on.close() }
|
||||
|
||||
const explicitOff = await fixture({ type: 'dingtalk', settings: { include_uploaded_files: false } })
|
||||
try {
|
||||
assert.equal(explicitOff.vm.dingtalkIncludeUploadedFiles, false)
|
||||
} finally { explicitOff.close() }
|
||||
})
|
||||
|
||||
test('toggling the DingTalk uploaded-file switch writes the settings key', async () => {
|
||||
const f = await fixture({ type: 'dingtalk', settings: {} })
|
||||
try {
|
||||
f.vm.dingtalkIncludeUploadedFiles = true
|
||||
assert.equal(f.vm.form.config.settings.include_uploaded_files, true)
|
||||
f.vm.dingtalkIncludeUploadedFiles = false
|
||||
assert.equal(f.vm.form.config.settings.include_uploaded_files, false)
|
||||
// The switch is scoped to DingTalk: no other connector's key is written.
|
||||
assert.equal(f.vm.form.config.settings.include_sheets, undefined)
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
test('Cloud hierarchy limitation stays visible after an empty space expansion', async () => {
|
||||
const f = await fixture()
|
||||
try {
|
||||
f.vm.resources = [{
|
||||
external_id: 'space-1',
|
||||
name: 'Cloud space',
|
||||
type: 'space',
|
||||
has_children: true,
|
||||
metadata: { hierarchy_limitation: 'cloud_top_level_containers' },
|
||||
}]
|
||||
f.vm.expandedResourceIds = new Set(['space-1'])
|
||||
await nextTick()
|
||||
assert.equal(f.vm.visibleTree.some((row: any) => row.noticeAfter), true)
|
||||
|
||||
f.vm.expandedResourceIds = new Set()
|
||||
f.vm.loadedChildrenIds = new Set(['space-1'])
|
||||
f.vm.resources = [{ ...f.vm.resources[0], has_children: false }]
|
||||
await nextTick()
|
||||
assert.equal(f.vm.visibleTree.some((row: any) => row.noticeAfter), true)
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
for (const type of ['feishu', 'lark', 'feishu_drive', 'lark_drive']) {
|
||||
test(`${type} preserves inherited parse mode when saving unrelated settings`, async () => {
|
||||
const settings = { timezone: 'Asia/Shanghai', resync_required: true }
|
||||
const f = await fixture({ type, settings })
|
||||
try {
|
||||
assert.equal(f.vm.feishuParseMode, '')
|
||||
assert.equal(f.vm.form.config.settings.parse_mode, undefined)
|
||||
f.vm.form.name = 'Renamed source'
|
||||
await f.vm.handleSubmit()
|
||||
const saved = f.calls.find(call => call.method === 'updateDataSource')
|
||||
assert.ok(saved)
|
||||
assert.deepEqual(saved.args[1].config.settings, settings)
|
||||
assert.equal('parse_mode' in settings, false, 'opening the editor must not mutate props')
|
||||
} finally { f.close() }
|
||||
})
|
||||
}
|
||||
|
||||
test('Feishu explicit mode changes are saved without mutating the source configuration', async () => {
|
||||
const settings = { parse_mode: 'export', timezone: 'Asia/Shanghai' }
|
||||
const f = await fixture({ type: 'feishu', settings })
|
||||
try {
|
||||
assert.equal(f.vm.feishuParseMode, 'export')
|
||||
f.vm.feishuParseMode = 'blocks'
|
||||
assert.equal(settings.parse_mode, 'export')
|
||||
assert.equal(f.vm.buildConfigPayload().settings.parse_mode, 'blocks')
|
||||
f.vm.feishuParseMode = ''
|
||||
assert.deepEqual(JSON.parse(JSON.stringify(f.vm.buildConfigPayload().settings)), { timezone: 'Asia/Shanghai' })
|
||||
assert.equal(settings.parse_mode, 'export')
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
test('new Feishu sources keep the blocks default and do not leak it to another connector', async () => {
|
||||
const f = await fixture({ create: true })
|
||||
try {
|
||||
f.vm.selectType(f.vm.connectorDefs.find((def: any) => def.type === 'feishu'))
|
||||
assert.equal(f.vm.feishuParseMode, 'blocks')
|
||||
f.vm.selectType(f.vm.connectorDefs.find((def: any) => def.type === 'gitlab'))
|
||||
assert.equal(f.vm.form.config.settings.parse_mode, undefined)
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
|
||||
test('Confluence PAT permits connection testing and saving without Basic credentials', async () => {
|
||||
const f = await fixture({ create: true, configured: false, settings: {} })
|
||||
try {
|
||||
f.vm.selectType(f.vm.connectorDefs.find((def: any) => def.type === 'confluence'))
|
||||
f.vm.form.config.credentials = { edition: 'server', base_url: 'https://confluence.test/wiki', token: 'pat-value' }
|
||||
await nextTick()
|
||||
const fields = f.vm.displayedCredentialFields
|
||||
assert.equal(fields.find((field: any) => field.key === 'token').secret, true)
|
||||
assert.equal(fields.find((field: any) => field.key === 'username').optional, true)
|
||||
assert.equal(fields.find((field: any) => field.key === 'password').optional, true)
|
||||
assert.equal(fields.some((field: any) => field.key === 'api_token'), false)
|
||||
await f.vm.testConnection()
|
||||
assert.equal(f.vm.testResult, 'success')
|
||||
assert.equal(f.calls.find(c => c.method === 'validateCredentials')?.args[1].token, 'pat-value')
|
||||
await f.vm.loadResources()
|
||||
const created = f.calls.find(c => c.method === 'createDataSource')?.args[0]
|
||||
assert.equal(created.config.credentials.token, 'pat-value')
|
||||
assert.equal(created.config.settings.token, undefined)
|
||||
assert.deepEqual(f.warnings, [])
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
test('Confluence requires Basic credentials without a PAT and hides PAT in Cloud', async () => {
|
||||
const f = await fixture({ type: 'confluence', configured: false, settings: {} })
|
||||
try {
|
||||
f.vm.form.config.credentials = { edition: 'server', base_url: 'https://confluence.test/wiki', token: ' ' }
|
||||
await nextTick()
|
||||
assert.equal(f.vm.displayedCredentialFields.find((field: any) => field.key === 'username').optional, false)
|
||||
assert.equal(f.vm.displayedCredentialFields.find((field: any) => field.key === 'password').optional, false)
|
||||
await f.vm.testConnection()
|
||||
assert.equal(f.calls.some(c => c.method === 'validateCredentials'), false)
|
||||
f.vm.form.config.credentials.edition = 'cloud'
|
||||
f.vm.form.config.credentials.token = 'stale-server-token'
|
||||
await nextTick()
|
||||
assert.deepEqual(Array.from(f.vm.displayedCredentialFields, (field: any) => field.key), ['base_url', 'username', 'api_token'])
|
||||
assert.equal(f.vm.displayedCredentialFields.find((field: any) => field.key === 'username').optional, false)
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
|
||||
test('Confluence PAT replacement uses the credentials subresource and keeps the token out of settings', async () => {
|
||||
const f = await fixture({ type: 'confluence', settings: { edition: 'server', base_url: 'https://confluence.test/wiki' } })
|
||||
try {
|
||||
f.vm.enterReplaceCredentials()
|
||||
f.vm.form.config.credentials.token = 'replacement-pat'
|
||||
await nextTick()
|
||||
await f.vm.testConnection()
|
||||
assert.equal(f.vm.testResult, 'success')
|
||||
await f.vm.handleSubmit()
|
||||
const replacement = f.calls.find(c => c.method === 'putDataSourceCredentials')
|
||||
assert.equal(replacement?.args[1].token, 'replacement-pat')
|
||||
const update = f.calls.find(c => c.method === 'updateDataSource')?.args[1]
|
||||
assert.deepEqual(update.config.credentials, {})
|
||||
assert.equal(update.config.settings.token, undefined)
|
||||
} finally { f.close() }
|
||||
})
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,653 @@
|
||||
<script setup lang="ts">
|
||||
import { fmtBeijingTime } from '@/utils/datetime'
|
||||
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
|
||||
import { MessagePlugin } from 'tdesign-vue-next'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { useConnectorLabel } from '@/composables/useConnectorLabel'
|
||||
import {
|
||||
listDataSources,
|
||||
deleteDataSource,
|
||||
triggerSync,
|
||||
pauseDataSource,
|
||||
resumeDataSource,
|
||||
type DataSource,
|
||||
} from '@/api/datasource'
|
||||
import { humanizeCron, relativeTime } from '@/utils/cronHumanize'
|
||||
import DataSourceEditorDialog from './DataSourceEditorDialog.vue'
|
||||
import DataSourceSyncLogs from './DataSourceSyncLogs.vue'
|
||||
import DataSourceTypeIcon from './DataSourceTypeIcon.vue'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import { useAssistantDataChange } from '@/utils/assistantDataChange'
|
||||
|
||||
const props = defineProps<{ kbId: string }>()
|
||||
const emit = defineEmits<{ (e: 'count', value: number): void }>()
|
||||
const { t } = useI18n()
|
||||
const authStore = useAuthStore()
|
||||
|
||||
// 后端 /datasource 的 list/logs 是 Viewer+,但所有写操作(POST/PUT/DELETE
|
||||
// 以及 sync/pause/resume/validate)都是 Admin+。低权限用户保留只读视图,
|
||||
// 增删改和触发同步全部隐藏,而不是按下去再撞 403。
|
||||
const canManageDataSource = computed(() => authStore.hasRole('admin'))
|
||||
|
||||
const dataSources = ref<DataSource[]>([])
|
||||
const loading = ref(false)
|
||||
const editorVisible = ref(false)
|
||||
const editingDs = ref<DataSource | null>(null)
|
||||
const logsVisible = ref(false)
|
||||
const logsDsId = ref('')
|
||||
const logsDsName = ref('')
|
||||
const pollTimer = ref<number | null>(null)
|
||||
|
||||
function stopPolling() {
|
||||
if (pollTimer.value !== null) {
|
||||
window.clearTimeout(pollTimer.value)
|
||||
pollTimer.value = null
|
||||
}
|
||||
}
|
||||
|
||||
function schedulePolling() {
|
||||
stopPolling()
|
||||
pollTimer.value = window.setTimeout(() => {
|
||||
loadList(true)
|
||||
}, 3000)
|
||||
}
|
||||
|
||||
async function loadList(silent = false) {
|
||||
if (!silent) loading.value = true
|
||||
try {
|
||||
const res = await listDataSources(props.kbId)
|
||||
dataSources.value = res?.data || res || []
|
||||
emit('count', dataSources.value.length)
|
||||
|
||||
const hasRunningSync = dataSources.value.some(ds => ds.latest_sync_log?.status === 'running')
|
||||
if (hasRunningSync) {
|
||||
schedulePolling()
|
||||
} else {
|
||||
stopPolling()
|
||||
}
|
||||
} catch (e: any) {
|
||||
console.error(e)
|
||||
} finally {
|
||||
if (!silent) loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function openCreate() {
|
||||
editingDs.value = null
|
||||
editorVisible.value = true
|
||||
}
|
||||
|
||||
function openEdit(ds: DataSource) {
|
||||
editingDs.value = ds
|
||||
editorVisible.value = true
|
||||
}
|
||||
|
||||
function openLogs(ds: DataSource) {
|
||||
logsDsId.value = ds.id
|
||||
logsDsName.value = ds.name
|
||||
logsVisible.value = true
|
||||
}
|
||||
|
||||
async function removeDataSource(ds: DataSource) {
|
||||
try {
|
||||
await deleteDataSource(ds.id)
|
||||
MessagePlugin.success(t('datasource.deleteSuccess'))
|
||||
await loadList()
|
||||
} catch (e: any) {
|
||||
MessagePlugin.error(e?.message || e?.error || t('datasource.deleteFailed'))
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSync(ds: DataSource) {
|
||||
try {
|
||||
await triggerSync(ds.id)
|
||||
MessagePlugin.success(t('datasource.syncTriggered'))
|
||||
await loadList(true)
|
||||
} catch (e: any) {
|
||||
MessagePlugin.error(e?.message || e?.error || t('datasource.syncFailed'))
|
||||
}
|
||||
}
|
||||
|
||||
async function handlePause(ds: DataSource) {
|
||||
try {
|
||||
await pauseDataSource(ds.id)
|
||||
MessagePlugin.success(t('datasource.paused'))
|
||||
loadList()
|
||||
} catch (e: any) {
|
||||
MessagePlugin.error(e?.message || e?.error || t('datasource.pauseFailed'))
|
||||
}
|
||||
}
|
||||
|
||||
async function handleResume(ds: DataSource) {
|
||||
try {
|
||||
await resumeDataSource(ds.id)
|
||||
MessagePlugin.success(t('datasource.resumed'))
|
||||
loadList()
|
||||
} catch (e: any) {
|
||||
MessagePlugin.error(e?.message || e?.error || t('datasource.resumeFailed'))
|
||||
}
|
||||
}
|
||||
|
||||
function statusLabel(status: string) {
|
||||
return t(`datasource.status.${status}`)
|
||||
}
|
||||
|
||||
// Shared with DataSourceTypeIcon: the icon's alt text and this subtitle have to
|
||||
// name a connector the same way. The helper moved to a composable because the
|
||||
// inline `t(key) || type` it replaced never fell back — vue-i18n echoes the key
|
||||
// back for a missing message — so a connector with no translation (the registry
|
||||
// ships several) rendered as "datasource.connector.github".
|
||||
const { connectorLabel } = useConnectorLabel()
|
||||
|
||||
function syncModeLabel(mode: string) {
|
||||
return t(`datasource.syncMode.${mode}`)
|
||||
}
|
||||
|
||||
function scheduleLabel(cron: string) {
|
||||
return humanizeCron(cron, t)
|
||||
}
|
||||
|
||||
function lastSyncTime(ds: DataSource) {
|
||||
return relativeTime(ds.last_sync_at, t)
|
||||
}
|
||||
|
||||
function lastSyncFullTime(ds: DataSource) {
|
||||
if (!ds.last_sync_at) return ''
|
||||
return fmtBeijingTime(ds.last_sync_at)
|
||||
}
|
||||
|
||||
function syncResultPills(ds: DataSource) {
|
||||
const log = ds.latest_sync_log
|
||||
if (!log) return []
|
||||
const pills: { text: string; cls: string }[] = []
|
||||
if (log.items_created > 0) pills.push({ text: `+${log.items_created}`, cls: 'created' })
|
||||
if (log.items_updated > 0) pills.push({ text: `~${log.items_updated}`, cls: 'updated' })
|
||||
if (log.items_deleted > 0) pills.push({ text: `-${log.items_deleted}`, cls: 'deleted' })
|
||||
if (log.items_failed > 0) pills.push({ text: `${log.items_failed} ${t('datasource.logMetric.failed')}`, cls: 'failed' })
|
||||
if (log.items_skipped > 0) pills.push({ text: `${log.items_skipped} ${t('datasource.logMetric.skipped')}`, cls: 'skipped' })
|
||||
return pills
|
||||
}
|
||||
|
||||
function lastSyncStatusLabel(ds: DataSource) {
|
||||
const log = ds.latest_sync_log
|
||||
if (!log) return '--'
|
||||
return t(`datasource.logStatus.${log.status}`)
|
||||
}
|
||||
|
||||
function isSyncRunning(ds: DataSource) {
|
||||
return ds.latest_sync_log?.status === 'running'
|
||||
}
|
||||
|
||||
function onEditorSaved() {
|
||||
editorVisible.value = false
|
||||
loadList()
|
||||
}
|
||||
|
||||
onMounted(loadList)
|
||||
useAssistantDataChange(() => { void loadList(true) }, { areas: ['data_source'] })
|
||||
onBeforeUnmount(stopPolling)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="ds-settings">
|
||||
<div class="section-header">
|
||||
<h2>{{ t('datasource.title') }}</h2>
|
||||
<p class="section-description">{{ t('datasource.description') }}</p>
|
||||
</div>
|
||||
|
||||
<t-loading :loading="loading" size="small" class="ds-list-loading">
|
||||
<div
|
||||
v-if="!loading && dataSources.length === 0 && !canManageDataSource"
|
||||
class="empty-state"
|
||||
>
|
||||
<t-empty :description="t('datasource.empty')" />
|
||||
</div>
|
||||
|
||||
<div v-else-if="!loading" class="ds-grid">
|
||||
<component
|
||||
:is="canManageDataSource ? 'button' : 'div'"
|
||||
v-for="ds in dataSources"
|
||||
:key="ds.id"
|
||||
:type="canManageDataSource ? 'button' : undefined"
|
||||
:class="['ds-card', `ds-card--${ds.type}`, { 'ds-card--clickable': canManageDataSource }]"
|
||||
@click="canManageDataSource ? openEdit(ds) : undefined"
|
||||
>
|
||||
<div class="ds-card__badge">
|
||||
<DataSourceTypeIcon :type="ds.type" variant="badge" />
|
||||
</div>
|
||||
<div class="ds-card__body">
|
||||
<div class="ds-card__header">
|
||||
<h3 class="ds-card__title" :title="ds.name">{{ ds.name }}</h3>
|
||||
<div class="ds-card__actions" @click.stop>
|
||||
<t-dropdown trigger="click" :min-column-width="140" attach="body">
|
||||
<t-button
|
||||
variant="text"
|
||||
shape="square"
|
||||
size="small"
|
||||
class="ds-card__action-btn"
|
||||
@click.stop
|
||||
>
|
||||
<template #icon><t-icon name="ellipsis" /></template>
|
||||
</t-button>
|
||||
<template #dropdown>
|
||||
<t-dropdown-menu>
|
||||
<t-dropdown-item v-if="canManageDataSource" @click="openEdit(ds)">
|
||||
<t-icon name="edit" /> {{ t('datasource.edit') }}
|
||||
</t-dropdown-item>
|
||||
<t-dropdown-item
|
||||
v-if="canManageDataSource"
|
||||
:disabled="isSyncRunning(ds)"
|
||||
@click="handleSync(ds)"
|
||||
>
|
||||
<t-icon name="refresh" :class="{ 'ds-icon-spin': isSyncRunning(ds) }" />
|
||||
{{ isSyncRunning(ds) ? t('datasource.logStatus.running') : t('datasource.syncNow') }}
|
||||
</t-dropdown-item>
|
||||
<t-dropdown-item @click="openLogs(ds)">
|
||||
<t-icon name="root-list" /> {{ t('datasource.logs') }}
|
||||
</t-dropdown-item>
|
||||
<t-dropdown-item
|
||||
v-if="canManageDataSource && ds.status === 'active'"
|
||||
@click="handlePause(ds)"
|
||||
>
|
||||
<t-icon name="pause-circle" /> {{ t('datasource.pause') }}
|
||||
</t-dropdown-item>
|
||||
<t-dropdown-item
|
||||
v-else-if="canManageDataSource && ds.status === 'paused'"
|
||||
@click="handleResume(ds)"
|
||||
>
|
||||
<t-icon name="play-circle" /> {{ t('datasource.resume') }}
|
||||
</t-dropdown-item>
|
||||
<t-dropdown-item
|
||||
v-if="canManageDataSource"
|
||||
theme="error"
|
||||
class="ds-dropdown-delete-item"
|
||||
>
|
||||
<t-popconfirm
|
||||
:content="t('datasource.deleteConfirm')"
|
||||
:confirm-btn="{ content: t('datasource.delete'), theme: 'danger' }"
|
||||
:cancel-btn="{ content: t('common.cancel') }"
|
||||
placement="left"
|
||||
attach="body"
|
||||
@confirm="removeDataSource(ds)"
|
||||
>
|
||||
<span class="ds-dropdown-delete-trigger" @click.stop>
|
||||
<t-icon name="delete" />
|
||||
<span>{{ t('datasource.delete') }}</span>
|
||||
</span>
|
||||
</t-popconfirm>
|
||||
</t-dropdown-item>
|
||||
</t-dropdown-menu>
|
||||
</template>
|
||||
</t-dropdown>
|
||||
</div>
|
||||
</div>
|
||||
<p class="ds-card__subtitle">
|
||||
{{ connectorLabel(ds.type) }} · {{ syncModeLabel(ds.sync_mode) }}
|
||||
<span class="ds-card__sep">·</span>
|
||||
<span class="ds-card__status" :class="`ds-card__status--${ds.status}`">
|
||||
<span class="ds-status-dot" aria-hidden="true" />
|
||||
{{ statusLabel(ds.status) }}
|
||||
</span>
|
||||
</p>
|
||||
<p class="ds-card__detail">
|
||||
{{ scheduleLabel(ds.sync_schedule) }}
|
||||
<span class="ds-card__sep">·</span>
|
||||
<t-tooltip :content="lastSyncFullTime(ds)" :disabled="!lastSyncFullTime(ds)">
|
||||
<span>{{ lastSyncTime(ds) || '--' }}</span>
|
||||
</t-tooltip>
|
||||
<template v-if="ds.latest_sync_log">
|
||||
<span class="ds-card__sep">·</span>
|
||||
<span
|
||||
class="ds-card__sync-result"
|
||||
:class="`ds-card__sync-result--${ds.latest_sync_log.status}`"
|
||||
>
|
||||
{{ lastSyncStatusLabel(ds) }}
|
||||
</span>
|
||||
<span
|
||||
v-for="pill in syncResultPills(ds)"
|
||||
:key="pill.cls"
|
||||
class="ds-card__metric"
|
||||
>{{ pill.text }}</span>
|
||||
</template>
|
||||
</p>
|
||||
<div v-if="ds.error_message" class="ds-card__error">
|
||||
<t-icon name="error-circle-filled" size="14px" />
|
||||
<span>{{ ds.error_message }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</component>
|
||||
|
||||
<button
|
||||
v-if="canManageDataSource"
|
||||
type="button"
|
||||
class="ds-card ds-card--add"
|
||||
@click="openCreate"
|
||||
>
|
||||
<span class="ds-card--add__icon" aria-hidden="true">
|
||||
<t-icon name="add" />
|
||||
</span>
|
||||
<span class="ds-card--add__label">{{ t('datasource.add') }}</span>
|
||||
</button>
|
||||
</div>
|
||||
</t-loading>
|
||||
|
||||
<DataSourceEditorDialog
|
||||
v-model:visible="editorVisible"
|
||||
:kb-id="kbId"
|
||||
:data-source="editingDs"
|
||||
@saved="onEditorSaved"
|
||||
/>
|
||||
|
||||
<DataSourceSyncLogs
|
||||
v-model:visible="logsVisible"
|
||||
:data-source-id="logsDsId"
|
||||
:data-source-name="logsDsName"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped lang="less">
|
||||
@import './datasource-surface.less';
|
||||
.ds-settings {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.section-header {
|
||||
margin-bottom: 28px;
|
||||
|
||||
h2 {
|
||||
font-size: var(--app-text-3xl);
|
||||
font-weight: 600;
|
||||
color: var(--td-text-color-primary);
|
||||
margin: 0 0 8px 0;
|
||||
}
|
||||
|
||||
.section-description {
|
||||
font-size: var(--app-text-base);
|
||||
color: var(--td-text-color-secondary);
|
||||
margin: 0;
|
||||
line-height: 1.6;
|
||||
}
|
||||
}
|
||||
|
||||
.ds-list-loading {
|
||||
min-height: 120px;
|
||||
}
|
||||
|
||||
.empty-state {
|
||||
padding: 32px 0;
|
||||
}
|
||||
|
||||
.ds-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
|
||||
gap: 12px;
|
||||
|
||||
.ds-card--add {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
.ds-card {
|
||||
position: relative;
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 12px;
|
||||
padding: 14px 16px;
|
||||
.ds-surface-card();
|
||||
text-align: left;
|
||||
font: inherit;
|
||||
color: inherit;
|
||||
min-width: 0;
|
||||
|
||||
&--clickable {
|
||||
cursor: pointer;
|
||||
width: 100%;
|
||||
.ds-surface-card--interactive();
|
||||
}
|
||||
|
||||
&--add {
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
min-height: 68px;
|
||||
border-style: dashed;
|
||||
background: transparent;
|
||||
color: var(--td-text-color-placeholder);
|
||||
cursor: pointer;
|
||||
width: 100%;
|
||||
|
||||
&:hover,
|
||||
&:focus-visible {
|
||||
color: var(--td-brand-color);
|
||||
border-color: var(--td-brand-color);
|
||||
background: color-mix(in srgb, var(--td-brand-color) 6%, transparent);
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
&:focus-visible {
|
||||
outline: 2px solid var(--td-brand-color);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
&__icon {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
border-radius: var(--app-radius-md);
|
||||
background: color-mix(in srgb, var(--td-brand-color) 10%, transparent);
|
||||
color: var(--td-brand-color);
|
||||
font-size: var(--app-text-2xl);
|
||||
}
|
||||
|
||||
&__label {
|
||||
font-size: var(--app-text-md);
|
||||
font-weight: 500;
|
||||
line-height: 1.4;
|
||||
}
|
||||
}
|
||||
|
||||
&__badge {
|
||||
flex-shrink: 0;
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
border-radius: 9px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
margin-top: 1px;
|
||||
font-size: var(--app-text-lg);
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.02em;
|
||||
background: color-mix(in srgb, var(--td-brand-color) 12%, transparent);
|
||||
color: #07c05f;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
&--feishu .ds-card__badge,
|
||||
&--notion .ds-card__badge,
|
||||
&--yuque .ds-card__badge,
|
||||
&--ima .ds-card__badge,
|
||||
&--rss .ds-card__badge {
|
||||
background: var(--td-bg-color-container);
|
||||
box-shadow: inset 0 0 0 1px var(--td-component-stroke);
|
||||
}
|
||||
|
||||
&__body {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
&__header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
&__title {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
margin: 0;
|
||||
font-size: var(--app-text-base);
|
||||
font-weight: 600;
|
||||
line-height: 1.4;
|
||||
color: var(--td-text-color-primary);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
&__subtitle {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px;
|
||||
margin: 2px 0 0;
|
||||
font-size: var(--app-text-sm);
|
||||
line-height: 1.5;
|
||||
color: var(--td-text-color-secondary);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
&__status {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
|
||||
&--active {
|
||||
color: var(--td-success-color);
|
||||
}
|
||||
|
||||
&--paused {
|
||||
color: var(--td-warning-color);
|
||||
}
|
||||
|
||||
&--error {
|
||||
color: var(--td-error-color);
|
||||
}
|
||||
}
|
||||
|
||||
&__detail {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px;
|
||||
margin: 4px 0 0;
|
||||
font-size: var(--app-text-sm);
|
||||
line-height: 1.45;
|
||||
color: var(--td-text-color-placeholder);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
&__sync-result {
|
||||
font-weight: 500;
|
||||
color: var(--td-text-color-secondary);
|
||||
|
||||
&--success {
|
||||
color: var(--td-success-color);
|
||||
}
|
||||
|
||||
&--failed {
|
||||
color: var(--td-error-color);
|
||||
}
|
||||
|
||||
&--running {
|
||||
color: var(--td-brand-color);
|
||||
}
|
||||
|
||||
&--partial {
|
||||
color: var(--td-warning-color);
|
||||
}
|
||||
}
|
||||
|
||||
&__metric {
|
||||
font-size: var(--app-text-xs);
|
||||
font-variant-numeric: tabular-nums;
|
||||
color: var(--td-text-color-disabled);
|
||||
}
|
||||
|
||||
&__sep {
|
||||
color: var(--td-text-color-disabled);
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
&__error {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 6px;
|
||||
margin-top: 8px;
|
||||
padding: 8px 10px;
|
||||
border-radius: var(--app-radius-sm);
|
||||
background: var(--td-error-color-1);
|
||||
color: var(--td-error-color);
|
||||
font-size: var(--app-text-sm);
|
||||
line-height: 1.45;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
&__actions {
|
||||
flex-shrink: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
&__action-btn {
|
||||
flex-shrink: 0;
|
||||
padding: 2px;
|
||||
opacity: 0;
|
||||
color: var(--td-text-color-placeholder);
|
||||
transition: opacity var(--app-motion-fast) ease, color var(--app-motion-fast) ease;
|
||||
|
||||
&:hover,
|
||||
&:focus-visible {
|
||||
background: var(--td-bg-color-secondarycontainer);
|
||||
color: var(--td-text-color-primary);
|
||||
}
|
||||
}
|
||||
|
||||
&:hover .ds-card__action-btn,
|
||||
&:focus-within .ds-card__action-btn,
|
||||
&__actions:focus-within .ds-card__action-btn {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
.ds-status-dot {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
border-radius: 50%;
|
||||
background: currentColor;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.ds-icon-spin {
|
||||
animation: wk-spin 1s linear infinite;
|
||||
}
|
||||
|
||||
:deep(.t-dropdown__item.ds-dropdown-delete-item) {
|
||||
border-top: 1px solid var(--td-component-stroke);
|
||||
margin-top: 4px;
|
||||
padding-top: 4px;
|
||||
|
||||
.t-popup__reference {
|
||||
display: block;
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
.ds-dropdown-delete-trigger {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
width: 100%;
|
||||
cursor: pointer;
|
||||
line-height: 22px;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,613 @@
|
||||
<script setup lang="ts">
|
||||
import { fmtBeijingTime } from '@/utils/datetime'
|
||||
import { ref, watch, computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { getSyncLogs, type SyncLog, type SyncItemError } from '@/api/datasource'
|
||||
|
||||
const props = defineProps<{
|
||||
dataSourceId: string
|
||||
dataSourceName?: string
|
||||
}>()
|
||||
const visible = defineModel<boolean>('visible', { default: false })
|
||||
const { t } = useI18n()
|
||||
|
||||
const logs = ref<SyncLog[]>([])
|
||||
const loading = ref(false)
|
||||
const loadingMore = ref(false)
|
||||
const hasMore = ref(false)
|
||||
const expandedId = ref('')
|
||||
const pageSize = 50
|
||||
|
||||
async function fetchLogs(reset = true) {
|
||||
if (!props.dataSourceId) return
|
||||
|
||||
if (reset) {
|
||||
loading.value = true
|
||||
} else {
|
||||
loadingMore.value = true
|
||||
}
|
||||
|
||||
try {
|
||||
const offset = reset ? 0 : logs.value.length
|
||||
const res = await getSyncLogs(props.dataSourceId, pageSize, offset)
|
||||
const items = res?.data || res || []
|
||||
logs.value = reset ? items : [...logs.value, ...items]
|
||||
hasMore.value = items.length === pageSize
|
||||
} catch { /* ignore */ }
|
||||
|
||||
if (reset) {
|
||||
loading.value = false
|
||||
} else {
|
||||
loadingMore.value = false
|
||||
}
|
||||
}
|
||||
|
||||
watch(visible, (v) => {
|
||||
if (!v) return
|
||||
expandedId.value = ''
|
||||
fetchLogs(true)
|
||||
})
|
||||
|
||||
function toggleExpand(id: string) {
|
||||
expandedId.value = expandedId.value === id ? '' : id
|
||||
}
|
||||
|
||||
function loadMore() {
|
||||
if (loading.value || loadingMore.value || !hasMore.value) return
|
||||
fetchLogs(false)
|
||||
}
|
||||
|
||||
// --- Stats ---
|
||||
const stats = computed(() => {
|
||||
const total = logs.value.length
|
||||
const success = logs.value.filter(l => l.status === 'success').length
|
||||
const failed = logs.value.filter(l => l.status === 'failed').length
|
||||
const totalItems = logs.value.reduce((acc, l) => acc + (l.items_created || 0) + (l.items_updated || 0), 0)
|
||||
return { total, success, failed, totalItems }
|
||||
})
|
||||
|
||||
// --- Helpers ---
|
||||
function statusIcon(status: string) {
|
||||
switch (status) {
|
||||
case 'success': return 'check-circle-filled'
|
||||
case 'running': return 'loading'
|
||||
case 'failed': return 'close-circle-filled'
|
||||
case 'partial': return 'error-circle-filled'
|
||||
case 'canceled': return 'minus-circle-filled'
|
||||
default: return 'info-circle-filled'
|
||||
}
|
||||
}
|
||||
|
||||
function statusColor(status: string) {
|
||||
switch (status) {
|
||||
case 'success': return 'var(--td-success-color)'
|
||||
case 'running': return 'var(--td-brand-color)'
|
||||
case 'failed': return 'var(--td-error-color)'
|
||||
case 'partial': return 'var(--td-warning-color)'
|
||||
default: return 'var(--td-text-color-placeholder)'
|
||||
}
|
||||
}
|
||||
|
||||
function formatTime(ts: string | null) {
|
||||
if (!ts) return '--'
|
||||
const d = new Date(ts)
|
||||
if (isNaN(d.getTime())) return '--'
|
||||
return fmtBeijingTime(d) || '--'
|
||||
}
|
||||
|
||||
function formatDate(ts: string | null) {
|
||||
if (!ts) return ''
|
||||
const d = new Date(ts)
|
||||
if (isNaN(d.getTime())) return ''
|
||||
const pad = (n: number) => String(n).padStart(2, '0')
|
||||
return `${pad(d.getMonth() + 1)}-${pad(d.getDate())}`
|
||||
}
|
||||
|
||||
function formatHourMin(ts: string | null) {
|
||||
if (!ts) return ''
|
||||
const d = new Date(ts)
|
||||
if (isNaN(d.getTime())) return ''
|
||||
const pad = (n: number) => String(n).padStart(2, '0')
|
||||
return `${pad(d.getHours())}:${pad(d.getMinutes())}`
|
||||
}
|
||||
|
||||
function duration(log: SyncLog) {
|
||||
if (!log.started_at || !log.finished_at) return '--'
|
||||
const ms = new Date(log.finished_at).getTime() - new Date(log.started_at).getTime()
|
||||
if (ms < 0) return '--'
|
||||
if (ms < 1000) return `<1s`
|
||||
const sec = Math.round(ms / 1000)
|
||||
if (sec < 60) return `${sec}s`
|
||||
return `${Math.floor(sec / 60)}m${sec % 60}s`
|
||||
}
|
||||
|
||||
function hasPills(log: SyncLog) {
|
||||
return log.items_created > 0 || log.items_updated > 0 || log.items_deleted > 0 || log.items_skipped > 0 || log.items_failed > 0
|
||||
}
|
||||
|
||||
// Cap the per-item failure list so a sync that failed thousands of documents
|
||||
// doesn't render an unbounded wall of text; the remainder is summarised.
|
||||
const FAILED_ITEMS_CAP = 50
|
||||
|
||||
function failedItems(log: SyncLog): SyncItemError[] {
|
||||
return (log.result?.errors || []).slice(0, FAILED_ITEMS_CAP)
|
||||
}
|
||||
|
||||
// Render one failure sample. The backend sends a stable i18n `code` (+ params)
|
||||
// so the reason is localised to the viewer's language; `message` is the fallback
|
||||
// for old logs / codes this client doesn't know. The document title is kept
|
||||
// separate and prefixed as "title — reason".
|
||||
function formatSyncError(e: SyncItemError): string {
|
||||
let reason = ''
|
||||
if (e.code) {
|
||||
const key = `datasource.syncError.${e.code}`
|
||||
const localised = t(key, (e.params || {}) as Record<string, unknown>)
|
||||
reason = localised === key ? (e.message || e.code) : localised
|
||||
} else {
|
||||
reason = e.message || ''
|
||||
}
|
||||
return e.title ? (reason ? `${e.title} — ${reason}` : e.title) : reason
|
||||
}
|
||||
|
||||
// Group logs by date
|
||||
const groupedLogs = computed(() => {
|
||||
const groups: { date: string; logs: SyncLog[] }[] = []
|
||||
let currentDate = ''
|
||||
for (const log of logs.value) {
|
||||
const d = formatDate(log.started_at)
|
||||
if (d !== currentDate) {
|
||||
currentDate = d
|
||||
groups.push({ date: d, logs: [] })
|
||||
}
|
||||
groups[groups.length - 1].logs.push(log)
|
||||
}
|
||||
return groups
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<t-drawer
|
||||
v-model:visible="visible"
|
||||
size="480px"
|
||||
destroy-on-close
|
||||
class="ds-logs-drawer"
|
||||
>
|
||||
<template #header>
|
||||
<div class="logs-drawer-header">
|
||||
<span class="logs-drawer-title">
|
||||
{{ props.dataSourceName ? `${t('datasource.syncHistory')} · ${props.dataSourceName}` : t('datasource.syncHistory') }}
|
||||
</span>
|
||||
<t-tooltip :content="t('datasource.refreshLogs')">
|
||||
<t-button
|
||||
size="small"
|
||||
variant="text"
|
||||
shape="square"
|
||||
:loading="loading"
|
||||
@click="fetchLogs"
|
||||
>
|
||||
<template #icon><t-icon name="refresh" /></template>
|
||||
</t-button>
|
||||
</t-tooltip>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<div v-if="loading" style="text-align:center;padding:60px"><t-loading /></div>
|
||||
|
||||
<div v-else-if="logs.length === 0" class="logs-empty">
|
||||
<t-icon name="root-list" size="40px" />
|
||||
<p>{{ t('datasource.noLogs') }}</p>
|
||||
</div>
|
||||
|
||||
<template v-else>
|
||||
<!-- Summary -->
|
||||
<div class="logs-summary">
|
||||
<div class="summary-stat">
|
||||
<span class="stat-num">{{ stats.total }}</span>
|
||||
<span class="stat-label">{{ t('datasource.logSummary.total') }}</span>
|
||||
</div>
|
||||
<div class="summary-stat">
|
||||
<span class="stat-num success">{{ stats.success }}</span>
|
||||
<span class="stat-label">{{ t('datasource.logSummary.success') }}</span>
|
||||
</div>
|
||||
<div class="summary-stat">
|
||||
<span class="stat-num error">{{ stats.failed }}</span>
|
||||
<span class="stat-label">{{ t('datasource.logSummary.failed') }}</span>
|
||||
</div>
|
||||
<div class="summary-stat">
|
||||
<span class="stat-num">{{ stats.totalItems }}</span>
|
||||
<span class="stat-label">{{ t('datasource.logSummary.items') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Timeline grouped by date -->
|
||||
<div class="timeline">
|
||||
<div v-for="group in groupedLogs" :key="group.date" class="timeline-group">
|
||||
<div class="timeline-date">{{ group.date }}</div>
|
||||
|
||||
<div
|
||||
v-for="log in group.logs"
|
||||
:key="log.id"
|
||||
class="timeline-item"
|
||||
@click="toggleExpand(log.id)"
|
||||
>
|
||||
<!-- Dot -->
|
||||
<div class="tl-dot-col">
|
||||
<span class="tl-dot" :style="{ background: statusColor(log.status) }">
|
||||
<t-icon v-if="log.status === 'running'" name="loading" size="10px" class="tl-spin" />
|
||||
</span>
|
||||
<span class="tl-line"></span>
|
||||
</div>
|
||||
|
||||
<!-- Content -->
|
||||
<div class="tl-content">
|
||||
<div class="tl-header">
|
||||
<span class="tl-status" :style="{ color: statusColor(log.status) }">
|
||||
{{ t(`datasource.logStatus.${log.status}`) }}
|
||||
</span>
|
||||
<span class="tl-time">{{ formatHourMin(log.started_at) }}</span>
|
||||
<span v-if="log.finished_at" class="tl-duration">{{ duration(log) }}</span>
|
||||
</div>
|
||||
|
||||
<!-- Pills -->
|
||||
<div v-if="hasPills(log)" class="tl-pills">
|
||||
<span v-if="log.items_created > 0" class="pill created">+{{ log.items_created }}</span>
|
||||
<span v-if="log.items_updated > 0" class="pill updated">~{{ log.items_updated }}</span>
|
||||
<span v-if="log.items_deleted > 0" class="pill deleted">-{{ log.items_deleted }}</span>
|
||||
<span v-if="log.items_skipped > 0" class="pill skipped">{{ log.items_skipped }} {{ t('datasource.logMetric.skipped') }}</span>
|
||||
<span v-if="log.items_failed > 0" class="pill failed">{{ log.items_failed }} {{ t('datasource.logMetric.failed') }}</span>
|
||||
</div>
|
||||
|
||||
<!-- Expanded -->
|
||||
<div v-if="expandedId === log.id" class="tl-detail" @click.stop>
|
||||
<div class="detail-row">
|
||||
<span class="detail-label">{{ t('datasource.logDetail.startTime') }}</span>
|
||||
<span>{{ formatTime(log.started_at) }}</span>
|
||||
</div>
|
||||
<div class="detail-row">
|
||||
<span class="detail-label">{{ t('datasource.logDetail.endTime') }}</span>
|
||||
<span>{{ formatTime(log.finished_at) }}</span>
|
||||
</div>
|
||||
<div v-if="log.items_total > 0" class="detail-row">
|
||||
<span class="detail-label">{{ t('datasource.logMetric.total') }}</span>
|
||||
<span>{{ log.items_total }}</span>
|
||||
</div>
|
||||
<!-- Localised failure summary; raw error_message only for a
|
||||
pure infra failure with no per-document detail. -->
|
||||
<div v-if="log.items_failed > 0" class="tl-error">
|
||||
{{ t('datasource.logDetail.docsFailedSummary', { n: log.items_failed }) }}
|
||||
</div>
|
||||
<div v-else-if="log.error_message" class="tl-error">
|
||||
{{ log.error_message }}
|
||||
</div>
|
||||
|
||||
<!-- Per-item failures: which documents failed and why.
|
||||
The true count is items_failed (a bounded int); result.errors
|
||||
is only a capped sample the backend retains for display. -->
|
||||
<div v-if="failedItems(log).length" class="tl-failed">
|
||||
<div class="tl-failed-title">
|
||||
{{ t('datasource.logDetail.failedItems') }} ({{ log.items_failed }})
|
||||
</div>
|
||||
<div v-for="(e, i) in failedItems(log)" :key="i" class="tl-failed-item" :title="formatSyncError(e)">
|
||||
{{ formatSyncError(e) }}
|
||||
</div>
|
||||
<div v-if="log.items_failed > failedItems(log).length" class="tl-failed-more">
|
||||
{{ t('datasource.logDetail.failedItemsMore', { n: (log.items_failed - failedItems(log).length) }) }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="logs-load-more">
|
||||
<t-button
|
||||
v-if="hasMore"
|
||||
variant="outline"
|
||||
block
|
||||
:loading="loadingMore"
|
||||
@click="loadMore"
|
||||
>
|
||||
{{ t('common.loadMore') }}
|
||||
</t-button>
|
||||
<span v-else class="logs-load-more-text">{{ t('common.noMoreData') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</t-drawer>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.logs-empty {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 80px 0;
|
||||
color: var(--td-text-color-placeholder);
|
||||
font-size: var(--app-text-md);
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
/* --- Summary --- */
|
||||
.logs-summary {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
padding-bottom: 24px;
|
||||
margin-bottom: 12px;
|
||||
border-bottom: 1px solid var(--td-border-level-1-color);
|
||||
}
|
||||
|
||||
.summary-stat {
|
||||
flex: 1;
|
||||
text-align: center;
|
||||
padding: 16px 8px;
|
||||
border-radius: var(--app-radius-xl);
|
||||
background: var(--td-bg-color-container);
|
||||
border: 1px solid var(--td-border-level-1-color);
|
||||
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.02);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.stat-num {
|
||||
font-size: var(--app-text-3xl);
|
||||
font-weight: 700;
|
||||
color: var(--td-text-color-primary);
|
||||
line-height: 1.2;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.stat-num.success { color: var(--td-success-color); }
|
||||
.stat-num.error { color: var(--td-error-color); }
|
||||
|
||||
.stat-label {
|
||||
font-size: var(--app-text-xs);
|
||||
font-weight: 500;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.5px;
|
||||
color: var(--td-text-color-placeholder);
|
||||
}
|
||||
|
||||
/* --- Timeline --- */
|
||||
.timeline {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.timeline-group {
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.timeline-date {
|
||||
font-size: var(--app-text-xs);
|
||||
font-weight: 600;
|
||||
color: var(--td-text-color-placeholder);
|
||||
padding: 12px 0 8px 24px;
|
||||
position: sticky;
|
||||
top: 0;
|
||||
background: var(--td-bg-color-container);
|
||||
z-index: 1;
|
||||
letter-spacing: 0.5px;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.timeline-item {
|
||||
display: flex;
|
||||
cursor: pointer;
|
||||
position: relative;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.logs-load-more {
|
||||
padding: 16px 0 8px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.logs-load-more-text {
|
||||
font-size: var(--app-text-sm);
|
||||
color: var(--td-text-color-placeholder);
|
||||
}
|
||||
|
||||
/* --- Dot column: continuous line --- */
|
||||
.tl-dot-col {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
width: 24px;
|
||||
flex-shrink: 0;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
/* Continuous vertical line behind dots */
|
||||
.tl-dot-col::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
left: 50%;
|
||||
width: 1.5px;
|
||||
background: var(--td-border-level-1-color);
|
||||
transform: translateX(-50%);
|
||||
}
|
||||
|
||||
.timeline-group:last-child .timeline-item:last-child .tl-dot-col::before {
|
||||
bottom: 50%;
|
||||
}
|
||||
|
||||
.tl-dot {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
flex-shrink: 0;
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
margin-top: 18px;
|
||||
box-shadow: 0 0 0 4px var(--td-bg-color-container);
|
||||
}
|
||||
|
||||
.tl-dot .tl-spin {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.tl-line {
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* --- Content --- */
|
||||
.tl-content {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
padding: 12px 14px;
|
||||
border-radius: var(--app-radius-lg);
|
||||
transition: background var(--app-motion-base) ease;
|
||||
}
|
||||
|
||||
.timeline-item:hover .tl-content {
|
||||
background: var(--td-bg-color-secondarycontainer);
|
||||
}
|
||||
|
||||
.tl-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.tl-status {
|
||||
font-size: var(--app-text-md);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.tl-time {
|
||||
font-size: var(--app-text-sm);
|
||||
color: var(--td-text-color-placeholder);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.tl-duration {
|
||||
margin-left: auto;
|
||||
font-size: var(--app-text-xs);
|
||||
font-weight: 500;
|
||||
color: var(--td-text-color-placeholder);
|
||||
font-variant-numeric: tabular-nums;
|
||||
background: var(--td-bg-color-component);
|
||||
padding: 2px 6px;
|
||||
border-radius: var(--app-radius-xs);
|
||||
}
|
||||
|
||||
/* --- Pills --- */
|
||||
.tl-pills {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px;
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
.pill {
|
||||
font-size: var(--app-text-xs);
|
||||
padding: 1px 6px;
|
||||
border-radius: var(--app-radius-xs);
|
||||
font-weight: 500;
|
||||
line-height: 18px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.pill.created { background: var(--td-success-color-1); color: var(--td-success-color); }
|
||||
.pill.updated { background: var(--td-brand-color-light); color: var(--td-brand-color); }
|
||||
.pill.deleted { background: var(--td-warning-color-1); color: var(--td-warning-color); }
|
||||
.pill.skipped { background: var(--td-bg-color-component); color: var(--td-text-color-placeholder); }
|
||||
.pill.failed { background: var(--td-error-color-1); color: var(--td-error-color); }
|
||||
|
||||
/* --- Expanded detail --- */
|
||||
.tl-detail {
|
||||
margin-top: 12px;
|
||||
padding-top: 12px;
|
||||
border-top: 1px dashed var(--td-border-level-2-color);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.detail-row {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
font-size: var(--app-text-sm);
|
||||
color: var(--td-text-color-primary);
|
||||
line-height: 20px;
|
||||
}
|
||||
|
||||
.detail-label {
|
||||
color: var(--td-text-color-placeholder);
|
||||
}
|
||||
|
||||
.tl-error {
|
||||
margin-top: 8px;
|
||||
padding: 8px 12px;
|
||||
border-radius: var(--app-radius-sm);
|
||||
background: var(--td-error-color-1);
|
||||
color: var(--td-error-color);
|
||||
font-size: var(--app-text-sm);
|
||||
line-height: 1.5;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
/* --- Per-item failure list --- */
|
||||
.tl-failed {
|
||||
margin-top: 8px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
.tl-failed-title {
|
||||
font-size: var(--app-text-xs);
|
||||
font-weight: 600;
|
||||
color: var(--td-error-color);
|
||||
margin-bottom: 2px;
|
||||
}
|
||||
|
||||
.tl-failed-item {
|
||||
font-size: var(--app-text-xs);
|
||||
line-height: 1.5;
|
||||
color: var(--td-text-color-secondary);
|
||||
padding: 2px 8px;
|
||||
border-left: 2px solid var(--td-error-color-3);
|
||||
background: var(--td-bg-color-container);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.tl-failed-more {
|
||||
font-size: var(--app-text-xs);
|
||||
color: var(--td-text-color-placeholder);
|
||||
padding: 2px 8px;
|
||||
}
|
||||
|
||||
/* --- Drawer header --- */
|
||||
.logs-drawer-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.logs-drawer-title {
|
||||
font-size: var(--app-text-xl);
|
||||
font-weight: 600;
|
||||
color: var(--td-text-color-primary);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* --- Drawer overrides --- */
|
||||
.ds-logs-drawer :deep(.t-drawer__header) {
|
||||
padding: 20px 24px;
|
||||
border-bottom: 1px solid var(--td-border-level-1-color);
|
||||
}
|
||||
|
||||
.ds-logs-drawer :deep(.t-drawer__body) {
|
||||
padding: 20px 24px;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,85 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { after, before, test } from 'node:test'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { createServer, type ViteDevServer } from 'vite'
|
||||
import vue from '@vitejs/plugin-vue'
|
||||
import { createSSRApp, h, type Component } from 'vue'
|
||||
import { renderToString } from 'vue/server-renderer'
|
||||
import { createI18n } from 'vue-i18n'
|
||||
import en from '../../../i18n/locales/en-US'
|
||||
import zh from '../../../i18n/locales/zh-CN'
|
||||
|
||||
let server: ViteDevServer
|
||||
let Icon: Component
|
||||
|
||||
before(async () => {
|
||||
server = await createServer({
|
||||
configFile: false, optimizeDeps: { noDiscovery: true, entries: [] }, plugins: [vue()],
|
||||
resolve: { alias: { '@': fileURLToPath(new URL('../../../', import.meta.url)) } },
|
||||
server: { middlewareMode: true }, appType: 'custom',
|
||||
})
|
||||
Icon = (await server.ssrLoadModule('/src/views/knowledge/settings/DataSourceTypeIcon.vue')).default
|
||||
})
|
||||
after(async () => { await server?.close() })
|
||||
|
||||
async function render(type: string, locale: 'zh-CN' | 'en-US') {
|
||||
const app = createSSRApp({ render: () => h(Icon, { type }) })
|
||||
app.use(createI18n({
|
||||
legacy: false,
|
||||
locale,
|
||||
fallbackLocale: locale,
|
||||
messages: locale === 'zh-CN' ? { 'zh-CN': zh } : { 'en-US': en },
|
||||
}))
|
||||
return renderToString(app)
|
||||
}
|
||||
|
||||
// The icon carries the same localized name the card subtitle and the type picker show,
|
||||
// so screen readers and copied page text never see the internal connector identifier.
|
||||
test('a connected source names its icon with the localized display name, not the raw type', async () => {
|
||||
const html = await render('dingtalk', 'zh-CN')
|
||||
assert.ok(html.includes('ds-type-icon__img'), 'the icon image must render, otherwise this asserts nothing')
|
||||
assert.ok(html.includes('alt="钉钉文档"'), `expected the zh-CN display name, got: ${html}`)
|
||||
assert.ok(!html.includes('alt="dingtalk"'), `the raw type leaked into alt: ${html}`)
|
||||
})
|
||||
|
||||
test('the icon name follows the active locale', async () => {
|
||||
const html = await render('dingtalk', 'en-US')
|
||||
assert.ok(html.includes('ds-type-icon__img'), 'the icon image must render, otherwise this asserts nothing')
|
||||
assert.ok(html.includes('alt="DingTalk Docs"'), `expected the en-US display name, got: ${html}`)
|
||||
assert.ok(!html.includes('alt="dingtalk"'), `the raw type leaked into alt: ${html}`)
|
||||
})
|
||||
|
||||
test('every icon-backed connector uses its localized name', async () => {
|
||||
const icons = await server.ssrLoadModule('/src/views/knowledge/settings/datasourceIcons.ts')
|
||||
const types = Object.keys(icons.datasourceIconMap)
|
||||
assert.ok(types.length > 0, 'the icon map must not be empty')
|
||||
for (const locale of ['zh-CN', 'en-US'] as const) {
|
||||
const names: Record<string, string> = (locale === 'zh-CN' ? zh : en).datasource.connector
|
||||
for (const type of types) {
|
||||
const html = await render(type, locale)
|
||||
assert.ok(
|
||||
html.includes(`alt="${names[type]}"`),
|
||||
`${locale} ${type}: expected alt="${names[type]}", got: ${html}`,
|
||||
)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
// A type can gain an icon before its `datasource.connector.*` message lands, and a data
|
||||
// source created through the API can carry a type the UI never listed. vue-i18n echoes
|
||||
// the key back for a missing message, so a plain `t(key) || type` would put the
|
||||
// untranslated "datasource.connector.github" in the alt text.
|
||||
test('an icon-backed type without a translation falls back to the bare type', async () => {
|
||||
const icons = await server.ssrLoadModule('/src/views/knowledge/settings/datasourceIcons.ts')
|
||||
const zhNames: Record<string, string> = zh.datasource.connector
|
||||
assert.ok(!zhNames.github, 'github must stay without a translation for this test to mean anything')
|
||||
icons.datasourceIconMap.github = 'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg"/>'
|
||||
try {
|
||||
const html = await render('github', 'zh-CN')
|
||||
assert.ok(html.includes('ds-type-icon__img'), 'the icon image must render, otherwise this asserts nothing')
|
||||
assert.ok(html.includes('alt="github"'), `expected a fallback to the raw type, got: ${html}`)
|
||||
assert.ok(!html.includes('datasource.connector.github'), `an untranslated key leaked into alt: ${html}`)
|
||||
} finally {
|
||||
delete icons.datasourceIconMap.github
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,101 @@
|
||||
<script setup lang="ts">
|
||||
import { getDatasourceIconUrl, datasourceIconMap } from './datasourceIcons'
|
||||
import { useConnectorLabel } from '@/composables/useConnectorLabel'
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
type: string
|
||||
size?: number
|
||||
/** inline: 类型选择等小尺寸场景;badge: 嵌入 ds-card__badge 等父级徽章容器 */
|
||||
variant?: 'inline' | 'badge'
|
||||
}>(), {
|
||||
size: 20,
|
||||
variant: 'inline',
|
||||
})
|
||||
|
||||
// The card subtitle and the connector picker resolve the same name through this
|
||||
// composable, so the icon's alt text and the visible label next to it cannot
|
||||
// disagree. Screen readers and copied page text get "钉钉文档", not "dingtalk".
|
||||
const { connectorLabel } = useConnectorLabel()
|
||||
|
||||
const iconMap = datasourceIconMap
|
||||
|
||||
function fallbackText(type: string) {
|
||||
switch (type) {
|
||||
case 'feishu':
|
||||
return 'F'
|
||||
case 'lark':
|
||||
return 'L'
|
||||
case 'notion':
|
||||
return 'N'
|
||||
case 'yuque':
|
||||
return 'Y'
|
||||
case 'ima':
|
||||
return 'I'
|
||||
default:
|
||||
return type.slice(0, 1).toUpperCase() || '?'
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<span
|
||||
class="ds-type-icon"
|
||||
:class="`ds-type-icon--${variant}`"
|
||||
:style="variant === 'inline' ? { width: `${size}px`, height: `${size}px` } : undefined"
|
||||
>
|
||||
<img
|
||||
v-if="iconMap[type]"
|
||||
:src="iconMap[type]"
|
||||
:alt="connectorLabel(type)"
|
||||
class="ds-type-icon__img"
|
||||
:style="variant === 'inline' ? { width: `${size}px`, height: `${size}px` } : undefined"
|
||||
>
|
||||
<span v-else class="ds-type-icon-fallback">{{ fallbackText(type) }}</span>
|
||||
</span>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.ds-type-icon {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex-shrink: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.ds-type-icon--inline {
|
||||
border-radius: var(--app-radius-sm);
|
||||
background: var(--td-bg-color-component);
|
||||
}
|
||||
|
||||
.ds-type-icon--inline .ds-type-icon__img {
|
||||
display: block;
|
||||
object-fit: contain;
|
||||
}
|
||||
|
||||
.ds-type-icon--inline .ds-type-icon-fallback {
|
||||
font-size: var(--app-text-xs);
|
||||
font-weight: 600;
|
||||
color: var(--td-text-color-placeholder);
|
||||
}
|
||||
|
||||
.ds-type-icon--badge {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.ds-type-icon--badge .ds-type-icon__img {
|
||||
display: block;
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
object-fit: contain;
|
||||
}
|
||||
|
||||
.ds-type-icon--badge .ds-type-icon-fallback {
|
||||
font-size: var(--app-text-lg);
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.02em;
|
||||
color: inherit;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,851 @@
|
||||
<template>
|
||||
<div class="graph-settings" :class="{ 'graph-settings--embedded': embedded }">
|
||||
<div v-if="!embedded" class="section-header">
|
||||
<h2>{{ t('graphSettings.title') }}</h2>
|
||||
<p class="section-description">{{ t('graphSettings.description') }}</p>
|
||||
</div>
|
||||
<div v-if="!isGraphDatabaseEnabled" class="graph-disabled">
|
||||
<span class="graph-disabled-icon"><t-icon name="chart-bubble" /></span>
|
||||
<div class="graph-disabled-text">
|
||||
<p>{{ t('graphSettings.disabledWarning') }}</p>
|
||||
</div>
|
||||
<t-button
|
||||
v-if="!embedded"
|
||||
size="small"
|
||||
theme="primary"
|
||||
variant="outline"
|
||||
@click="handleOpenGraphGuide"
|
||||
>
|
||||
<template #icon><t-icon name="help-circle" /></template>
|
||||
{{ t('graphSettings.howToEnable') }}
|
||||
</t-button>
|
||||
</div>
|
||||
|
||||
<div v-if="isGraphDatabaseEnabled" class="settings-group">
|
||||
<!-- 启用实体关系提取 -->
|
||||
<div class="setting-row">
|
||||
<div class="setting-info">
|
||||
<label>{{ t('graphSettings.enableLabel') }}</label>
|
||||
<p class="desc">{{ t('graphSettings.enableDescription') }}</p>
|
||||
</div>
|
||||
<div class="setting-control">
|
||||
<t-switch
|
||||
v-model="localGraphExtract.enabled"
|
||||
@change="handleEnabledChange"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="localGraphExtract.enabled" class="setting-row vertical">
|
||||
<div class="setting-info">
|
||||
<label>{{ t('graphSettings.customInstructionsLabel') }}</label>
|
||||
<p class="desc">{{ t('graphSettings.customInstructionsDescription') }}</p>
|
||||
</div>
|
||||
<div class="setting-control full-width">
|
||||
<t-textarea
|
||||
v-model="localGraphExtract.customInstructions"
|
||||
:placeholder="t('graphSettings.customInstructionsPlaceholder')"
|
||||
:maxlength="4000"
|
||||
:autosize="{ minRows: 3, maxRows: 8 }"
|
||||
@change="handleConfigChange"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 关系类型配置 -->
|
||||
<div v-if="localGraphExtract.enabled" class="setting-row vertical">
|
||||
<div class="setting-info">
|
||||
<label>{{ t('graphSettings.tagsLabel') }}</label>
|
||||
<p class="desc">{{ t('graphSettings.tagsDescription') }}</p>
|
||||
</div>
|
||||
<div class="setting-control full-width">
|
||||
<div class="tags-control-group">
|
||||
<t-button
|
||||
v-if="canRunGraphExtract"
|
||||
theme="default"
|
||||
size="medium"
|
||||
:disabled="!modelStatus.llm.available"
|
||||
:loading="tagFabring"
|
||||
@click="handleFabriTag"
|
||||
class="gen-tags-btn"
|
||||
>
|
||||
{{ t('graphSettings.generateRandomTags') }}
|
||||
</t-button>
|
||||
<t-select
|
||||
v-model="localGraphExtract.tags"
|
||||
multiple
|
||||
:placeholder="t('graphSettings.tagsPlaceholder')"
|
||||
clearable
|
||||
creatable
|
||||
filterable
|
||||
@change="handleTagsChange"
|
||||
style="flex: 1; min-width: 400px;"
|
||||
/>
|
||||
</div>
|
||||
<div v-if="!modelStatus.llm.available" class="control-tip">
|
||||
<t-icon name="info-circle" class="tip-icon" />
|
||||
<span>{{ t('graphSettings.completeModelConfig') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 示例文本 -->
|
||||
<div v-if="localGraphExtract.enabled" class="setting-row vertical">
|
||||
<div class="setting-info">
|
||||
<label>{{ t('graphSettings.sampleTextLabel') }}</label>
|
||||
<p class="desc">{{ t('graphSettings.sampleTextDescription') }}</p>
|
||||
</div>
|
||||
<div class="setting-control full-width">
|
||||
<div class="text-control-group">
|
||||
<t-button
|
||||
v-if="canRunGraphExtract"
|
||||
theme="default"
|
||||
size="medium"
|
||||
:disabled="!modelStatus.llm.available"
|
||||
:loading="textFabring"
|
||||
@click="handleFabriText"
|
||||
class="gen-text-btn"
|
||||
>
|
||||
{{ t('graphSettings.generateRandomText') }}
|
||||
</t-button>
|
||||
<t-textarea
|
||||
v-model="localGraphExtract.text"
|
||||
:placeholder="t('graphSettings.sampleTextPlaceholder')"
|
||||
:autosize="{ minRows: 6, maxRows: 12 }"
|
||||
show-word-limit
|
||||
maxlength="5000"
|
||||
@change="handleTextChange"
|
||||
style="width: 100%;"
|
||||
/>
|
||||
</div>
|
||||
<div v-if="!modelStatus.llm.available" class="control-tip">
|
||||
<t-icon name="info-circle" class="tip-icon" />
|
||||
<span>{{ t('graphSettings.completeModelConfig') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 实体列表 -->
|
||||
<div v-if="localGraphExtract.enabled && localGraphExtract.nodes.length > 0" class="setting-row vertical">
|
||||
<div class="setting-info">
|
||||
<label>{{ t('graphSettings.entityListLabel') }}</label>
|
||||
<p class="desc">{{ t('graphSettings.entityListDescription') }}</p>
|
||||
</div>
|
||||
<div class="setting-control full-width">
|
||||
<div class="node-list">
|
||||
<div v-for="(node, nodeIndex) in localGraphExtract.nodes" :key="nodeIndex" class="node-item">
|
||||
<div class="node-header">
|
||||
<t-icon name="user" class="node-icon" />
|
||||
<t-input
|
||||
v-model="node.name"
|
||||
:placeholder="t('graphSettings.nodeNamePlaceholder')"
|
||||
@change="handleNodesChange"
|
||||
class="node-name-input"
|
||||
/>
|
||||
<t-button
|
||||
theme="default"
|
||||
size="small"
|
||||
@click="removeNode(nodeIndex)"
|
||||
>
|
||||
<t-icon name="delete" />
|
||||
</t-button>
|
||||
</div>
|
||||
<div class="node-attributes">
|
||||
<div v-for="(attribute, attrIndex) in node.attributes" :key="attrIndex" class="attribute-item">
|
||||
<t-input
|
||||
v-model="node.attributes[attrIndex]"
|
||||
:placeholder="t('graphSettings.attributePlaceholder')"
|
||||
@change="handleNodesChange"
|
||||
class="attribute-input"
|
||||
/>
|
||||
<t-button
|
||||
theme="default"
|
||||
size="small"
|
||||
@click="removeAttribute(nodeIndex, attrIndex)"
|
||||
>
|
||||
<t-icon name="close" />
|
||||
</t-button>
|
||||
</div>
|
||||
<t-button
|
||||
theme="default"
|
||||
size="small"
|
||||
@click="addAttribute(nodeIndex)"
|
||||
class="add-attr-btn"
|
||||
>
|
||||
{{ t('graphSettings.addAttribute') }}
|
||||
</t-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 添加实体按钮 -->
|
||||
<div v-if="localGraphExtract.enabled" class="setting-row">
|
||||
<div class="setting-info">
|
||||
<label>{{ t('graphSettings.manageEntitiesLabel') }}</label>
|
||||
<p class="desc">{{ t('graphSettings.manageEntitiesDescription') }}</p>
|
||||
</div>
|
||||
<div class="setting-control">
|
||||
<t-button
|
||||
theme="primary"
|
||||
@click="addNode"
|
||||
>
|
||||
{{ t('graphSettings.addEntity') }}
|
||||
</t-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 关系列表 -->
|
||||
<div v-if="localGraphExtract.enabled && localGraphExtract.relations.length > 0" class="setting-row vertical">
|
||||
<div class="setting-info">
|
||||
<label>{{ t('graphSettings.relationListLabel') }}</label>
|
||||
<p class="desc">{{ t('graphSettings.relationListDescription') }}</p>
|
||||
</div>
|
||||
<div class="setting-control full-width">
|
||||
<div class="relation-list">
|
||||
<div v-for="(relation, index) in localGraphExtract.relations" :key="index" class="relation-item">
|
||||
<t-select
|
||||
v-model="relation.node1"
|
||||
:placeholder="t('graphSettings.selectEntity')"
|
||||
@change="handleRelationsChange"
|
||||
class="relation-select"
|
||||
>
|
||||
<t-option
|
||||
v-for="node in localGraphExtract.nodes"
|
||||
:key="node.name"
|
||||
:value="node.name"
|
||||
:label="node.name"
|
||||
/>
|
||||
</t-select>
|
||||
<t-icon name="arrow-right" class="relation-arrow" />
|
||||
<t-select
|
||||
v-model="relation.type"
|
||||
:placeholder="t('graphSettings.selectRelationType')"
|
||||
clearable
|
||||
creatable
|
||||
filterable
|
||||
@change="handleRelationsChange"
|
||||
class="relation-select"
|
||||
>
|
||||
<t-option
|
||||
v-for="tag in localGraphExtract.tags"
|
||||
:key="tag"
|
||||
:value="tag"
|
||||
:label="tag"
|
||||
/>
|
||||
</t-select>
|
||||
<t-icon name="arrow-right" class="relation-arrow" />
|
||||
<t-select
|
||||
v-model="relation.node2"
|
||||
:placeholder="t('graphSettings.selectEntity')"
|
||||
@change="handleRelationsChange"
|
||||
class="relation-select"
|
||||
>
|
||||
<t-option
|
||||
v-for="node in localGraphExtract.nodes"
|
||||
:key="node.name"
|
||||
:value="node.name"
|
||||
:label="node.name"
|
||||
/>
|
||||
</t-select>
|
||||
<t-button
|
||||
theme="default"
|
||||
size="small"
|
||||
@click="removeRelation(index)"
|
||||
>
|
||||
<t-icon name="delete" />
|
||||
</t-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 添加关系按钮 -->
|
||||
<div v-if="localGraphExtract.enabled" class="setting-row">
|
||||
<div class="setting-info">
|
||||
<label>{{ t('graphSettings.manageRelationsLabel') }}</label>
|
||||
<p class="desc">{{ t('graphSettings.manageRelationsDescription') }}</p>
|
||||
</div>
|
||||
<div class="setting-control">
|
||||
<t-button
|
||||
theme="primary"
|
||||
@click="addRelation"
|
||||
>
|
||||
{{ t('graphSettings.addRelation') }}
|
||||
</t-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 提取操作按钮 -->
|
||||
<div v-if="localGraphExtract.enabled" class="setting-row">
|
||||
<div class="setting-info">
|
||||
<label>{{ t('graphSettings.extractActionsLabel') }}</label>
|
||||
<p class="desc">{{ t('graphSettings.extractActionsDescription') }}</p>
|
||||
</div>
|
||||
<div class="setting-control">
|
||||
<div class="action-buttons">
|
||||
<t-button
|
||||
v-if="canRunGraphExtract"
|
||||
theme="primary"
|
||||
:disabled="!modelStatus.llm.available || !localGraphExtract.text"
|
||||
:loading="extracting"
|
||||
@click="handleExtract"
|
||||
>
|
||||
{{ extracting ? t('graphSettings.extracting') : t('graphSettings.startExtraction') }}
|
||||
</t-button>
|
||||
<t-button
|
||||
theme="default"
|
||||
@click="defaultExtractExample"
|
||||
>
|
||||
{{ t('graphSettings.defaultExample') }}
|
||||
</t-button>
|
||||
<t-button
|
||||
theme="default"
|
||||
@click="clearExtractExample"
|
||||
>
|
||||
{{ t('graphSettings.clearExample') }}
|
||||
</t-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, watch, onMounted, computed } from 'vue'
|
||||
import { MessagePlugin } from 'tdesign-vue-next'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { extractTextRelations, fabriText, fabriTag, type Node, type Relation } from '@/api/initialization'
|
||||
import { useEditorResourcesStore } from '@/stores/editorResources'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import { docsUrl } from '@/utils/docsUrl'
|
||||
|
||||
const { t } = useI18n()
|
||||
const authStore = useAuthStore()
|
||||
|
||||
// canRunGraphExtract 对应后端 POST /initialization/extract/{fabri-tag,fabri-text,
|
||||
// text-relation} 的 g.Admin() 守卫——这三个都是会调用大模型 + 写库的 admin
|
||||
// 工具。Contributor 看到按钮点了只会撞 403。
|
||||
const canRunGraphExtract = computed(() => authStore.hasRole('admin'))
|
||||
|
||||
interface GraphExtractConfig {
|
||||
enabled: boolean
|
||||
text: string
|
||||
tags: string[]
|
||||
nodes: Node[]
|
||||
relations: Relation[]
|
||||
customInstructions?: string
|
||||
}
|
||||
|
||||
interface Props {
|
||||
graphExtract: GraphExtractConfig
|
||||
modelId: string
|
||||
allModels?: any[]
|
||||
embedded?: boolean
|
||||
}
|
||||
|
||||
const props = withDefaults(defineProps<Props>(), {
|
||||
embedded: false,
|
||||
})
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:graphExtract': [value: GraphExtractConfig]
|
||||
}>()
|
||||
|
||||
const modelStatus = computed(() => ({
|
||||
llm: {
|
||||
available: !!props.modelId
|
||||
}
|
||||
}))
|
||||
|
||||
// 本地状态
|
||||
const localGraphExtract = ref<GraphExtractConfig>({
|
||||
...props.graphExtract,
|
||||
nodes: props.graphExtract.nodes || [],
|
||||
relations: props.graphExtract.relations || [],
|
||||
customInstructions: props.graphExtract.customInstructions || ''
|
||||
})
|
||||
|
||||
// 加载状态
|
||||
const tagFabring = ref(false)
|
||||
const textFabring = ref(false)
|
||||
const extracting = ref(false)
|
||||
|
||||
// 系统信息
|
||||
const systemInfo = ref<any>(null)
|
||||
|
||||
// 计算图数据库是否启用
|
||||
const isGraphDatabaseEnabled = computed(() => {
|
||||
return systemInfo.value?.graph_database_engine && systemInfo.value.graph_database_engine !== 'Not Enabled'
|
||||
})
|
||||
|
||||
// Watch for prop changes
|
||||
watch(() => props.graphExtract, (newVal) => {
|
||||
localGraphExtract.value = {
|
||||
...newVal,
|
||||
nodes: newVal.nodes || [],
|
||||
relations: newVal.relations || [],
|
||||
customInstructions: newVal.customInstructions || ''
|
||||
}
|
||||
}, { deep: true })
|
||||
|
||||
// 处理配置变更
|
||||
const handleConfigChange = () => {
|
||||
emit('update:graphExtract', localGraphExtract.value)
|
||||
}
|
||||
|
||||
// 处理启用/禁用切换
|
||||
const handleEnabledChange = () => {
|
||||
// 当关闭提取功能时,清空示例数据,但保留自定义指令以便再次启用时恢复。
|
||||
if (!localGraphExtract.value.enabled) {
|
||||
localGraphExtract.value.text = ''
|
||||
localGraphExtract.value.tags = []
|
||||
localGraphExtract.value.nodes = []
|
||||
localGraphExtract.value.relations = []
|
||||
}
|
||||
handleConfigChange()
|
||||
}
|
||||
|
||||
const handleTagsChange = () => {
|
||||
handleConfigChange()
|
||||
}
|
||||
|
||||
const handleTextChange = () => {
|
||||
handleConfigChange()
|
||||
}
|
||||
|
||||
const handleNodesChange = () => {
|
||||
handleConfigChange()
|
||||
}
|
||||
|
||||
const handleRelationsChange = () => {
|
||||
handleConfigChange()
|
||||
}
|
||||
|
||||
// 节点操作
|
||||
const addNode = () => {
|
||||
if (!localGraphExtract.value.nodes) {
|
||||
localGraphExtract.value.nodes = []
|
||||
}
|
||||
localGraphExtract.value.nodes.push({
|
||||
name: '',
|
||||
attributes: []
|
||||
})
|
||||
handleNodesChange()
|
||||
}
|
||||
|
||||
const removeNode = (index: number) => {
|
||||
localGraphExtract.value.nodes.splice(index, 1)
|
||||
handleNodesChange()
|
||||
}
|
||||
|
||||
const addAttribute = (nodeIndex: number) => {
|
||||
localGraphExtract.value.nodes[nodeIndex].attributes.push('')
|
||||
handleNodesChange()
|
||||
}
|
||||
|
||||
const removeAttribute = (nodeIndex: number, attrIndex: number) => {
|
||||
localGraphExtract.value.nodes[nodeIndex].attributes.splice(attrIndex, 1)
|
||||
handleNodesChange()
|
||||
}
|
||||
|
||||
// 关系操作
|
||||
const addRelation = () => {
|
||||
if (!localGraphExtract.value.relations) {
|
||||
localGraphExtract.value.relations = []
|
||||
}
|
||||
localGraphExtract.value.relations.push({
|
||||
node1: '',
|
||||
node2: '',
|
||||
type: ''
|
||||
})
|
||||
handleRelationsChange()
|
||||
}
|
||||
|
||||
const removeRelation = (index: number) => {
|
||||
localGraphExtract.value.relations.splice(index, 1)
|
||||
handleRelationsChange()
|
||||
}
|
||||
|
||||
// 生成随机标签
|
||||
const handleFabriTag = async () => {
|
||||
tagFabring.value = true
|
||||
try {
|
||||
const response = await fabriTag({})
|
||||
localGraphExtract.value.tags = response.tags || []
|
||||
handleTagsChange()
|
||||
MessagePlugin.success(t('graphSettings.tagsGenerated'))
|
||||
} catch (error: any) {
|
||||
console.error('Failed to generate tags:', error)
|
||||
MessagePlugin.error(t('graphSettings.tagsGenerateFailed'))
|
||||
} finally {
|
||||
tagFabring.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// 生成随机文本
|
||||
const handleFabriText = async () => {
|
||||
if (!props.modelId) {
|
||||
MessagePlugin.warning(t('graphSettings.completeModelConfig'))
|
||||
return
|
||||
}
|
||||
|
||||
textFabring.value = true
|
||||
try {
|
||||
const response = await fabriText({
|
||||
tags: localGraphExtract.value.tags,
|
||||
model_id: props.modelId
|
||||
})
|
||||
localGraphExtract.value.text = response.text || ''
|
||||
handleTextChange()
|
||||
MessagePlugin.success(t('graphSettings.textGenerated'))
|
||||
} catch (error: any) {
|
||||
console.error('Failed to generate text:', error)
|
||||
MessagePlugin.error(t('graphSettings.textGenerateFailed'))
|
||||
} finally {
|
||||
textFabring.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// 提取实体关系
|
||||
const handleExtract = async () => {
|
||||
if (!props.modelId) {
|
||||
MessagePlugin.warning(t('graphSettings.completeModelConfig'))
|
||||
return
|
||||
}
|
||||
|
||||
if (!localGraphExtract.value.text) {
|
||||
MessagePlugin.warning(t('graphSettings.pleaseInputText'))
|
||||
return
|
||||
}
|
||||
|
||||
extracting.value = true
|
||||
try {
|
||||
const response = await extractTextRelations({
|
||||
text: localGraphExtract.value.text,
|
||||
tags: localGraphExtract.value.tags,
|
||||
model_id: props.modelId
|
||||
})
|
||||
localGraphExtract.value.nodes = response.nodes || []
|
||||
localGraphExtract.value.relations = response.relations || []
|
||||
handleNodesChange()
|
||||
MessagePlugin.success(t('graphSettings.extractSuccess'))
|
||||
} catch (error: any) {
|
||||
console.error('Failed to extract relations:', error)
|
||||
MessagePlugin.error(t('graphSettings.extractFailed'))
|
||||
} finally {
|
||||
extracting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// 默认示例
|
||||
const defaultExtractExample = () => {
|
||||
localGraphExtract.value.text = `"Romeo and Juliet" is a tragedy written by William Shakespeare early in his career, and is one of the most frequently performed plays in world literature. The play follows two young lovers from feuding families in Verona, Italy — the Montagues and the Capulets. Written around 1594-1596, it was first published in quarto in 1597. The full title is "The Most Excellent and Lamentable Tragedy of Romeo and Juliet." The story has been adapted countless times for stage, film, and other media.`
|
||||
localGraphExtract.value.tags = ['Author', 'Alias']
|
||||
localGraphExtract.value.nodes = [
|
||||
{name: 'Romeo and Juliet', attributes: ['One of the most frequently performed plays', 'Written around 1594-1596', 'A tragedy']},
|
||||
{name: 'The Most Excellent and Lamentable Tragedy of Romeo and Juliet', attributes: ['Full title of Romeo and Juliet']},
|
||||
{name: 'William Shakespeare', attributes: ['English playwright', 'Author of Romeo and Juliet']},
|
||||
{name: 'Verona', attributes: ['City in Italy', 'Setting of the play']}
|
||||
]
|
||||
localGraphExtract.value.relations = [
|
||||
{node1: 'Romeo and Juliet', node2: 'The Most Excellent and Lamentable Tragedy of Romeo and Juliet', type: 'Alias'},
|
||||
{node1: 'Romeo and Juliet', node2: 'William Shakespeare', type: 'Author'},
|
||||
{node1: 'Romeo and Juliet', node2: 'Verona', type: 'Setting'}
|
||||
]
|
||||
handleNodesChange()
|
||||
MessagePlugin.success(t('graphSettings.exampleLoaded'))
|
||||
}
|
||||
|
||||
// 清除示例
|
||||
const clearExtractExample = () => {
|
||||
localGraphExtract.value.text = ''
|
||||
localGraphExtract.value.tags = []
|
||||
localGraphExtract.value.nodes = []
|
||||
localGraphExtract.value.relations = []
|
||||
handleNodesChange()
|
||||
MessagePlugin.success(t('graphSettings.exampleCleared'))
|
||||
}
|
||||
|
||||
const editorResources = useEditorResourcesStore()
|
||||
|
||||
// 加载系统信息
|
||||
const loadSystemInfo = async (force = false) => {
|
||||
try {
|
||||
await editorResources.ensureSystemInfo(force)
|
||||
systemInfo.value = editorResources.systemInfo
|
||||
} catch (error: any) {
|
||||
console.error('Failed to load system info:', error)
|
||||
}
|
||||
}
|
||||
|
||||
const graphGuideUrl =
|
||||
import.meta.env.VITE_KG_GUIDE_URL || docsUrl('knowledgeGraph')
|
||||
|
||||
// Open guide documentation to show how to enable graph database
|
||||
const handleOpenGraphGuide = () => {
|
||||
window.open(graphGuideUrl, '_blank', 'noopener')
|
||||
}
|
||||
|
||||
// 初始化
|
||||
onMounted(async () => {
|
||||
await loadSystemInfo()
|
||||
})
|
||||
</script>
|
||||
|
||||
<style lang="less" scoped>
|
||||
.graph-settings {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.section-header {
|
||||
margin-bottom: 20px;
|
||||
|
||||
h2 {
|
||||
font-size: var(--app-text-3xl);
|
||||
font-weight: 600;
|
||||
color: var(--td-text-color-primary);
|
||||
margin: 0 0 6px 0;
|
||||
}
|
||||
|
||||
.section-description {
|
||||
font-size: var(--app-text-base);
|
||||
color: var(--td-text-color-secondary);
|
||||
margin: 0;
|
||||
line-height: 1.5;
|
||||
}
|
||||
}
|
||||
|
||||
.graph-disabled {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 12px 14px;
|
||||
border: 1px dashed var(--td-component-stroke);
|
||||
border-radius: var(--app-radius-md);
|
||||
background: var(--td-bg-color-secondarycontainer);
|
||||
}
|
||||
|
||||
.graph-disabled-icon {
|
||||
display: inline-flex;
|
||||
flex-shrink: 0;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
border-radius: var(--app-radius-md);
|
||||
font-size: var(--app-text-2xl);
|
||||
color: var(--td-warning-color);
|
||||
background: var(--td-warning-color-light);
|
||||
}
|
||||
|
||||
.graph-disabled-text {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
|
||||
p {
|
||||
margin: 0;
|
||||
font-size: var(--app-text-md);
|
||||
line-height: 1.5;
|
||||
color: var(--td-text-color-secondary);
|
||||
}
|
||||
}
|
||||
|
||||
.settings-group {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0;
|
||||
}
|
||||
|
||||
.setting-row {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
padding: 16px 0;
|
||||
border-bottom: 1px solid var(--td-component-stroke);
|
||||
|
||||
&:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
&.vertical {
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
|
||||
.setting-control {
|
||||
width: 100%;
|
||||
max-width: 100%;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.setting-info {
|
||||
flex: 0 0 40%;
|
||||
max-width: 40%;
|
||||
padding-right: 24px;
|
||||
|
||||
label {
|
||||
font-size: var(--app-text-lg);
|
||||
font-weight: 500;
|
||||
color: var(--td-text-color-primary);
|
||||
display: block;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.desc {
|
||||
font-size: var(--app-text-md);
|
||||
color: var(--td-text-color-secondary);
|
||||
margin: 0;
|
||||
line-height: 1.5;
|
||||
}
|
||||
}
|
||||
|
||||
.setting-control {
|
||||
flex: 0 0 55%;
|
||||
max-width: 55%;
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
align-items: center;
|
||||
|
||||
&.full-width {
|
||||
width: 100%;
|
||||
max-width: 100%;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: 12px;
|
||||
}
|
||||
}
|
||||
|
||||
.tags-control-group,
|
||||
.text-control-group {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
width: 100%;
|
||||
align-items: flex-start;
|
||||
}
|
||||
|
||||
.text-control-group {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.control-tip {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: var(--app-text-md);
|
||||
color: var(--td-text-color-secondary);
|
||||
|
||||
.tip-icon {
|
||||
color: var(--td-brand-color);
|
||||
}
|
||||
}
|
||||
|
||||
.node-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.node-item {
|
||||
background: var(--td-bg-color-container);
|
||||
border: 1px solid var(--td-component-stroke);
|
||||
border-radius: var(--app-radius-md);
|
||||
padding: 16px;
|
||||
}
|
||||
|
||||
.node-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
margin-bottom: 12px;
|
||||
|
||||
.node-icon {
|
||||
font-size: var(--app-text-3xl);
|
||||
color: var(--td-brand-color);
|
||||
}
|
||||
|
||||
.node-name-input {
|
||||
flex: 1;
|
||||
}
|
||||
}
|
||||
|
||||
.node-attributes {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
padding-left: 32px;
|
||||
}
|
||||
|
||||
.attribute-item {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
align-items: center;
|
||||
|
||||
.attribute-input {
|
||||
flex: 1;
|
||||
}
|
||||
}
|
||||
|
||||
.add-attr-btn {
|
||||
align-self: flex-start;
|
||||
}
|
||||
|
||||
.relation-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.relation-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 12px;
|
||||
background: var(--td-bg-color-container);
|
||||
border: 1px solid var(--td-component-stroke);
|
||||
border-radius: var(--app-radius-md);
|
||||
|
||||
.relation-select {
|
||||
flex: 1;
|
||||
min-width: 150px;
|
||||
}
|
||||
|
||||
.relation-arrow {
|
||||
color: var(--td-text-color-secondary);
|
||||
font-size: var(--app-text-xl);
|
||||
}
|
||||
}
|
||||
|
||||
.action-buttons {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.graph-settings--embedded {
|
||||
.graph-disabled {
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.setting-row:not(.vertical) {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
gap: 8px;
|
||||
padding: 12px 0;
|
||||
}
|
||||
|
||||
.setting-row:not(.vertical) .setting-info {
|
||||
flex: none;
|
||||
max-width: none;
|
||||
padding-right: 0;
|
||||
}
|
||||
|
||||
.setting-row:not(.vertical) .setting-control {
|
||||
align-self: flex-start;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,465 @@
|
||||
<template>
|
||||
<div class="kb-advanced-settings" :class="{ 'kb-advanced-settings--embedded': embedded }">
|
||||
<div v-if="!embedded" class="section-header">
|
||||
<h2>{{ $t('knowledgeEditor.advanced.title') }}</h2>
|
||||
<p class="section-description">{{ $t('knowledgeEditor.advanced.description') }}</p>
|
||||
</div>
|
||||
|
||||
<div class="settings-group">
|
||||
<!-- Question Generation feature (only useful for RAG indexing) -->
|
||||
<template v-if="ragEnabled !== false">
|
||||
<div class="setting-row">
|
||||
<div class="setting-info">
|
||||
<label>{{ $t('knowledgeEditor.advanced.questionGeneration.label') }}</label>
|
||||
<p class="desc">{{ $t('knowledgeEditor.advanced.questionGeneration.description') }}</p>
|
||||
</div>
|
||||
<div class="setting-control">
|
||||
<t-switch
|
||||
v-model="localQuestionGeneration.enabled"
|
||||
@change="handleQuestionGenerationToggle"
|
||||
size="medium"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Question Generation configuration -->
|
||||
<div v-if="localQuestionGeneration.enabled" class="subsection">
|
||||
<div class="setting-row">
|
||||
<div class="setting-info">
|
||||
<label>{{ $t('knowledgeEditor.advanced.questionGeneration.countLabel') }}</label>
|
||||
<p class="desc">{{ $t('knowledgeEditor.advanced.questionGeneration.countDescription') }}</p>
|
||||
</div>
|
||||
<div class="setting-control">
|
||||
<t-input-number
|
||||
v-model="localQuestionGeneration.questionCount"
|
||||
:min="1"
|
||||
:max="10"
|
||||
:step="1"
|
||||
theme="normal"
|
||||
@change="handleQuestionGenerationChange"
|
||||
style="width: 120px;"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div class="setting-row setting-row-vertical">
|
||||
<div class="setting-info">
|
||||
<label>{{ $t('knowledgeEditor.advanced.questionGeneration.instructionsLabel') }}</label>
|
||||
<p class="desc">{{ $t('knowledgeEditor.advanced.questionGeneration.instructionsDescription') }}</p>
|
||||
</div>
|
||||
<div class="setting-control">
|
||||
<t-textarea
|
||||
v-model="localQuestionGeneration.customInstructions"
|
||||
:placeholder="$t('knowledgeEditor.advanced.questionGeneration.instructionsPlaceholder')"
|
||||
:maxlength="4000"
|
||||
:autosize="{ minRows: 3, maxRows: 8 }"
|
||||
@change="handleQuestionGenerationChange"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<div class="setting-row">
|
||||
<div class="setting-info">
|
||||
<label>{{ $t('knowledgeEditor.advanced.autoTag.label') }}</label>
|
||||
<p class="desc">{{ $t('knowledgeEditor.advanced.autoTag.description') }}</p>
|
||||
</div>
|
||||
<div class="setting-control">
|
||||
<t-switch v-model="localAutoTag.enabled" size="medium" @change="emitAutoTag" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="localAutoTag.enabled" class="subsection">
|
||||
<div class="setting-row setting-row-vertical">
|
||||
<div class="setting-info">
|
||||
<label>{{ $t('knowledgeEditor.advanced.autoTag.modelLabel') }}</label>
|
||||
<p class="desc">{{ $t('knowledgeEditor.advanced.autoTag.modelDescription') }}</p>
|
||||
</div>
|
||||
<div class="setting-control">
|
||||
<ModelSelector
|
||||
model-type="KnowledgeQA"
|
||||
:selected-model-id="localAutoTag.modelId"
|
||||
:all-models="allModels"
|
||||
clearable
|
||||
:placeholder="$t('knowledgeEditor.advanced.autoTag.modelPlaceholder')"
|
||||
@update:selected-model-id="(value: string) => { localAutoTag.modelId = value; emitAutoTag() }"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div class="setting-row">
|
||||
<div class="setting-info">
|
||||
<label>{{ $t('knowledgeEditor.advanced.autoTag.maxTagsLabel') }}</label>
|
||||
<p class="desc">{{ $t('knowledgeEditor.advanced.autoTag.maxTagsDescription') }}</p>
|
||||
</div>
|
||||
<div class="setting-control">
|
||||
<t-input-number
|
||||
v-model="localAutoTag.maxTags"
|
||||
:min="1"
|
||||
:max="10"
|
||||
:step="1"
|
||||
theme="normal"
|
||||
style="width: 120px;"
|
||||
@change="emitAutoTag"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div class="setting-row">
|
||||
<div class="setting-info">
|
||||
<label>{{ $t('knowledgeEditor.advanced.autoTag.skipIfTaggedLabel') }}</label>
|
||||
<p class="desc">{{ $t('knowledgeEditor.advanced.autoTag.skipIfTaggedDescription') }}</p>
|
||||
</div>
|
||||
<div class="setting-control">
|
||||
<t-switch v-model="localAutoTag.skipIfTagged" size="medium" @change="emitAutoTag" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="setting-row">
|
||||
<div class="setting-info">
|
||||
<label>{{ $t('knowledgeEditor.advanced.profile.label') }}</label>
|
||||
<p class="desc">{{ $t('knowledgeEditor.advanced.profile.description') }}</p>
|
||||
</div>
|
||||
<div class="setting-control">
|
||||
<t-switch v-model="localProfile.enabled" size="medium" @change="emitProfile" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="localProfile.enabled" class="subsection">
|
||||
<div class="setting-row setting-row-vertical">
|
||||
<div class="setting-info">
|
||||
<label>{{ $t('knowledgeEditor.advanced.profile.modelLabel') }}</label>
|
||||
<p class="desc">{{ $t('knowledgeEditor.advanced.profile.modelDescription') }}</p>
|
||||
</div>
|
||||
<div class="setting-control">
|
||||
<ModelSelector
|
||||
model-type="KnowledgeQA"
|
||||
:selected-model-id="localProfile.modelId"
|
||||
:all-models="allModels"
|
||||
clearable
|
||||
:placeholder="$t('knowledgeEditor.advanced.profile.modelPlaceholder')"
|
||||
@update:selected-model-id="(value: string) => { localProfile.modelId = value; emitProfile() }"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div class="setting-row setting-row-vertical">
|
||||
<div class="setting-info">
|
||||
<label>{{ $t('knowledgeEditor.advanced.profile.instructionsLabel') }}</label>
|
||||
<p class="desc">{{ $t('knowledgeEditor.advanced.profile.instructionsDescription') }}</p>
|
||||
</div>
|
||||
<div class="setting-control">
|
||||
<t-textarea
|
||||
v-model="localProfile.customInstructions"
|
||||
:placeholder="$t('knowledgeEditor.advanced.profile.instructionsPlaceholder')"
|
||||
:maxlength="2000"
|
||||
:autosize="{ minRows: 2, maxRows: 6 }"
|
||||
@change="emitProfile"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="setting-row setting-row-vertical">
|
||||
<div class="setting-info">
|
||||
<label>{{ $t('knowledgeEditor.advanced.tableMetadataInstructions.label') }}</label>
|
||||
<p class="desc">{{ $t('knowledgeEditor.advanced.tableMetadataInstructions.description') }}</p>
|
||||
</div>
|
||||
<div class="setting-control">
|
||||
<t-textarea
|
||||
:model-value="tableMetadataInstructions"
|
||||
:placeholder="$t('knowledgeEditor.advanced.tableMetadataInstructions.placeholder')"
|
||||
:maxlength="4000"
|
||||
:autosize="{ minRows: 3, maxRows: 8 }"
|
||||
@change="(value: string) => emit('update:tableMetadataInstructions', value)"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, watch } from 'vue'
|
||||
import ModelSelector from '@/components/ModelSelector.vue'
|
||||
|
||||
interface QuestionGenerationConfig {
|
||||
enabled: boolean
|
||||
questionCount: number
|
||||
customInstructions?: string
|
||||
}
|
||||
|
||||
interface AutoTagConfig {
|
||||
enabled: boolean
|
||||
modelId: string
|
||||
maxTags: number
|
||||
skipIfTagged: boolean
|
||||
}
|
||||
|
||||
interface ProfileConfig {
|
||||
enabled: boolean
|
||||
modelId: string
|
||||
customInstructions: string
|
||||
}
|
||||
|
||||
interface Props {
|
||||
questionGeneration?: QuestionGenerationConfig
|
||||
autoTag?: AutoTagConfig
|
||||
profileConfig?: ProfileConfig
|
||||
ragEnabled?: boolean
|
||||
allModels?: any[]
|
||||
embedded?: boolean
|
||||
tableMetadataInstructions?: string
|
||||
}
|
||||
|
||||
const props = withDefaults(defineProps<Props>(), {
|
||||
embedded: false,
|
||||
})
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:questionGeneration': [value: QuestionGenerationConfig]
|
||||
'update:autoTag': [value: AutoTagConfig]
|
||||
'update:profileConfig': [value: ProfileConfig]
|
||||
'update:tableMetadataInstructions': [value: string]
|
||||
}>()
|
||||
|
||||
const localProfile = ref<ProfileConfig>(
|
||||
props.profileConfig
|
||||
? { ...props.profileConfig }
|
||||
: { enabled: false, modelId: '', customInstructions: '' }
|
||||
)
|
||||
|
||||
watch(() => props.profileConfig, (newVal) => {
|
||||
if (newVal) localProfile.value = { ...newVal }
|
||||
}, { deep: true })
|
||||
|
||||
const emitProfile = () => {
|
||||
emit('update:profileConfig', { ...localProfile.value })
|
||||
}
|
||||
|
||||
const localQuestionGeneration = ref<QuestionGenerationConfig>(
|
||||
props.questionGeneration
|
||||
? { ...props.questionGeneration, customInstructions: props.questionGeneration.customInstructions || '' }
|
||||
: { enabled: false, questionCount: 3, customInstructions: '' }
|
||||
)
|
||||
|
||||
const localAutoTag = ref<AutoTagConfig>(
|
||||
props.autoTag ? { ...props.autoTag } : { enabled: false, modelId: '', maxTags: 3, skipIfTagged: true }
|
||||
)
|
||||
|
||||
watch(() => props.questionGeneration, (newVal) => {
|
||||
if (newVal) {
|
||||
localQuestionGeneration.value = { customInstructions: '', ...newVal }
|
||||
}
|
||||
}, { deep: true })
|
||||
|
||||
watch(() => props.autoTag, (newVal) => {
|
||||
if (newVal) localAutoTag.value = { ...newVal }
|
||||
}, { deep: true })
|
||||
|
||||
const emitAutoTag = () => {
|
||||
if (!localAutoTag.value.maxTags) localAutoTag.value.maxTags = 3
|
||||
localAutoTag.value.maxTags = Math.min(10, Math.max(1, Math.trunc(localAutoTag.value.maxTags)))
|
||||
emit('update:autoTag', { ...localAutoTag.value })
|
||||
}
|
||||
|
||||
const handleQuestionGenerationToggle = () => {
|
||||
if (!localQuestionGeneration.value.enabled) {
|
||||
localQuestionGeneration.value.questionCount = 3
|
||||
}
|
||||
emit('update:questionGeneration', localQuestionGeneration.value)
|
||||
}
|
||||
|
||||
const handleQuestionGenerationChange = () => {
|
||||
emit('update:questionGeneration', localQuestionGeneration.value)
|
||||
}
|
||||
</script>
|
||||
|
||||
<style lang="less" scoped>
|
||||
.kb-advanced-settings {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.section-header {
|
||||
margin-bottom: 20px;
|
||||
|
||||
h2 {
|
||||
font-size: var(--app-text-3xl);
|
||||
font-weight: 600;
|
||||
color: var(--td-text-color-primary);
|
||||
margin: 0 0 6px 0;
|
||||
}
|
||||
|
||||
.section-description {
|
||||
font-size: var(--app-text-base);
|
||||
color: var(--td-text-color-secondary);
|
||||
margin: 0;
|
||||
line-height: 1.5;
|
||||
}
|
||||
}
|
||||
|
||||
.settings-group {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0;
|
||||
}
|
||||
|
||||
.setting-row {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
padding: 16px 0;
|
||||
border-bottom: 1px solid var(--td-component-stroke);
|
||||
|
||||
&:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
}
|
||||
|
||||
.setting-info {
|
||||
flex: 0 0 40%;
|
||||
max-width: 40%;
|
||||
padding-right: 24px;
|
||||
|
||||
label {
|
||||
font-size: var(--app-text-lg);
|
||||
font-weight: 500;
|
||||
color: var(--td-text-color-primary);
|
||||
display: block;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.desc {
|
||||
font-size: var(--app-text-md);
|
||||
color: var(--td-text-color-secondary);
|
||||
margin: 0;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.hint {
|
||||
font-size: var(--app-text-sm);
|
||||
color: var(--td-text-color-placeholder);
|
||||
margin: 6px 0 0 0;
|
||||
line-height: 1.5;
|
||||
}
|
||||
}
|
||||
|
||||
.setting-control {
|
||||
flex: 0 0 55%;
|
||||
max-width: 55%;
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.setting-row-vertical {
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
|
||||
.setting-info,
|
||||
.setting-control {
|
||||
flex: none;
|
||||
width: 100%;
|
||||
max-width: none;
|
||||
padding-right: 0;
|
||||
}
|
||||
|
||||
.setting-control {
|
||||
display: block;
|
||||
}
|
||||
}
|
||||
|
||||
.kb-advanced-settings:not(.kb-advanced-settings--embedded) {
|
||||
.setting-row:has(> .setting-control > .t-switch) {
|
||||
align-items: center;
|
||||
|
||||
.setting-info {
|
||||
flex: 1;
|
||||
max-width: none;
|
||||
}
|
||||
|
||||
.setting-control {
|
||||
flex: none;
|
||||
max-width: none;
|
||||
}
|
||||
}
|
||||
|
||||
.setting-row:has(+ .subsection) {
|
||||
border-bottom: none;
|
||||
padding-bottom: 12px;
|
||||
}
|
||||
|
||||
.subsection {
|
||||
margin-bottom: 4px;
|
||||
padding: 0 16px;
|
||||
background: var(--td-bg-color-secondarycontainer);
|
||||
border-radius: var(--app-radius-md);
|
||||
|
||||
.setting-row {
|
||||
padding: 14px 0;
|
||||
}
|
||||
|
||||
.setting-row-vertical {
|
||||
gap: 8px;
|
||||
}
|
||||
}
|
||||
|
||||
.subsection + .setting-row {
|
||||
margin-top: 12px;
|
||||
border-top: 1px solid var(--td-component-stroke);
|
||||
}
|
||||
}
|
||||
|
||||
.required {
|
||||
color: var(--td-error-color);
|
||||
margin-left: 2px;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.kb-advanced-settings--embedded {
|
||||
.setting-row {
|
||||
padding: 12px 0;
|
||||
}
|
||||
|
||||
.setting-row:has(.t-switch) {
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
|
||||
.setting-info {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
max-width: none;
|
||||
padding-right: 0;
|
||||
}
|
||||
|
||||
.setting-control {
|
||||
flex: none;
|
||||
align-self: center;
|
||||
}
|
||||
}
|
||||
|
||||
.subsection .setting-row {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
gap: 8px;
|
||||
|
||||
.setting-info {
|
||||
flex: none;
|
||||
max-width: none;
|
||||
padding-right: 0;
|
||||
}
|
||||
|
||||
.setting-control {
|
||||
align-self: flex-start;
|
||||
}
|
||||
}
|
||||
|
||||
.subsection {
|
||||
margin-top: 0;
|
||||
padding: 0;
|
||||
border: none;
|
||||
background: none;
|
||||
}
|
||||
}
|
||||
|
||||
</style>
|
||||
@@ -0,0 +1,725 @@
|
||||
<template>
|
||||
<div class="kb-chunking-debug">
|
||||
<!-- Inline text trigger: sits next to the strategy selector so users
|
||||
discover the test action exactly when they're thinking about which
|
||||
strategy to pick. Kept as a text-style button to match the project's
|
||||
secondary-action convention (no heavy outline / filled treatment). -->
|
||||
<t-button
|
||||
type="button"
|
||||
theme="primary"
|
||||
variant="text"
|
||||
size="medium"
|
||||
class="debug-trigger"
|
||||
@click="open = true"
|
||||
>
|
||||
<template #icon><play-circle-icon /></template>
|
||||
{{ $t('knowledgeEditor.chunking.debug.toggle') }}
|
||||
</t-button>
|
||||
|
||||
<t-drawer
|
||||
v-model:visible="open"
|
||||
:header="$t('knowledgeEditor.chunking.debug.toggle')"
|
||||
:footer="false"
|
||||
size="720px"
|
||||
placement="right"
|
||||
:close-on-overlay-click="true"
|
||||
:destroy-on-close="false"
|
||||
attach="body"
|
||||
:z-index="3000"
|
||||
>
|
||||
<div class="drawer-body">
|
||||
<!-- Input section -->
|
||||
<section class="drawer-section">
|
||||
<div class="section-title-row">
|
||||
<div class="section-title">{{ $t('knowledgeEditor.chunking.debug.sampleLabel') }}</div>
|
||||
<div class="sample-presets">
|
||||
<span class="presets-label">{{ $t('knowledgeEditor.chunking.debug.presetLabel') }}</span>
|
||||
<t-button
|
||||
v-for="p in samples"
|
||||
:key="p.id"
|
||||
type="button"
|
||||
variant="text"
|
||||
size="small"
|
||||
class="preset-chip"
|
||||
@click="loadSample(p.id)"
|
||||
>
|
||||
{{ $t(`knowledgeEditor.chunking.debug.${p.labelKey}`) }}
|
||||
</t-button>
|
||||
</div>
|
||||
</div>
|
||||
<t-textarea
|
||||
v-model="sample"
|
||||
:placeholder="$t('knowledgeEditor.chunking.debug.samplePlaceholder')"
|
||||
:autosize="{ minRows: 6, maxRows: 12 }"
|
||||
:maxlength="MAX_CHARS"
|
||||
/>
|
||||
<div class="input-actions">
|
||||
<!-- type="button" prevents any accidental parent-form submit. -->
|
||||
<t-button
|
||||
type="button"
|
||||
theme="primary"
|
||||
:loading="loading"
|
||||
:disabled="!sample || sample.length === 0"
|
||||
@click.prevent.stop="runPreview"
|
||||
>
|
||||
<template #icon><play-circle-icon /></template>
|
||||
{{ $t('knowledgeEditor.chunking.debug.runButton') }}
|
||||
</t-button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Loading state — explicit so the user sees something is happening
|
||||
even if the result block hasn't appeared yet. -->
|
||||
<div v-if="loading" class="debug-loading">
|
||||
<t-loading size="small" />
|
||||
<span>{{ $t('knowledgeEditor.chunking.debug.loading') }}</span>
|
||||
</div>
|
||||
|
||||
<!-- Error block: prominent so it can't be missed when an API call fails. -->
|
||||
<div v-else-if="error" class="debug-error">
|
||||
<error-circle-icon class="error-icon" />
|
||||
<div>
|
||||
<strong>{{ $t('knowledgeEditor.chunking.debug.errorPrefix') }}</strong>
|
||||
<span>{{ error }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<section v-else-if="result" class="drawer-section debug-result">
|
||||
<!-- Tier summary -->
|
||||
<div class="result-header">
|
||||
<div class="tier-row">
|
||||
<span class="result-label">{{ $t('knowledgeEditor.chunking.debug.selectedTier') }}:</span>
|
||||
<t-tag
|
||||
:theme="tierTheme(result.selected_tier)"
|
||||
variant="light-outline"
|
||||
size="medium"
|
||||
>
|
||||
{{ tierDisplay(result.selected_tier) }}
|
||||
</t-tag>
|
||||
<span v-if="fallbackWarning" class="fallback-warning">
|
||||
{{ $t('knowledgeEditor.chunking.debug.fallbackWarning') }}
|
||||
</span>
|
||||
</div>
|
||||
<div v-if="(result.rejected || []).length > 0" class="tier-row">
|
||||
<span class="result-label">{{ $t('knowledgeEditor.chunking.debug.rejected') }}:</span>
|
||||
<span class="rejection-list">
|
||||
<t-tag
|
||||
v-for="r in (result.rejected || [])"
|
||||
:key="r.tier"
|
||||
theme="default"
|
||||
variant="light"
|
||||
size="small"
|
||||
>
|
||||
{{ tierDisplay(r.tier) }}: {{ r.reason }}
|
||||
</t-tag>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Profile stats -->
|
||||
<div class="profile-grid">
|
||||
<div class="profile-cell">
|
||||
<div class="cell-value">{{ result.profile.total_lines }}</div>
|
||||
<div class="cell-label">{{ $t('knowledgeEditor.chunking.debug.profile.lines') }}</div>
|
||||
</div>
|
||||
<div class="profile-cell">
|
||||
<div class="cell-value">{{ result.profile.total_chars }}</div>
|
||||
<div class="cell-label">{{ $t('knowledgeEditor.chunking.debug.profile.chars') }}</div>
|
||||
</div>
|
||||
<div class="profile-cell">
|
||||
<div class="cell-value">{{ result.profile.md_heading_total }}</div>
|
||||
<div class="cell-label">{{ $t('knowledgeEditor.chunking.debug.profile.headings') }}</div>
|
||||
</div>
|
||||
<div class="profile-cell">
|
||||
<div class="cell-value">{{ result.profile.form_feed_count }}</div>
|
||||
<div class="cell-label">{{ $t('knowledgeEditor.chunking.debug.profile.pageBreaks') }}</div>
|
||||
</div>
|
||||
<div class="profile-cell">
|
||||
<div class="cell-value">
|
||||
{{
|
||||
result.profile.german_chapter_count +
|
||||
result.profile.english_chapter_count +
|
||||
result.profile.chinese_chapter_count
|
||||
}}
|
||||
</div>
|
||||
<div class="cell-label">{{ $t('knowledgeEditor.chunking.debug.profile.chapterMarkers') }}</div>
|
||||
</div>
|
||||
<div class="profile-cell">
|
||||
<div class="cell-value">{{ (result.profile.detected_langs || []).join(', ') || '—' }}</div>
|
||||
<div class="cell-label">{{ $t('knowledgeEditor.chunking.debug.profile.languages') }}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Chunk stats line -->
|
||||
<div class="chunk-stats">
|
||||
<span class="stats-count">
|
||||
<strong>{{ result.stats.count }}</strong>
|
||||
{{ $t('knowledgeEditor.chunking.debug.stats.chunks') }}
|
||||
</span>
|
||||
<span class="stats-sep">·</span>
|
||||
<span>Ø {{ result.stats.avg_chars }}</span>
|
||||
<span class="stats-sep">·</span>
|
||||
<span>σ {{ result.stats.stddev_chars }}</span>
|
||||
<span class="stats-sep">·</span>
|
||||
<span>min {{ result.stats.min_chars }}</span>
|
||||
<span class="stats-sep">·</span>
|
||||
<span>max {{ result.stats.max_chars }}</span>
|
||||
<span v-if="result.stats.truncated_to" class="truncation-hint">
|
||||
{{ $t('knowledgeEditor.chunking.debug.stats.truncated', { total: result.stats.truncated_to }) }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<!-- Chunks list — no inner scroll; the drawer body handles scrolling
|
||||
so expanded cards always show their full content. -->
|
||||
<ol class="chunks-list">
|
||||
<li
|
||||
v-for="c in result.chunks"
|
||||
:key="c.seq"
|
||||
class="chunk-card"
|
||||
:class="{ expanded: expandedChunks.has(c.seq) }"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="chunk-meta"
|
||||
:aria-expanded="expandedChunks.has(c.seq)"
|
||||
@click="toggleChunk(c.seq)"
|
||||
>
|
||||
<span class="chunk-seq">#{{ c.seq }}</span>
|
||||
<span class="chunk-size">
|
||||
{{ c.size_chars }} {{ $t('knowledgeEditor.chunking.characters') }}
|
||||
<span class="chunk-tokens">· ~{{ c.size_tokens_approx }} tok</span>
|
||||
</span>
|
||||
<span class="chunk-pos">{{ c.start }}–{{ c.end }}</span>
|
||||
<span v-if="c.context_header" class="chunk-context-pill" :title="c.context_header">
|
||||
{{ c.context_header }}
|
||||
</span>
|
||||
<chevron-down-icon class="chunk-toggle" :class="{ open: expandedChunks.has(c.seq) }" />
|
||||
</button>
|
||||
<div class="chunk-body" :class="{ collapsed: !expandedChunks.has(c.seq) }">
|
||||
<pre class="chunk-text">{{ c.content }}</pre>
|
||||
</div>
|
||||
</li>
|
||||
</ol>
|
||||
</section>
|
||||
</div>
|
||||
</t-drawer>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, watch } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { MessagePlugin } from 'tdesign-vue-next'
|
||||
import {
|
||||
ChevronDownIcon,
|
||||
PlayCircleIcon,
|
||||
ErrorCircleIcon,
|
||||
} from 'tdesign-icons-vue-next'
|
||||
import { previewChunking } from '@/api/chunker'
|
||||
import type { PreviewChunkingResponse, StrategyTier } from '@/types/chunker'
|
||||
import { CHUNKING_SAMPLES, DEFAULT_SAMPLE_ID } from './chunkingSamples'
|
||||
|
||||
interface Props {
|
||||
config: {
|
||||
chunkSize: number
|
||||
chunkOverlap: number
|
||||
separators: string[]
|
||||
enableParentChild: boolean
|
||||
parentChunkSize: number
|
||||
childChunkSize: number
|
||||
strategy?: string
|
||||
tokenLimit?: number
|
||||
languages?: string[]
|
||||
}
|
||||
}
|
||||
|
||||
const props = defineProps<Props>()
|
||||
const { t } = useI18n()
|
||||
|
||||
// Mirrors handler.previewMaxChars on the backend. Keep in sync.
|
||||
const MAX_CHARS = 64 * 1024
|
||||
|
||||
const open = ref(false)
|
||||
const sample = ref('')
|
||||
const loading = ref(false)
|
||||
const error = ref('')
|
||||
const result = ref<PreviewChunkingResponse | null>(null)
|
||||
const expandedChunks = ref(new Set<number>())
|
||||
|
||||
const samples = CHUNKING_SAMPLES
|
||||
|
||||
// Auto-load the default preset the first time the user opens the drawer with
|
||||
// an empty textarea. We don't overwrite their input on subsequent opens, and
|
||||
// we don't pre-load on component mount (zero cost when the drawer is unused).
|
||||
watch(open, (isOpen) => {
|
||||
if (isOpen && sample.value.trim() === '') {
|
||||
loadSample(DEFAULT_SAMPLE_ID)
|
||||
}
|
||||
})
|
||||
|
||||
const loadSample = (id: string) => {
|
||||
const preset = samples.find((s) => s.id === id)
|
||||
if (!preset) return
|
||||
sample.value = preset.text
|
||||
// Clear any previous run so the user isn't looking at stale results
|
||||
// attributed to the old text.
|
||||
result.value = null
|
||||
error.value = ''
|
||||
expandedChunks.value = new Set()
|
||||
}
|
||||
|
||||
const fallbackWarning = computed(() => {
|
||||
if (!result.value) return false
|
||||
return result.value.selected_tier === 'legacy' && (result.value.rejected || []).length > 0
|
||||
})
|
||||
|
||||
const runPreview = async () => {
|
||||
loading.value = true
|
||||
error.value = ''
|
||||
result.value = null
|
||||
expandedChunks.value = new Set()
|
||||
try {
|
||||
// Send all fields explicitly (including empty / 0 / []) so the
|
||||
// preview faithfully reflects what would happen on save. Mirrors
|
||||
// the buildSubmitData convention in KnowledgeBaseEditorModal.
|
||||
const resp = await previewChunking({
|
||||
text: sample.value,
|
||||
chunking_config: {
|
||||
chunk_size: props.config.chunkSize,
|
||||
chunk_overlap: props.config.chunkOverlap,
|
||||
separators: props.config.separators,
|
||||
enable_parent_child: props.config.enableParentChild,
|
||||
parent_chunk_size: props.config.parentChunkSize,
|
||||
child_chunk_size: props.config.childChunkSize,
|
||||
strategy: props.config.strategy ?? '',
|
||||
token_limit: props.config.tokenLimit ?? 0,
|
||||
languages: props.config.languages ?? []
|
||||
}
|
||||
})
|
||||
// The axios interceptor in utils/request.ts already unwraps the
|
||||
// outer envelope and returns the response body. So resp here is
|
||||
// { success: true, data: PreviewChunkingResponse } directly.
|
||||
// If the backend ever responds with 200 + { success: false, error },
|
||||
// surface that error instead of swallowing it under a generic message.
|
||||
if (!resp) {
|
||||
throw new Error('empty response')
|
||||
}
|
||||
if (resp.success !== true) {
|
||||
throw new Error((resp as any).error || 'preview failed')
|
||||
}
|
||||
if (!resp.data) {
|
||||
throw new Error('response missing data')
|
||||
}
|
||||
result.value = resp.data
|
||||
} catch (e: any) {
|
||||
// Pull a useful message out of the error shapes our request layer
|
||||
// produces: rejected interceptor sends { status, message, ... }.
|
||||
const msg =
|
||||
e?.message ||
|
||||
(typeof e === 'string' ? e : '') ||
|
||||
'unknown error'
|
||||
error.value = msg
|
||||
// Console log so users can debug from DevTools too.
|
||||
console.error('[KBChunkingDebug] previewChunking failed:', e)
|
||||
// Toast for visibility.
|
||||
MessagePlugin.error(t('knowledgeEditor.chunking.debug.errorPrefix') + ': ' + msg)
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const toggleChunk = (seq: number) => {
|
||||
const next = new Set(expandedChunks.value)
|
||||
if (next.has(seq)) next.delete(seq)
|
||||
else next.add(seq)
|
||||
expandedChunks.value = next
|
||||
}
|
||||
|
||||
// `recursive` and `legacy` use the same SplitText path under the hood
|
||||
// (see internal/infrastructure/chunker/strategy.go); their distinction is
|
||||
// only a debugging hint about how the tier was reached. Surface them under
|
||||
// the user-facing legacy label to avoid implying two different splitters.
|
||||
const normalizeTier = (tier: StrategyTier): StrategyTier =>
|
||||
tier === 'recursive' ? 'legacy' : tier
|
||||
|
||||
const tierDisplay = (tier: StrategyTier) => {
|
||||
return t(`knowledgeEditor.chunking.strategies.${normalizeTier(tier)}.label`)
|
||||
}
|
||||
|
||||
const tierTheme = (tier: StrategyTier) => {
|
||||
switch (normalizeTier(tier)) {
|
||||
case 'heading':
|
||||
case 'heuristic':
|
||||
return 'success'
|
||||
case 'recursive':
|
||||
return 'primary'
|
||||
case 'legacy':
|
||||
default:
|
||||
return 'default'
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style lang="less" scoped>
|
||||
.kb-chunking-debug {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
// TDesign's primary text-button renders a filled hover background that
|
||||
// looks out of place in this right-aligned slot — it reads as a floating
|
||||
// color block rather than a link. Strip the hover/focus/active surfaces
|
||||
// and just shift the text colour, giving the trigger a lightweight
|
||||
// "inline link" feel that matches the rest of the secondary actions.
|
||||
.debug-trigger {
|
||||
--td-bg-color-container-hover: transparent;
|
||||
padding-left: 0;
|
||||
padding-right: 0;
|
||||
font-weight: 600;
|
||||
|
||||
&:hover,
|
||||
&:focus,
|
||||
&.t-is-active,
|
||||
&:active {
|
||||
background-color: transparent !important;
|
||||
color: var(--td-brand-color-hover);
|
||||
}
|
||||
|
||||
&:active {
|
||||
color: var(--td-brand-color-active);
|
||||
}
|
||||
}
|
||||
|
||||
.drawer-body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 20px;
|
||||
}
|
||||
|
||||
.drawer-section {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.section-title-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.section-title {
|
||||
font-size: var(--app-text-md);
|
||||
font-weight: 500;
|
||||
color: var(--td-text-color-primary);
|
||||
}
|
||||
|
||||
.sample-presets {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
flex-wrap: wrap;
|
||||
|
||||
.presets-label {
|
||||
font-size: var(--app-text-sm);
|
||||
color: var(--td-text-color-placeholder);
|
||||
margin-right: 4px;
|
||||
}
|
||||
|
||||
.preset-chip {
|
||||
--td-comp-paddinglr-s: 8px;
|
||||
color: var(--td-text-color-secondary);
|
||||
font-size: var(--app-text-sm);
|
||||
|
||||
&:hover {
|
||||
color: var(--td-brand-color);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.input-actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
// debug-result manages its own internal vertical rhythm via margin-bottom
|
||||
// on each block; drop the section-level gap so spacing isn't doubled.
|
||||
.debug-result {
|
||||
gap: 0;
|
||||
}
|
||||
|
||||
.debug-loading {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 12px 14px;
|
||||
background: var(--td-bg-color-container-hover);
|
||||
border-radius: var(--app-radius-sm);
|
||||
font-size: var(--app-text-md);
|
||||
color: var(--td-text-color-secondary);
|
||||
}
|
||||
|
||||
.debug-error {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 10px;
|
||||
padding: 12px 14px;
|
||||
background: var(--td-error-color-light);
|
||||
border-radius: var(--app-radius-sm);
|
||||
font-size: var(--app-text-md);
|
||||
color: var(--td-error-color);
|
||||
|
||||
.error-icon {
|
||||
flex-shrink: 0;
|
||||
margin-top: 2px;
|
||||
font-size: var(--app-text-xl);
|
||||
}
|
||||
|
||||
strong {
|
||||
display: block;
|
||||
margin-bottom: 2px;
|
||||
}
|
||||
|
||||
span {
|
||||
color: var(--td-error-color);
|
||||
font-weight: 400;
|
||||
word-break: break-word;
|
||||
}
|
||||
}
|
||||
|
||||
.result-header {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
margin-bottom: 16px;
|
||||
padding-bottom: 12px;
|
||||
border-bottom: 1px dashed var(--td-component-stroke);
|
||||
}
|
||||
|
||||
.tier-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
font-size: var(--app-text-md);
|
||||
}
|
||||
|
||||
.result-label {
|
||||
color: var(--td-text-color-secondary);
|
||||
font-weight: 500;
|
||||
min-width: 120px;
|
||||
}
|
||||
|
||||
.rejection-list {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.fallback-warning {
|
||||
color: var(--td-warning-color);
|
||||
font-size: var(--app-text-sm);
|
||||
}
|
||||
|
||||
.profile-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(110px, 1fr));
|
||||
gap: 1px;
|
||||
margin-bottom: 16px;
|
||||
background: var(--td-component-stroke);
|
||||
border: 1px solid var(--td-component-stroke);
|
||||
border-radius: var(--app-radius-sm);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.profile-cell {
|
||||
padding: 12px 8px;
|
||||
text-align: center;
|
||||
background: var(--td-bg-color-container);
|
||||
}
|
||||
|
||||
.cell-value {
|
||||
font-size: var(--app-text-2xl);
|
||||
font-weight: 600;
|
||||
font-variant-numeric: tabular-nums;
|
||||
color: var(--td-text-color-primary);
|
||||
line-height: 1.2;
|
||||
}
|
||||
|
||||
.cell-label {
|
||||
margin-top: 4px;
|
||||
font-size: var(--app-text-xs);
|
||||
color: var(--td-text-color-secondary);
|
||||
}
|
||||
|
||||
.chunk-stats {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: baseline;
|
||||
gap: 8px;
|
||||
margin-bottom: 12px;
|
||||
padding: 10px 14px;
|
||||
background: var(--td-bg-color-container-hover);
|
||||
border-radius: var(--app-radius-sm);
|
||||
font-size: var(--app-text-md);
|
||||
color: var(--td-text-color-secondary);
|
||||
font-variant-numeric: tabular-nums;
|
||||
|
||||
.stats-count strong {
|
||||
margin-right: 4px;
|
||||
color: var(--td-text-color-primary);
|
||||
font-size: var(--app-text-base);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.stats-sep {
|
||||
color: var(--td-text-color-placeholder);
|
||||
}
|
||||
}
|
||||
|
||||
.truncation-hint {
|
||||
margin-left: auto;
|
||||
color: var(--td-warning-color);
|
||||
font-size: var(--app-text-sm);
|
||||
}
|
||||
|
||||
.chunks-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
.chunk-card {
|
||||
border: 1px solid var(--td-component-stroke);
|
||||
border-radius: var(--app-radius-sm);
|
||||
background: var(--td-bg-color-container);
|
||||
overflow: hidden;
|
||||
transition: border-color var(--app-motion-fast) ease, box-shadow var(--app-motion-fast) ease;
|
||||
|
||||
&.expanded {
|
||||
border-color: var(--td-brand-color-light-active);
|
||||
box-shadow: 0 0 0 1px var(--td-brand-color-light) inset;
|
||||
}
|
||||
}
|
||||
|
||||
.chunk-meta {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
width: 100%;
|
||||
margin: 0;
|
||||
padding: 10px 14px;
|
||||
background: var(--td-bg-color-container-hover);
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
font-size: var(--app-text-sm);
|
||||
color: var(--td-text-color-secondary);
|
||||
text-align: left;
|
||||
|
||||
&:hover {
|
||||
background: var(--td-bg-color-component-hover);
|
||||
}
|
||||
|
||||
&:focus-visible {
|
||||
outline: 2px solid var(--td-brand-color-focus);
|
||||
outline-offset: -2px;
|
||||
}
|
||||
}
|
||||
|
||||
.chunk-seq {
|
||||
flex-shrink: 0;
|
||||
color: var(--td-text-color-primary);
|
||||
font-weight: 600;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.chunk-size {
|
||||
flex-shrink: 0;
|
||||
color: var(--td-text-color-primary);
|
||||
font-variant-numeric: tabular-nums;
|
||||
|
||||
.chunk-tokens {
|
||||
color: var(--td-text-color-secondary);
|
||||
font-weight: 400;
|
||||
}
|
||||
}
|
||||
|
||||
.chunk-pos {
|
||||
flex-shrink: 0;
|
||||
color: var(--td-text-color-placeholder);
|
||||
font-family: var(--td-font-family-mono);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.chunk-context-pill {
|
||||
flex: 0 1 auto;
|
||||
min-width: 0;
|
||||
max-width: 240px;
|
||||
padding: 2px 8px;
|
||||
background: var(--td-brand-color-light);
|
||||
color: var(--td-brand-color);
|
||||
border-radius: var(--app-radius-lg);
|
||||
font-size: var(--app-text-xs);
|
||||
font-family: var(--td-font-family-mono);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.chunk-toggle {
|
||||
margin-left: auto;
|
||||
flex-shrink: 0;
|
||||
font-size: var(--app-text-xl);
|
||||
color: var(--td-text-color-secondary);
|
||||
transition: transform var(--app-motion-fast) ease;
|
||||
|
||||
&.open {
|
||||
transform: rotate(180deg);
|
||||
}
|
||||
}
|
||||
|
||||
.chunk-body {
|
||||
border-top: 1px solid var(--td-component-stroke);
|
||||
background: var(--td-bg-color-container);
|
||||
}
|
||||
|
||||
.chunk-text {
|
||||
margin: 0;
|
||||
padding: 12px 14px;
|
||||
font-size: 12.5px;
|
||||
line-height: 1.6;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
color: var(--td-text-color-primary);
|
||||
font-family: var(--td-font-family-mono);
|
||||
}
|
||||
|
||||
// Collapsed preview: clamp the visible lines so each card stays compact, but
|
||||
// stays a real text block (not a JS slice) so wrapping/spacing match the
|
||||
// expanded view exactly.
|
||||
.chunk-body.collapsed .chunk-text {
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 3;
|
||||
-webkit-box-orient: vertical;
|
||||
overflow: hidden;
|
||||
position: relative;
|
||||
|
||||
&::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
inset: auto 0 0 0;
|
||||
height: 28px;
|
||||
background: linear-gradient(
|
||||
to bottom,
|
||||
transparent,
|
||||
var(--td-bg-color-container)
|
||||
);
|
||||
pointer-events: none;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,691 @@
|
||||
<template>
|
||||
<div class="kb-chunking-settings" :class="{ 'kb-chunking-settings--embedded': embedded }">
|
||||
<div v-if="!embedded" class="section-header">
|
||||
<div class="section-header-text">
|
||||
<h2>{{ $t('knowledgeEditor.chunking.title') }}</h2>
|
||||
<p class="section-description">{{ $t('knowledgeEditor.chunking.description') }}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="settings-group">
|
||||
<!-- Strategy -->
|
||||
<div class="setting-row">
|
||||
<div class="setting-info">
|
||||
<label>{{ $t('knowledgeEditor.chunking.strategyLabel') }}</label>
|
||||
<p class="desc">{{ $t('knowledgeEditor.chunking.strategyDescription') }}</p>
|
||||
</div>
|
||||
<div class="setting-control strategy-control">
|
||||
<t-select
|
||||
v-model="localStrategy"
|
||||
:options="strategyOptions"
|
||||
:placeholder="$t('knowledgeEditor.chunking.strategyPlaceholder')"
|
||||
:clearable="true"
|
||||
@change="handleStrategyChange"
|
||||
:style="selectStyle"
|
||||
/>
|
||||
<!-- Test trigger sits right next to the strategy picker so users
|
||||
discover it exactly when they're deciding which strategy to
|
||||
use on their content. -->
|
||||
<KBChunkingDebug v-if="!embedded" :config="debugConfig" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Strategy explanation panel -->
|
||||
<div v-if="currentStrategyInfo" class="strategy-info-panel">
|
||||
<t-icon name="info-circle" class="strategy-info-icon" />
|
||||
<p>
|
||||
<strong>{{ currentStrategyInfo.label }}:</strong>
|
||||
{{ currentStrategyInfo.tooltip }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<!-- Chunk Size -->
|
||||
<div class="setting-row">
|
||||
<div class="setting-info">
|
||||
<label>{{ $t('knowledgeEditor.chunking.sizeLabel') }}</label>
|
||||
<p class="desc">{{ $t('knowledgeEditor.chunking.sizeDescription') }}</p>
|
||||
</div>
|
||||
<div class="setting-control">
|
||||
<div class="slider-container">
|
||||
<t-slider
|
||||
v-model="localChunkSize"
|
||||
:min="100"
|
||||
:max="4000"
|
||||
:step="50"
|
||||
:marks="embedded ? undefined : chunkSizeMarks"
|
||||
@change="handleChunkSizeChange"
|
||||
:style="sliderStyle"
|
||||
/>
|
||||
<span class="value-display">{{ localChunkSize }} {{ $t('knowledgeEditor.chunking.characters') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Chunk Overlap -->
|
||||
<div class="setting-row">
|
||||
<div class="setting-info">
|
||||
<label>{{ $t('knowledgeEditor.chunking.overlapLabel') }}</label>
|
||||
<p class="desc">{{ $t('knowledgeEditor.chunking.overlapDescription') }}</p>
|
||||
<p v-if="overlapTooHigh" class="warn">{{ $t('knowledgeEditor.chunking.overlapWarning') }}</p>
|
||||
</div>
|
||||
<div class="setting-control">
|
||||
<div class="slider-container">
|
||||
<t-slider
|
||||
v-model="localChunkOverlap"
|
||||
:min="0"
|
||||
:max="500"
|
||||
:step="20"
|
||||
:marks="embedded ? undefined : chunkOverlapMarks"
|
||||
@change="handleChunkOverlapChange"
|
||||
:style="sliderStyle"
|
||||
/>
|
||||
<span class="value-display">{{ localChunkOverlap }} {{ $t('knowledgeEditor.chunking.characters') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Separators -->
|
||||
<div class="setting-row setting-row--separators">
|
||||
<div class="setting-info">
|
||||
<label>{{ $t('knowledgeEditor.chunking.separatorsLabel') }}</label>
|
||||
<p class="desc">{{ $t('knowledgeEditor.chunking.separatorsDescription') }}</p>
|
||||
</div>
|
||||
<div class="setting-control">
|
||||
<t-select
|
||||
v-model="localSeparators"
|
||||
:options="separatorOptions"
|
||||
multiple
|
||||
creatable
|
||||
filterable
|
||||
:placeholder="$t('knowledgeEditor.chunking.separatorsPlaceholder')"
|
||||
@change="handleSeparatorsChange"
|
||||
:style="selectStyle"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Parent-Child Chunking -->
|
||||
<div class="setting-row setting-row--toggle">
|
||||
<div class="setting-info">
|
||||
<label>{{ $t('knowledgeEditor.chunking.parentChildLabel') }}</label>
|
||||
<p class="desc">{{ $t('knowledgeEditor.chunking.parentChildDescription') }}</p>
|
||||
</div>
|
||||
<div class="setting-control">
|
||||
<t-switch
|
||||
v-model="localEnableParentChild"
|
||||
@change="handleParentChildChange"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Parent Chunk Size -->
|
||||
<div v-if="localEnableParentChild" class="setting-row">
|
||||
<div class="setting-info">
|
||||
<label>{{ $t('knowledgeEditor.chunking.parentChunkSizeLabel') }}</label>
|
||||
<p class="desc">{{ $t('knowledgeEditor.chunking.parentChunkSizeDescription') }}</p>
|
||||
</div>
|
||||
<div class="setting-control">
|
||||
<div class="slider-container">
|
||||
<t-slider
|
||||
v-model="localParentChunkSize"
|
||||
:min="512"
|
||||
:max="8192"
|
||||
:step="64"
|
||||
:marks="embedded ? undefined : parentChunkSizeMarks"
|
||||
@change="handleParentChunkSizeChange"
|
||||
:style="sliderStyle"
|
||||
/>
|
||||
<span class="value-display">{{ localParentChunkSize }} {{ $t('knowledgeEditor.chunking.characters') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Child Chunk Size -->
|
||||
<div v-if="localEnableParentChild" class="setting-row">
|
||||
<div class="setting-info">
|
||||
<label>{{ $t('knowledgeEditor.chunking.childChunkSizeLabel') }}</label>
|
||||
<p class="desc">{{ $t('knowledgeEditor.chunking.childChunkSizeDescription') }}</p>
|
||||
</div>
|
||||
<div class="setting-control">
|
||||
<div class="slider-container">
|
||||
<t-slider
|
||||
v-model="localChildChunkSize"
|
||||
:min="64"
|
||||
:max="2048"
|
||||
:step="32"
|
||||
:marks="embedded ? undefined : childChunkSizeMarks"
|
||||
@change="handleChildChunkSizeChange"
|
||||
:style="sliderStyle"
|
||||
/>
|
||||
<span class="value-display">{{ localChildChunkSize }} {{ $t('knowledgeEditor.chunking.characters') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Advanced section toggle -->
|
||||
<button type="button" class="advanced-toggle" @click="advancedOpen = !advancedOpen">
|
||||
<chevron-right-icon class="toggle-arrow" :class="{ open: advancedOpen }" />
|
||||
<span>{{ $t('knowledgeEditor.chunking.advancedLabel') }}</span>
|
||||
</button>
|
||||
|
||||
<div v-if="advancedOpen" class="advanced-section">
|
||||
<!-- Token Limit -->
|
||||
<div class="setting-row" :class="{ disabled: advancedDisabled }">
|
||||
<div class="setting-info">
|
||||
<label>{{ $t('knowledgeEditor.chunking.tokenLimitLabel') }}</label>
|
||||
<p class="desc">{{ $t('knowledgeEditor.chunking.tokenLimitDescription') }}</p>
|
||||
</div>
|
||||
<div class="setting-control">
|
||||
<t-input-number
|
||||
v-model="localTokenLimit"
|
||||
:min="0"
|
||||
:max="8192"
|
||||
:step="64"
|
||||
:disabled="advancedDisabled"
|
||||
@change="handleTokenLimitChange"
|
||||
style="width: 200px;"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Languages -->
|
||||
<div class="setting-row" :class="{ disabled: advancedDisabled }">
|
||||
<div class="setting-info">
|
||||
<label>{{ $t('knowledgeEditor.chunking.languagesLabel') }}</label>
|
||||
<p class="desc">{{ $t('knowledgeEditor.chunking.languagesDescription') }}</p>
|
||||
</div>
|
||||
<div class="setting-control">
|
||||
<t-select
|
||||
v-model="localLanguages"
|
||||
:options="languageOptions"
|
||||
multiple
|
||||
:disabled="advancedDisabled"
|
||||
:placeholder="$t('knowledgeEditor.chunking.languagesPlaceholder')"
|
||||
@change="handleLanguagesChange"
|
||||
:style="selectStyle"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, watch, computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { ChevronRightIcon } from 'tdesign-icons-vue-next'
|
||||
import KBChunkingDebug from './KBChunkingDebug.vue'
|
||||
|
||||
interface ParserEngineRule {
|
||||
file_types: string[]
|
||||
engine: string
|
||||
xlsx_first_row_as_header?: boolean
|
||||
}
|
||||
|
||||
// Slider ranges defined in this file (min/max props on t-slider) mirror
|
||||
// the validated bounds in the backend splitter:
|
||||
// ChunkSize: 100–4000 (default 512). 100 = too fragmented to be
|
||||
// useful; 4000 = approaches the 7500-char absoluteMaxSize
|
||||
// that the splitter hard-caps to anyway.
|
||||
// ChunkOverlap: 0–500 (default 80). Backend caps to ChunkSize/2
|
||||
// when set higher than that.
|
||||
// ParentChunkSize: 512–8192 (default 4096 ≈ 1000 EN tokens).
|
||||
// ChildChunkSize: 64–2048 (default 384 ≈ 80 EN tokens, sweet spot for
|
||||
// sentence-transformer / BGE embedders).
|
||||
// TokenLimit: 0–8192 (default 0 = off, char-based budget only).
|
||||
// Set to 200 for MiniLM (256-tok limit), 400 for BGE/
|
||||
// Cohere (512-tok), leave at 0 for OpenAI/Voyage/Jina-v3.
|
||||
interface ChunkingConfig {
|
||||
chunkSize: number
|
||||
chunkOverlap: number
|
||||
separators: string[]
|
||||
parserEngineRules?: ParserEngineRule[]
|
||||
enableParentChild: boolean
|
||||
parentChunkSize: number
|
||||
childChunkSize: number
|
||||
// Adaptive chunking strategy. Empty string = legacy / not set.
|
||||
strategy?: string
|
||||
// Cap chunk size in approx tokens. 0 = char-based budget only.
|
||||
tokenLimit?: number
|
||||
// Language hints for heuristic patterns (de/en/zh).
|
||||
languages?: string[]
|
||||
}
|
||||
|
||||
interface Props {
|
||||
config: ChunkingConfig
|
||||
embedded?: boolean
|
||||
}
|
||||
|
||||
const props = withDefaults(defineProps<Props>(), {
|
||||
embedded: false,
|
||||
})
|
||||
|
||||
const selectStyle = computed(() => (props.embedded ? { width: '100%' } : { width: '280px' }))
|
||||
const sliderStyle = computed(() => (props.embedded ? { width: '100%' } : { width: '200px' }))
|
||||
|
||||
const chunkSizeMarks = { 100: '100', 1000: '1000', 2000: '2000', 4000: '4000' }
|
||||
const chunkOverlapMarks = { 0: '0', 250: '250', 500: '500' }
|
||||
const parentChunkSizeMarks = { 512: '512', 2048: '2048', 4096: '4096', 8192: '8192' }
|
||||
const childChunkSizeMarks = { 64: '64', 384: '384', 1024: '1024', 2048: '2048' }
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:config': [value: ChunkingConfig]
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const localChunkSize = ref(props.config.chunkSize)
|
||||
const localChunkOverlap = ref(props.config.chunkOverlap)
|
||||
const localSeparators = ref([...props.config.separators])
|
||||
const localEnableParentChild = ref(props.config.enableParentChild ?? false)
|
||||
const localParentChunkSize = ref(props.config.parentChunkSize || 4096)
|
||||
const localChildChunkSize = ref(props.config.childChunkSize || 384)
|
||||
const localStrategy = ref(props.config.strategy ?? '')
|
||||
const localTokenLimit = ref(props.config.tokenLimit ?? 0)
|
||||
const localLanguages = ref<string[]>([...(props.config.languages ?? [])])
|
||||
const advancedOpen = ref(false)
|
||||
|
||||
const strategyOptions = computed(() => [
|
||||
{
|
||||
label: t('knowledgeEditor.chunking.strategies.auto.label'),
|
||||
value: 'auto',
|
||||
tooltip: t('knowledgeEditor.chunking.strategies.auto.tooltip')
|
||||
},
|
||||
{
|
||||
label: t('knowledgeEditor.chunking.strategies.heading.label'),
|
||||
value: 'heading',
|
||||
tooltip: t('knowledgeEditor.chunking.strategies.heading.tooltip')
|
||||
},
|
||||
{
|
||||
label: t('knowledgeEditor.chunking.strategies.heuristic.label'),
|
||||
value: 'heuristic',
|
||||
tooltip: t('knowledgeEditor.chunking.strategies.heuristic.tooltip')
|
||||
},
|
||||
{
|
||||
label: t('knowledgeEditor.chunking.strategies.legacy.label'),
|
||||
value: 'legacy',
|
||||
tooltip: t('knowledgeEditor.chunking.strategies.legacy.tooltip')
|
||||
}
|
||||
])
|
||||
|
||||
const currentStrategyInfo = computed(() => {
|
||||
if (!localStrategy.value) {
|
||||
return null
|
||||
}
|
||||
return strategyOptions.value.find(o => o.value === localStrategy.value) ?? null
|
||||
})
|
||||
|
||||
const advancedDisabled = computed(() => localStrategy.value === 'legacy')
|
||||
|
||||
const overlapTooHigh = computed(
|
||||
() => localChunkOverlap.value > 0 && localChunkOverlap.value >= localChunkSize.value / 2
|
||||
)
|
||||
|
||||
// Live config snapshot for the debug panel — uses current local form values
|
||||
// so the panel reflects edits immediately without waiting for save.
|
||||
const debugConfig = computed(() => ({
|
||||
chunkSize: localChunkSize.value,
|
||||
chunkOverlap: localChunkOverlap.value,
|
||||
separators: localSeparators.value,
|
||||
enableParentChild: localEnableParentChild.value,
|
||||
parentChunkSize: localParentChunkSize.value,
|
||||
childChunkSize: localChildChunkSize.value,
|
||||
strategy: localStrategy.value,
|
||||
tokenLimit: localTokenLimit.value,
|
||||
languages: localLanguages.value
|
||||
}))
|
||||
|
||||
const languageOptions = computed(() => [
|
||||
{ label: t('knowledgeEditor.chunking.languageOptions.de'), value: 'de' },
|
||||
{ label: t('knowledgeEditor.chunking.languageOptions.en'), value: 'en' },
|
||||
{ label: t('knowledgeEditor.chunking.languageOptions.zh'), value: 'zh' }
|
||||
])
|
||||
|
||||
const separatorOptions = computed(() => [
|
||||
{ label: t('knowledgeEditor.chunking.separators.doubleNewline'), value: '\n\n' },
|
||||
{ label: t('knowledgeEditor.chunking.separators.singleNewline'), value: '\n' },
|
||||
{ label: t('knowledgeEditor.chunking.separators.periodCn'), value: '。' },
|
||||
{ label: t('knowledgeEditor.chunking.separators.exclamationCn'), value: '!' },
|
||||
{ label: t('knowledgeEditor.chunking.separators.questionCn'), value: '?' },
|
||||
{ label: t('knowledgeEditor.chunking.separators.semicolonCn'), value: ';' },
|
||||
{ label: t('knowledgeEditor.chunking.separators.semicolonEn'), value: ';' },
|
||||
{ label: t('knowledgeEditor.chunking.separators.space'), value: ' ' }
|
||||
])
|
||||
|
||||
watch(() => props.config, (newConfig) => {
|
||||
localChunkSize.value = newConfig.chunkSize
|
||||
localChunkOverlap.value = newConfig.chunkOverlap
|
||||
localSeparators.value = [...newConfig.separators]
|
||||
localEnableParentChild.value = newConfig.enableParentChild ?? false
|
||||
localParentChunkSize.value = newConfig.parentChunkSize || 4096
|
||||
localChildChunkSize.value = newConfig.childChunkSize || 384
|
||||
localStrategy.value = newConfig.strategy ?? ''
|
||||
localTokenLimit.value = newConfig.tokenLimit ?? 0
|
||||
localLanguages.value = [...(newConfig.languages ?? [])]
|
||||
}, { deep: true })
|
||||
|
||||
const handleChunkSizeChange = () => { emitUpdate() }
|
||||
const handleChunkOverlapChange = () => { emitUpdate() }
|
||||
const handleSeparatorsChange = () => { emitUpdate() }
|
||||
const handleParentChildChange = () => { emitUpdate() }
|
||||
const handleParentChunkSizeChange = () => { emitUpdate() }
|
||||
const handleChildChunkSizeChange = () => { emitUpdate() }
|
||||
const handleStrategyChange = () => { emitUpdate() }
|
||||
const handleTokenLimitChange = () => { emitUpdate() }
|
||||
const handleLanguagesChange = () => { emitUpdate() }
|
||||
|
||||
const emitUpdate = () => {
|
||||
// Spread arrays so the parent gets its own copy. Mutating the emitted
|
||||
// arrays from outside must not leak back into our reactive state and
|
||||
// cause two-way ref drift between the form and the editor model.
|
||||
emit('update:config', {
|
||||
chunkSize: localChunkSize.value,
|
||||
chunkOverlap: localChunkOverlap.value,
|
||||
separators: [...localSeparators.value],
|
||||
parserEngineRules: props.config.parserEngineRules,
|
||||
enableParentChild: localEnableParentChild.value,
|
||||
parentChunkSize: localParentChunkSize.value,
|
||||
childChunkSize: localChildChunkSize.value,
|
||||
strategy: localStrategy.value,
|
||||
tokenLimit: localTokenLimit.value,
|
||||
languages: [...localLanguages.value]
|
||||
})
|
||||
}
|
||||
</script>
|
||||
|
||||
<style lang="less" scoped>
|
||||
.kb-chunking-settings {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.section-header {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
// Stick to the top of the scrollable section so the section title remains
|
||||
// visible while the user scrolls through a long form. Negative top and
|
||||
// matching negative margins compensate for content-wrapper's padding
|
||||
// (24px 32px) so the sticky band visually spans the full width when stuck.
|
||||
position: sticky;
|
||||
top: -24px;
|
||||
z-index: 5;
|
||||
background: var(--td-bg-color-container);
|
||||
padding: 24px 32px 12px 32px;
|
||||
margin: -24px -32px 16px -32px;
|
||||
border-bottom: 1px solid var(--td-component-stroke);
|
||||
|
||||
.section-header-text {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
h2 {
|
||||
font-size: var(--app-text-3xl);
|
||||
font-weight: 600;
|
||||
color: var(--td-text-color-primary);
|
||||
margin: 0 0 6px 0;
|
||||
}
|
||||
|
||||
.section-description {
|
||||
font-size: var(--app-text-base);
|
||||
color: var(--td-text-color-secondary);
|
||||
margin: 0;
|
||||
line-height: 1.5;
|
||||
}
|
||||
}
|
||||
|
||||
.settings-group {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0;
|
||||
}
|
||||
|
||||
.setting-row {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
padding: 16px 0;
|
||||
border-bottom: 1px solid var(--td-component-stroke);
|
||||
|
||||
&:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
&.disabled {
|
||||
opacity: 0.5;
|
||||
}
|
||||
}
|
||||
|
||||
.strategy-info-panel {
|
||||
margin: 0 0 16px 0;
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 8px;
|
||||
padding: 10px 14px;
|
||||
background: var(--td-bg-color-secondarycontainer);
|
||||
border-radius: var(--app-radius-md);
|
||||
font-size: var(--app-text-md);
|
||||
color: var(--td-text-color-secondary);
|
||||
line-height: 1.5;
|
||||
|
||||
.strategy-info-icon {
|
||||
flex-shrink: 0;
|
||||
margin-top: 3px;
|
||||
font-size: var(--app-text-base);
|
||||
color: var(--td-brand-color);
|
||||
}
|
||||
|
||||
p {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
margin: 0;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
strong {
|
||||
color: var(--td-text-color-primary);
|
||||
}
|
||||
}
|
||||
|
||||
.setting-info {
|
||||
flex: 0 0 40%;
|
||||
max-width: 40%;
|
||||
padding-right: 24px;
|
||||
|
||||
label {
|
||||
font-size: var(--app-text-lg);
|
||||
font-weight: 500;
|
||||
color: var(--td-text-color-primary);
|
||||
display: block;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.desc {
|
||||
font-size: var(--app-text-md);
|
||||
color: var(--td-text-color-secondary);
|
||||
margin: 0;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.warn {
|
||||
font-size: var(--app-text-sm);
|
||||
color: var(--td-warning-color);
|
||||
margin: 4px 0 0 0;
|
||||
line-height: 1.4;
|
||||
}
|
||||
}
|
||||
|
||||
.setting-control {
|
||||
flex: 0 0 55%;
|
||||
max-width: 55%;
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
// Strategy row stacks the picker above the test trigger so the action has
|
||||
// room to breathe without competing with the select for horizontal space.
|
||||
// Both children stay right-aligned under the section's right column.
|
||||
.strategy-control {
|
||||
flex-direction: column;
|
||||
align-items: flex-end;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.slider-container {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
width: 100%;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.value-display {
|
||||
font-size: var(--app-text-base);
|
||||
color: var(--td-text-color-primary);
|
||||
font-weight: 500;
|
||||
min-width: 80px;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.advanced-toggle {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 16px 0 8px 0;
|
||||
margin: 0;
|
||||
background: transparent;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
font-size: var(--app-text-base);
|
||||
font-weight: 500;
|
||||
color: var(--td-text-color-secondary);
|
||||
user-select: none;
|
||||
|
||||
&:hover {
|
||||
color: var(--td-text-color-primary);
|
||||
}
|
||||
|
||||
&:focus-visible {
|
||||
outline: 2px solid var(--td-brand-color-focus);
|
||||
outline-offset: 2px;
|
||||
border-radius: var(--app-radius-xs);
|
||||
}
|
||||
}
|
||||
|
||||
.toggle-arrow {
|
||||
font-size: var(--app-text-xl);
|
||||
transition: transform var(--app-motion-fast) ease;
|
||||
|
||||
&.open {
|
||||
transform: rotate(90deg);
|
||||
}
|
||||
}
|
||||
|
||||
.advanced-section {
|
||||
// Visually grouped via the toggle above; avoid a left rule that hugs the
|
||||
// panel edge and looks detached from the rest of the form.
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
.kb-chunking-settings--embedded {
|
||||
.setting-row {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
gap: 10px;
|
||||
padding: 14px 0;
|
||||
}
|
||||
|
||||
.setting-row--toggle {
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
|
||||
.setting-info {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.setting-control {
|
||||
flex: none;
|
||||
width: auto;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
}
|
||||
|
||||
.setting-row--separators {
|
||||
padding-bottom: 18px;
|
||||
}
|
||||
|
||||
.setting-info {
|
||||
flex: none;
|
||||
max-width: none;
|
||||
padding-right: 0;
|
||||
|
||||
label {
|
||||
font-size: var(--app-text-base);
|
||||
}
|
||||
|
||||
.desc {
|
||||
font-size: var(--app-text-sm);
|
||||
}
|
||||
}
|
||||
|
||||
.setting-control {
|
||||
flex: none;
|
||||
max-width: none;
|
||||
justify-content: flex-start;
|
||||
align-items: stretch;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.strategy-control {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.strategy-info-panel {
|
||||
margin: -4px 0 10px;
|
||||
padding: 8px 12px;
|
||||
font-size: var(--app-text-sm);
|
||||
}
|
||||
|
||||
.slider-container {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
gap: 8px;
|
||||
width: 100%;
|
||||
justify-content: flex-start;
|
||||
}
|
||||
|
||||
.value-display {
|
||||
order: -1;
|
||||
text-align: left;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
:deep(.t-slider) {
|
||||
padding-bottom: 0;
|
||||
}
|
||||
|
||||
:deep(.t-select__wrap) {
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
:deep(.t-tag) {
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
.advanced-toggle {
|
||||
padding-top: 10px;
|
||||
}
|
||||
|
||||
.advanced-section .setting-row {
|
||||
padding: 14px 0;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,248 @@
|
||||
<template>
|
||||
<div class="kb-model-config">
|
||||
<div class="section-header">
|
||||
<h2>{{ $t('knowledgeEditor.models.title') }}</h2>
|
||||
<p class="section-description">{{ $t('knowledgeEditor.models.description') }}</p>
|
||||
</div>
|
||||
|
||||
<div class="settings-group">
|
||||
<!-- LLM 大语言模型 -->
|
||||
<div class="setting-row" data-guide="kb-create-llm">
|
||||
<div class="setting-info">
|
||||
<label>{{ $t('knowledgeEditor.models.llmLabel') }} <span class="required">*</span></label>
|
||||
<p class="desc">{{ $t('knowledgeEditor.models.llmDesc') }}</p>
|
||||
</div>
|
||||
<div class="setting-control">
|
||||
<ModelSelector
|
||||
ref="llmSelectorRef"
|
||||
model-type="KnowledgeQA"
|
||||
:selected-model-id="config.llmModelId"
|
||||
:all-models="allModels"
|
||||
@update:selected-model-id="handleLLMChange"
|
||||
@add-model="handleAddModel('chat')"
|
||||
:placeholder="$t('knowledgeEditor.models.llmPlaceholder')"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Embedding 嵌入模型: RAG 检索启用时必填; 纯 Wiki 时可选(用于目录归类相似度) -->
|
||||
<div v-if="ragEnabled !== false || wikiEnabled" class="setting-row" data-guide="kb-create-embedding">
|
||||
<div class="setting-info">
|
||||
<label>
|
||||
{{ $t('knowledgeEditor.models.embeddingLabel') }}
|
||||
<span v-if="ragEnabled" class="required">*</span>
|
||||
<span v-else-if="wikiEnabled" class="optional">{{ $t('knowledgeEditor.models.embeddingOptional') }}</span>
|
||||
</label>
|
||||
<p class="desc">
|
||||
{{ (wikiEnabled && ragEnabled === false)
|
||||
? $t('knowledgeEditor.models.embeddingWikiOptionalDesc')
|
||||
: $t('knowledgeEditor.models.embeddingDesc') }}
|
||||
</p>
|
||||
</div>
|
||||
<div class="setting-control setting-control--stacked">
|
||||
<ModelSelector
|
||||
ref="embeddingSelectorRef"
|
||||
model-type="Embedding"
|
||||
:selected-model-id="config.embeddingModelId"
|
||||
:all-models="allModels"
|
||||
:disabled="ragEnabled && hasFiles"
|
||||
:clearable="ragEnabled === false && wikiEnabled"
|
||||
@update:selected-model-id="handleEmbeddingChange"
|
||||
@add-model="handleAddModel('embedding')"
|
||||
:placeholder="$t('knowledgeEditor.models.embeddingPlaceholder')"
|
||||
/>
|
||||
<p v-if="ragEnabled && hasFiles" class="locked-hint">
|
||||
<t-icon name="lock-on" class="locked-hint-icon" />
|
||||
<span>{{ $t('knowledgeEditor.models.embeddingLocked') }}</span>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Wiki 合成模型 (仅当 Wiki 启用时显示) -->
|
||||
<div v-if="wikiEnabled" class="setting-row">
|
||||
<div class="setting-info">
|
||||
<label>{{ $t('knowledgeEditor.wiki.synthesisModelLabel') }}</label>
|
||||
<p class="desc">{{ $t('knowledgeEditor.wiki.synthesisModelTip') }}</p>
|
||||
</div>
|
||||
<div class="setting-control">
|
||||
<ModelSelector
|
||||
model-type="KnowledgeQA"
|
||||
:selected-model-id="config.wikiSynthesisModelId"
|
||||
:all-models="allModels"
|
||||
clearable
|
||||
@update:selected-model-id="handleWikiModelChange"
|
||||
@add-model="handleAddModel('knowledgeqa')"
|
||||
:placeholder="$t('knowledgeEditor.wiki.synthesisModelPlaceholder')"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
import { useUIStore } from '@/stores/ui'
|
||||
import ModelSelector from '@/components/ModelSelector.vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
interface ModelConfig {
|
||||
llmModelId?: string
|
||||
embeddingModelId?: string
|
||||
vllmModelId?: string
|
||||
wikiSynthesisModelId?: string
|
||||
}
|
||||
|
||||
interface Props {
|
||||
config: ModelConfig
|
||||
hasFiles: boolean
|
||||
wikiEnabled?: boolean
|
||||
ragEnabled?: boolean
|
||||
allModels?: any[]
|
||||
}
|
||||
|
||||
const props = defineProps<Props>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:config': [value: ModelConfig]
|
||||
}>()
|
||||
|
||||
const uiStore = useUIStore()
|
||||
const { t } = useI18n()
|
||||
|
||||
const llmSelectorRef = ref<InstanceType<typeof ModelSelector>>()
|
||||
const embeddingSelectorRef = ref<InstanceType<typeof ModelSelector>>()
|
||||
|
||||
const handleLLMChange = (modelId: string) => {
|
||||
emit('update:config', {
|
||||
...props.config,
|
||||
llmModelId: modelId
|
||||
})
|
||||
}
|
||||
|
||||
const handleEmbeddingChange = (modelId: string) => {
|
||||
emit('update:config', {
|
||||
...props.config,
|
||||
embeddingModelId: modelId
|
||||
})
|
||||
}
|
||||
|
||||
const handleWikiModelChange = (modelId: string) => {
|
||||
emit('update:config', {
|
||||
...props.config,
|
||||
wikiSynthesisModelId: modelId
|
||||
})
|
||||
}
|
||||
|
||||
const handleAddModel = (subSection: string) => {
|
||||
uiStore.openSettings('models', subSection)
|
||||
}
|
||||
</script>
|
||||
|
||||
<style lang="less" scoped>
|
||||
.kb-model-config {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.section-header {
|
||||
margin-bottom: 20px;
|
||||
|
||||
h2 {
|
||||
font-size: var(--app-text-3xl);
|
||||
font-weight: 600;
|
||||
color: var(--td-text-color-primary);
|
||||
margin: 0 0 6px 0;
|
||||
}
|
||||
|
||||
.section-description {
|
||||
font-size: var(--app-text-base);
|
||||
color: var(--td-text-color-secondary);
|
||||
margin: 0;
|
||||
line-height: 1.5;
|
||||
}
|
||||
}
|
||||
|
||||
.settings-group {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0;
|
||||
}
|
||||
|
||||
.setting-row {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
padding: 16px 0;
|
||||
border-bottom: 1px solid var(--td-component-stroke);
|
||||
|
||||
&:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
}
|
||||
|
||||
.setting-info {
|
||||
flex: 0 0 40%;
|
||||
max-width: 40%;
|
||||
padding-right: 24px;
|
||||
|
||||
label {
|
||||
font-size: var(--app-text-lg);
|
||||
font-weight: 500;
|
||||
color: var(--td-text-color-primary);
|
||||
display: block;
|
||||
margin-bottom: 4px;
|
||||
|
||||
.required {
|
||||
color: var(--td-error-color);
|
||||
margin-left: 2px;
|
||||
}
|
||||
|
||||
.optional {
|
||||
color: var(--td-text-color-placeholder);
|
||||
font-size: var(--app-text-sm);
|
||||
font-weight: 400;
|
||||
margin-left: 4px;
|
||||
}
|
||||
}
|
||||
|
||||
.desc {
|
||||
font-size: var(--app-text-md);
|
||||
color: var(--td-text-color-secondary);
|
||||
margin: 0;
|
||||
line-height: 1.5;
|
||||
}
|
||||
}
|
||||
|
||||
.setting-control {
|
||||
flex: 0 0 55%;
|
||||
max-width: 55%;
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
align-items: flex-start;
|
||||
|
||||
&--stacked {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
gap: 6px;
|
||||
}
|
||||
}
|
||||
|
||||
.locked-hint {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 6px;
|
||||
margin: 0;
|
||||
font-size: var(--app-text-sm);
|
||||
line-height: 18px;
|
||||
color: var(--td-text-color-secondary);
|
||||
|
||||
.locked-hint-icon {
|
||||
flex-shrink: 0;
|
||||
margin-top: 2px;
|
||||
font-size: var(--app-text-base);
|
||||
color: var(--td-text-color-placeholder);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -0,0 +1,581 @@
|
||||
<template>
|
||||
<div class="kb-parser-settings" :class="{ 'kb-parser-settings--embedded': embedded }">
|
||||
<div v-if="!embedded" class="section-header">
|
||||
<h2>{{ $t('kbSettings.parser.title') }}</h2>
|
||||
<p class="section-description">{{ $t('kbSettings.parser.description') }}</p>
|
||||
</div>
|
||||
|
||||
<div v-if="loading" class="loading-inline">
|
||||
<t-loading size="small" />
|
||||
<span>{{ $t('kbSettings.parser.loading') }}</span>
|
||||
</div>
|
||||
|
||||
<div v-else-if="fileTypeGroups.length === 0" class="empty-hint">
|
||||
<p>{{ $t('kbSettings.parser.noEngineAvailable') }}</p>
|
||||
</div>
|
||||
|
||||
<div v-else class="settings-group" :class="{ 'settings-group--embedded': embedded }">
|
||||
<div
|
||||
v-for="group in fileTypeGroups"
|
||||
:key="group.key"
|
||||
class="setting-row"
|
||||
>
|
||||
<div class="setting-info">
|
||||
<label class="group-label">
|
||||
<t-icon v-if="!embedded" :name="group.icon" class="group-icon" />
|
||||
{{ group.label }}
|
||||
</label>
|
||||
<div class="ext-tags">
|
||||
<span v-for="ext in group.extensions" :key="ext" class="ext-tag">.{{ ext }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="setting-control">
|
||||
<div class="parser-control-stack">
|
||||
<t-select
|
||||
:value="getEngineForGroup(group.extensions) || undefined"
|
||||
@change="(val: string) => handleEngineChange(group.extensions, val)"
|
||||
:style="embedded ? undefined : { width: '280px' }"
|
||||
:class="{ 'parser-engine-select--embedded': embedded }"
|
||||
:status="hasAvailableEngine(group.extensions) ? 'default' : 'warning'"
|
||||
:placeholder="$t('kbSettings.parser.noEngine')"
|
||||
:popup-props="{ overlayInnerStyle: { maxHeight: '240px' } }"
|
||||
>
|
||||
<t-option
|
||||
v-for="opt in getEngineOptions(group.extensions)"
|
||||
:key="opt.value"
|
||||
:value="opt.value"
|
||||
:label="opt.selectLabel"
|
||||
/>
|
||||
</t-select>
|
||||
<t-checkbox
|
||||
v-if="group.extensions.includes('xlsx') && getEngineForGroup(group.extensions) === 'builtin'"
|
||||
class="xlsx-header-option"
|
||||
:checked="getXLSXFirstRowAsHeader(group.extensions)"
|
||||
@change="(checked: boolean) => handleXLSXFirstRowAsHeaderChange(group.extensions, checked)"
|
||||
>
|
||||
{{ $t('kbSettings.parser.xlsxFirstRowAsHeader') }}
|
||||
</t-checkbox>
|
||||
<div v-if="!hasAvailableEngine(group.extensions)" class="no-engine-warning">
|
||||
<a class="go-settings" @click.prevent="goToParserSettings">{{ $t('kbSettings.parser.goConfig') }}</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, watch, computed, onMounted, onUnmounted } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { type ParserEngineInfo } from '@/api/system'
|
||||
import { useEditorResourcesStore } from '@/stores/editorResources'
|
||||
import { useUIStore } from '@/stores/ui'
|
||||
import { storeToRefs } from 'pinia'
|
||||
|
||||
const { t } = useI18n()
|
||||
const editorResources = useEditorResourcesStore()
|
||||
|
||||
function getEngineDisplayName(engineName: string): string {
|
||||
const key = `kbSettings.parser.engines.${engineName}.name`
|
||||
const translated = t(key)
|
||||
return translated !== key ? translated : engineName
|
||||
}
|
||||
|
||||
export interface ParserEngineRule {
|
||||
file_types: string[]
|
||||
engine: string
|
||||
xlsx_first_row_as_header?: boolean
|
||||
}
|
||||
|
||||
interface EngineOption {
|
||||
value: string
|
||||
selectLabel: string
|
||||
isDefault: boolean
|
||||
}
|
||||
|
||||
function buildOptionLabel(name: string, isDefault: boolean): string {
|
||||
const label = getEngineDisplayName(name)
|
||||
return isDefault ? `${label} (${t('kbSettings.parser.default')})` : label
|
||||
}
|
||||
|
||||
interface Props {
|
||||
parserEngineRules?: ParserEngineRule[]
|
||||
/** Compact layout for upload-confirm dialog */
|
||||
embedded?: boolean
|
||||
/** When set, only show file-type groups matching these extensions */
|
||||
relevantExtensions?: string[]
|
||||
}
|
||||
|
||||
const props = withDefaults(defineProps<Props>(), {
|
||||
parserEngineRules: () => [],
|
||||
embedded: false,
|
||||
relevantExtensions: () => [],
|
||||
})
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:parserEngineRules': [value: ParserEngineRule[]]
|
||||
}>()
|
||||
|
||||
const uiStore = useUIStore()
|
||||
const localEngineRules = ref<ParserEngineRule[]>([...props.parserEngineRules])
|
||||
const parserEngines = ref<ParserEngineInfo[]>([])
|
||||
const loading = ref(true)
|
||||
|
||||
const allFileTypes = computed(() => {
|
||||
const s = new Set<string>()
|
||||
for (const engine of parserEngines.value) {
|
||||
for (const ft of engine.FileTypes || []) {
|
||||
s.add(ft)
|
||||
}
|
||||
}
|
||||
return s
|
||||
})
|
||||
|
||||
const fileTypeGroups = computed(() => {
|
||||
const ft = allFileTypes.value
|
||||
const groups: { key: string; label: string; icon: string; extensions: string[] }[] = []
|
||||
|
||||
const pdfExts = ['pdf'].filter(e => ft.has(e))
|
||||
const officeExts = ['docx', 'doc'].filter(e => ft.has(e))
|
||||
const pptExts = ['pptx', 'ppt'].filter(e => ft.has(e))
|
||||
const excelExts = ['xlsx', 'xls'].filter(e => ft.has(e))
|
||||
const ebookExts = ['epub'].filter(e => ft.has(e))
|
||||
const webArchiveExts = ['mhtml'].filter(e => ft.has(e))
|
||||
const csvExts = ['csv'].filter(e => ft.has(e))
|
||||
const mdExts = ['md', 'markdown'].filter(e => ft.has(e))
|
||||
const txtExts = ['txt'].filter(e => ft.has(e))
|
||||
const jsonExts = ['json'].filter(e => ft.has(e))
|
||||
const imageExts = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'tiff', 'webp'].filter(e => ft.has(e))
|
||||
const audioExts = ['mp3', 'wav', 'm4a', 'flac', 'ogg'].filter(e => ft.has(e))
|
||||
const audiovisualExts = [...audioExts]
|
||||
|
||||
if (pdfExts.length) groups.push({ key: 'pdf', label: t('kbSettings.parser.fileTypePdf'), icon: 'file-pdf', extensions: pdfExts })
|
||||
if (officeExts.length) groups.push({ key: 'office', label: t('kbSettings.parser.fileTypeWord'), icon: 'file-word', extensions: officeExts })
|
||||
if (pptExts.length) groups.push({ key: 'ppt', label: t('kbSettings.parser.fileTypePpt'), icon: 'file-powerpoint', extensions: pptExts })
|
||||
if (excelExts.length) groups.push({ key: 'excel', label: t('kbSettings.parser.fileTypeExcel'), icon: 'file-excel', extensions: excelExts })
|
||||
if (ebookExts.length) groups.push({ key: 'ebook', label: t('kbSettings.parser.fileTypeEbook'), icon: 'file', extensions: ebookExts })
|
||||
if (webArchiveExts.length) groups.push({ key: 'webarchive', label: t('kbSettings.parser.fileTypeWebArchive'), icon: 'file', extensions: webArchiveExts })
|
||||
if (csvExts.length) groups.push({ key: 'csv', label: t('kbSettings.parser.fileTypeCsv'), icon: 'file-excel', extensions: csvExts })
|
||||
if (mdExts.length) groups.push({ key: 'markdown', label: 'Markdown', icon: 'file-code', extensions: mdExts })
|
||||
if (txtExts.length) groups.push({ key: 'text', label: t('kbSettings.parser.fileTypeText'), icon: 'file', extensions: txtExts })
|
||||
if (jsonExts.length) groups.push({ key: 'json', label: t('kbSettings.parser.fileTypeJson'), icon: 'file-code', extensions: jsonExts })
|
||||
if (imageExts.length) groups.push({ key: 'image', label: t('kbSettings.parser.fileTypeImage'), icon: 'image', extensions: imageExts })
|
||||
if (audiovisualExts.length) {
|
||||
groups.push({
|
||||
key: 'audiovisual',
|
||||
label: t('kbSettings.parser.fileTypeAudiovisual'),
|
||||
icon: 'sound',
|
||||
extensions: audiovisualExts,
|
||||
})
|
||||
}
|
||||
|
||||
// Keep the UI driven by the backend registry. New parser plugins can expose
|
||||
// file types without requiring another frontend release; known families get
|
||||
// friendly labels above and everything else gets a compact dynamic row.
|
||||
const grouped = new Set(groups.flatMap(group => group.extensions))
|
||||
for (const ext of [...ft].filter(ext => !grouped.has(ext) && ext !== 'url').sort()) {
|
||||
groups.push({ key: `dynamic-${ext}`, label: ext.toUpperCase(), icon: 'file-code', extensions: [ext] })
|
||||
}
|
||||
|
||||
const rel = props.relevantExtensions
|
||||
if (!rel?.length) return groups
|
||||
const relSet = new Set(rel)
|
||||
const filtered = groups.filter(g => g.extensions.some(e => relSet.has(e)))
|
||||
return filtered.length > 0 ? filtered : groups
|
||||
})
|
||||
|
||||
function getEngineOptions(extensions: string[]): EngineOption[] {
|
||||
const raw: { name: string; desc: string; fileTypes: string[]; available: boolean; reason: string }[] = []
|
||||
for (const engine of parserEngines.value) {
|
||||
const supports = extensions.some(ext => (engine.FileTypes || []).includes(ext))
|
||||
if (supports) {
|
||||
raw.push({
|
||||
name: engine.Name,
|
||||
desc: engine.Description || engine.Name,
|
||||
fileTypes: engine.FileTypes || [],
|
||||
available: engine.Available !== false,
|
||||
reason: engine.UnavailableReason || '',
|
||||
})
|
||||
}
|
||||
}
|
||||
const defaultName = pickDefaultEngineName(raw, extensions)
|
||||
return raw
|
||||
.filter(e => e.available)
|
||||
.map(e => ({
|
||||
value: e.name,
|
||||
selectLabel: buildOptionLabel(e.name, defaultName !== '' && e.name === defaultName),
|
||||
isDefault: defaultName !== '' && e.name === defaultName,
|
||||
}))
|
||||
}
|
||||
|
||||
// The "(default)" badge has to name the engine ingestion will actually pick, so
|
||||
// it is computed from the backend routing rather than from availability order:
|
||||
// preferAnydocWhenAvailable in internal/infrastructure/docparser/engines.go
|
||||
// simpleFormats in internal/infrastructure/docparser/builtin_converter.go
|
||||
// defaultParserEngineByType in internal/types/knowledgebase.go
|
||||
// DefaultParserEngine returns "" when nothing is pinned for a type, which sends
|
||||
// simple formats to the Go reader and everything else to docreader builtin.
|
||||
const simpleFileTypes = new Set([
|
||||
'md', 'markdown', 'txt', 'text', 'csv', 'json',
|
||||
'jpg', 'jpeg', 'png', 'gif', 'bmp', 'tiff', 'webp',
|
||||
'mp3', 'wav', 'm4a', 'flac', 'ogg',
|
||||
])
|
||||
|
||||
// anydoc has no document model for PDF, so the backend never defaults to it.
|
||||
const noAnydocFileTypes = new Set(['pdf'])
|
||||
|
||||
const pinnedEngineByFileType: Record<string, string> = {
|
||||
ppt: 'markitdown',
|
||||
pptx: 'markitdown',
|
||||
}
|
||||
|
||||
function defaultEngineForFileType(
|
||||
engines: { name: string; available: boolean; fileTypes: string[] }[],
|
||||
ext: string,
|
||||
): string {
|
||||
const usable = (name: string) =>
|
||||
engines.some(e => e.available && e.name === name && e.fileTypes.includes(ext))
|
||||
if (!simpleFileTypes.has(ext) && !noAnydocFileTypes.has(ext) && usable('anydoc')) {
|
||||
return 'anydoc'
|
||||
}
|
||||
const pinned = pinnedEngineByFileType[ext]
|
||||
if (pinned && usable(pinned)) return pinned
|
||||
const unpinned = simpleFileTypes.has(ext) ? 'simple' : 'builtin'
|
||||
return usable(unpinned) ? unpinned : ''
|
||||
}
|
||||
|
||||
function pickDefaultEngineName(
|
||||
engines: { name: string; available: boolean; fileTypes: string[] }[],
|
||||
extensions: string[],
|
||||
): string {
|
||||
const perFileType = extensions.map(ext => defaultEngineForFileType(engines, ext))
|
||||
const first = perFileType[0] ?? ''
|
||||
// One dropdown serves the whole group, so only badge a default when every
|
||||
// member of the group routes to the same engine.
|
||||
return perFileType.every(name => name === first) ? first : ''
|
||||
}
|
||||
|
||||
function hasAvailableEngine(extensions: string[]): boolean {
|
||||
return getEngineOptions(extensions).length > 0
|
||||
}
|
||||
|
||||
function getDefaultEngine(extensions: string[]): string {
|
||||
const opts = getEngineOptions(extensions)
|
||||
return opts.find(o => o.isDefault)?.value ?? ''
|
||||
}
|
||||
|
||||
function getEngineForGroup(extensions: string[]): string {
|
||||
for (const rule of localEngineRules.value) {
|
||||
if (rule.file_types.some(ft => extensions.includes(ft))) {
|
||||
return rule.engine
|
||||
}
|
||||
}
|
||||
return getDefaultEngine(extensions)
|
||||
}
|
||||
|
||||
function handleEngineChange(extensions: string[], engine: string) {
|
||||
const currentRule = getRuleForGroup(extensions)
|
||||
const otherRules = localEngineRules.value.filter(
|
||||
r => !r.file_types.some(ft => extensions.includes(ft))
|
||||
)
|
||||
if (engine) {
|
||||
otherRules.push({
|
||||
file_types: [...extensions],
|
||||
engine,
|
||||
...(currentRule?.xlsx_first_row_as_header !== undefined
|
||||
? { xlsx_first_row_as_header: currentRule.xlsx_first_row_as_header }
|
||||
: {}),
|
||||
})
|
||||
}
|
||||
localEngineRules.value = otherRules
|
||||
emit('update:parserEngineRules', buildCompleteRules())
|
||||
}
|
||||
|
||||
function getRuleForGroup(extensions: string[]): ParserEngineRule | undefined {
|
||||
return localEngineRules.value.find(
|
||||
rule => rule.file_types.some(fileType => extensions.includes(fileType))
|
||||
)
|
||||
}
|
||||
|
||||
function getXLSXFirstRowAsHeader(extensions: string[]): boolean {
|
||||
return getRuleForGroup(extensions)?.xlsx_first_row_as_header === true
|
||||
}
|
||||
|
||||
function handleXLSXFirstRowAsHeaderChange(extensions: string[], checked: boolean) {
|
||||
const rules = buildCompleteRules()
|
||||
const rule = rules.find(item => item.file_types.some(fileType => extensions.includes(fileType)))
|
||||
if (!rule) return
|
||||
|
||||
rule.xlsx_first_row_as_header = checked
|
||||
localEngineRules.value = rules
|
||||
emit('update:parserEngineRules', rules)
|
||||
}
|
||||
|
||||
function buildCompleteRules(): ParserEngineRule[] {
|
||||
const rules: ParserEngineRule[] = []
|
||||
for (const group of fileTypeGroups.value) {
|
||||
const engine = getEngineForGroup(group.extensions)
|
||||
if (engine) {
|
||||
const currentRule = getRuleForGroup(group.extensions)
|
||||
rules.push({
|
||||
file_types: [...group.extensions],
|
||||
engine,
|
||||
...(currentRule?.xlsx_first_row_as_header !== undefined
|
||||
? { xlsx_first_row_as_header: currentRule.xlsx_first_row_as_header }
|
||||
: {}),
|
||||
})
|
||||
}
|
||||
}
|
||||
return rules
|
||||
}
|
||||
|
||||
function goToParserSettings() {
|
||||
uiStore.openSettings('parser')
|
||||
}
|
||||
|
||||
async function loadEngines(force = false) {
|
||||
loading.value = true
|
||||
try {
|
||||
await editorResources.ensureParserEngines(force)
|
||||
parserEngines.value = editorResources.parserEngines as ParserEngineInfo[]
|
||||
} catch {
|
||||
parserEngines.value = []
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// Missing rules display getDefaultEngine() without turning a read-only visit
|
||||
// into a form edit. Only explicit user changes emit the completed rules.
|
||||
onMounted(loadEngines)
|
||||
|
||||
const { showSettingsModal } = storeToRefs(uiStore)
|
||||
watch(showSettingsModal, (open, wasOpen) => {
|
||||
if (wasOpen && !open) {
|
||||
loadEngines(true)
|
||||
}
|
||||
})
|
||||
|
||||
watch(() => props.parserEngineRules, (v) => {
|
||||
localEngineRules.value = v?.length ? [...v] : []
|
||||
}, { deep: true })
|
||||
</script>
|
||||
|
||||
<style lang="less" scoped>
|
||||
.kb-parser-settings {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.section-header {
|
||||
margin-bottom: 20px;
|
||||
|
||||
h2 {
|
||||
font-size: var(--app-text-3xl);
|
||||
font-weight: 600;
|
||||
color: var(--td-text-color-primary);
|
||||
margin: 0 0 6px 0;
|
||||
}
|
||||
|
||||
.section-description {
|
||||
font-size: var(--app-text-base);
|
||||
color: var(--td-text-color-secondary);
|
||||
margin: 0;
|
||||
line-height: 1.5;
|
||||
}
|
||||
}
|
||||
|
||||
.loading-inline {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 16px 0;
|
||||
}
|
||||
|
||||
.empty-hint {
|
||||
padding: 24px 0;
|
||||
color: var(--td-text-color-secondary);
|
||||
}
|
||||
|
||||
.settings-group {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0;
|
||||
}
|
||||
|
||||
.setting-row {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
padding: 16px 0;
|
||||
border-bottom: 1px solid var(--td-component-stroke);
|
||||
|
||||
&:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
}
|
||||
|
||||
.setting-info {
|
||||
flex: 0 0 40%;
|
||||
max-width: 40%;
|
||||
padding-right: 24px;
|
||||
|
||||
.group-label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.group-icon {
|
||||
font-size: var(--app-text-2xl);
|
||||
color: var(--td-text-color-secondary);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
label {
|
||||
font-size: var(--app-text-lg);
|
||||
font-weight: 500;
|
||||
color: var(--td-text-color-primary);
|
||||
display: block;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.ext-tags {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
margin-top: 6px;
|
||||
}
|
||||
|
||||
.ext-tag {
|
||||
display: inline-block;
|
||||
font-size: var(--app-text-sm);
|
||||
line-height: 1;
|
||||
color: var(--td-text-color-secondary);
|
||||
background: var(--td-bg-color-secondarycontainer);
|
||||
padding: 3px 8px;
|
||||
border-radius: var(--app-radius-xs);
|
||||
font-family: var(--app-font-family-mono);
|
||||
}
|
||||
|
||||
.desc {
|
||||
font-size: var(--app-text-md);
|
||||
color: var(--td-text-color-secondary);
|
||||
margin: 0;
|
||||
line-height: 1.5;
|
||||
}
|
||||
}
|
||||
|
||||
.setting-control {
|
||||
flex: 0 0 55%;
|
||||
max-width: 55%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-end;
|
||||
}
|
||||
|
||||
.parser-control-stack {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
gap: 10px;
|
||||
width: 280px;
|
||||
}
|
||||
|
||||
.xlsx-header-option {
|
||||
align-self: stretch;
|
||||
|
||||
:deep(.t-checkbox) {
|
||||
align-items: flex-start;
|
||||
}
|
||||
|
||||
:deep(.t-checkbox__label) {
|
||||
font-size: var(--app-text-sm);
|
||||
line-height: 1.5;
|
||||
text-align: left;
|
||||
white-space: normal;
|
||||
}
|
||||
}
|
||||
|
||||
.no-engine-warning {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
margin-top: 8px;
|
||||
font-size: var(--app-text-sm);
|
||||
color: var(--td-warning-color);
|
||||
line-height: 1.4;
|
||||
|
||||
.go-settings {
|
||||
color: var(--td-brand-color);
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
text-decoration: none;
|
||||
|
||||
&:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 下拉选项样式 ----
|
||||
.kb-parser-settings--embedded {
|
||||
.settings-group {
|
||||
border: 1px solid var(--td-component-stroke);
|
||||
border-radius: var(--app-radius-md);
|
||||
background: var(--td-bg-color-secondarycontainer);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.setting-row {
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
padding: 10px 14px;
|
||||
background: var(--td-bg-color-container);
|
||||
border-bottom: 1px solid var(--td-component-stroke);
|
||||
|
||||
&:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
}
|
||||
|
||||
.setting-info {
|
||||
flex: 0 0 168px;
|
||||
max-width: 168px;
|
||||
padding-right: 0;
|
||||
display: block;
|
||||
}
|
||||
|
||||
.setting-control {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
max-width: none;
|
||||
align-items: stretch;
|
||||
}
|
||||
|
||||
.parser-control-stack {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.group-label {
|
||||
font-size: var(--app-text-md);
|
||||
font-weight: 500;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.ext-tags {
|
||||
margin-top: 0;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.ext-tag {
|
||||
font-size: var(--app-text-xs);
|
||||
padding: 2px 6px;
|
||||
}
|
||||
|
||||
.parser-engine-select--embedded {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,336 @@
|
||||
<template>
|
||||
<div class="share-to-space-panel">
|
||||
<div class="share-panel-header">
|
||||
<div class="share-panel-header-row">
|
||||
<div class="share-panel-titlewrap">
|
||||
<h2 class="share-panel-title">{{ $t('organization.share.title') }}</h2>
|
||||
<t-popup placement="bottom-start" trigger="hover" overlay-class-name="wk-popover share-hint-popup-overlay"
|
||||
:overlay-inner-style="shareHintPopupInnerStyle">
|
||||
<button type="button" class="share-hint-trigger-btn" :aria-label="$t('knowledgeEditor.share.hintTitle')"
|
||||
:title="$t('knowledgeEditor.share.hintTitle')">
|
||||
<t-icon name="info-circle" size="16px" />
|
||||
</button>
|
||||
<template #content>
|
||||
<div class="share-hint-popover">
|
||||
<p class="share-hint-title">{{ $t('knowledgeEditor.share.hintTitle') }}</p>
|
||||
<p class="share-hint-desc">{{ $t('knowledgeEditor.share.tip1') }}</p>
|
||||
<p class="share-hint-desc">{{ $t('knowledgeEditor.share.tip2') }}</p>
|
||||
</div>
|
||||
</template>
|
||||
</t-popup>
|
||||
</div>
|
||||
</div>
|
||||
<p class="share-panel-desc">{{ $t('knowledgeEditor.share.description') }}</p>
|
||||
</div>
|
||||
|
||||
<div class="share-panel-list-wrap">
|
||||
<div class="share-panel-list-header">
|
||||
<div class="share-panel-titlewrap">
|
||||
<span class="share-panel-list-title">{{ $t('organization.share.sharedTo') }}</span>
|
||||
<span class="share-panel-count-badge">{{ filteredShares.length }}</span>
|
||||
</div>
|
||||
<div class="share-panel-actions">
|
||||
<div class="share-panel-search">
|
||||
<t-input v-model="searchQuery" size="small" :placeholder="$t('organization.share.searchPlaceholder')"
|
||||
clearable>
|
||||
<template #prefix-icon>
|
||||
<t-icon name="search" />
|
||||
</template>
|
||||
</t-input>
|
||||
</div>
|
||||
<t-popup v-if="canShare" v-model="addPopupVisible" trigger="click" placement="bottom-end" destroy-on-close
|
||||
overlay-class-name="share-add-popup-overlay">
|
||||
<t-button theme="primary" variant="outline" shape="square" size="small" class="share-panel-add-btn"
|
||||
:title="$t('knowledgeEditor.share.addShare')" :aria-label="$t('knowledgeEditor.share.addShare')">
|
||||
<template #icon><t-icon name="add" /></template>
|
||||
</t-button>
|
||||
<template #content>
|
||||
<div class="share-add-popup-inner" @click.stop>
|
||||
<div class="member-invite-popup-title">{{ $t('organization.share.addShareDialogTitle') }}</div>
|
||||
<div class="org-upgrade-fields">
|
||||
<div class="org-upgrade-field">
|
||||
<label class="org-upgrade-field-label">{{ $t('organization.share.selectOrg') }}</label>
|
||||
<ShareToSpaceOrgSelect v-model="selectedOrgId" :organizations="availableOrganizations"
|
||||
:loading="loadingOrgs" />
|
||||
</div>
|
||||
<div class="org-upgrade-field org-upgrade-field--last">
|
||||
<label class="org-upgrade-field-label">{{ $t('organization.share.permission') }}</label>
|
||||
<t-select v-model="selectedPermission" size="medium">
|
||||
<t-option value="viewer" :label="$t('organization.share.permissionReadonly')" />
|
||||
<t-option value="editor" :label="$t('organization.share.permissionEditable')" />
|
||||
</t-select>
|
||||
<p class="member-form-hint">{{ $t('organization.share.permissionTip') }}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="invite-popup-footer">
|
||||
<t-button variant="outline" :disabled="submitting" @click="addPopupVisible = false">
|
||||
{{ $t('common.cancel') }}
|
||||
</t-button>
|
||||
<t-button theme="primary" :loading="submitting" :disabled="!selectedOrgId" @click="handleShare">
|
||||
{{ $t('knowledgeEditor.share.addShare') }}
|
||||
</t-button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</t-popup>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="loadingShares && shares.length === 0" class="share-panel-loading">
|
||||
<t-loading size="small" />
|
||||
<span>{{ $t('organization.share.loading') }}</span>
|
||||
</div>
|
||||
<div v-else-if="filteredShares.length === 0" class="share-panel-empty">
|
||||
<t-empty :description="searchQuery.trim()
|
||||
? $t('organization.share.emptySearch', { q: searchQuery })
|
||||
: $t('organization.share.noShares')" />
|
||||
</div>
|
||||
<div v-else class="share-panel-table-shell">
|
||||
<t-table row-key="id" :data="filteredShares" :columns="shareColumns" size="medium" hover stripe
|
||||
:loading="loadingShares">
|
||||
<template #space="{ row }">
|
||||
<div class="share-space-cell">
|
||||
<span class="share-space-name">
|
||||
<SpaceAvatar :name="row.organization_name || ''"
|
||||
:avatar="getOrgForShare(row.organization_id)?.avatar" size="small" />
|
||||
<span class="share-space-name-text">{{ row.organization_name }}</span>
|
||||
</span>
|
||||
<span v-if="row.shared_by_username" class="share-space-meta">
|
||||
{{ $t('organization.share.sharedFrom') }} {{ row.shared_by_username }}
|
||||
</span>
|
||||
</div>
|
||||
</template>
|
||||
<template #permission="{ row }">
|
||||
<div class="share-permission-cell">
|
||||
<t-select v-if="canShare" :value="row.permission" size="small" class="share-permission-select"
|
||||
@change="(val: string) => handleUpdatePermission(row, val)">
|
||||
<t-option value="viewer" :label="$t('organization.share.permissionReadonly')" />
|
||||
<t-option value="editor" :label="$t('organization.share.permissionEditable')" />
|
||||
</t-select>
|
||||
<t-tag v-else size="small"
|
||||
:theme="row.permission === 'editor' || row.permission === 'admin' ? 'warning' : 'default'"
|
||||
variant="light">
|
||||
{{ permissionLabel(row.permission) }}
|
||||
</t-tag>
|
||||
</div>
|
||||
</template>
|
||||
<template #created_at="{ row }">{{ formatShareDate(row.created_at) }}</template>
|
||||
<template #actions="{ row }">
|
||||
<div v-if="canShare" class="share-table-actions">
|
||||
<t-popconfirm :content="$t('knowledgeEditor.share.unshareConfirm', { name: row.organization_name })"
|
||||
:confirm-btn="{ content: $t('common.confirm'), theme: 'danger' }"
|
||||
:cancel-btn="{ content: $t('common.cancel') }" placement="left" @confirm="handleUnshare(row)">
|
||||
<t-tooltip :content="$t('organization.share.unshareAction')" placement="top">
|
||||
<t-button theme="danger" shape="square" variant="text" size="small" @click.stop>
|
||||
<template #icon><t-icon name="delete" /></template>
|
||||
</t-button>
|
||||
</t-tooltip>
|
||||
</t-popconfirm>
|
||||
</div>
|
||||
</template>
|
||||
</t-table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, watch } from 'vue'
|
||||
import { MessagePlugin } from 'tdesign-vue-next'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { useOrganizationStore } from '@/stores/organization'
|
||||
import { listKBShares } from '@/api/organization'
|
||||
import type { KnowledgeBaseShare } from '@/api/organization'
|
||||
import SpaceAvatar from '@/components/SpaceAvatar.vue'
|
||||
import ShareToSpaceOrgSelect from '@/components/ShareToSpaceOrgSelect.vue'
|
||||
|
||||
const { t } = useI18n()
|
||||
const orgStore = useOrganizationStore()
|
||||
|
||||
function getOrgForShare(organizationId: string) {
|
||||
return orgStore.organizations.find(o => o.id === organizationId)
|
||||
}
|
||||
|
||||
interface Props {
|
||||
kbId: string
|
||||
canShare?: boolean
|
||||
}
|
||||
|
||||
const props = withDefaults(defineProps<Props>(), {
|
||||
canShare: false,
|
||||
})
|
||||
|
||||
const shareHintPopupInnerStyle = {
|
||||
boxSizing: 'border-box' as const,
|
||||
padding: '0',
|
||||
width: 'min(400px, calc(100vw - 24px))',
|
||||
maxWidth: 'min(400px, calc(100vw - 24px))',
|
||||
maxHeight: 'min(280px, 65vh)',
|
||||
overflow: 'hidden',
|
||||
}
|
||||
|
||||
const loadingOrgs = ref(false)
|
||||
const loadingShares = ref(false)
|
||||
const submitting = ref(false)
|
||||
const addPopupVisible = ref(false)
|
||||
const searchQuery = ref('')
|
||||
const selectedOrgId = ref('')
|
||||
const selectedPermission = ref<'viewer' | 'editor'>('viewer')
|
||||
const shares = ref<(KnowledgeBaseShare & { organization_name?: string })[]>([])
|
||||
|
||||
const availableOrganizations = computed(() => {
|
||||
const sharedOrgIds = new Set(shares.value.map(s => s.organization_id))
|
||||
return orgStore.organizations.filter(
|
||||
(org) =>
|
||||
!sharedOrgIds.has(org.id) &&
|
||||
(org.is_owner === true || org.my_role === 'admin' || org.my_role === 'editor')
|
||||
)
|
||||
})
|
||||
|
||||
const filteredShares = computed(() => {
|
||||
const query = searchQuery.value.trim().toLowerCase()
|
||||
if (!query) return shares.value
|
||||
return shares.value.filter((share) => {
|
||||
const haystack = [
|
||||
share.organization_name,
|
||||
share.shared_by_username,
|
||||
permissionLabel(share.permission),
|
||||
].filter(Boolean).join(' ').toLowerCase()
|
||||
return haystack.includes(query)
|
||||
})
|
||||
})
|
||||
|
||||
const shareColumns = computed(() => {
|
||||
const cols = [
|
||||
{ colKey: 'space', title: t('organization.share.columns.space'), ellipsis: true, minWidth: 180 },
|
||||
{ colKey: 'permission', title: t('organization.share.columns.permission'), width: 132 },
|
||||
{ colKey: 'created_at', title: t('organization.share.columns.sharedAt'), width: 154 },
|
||||
]
|
||||
if (props.canShare) {
|
||||
cols.push({ colKey: 'actions', title: t('organization.share.columns.operations'), width: 72, align: 'left' } as typeof cols[number])
|
||||
}
|
||||
return cols
|
||||
})
|
||||
|
||||
function permissionLabel(permission: string) {
|
||||
if (permission === 'editor' || permission === 'admin') {
|
||||
return t('organization.share.permissionEditable')
|
||||
}
|
||||
return t('organization.share.permissionReadonly')
|
||||
}
|
||||
|
||||
function formatShareDate(dateStr?: string) {
|
||||
if (!dateStr) return '—'
|
||||
const date = new Date(dateStr)
|
||||
if (Number.isNaN(date.getTime())) return dateStr
|
||||
return date.toLocaleDateString(undefined, { year: 'numeric', month: '2-digit', day: '2-digit' })
|
||||
}
|
||||
|
||||
async function loadOrganizations() {
|
||||
loadingOrgs.value = true
|
||||
try {
|
||||
await orgStore.fetchOrganizations()
|
||||
} finally {
|
||||
loadingOrgs.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function loadShares() {
|
||||
if (!props.kbId) return
|
||||
loadingShares.value = true
|
||||
try {
|
||||
const result = await listKBShares(props.kbId)
|
||||
if (result.success && result.data) {
|
||||
const sharesData = (result.data as { shares?: KnowledgeBaseShare[] }).shares || result.data
|
||||
const sharesList = Array.isArray(sharesData) ? sharesData : []
|
||||
shares.value = sharesList.map((share: KnowledgeBaseShare) => ({
|
||||
...share,
|
||||
organization_name: share.organization_name || orgStore.organizations.find(o => o.id === share.organization_id)?.name || share.organization_id
|
||||
}))
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to load shares:', e)
|
||||
} finally {
|
||||
loadingShares.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function handleShare() {
|
||||
if (!selectedOrgId.value) return
|
||||
|
||||
submitting.value = true
|
||||
try {
|
||||
const result = await orgStore.shareKnowledgeBase(props.kbId, {
|
||||
organization_id: selectedOrgId.value,
|
||||
permission: selectedPermission.value
|
||||
})
|
||||
if (result.success) {
|
||||
MessagePlugin.success(t('organization.share.shareSuccess'))
|
||||
selectedOrgId.value = ''
|
||||
selectedPermission.value = 'viewer'
|
||||
addPopupVisible.value = false
|
||||
await loadShares()
|
||||
} else {
|
||||
MessagePlugin.error(result.message || t('organization.share.shareFailed'))
|
||||
}
|
||||
} catch (e: unknown) {
|
||||
const message = e instanceof Error ? e.message : t('organization.share.shareFailed')
|
||||
MessagePlugin.error(message)
|
||||
} finally {
|
||||
submitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function handleUpdatePermission(share: KnowledgeBaseShare, newPermission: string) {
|
||||
if (share.permission === newPermission) return
|
||||
|
||||
try {
|
||||
const result = await orgStore.changeKnowledgeBaseSharePermission(props.kbId, share.id, {
|
||||
permission: newPermission as 'viewer' | 'editor'
|
||||
})
|
||||
if (result.success) {
|
||||
MessagePlugin.success(t('organization.roleUpdated'))
|
||||
await loadShares()
|
||||
} else {
|
||||
MessagePlugin.error(result.message || t('organization.roleUpdateFailed'))
|
||||
}
|
||||
} catch (e: unknown) {
|
||||
const message = e instanceof Error ? e.message : t('organization.roleUpdateFailed')
|
||||
MessagePlugin.error(message)
|
||||
}
|
||||
}
|
||||
|
||||
async function handleUnshare(share: KnowledgeBaseShare) {
|
||||
try {
|
||||
const result = await orgStore.unshareKnowledgeBase(
|
||||
props.kbId,
|
||||
share.id,
|
||||
share.organization_id
|
||||
)
|
||||
if (result.success) {
|
||||
MessagePlugin.success(t('organization.share.unshareSuccess'))
|
||||
await loadShares()
|
||||
} else {
|
||||
MessagePlugin.error(result.message || t('organization.share.unshareFailed'))
|
||||
}
|
||||
} catch (e: unknown) {
|
||||
const message = e instanceof Error ? e.message : t('organization.share.unshareFailed')
|
||||
MessagePlugin.error(message)
|
||||
}
|
||||
}
|
||||
|
||||
watch(() => props.kbId, async (newKbId) => {
|
||||
if (newKbId) {
|
||||
await Promise.all([loadOrganizations(), loadShares()])
|
||||
}
|
||||
}, { immediate: true })
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
@import '@/components/share-to-space-panel.less';
|
||||
</style>
|
||||
|
||||
<style lang="less">
|
||||
@import '@/components/share-to-space-panel.overlay.less';
|
||||
</style>
|
||||
@@ -0,0 +1,72 @@
|
||||
<template>
|
||||
<div class="kb-storage-settings">
|
||||
<div class="section-header">
|
||||
<h2>{{ $t('kbSettings.storage.title') }}</h2>
|
||||
<p class="section-description">{{ $t('kbSettings.storage.selectDescription') }}</p>
|
||||
</div>
|
||||
<div v-if="loading" class="loading-inline"><t-loading size="small" /><span>{{ $t('kbSettings.storage.loading') }}</span></div>
|
||||
<div v-else class="settings-group">
|
||||
<div class="setting-row">
|
||||
<div class="setting-info">
|
||||
<label>{{ $t('kbSettings.storage.instanceLabel') }}</label>
|
||||
<p class="desc">{{ $t('kbSettings.storage.instanceDesc') }}</p>
|
||||
</div>
|
||||
<div class="setting-control">
|
||||
<t-select v-model="localID" style="width:100%;min-width:260px" :disabled="!!props.hasFiles" @change="handleChange">
|
||||
<t-option v-for="backend in backends" :key="backend.id" :value="backend.id" :label="backend.name">
|
||||
<span class="select-option">
|
||||
<span>{{ backend.name }}</span>
|
||||
<t-tag theme="primary" variant="light" size="small">{{ backend.provider.toUpperCase() }}</t-tag>
|
||||
<t-tag v-if="backend.id === defaultID" variant="light" size="small">{{ $t('kbSettings.storage.defaultTag') }}</t-tag>
|
||||
</span>
|
||||
</t-option>
|
||||
</t-select>
|
||||
<p v-if="props.hasFiles" class="option-hint locked-hint">
|
||||
<t-icon name="lock-on" class="locked-hint-icon" />
|
||||
<span>{{ $t('kbSettings.storage.migrateHint') }}</span>
|
||||
</p>
|
||||
<p v-else-if="selected" class="option-hint">{{ selected.config.endpoint || selected.config.bucket_name || selected.config.path_prefix || $t('kbSettings.storage.localStorage') }}</p>
|
||||
<a href="javascript:void(0)" class="go-settings" @click.prevent="goToSettings">{{ $t('kbSettings.storage.manageInstances') }}</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { listStorageBackends, type StorageBackend } from '@/api/storage-backend'
|
||||
import { useUIStore } from '@/stores/ui'
|
||||
|
||||
const props = defineProps<{ storageBackendId?: string; storageProvider?: string; hasFiles?: boolean }>()
|
||||
const emit = defineEmits<{
|
||||
'update:storageBackendId': [value: string]
|
||||
'update:storageProvider': [value: string]
|
||||
}>()
|
||||
const uiStore = useUIStore()
|
||||
const loading = ref(false), backends = ref<StorageBackend[]>([]), defaultID = ref(''), localID = ref(props.storageBackendId || '')
|
||||
const selected = computed(() => backends.value.find(item => item.id === localID.value))
|
||||
|
||||
function handleChange() {
|
||||
emit('update:storageBackendId', localID.value)
|
||||
emit('update:storageProvider', selected.value?.provider || props.storageProvider || '')
|
||||
}
|
||||
async function load() {
|
||||
loading.value = true
|
||||
try {
|
||||
const response = await listStorageBackends()
|
||||
backends.value = (response.data || []).filter(item => item.status === 'active')
|
||||
defaultID.value = response.default_storage_backend_id || ''
|
||||
if (!localID.value) localID.value = defaultID.value || backends.value[0]?.id || ''
|
||||
if (localID.value) handleChange()
|
||||
} finally { loading.value = false }
|
||||
}
|
||||
function goToSettings() { uiStore.closeKBEditor?.(); uiStore.openSettings?.('storage') }
|
||||
watch(() => props.storageBackendId, value => { if (value) localID.value = value })
|
||||
onMounted(load)
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
.section-header{margin-bottom:20px}.section-header h2{font-size:var(--app-text-3xl);margin:0 0 6px}.section-description,.desc,.option-hint{color:var(--td-text-color-secondary)}
|
||||
.setting-row{display:flex;justify-content:space-between;gap:28px}.setting-info{flex:1}.setting-control{width:45%;min-width:300px}.select-option{display:flex;align-items:center;gap:8px}.option-hint{font-size:var(--app-text-sm);margin:8px 0}.locked-hint{display:flex;align-items:flex-start;gap:6px;line-height:18px}.locked-hint-icon{flex-shrink:0;margin-top:2px;font-size:var(--app-text-base);color:var(--td-text-color-placeholder)}.go-settings{font-size:var(--app-text-md);color:var(--td-brand-color)}.loading-inline{display:flex;gap:8px}
|
||||
</style>
|
||||
@@ -0,0 +1,296 @@
|
||||
<template>
|
||||
<div class="kb-vector-store-settings">
|
||||
<div class="section-header">
|
||||
<h2>{{ $t('kbSettings.vectorStore.title') }}</h2>
|
||||
<p class="section-description">{{ $t('kbSettings.vectorStore.description') }}</p>
|
||||
</div>
|
||||
|
||||
<div v-if="props.mode === 'create' && loading" class="loading-inline">
|
||||
<t-loading size="small" />
|
||||
<span>{{ $t('kbSettings.vectorStore.loading') }}</span>
|
||||
</div>
|
||||
|
||||
<!-- CREATE mode: dropdown -->
|
||||
<div v-else-if="props.mode === 'create'" class="settings-group">
|
||||
<div class="setting-row">
|
||||
<div class="setting-info">
|
||||
<label>{{ $t('kbSettings.vectorStore.engineLabel') }}</label>
|
||||
<p class="desc">{{ $t('kbSettings.vectorStore.engineDesc') }}</p>
|
||||
</div>
|
||||
<div class="setting-control">
|
||||
<t-select
|
||||
v-model="localVectorStoreId"
|
||||
size="medium"
|
||||
:placeholder="$t('kbSettings.vectorStore.systemDefault')"
|
||||
:clearable="true"
|
||||
style="width: 100%; min-width: 220px;"
|
||||
@change="handleChange"
|
||||
>
|
||||
<t-option :value="''" :label="$t('kbSettings.vectorStore.systemDefault')">
|
||||
<span class="select-option">
|
||||
<span>{{ $t('kbSettings.vectorStore.systemDefault') }}</span>
|
||||
<t-tag
|
||||
v-if="envEngineType"
|
||||
theme="primary"
|
||||
variant="light"
|
||||
size="small"
|
||||
>
|
||||
{{ envEngineType }}
|
||||
</t-tag>
|
||||
</span>
|
||||
</t-option>
|
||||
<t-option
|
||||
v-for="s in userStores"
|
||||
:key="s.id"
|
||||
:value="s.id || ''"
|
||||
:label="s.name"
|
||||
>
|
||||
<span class="select-option">
|
||||
<span>{{ s.name }}</span>
|
||||
<t-tag theme="success" variant="light" size="small">
|
||||
{{ s.engine_type }}
|
||||
</t-tag>
|
||||
</span>
|
||||
</t-option>
|
||||
</t-select>
|
||||
<p class="option-hint">{{ $t('kbSettings.vectorStore.immutableHint') }}</p>
|
||||
<a
|
||||
href="javascript:void(0)"
|
||||
class="go-settings"
|
||||
@click.prevent="goToVectorStoreSettings"
|
||||
>
|
||||
{{ $t('kbSettings.vectorStore.goGlobalSettings') }}
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- EDIT mode: read-only display -->
|
||||
<div v-else class="settings-group">
|
||||
<div class="setting-row">
|
||||
<div class="setting-info">
|
||||
<label>{{ $t('kbSettings.vectorStore.boundLabel') }}</label>
|
||||
<p class="desc">{{ $t('kbSettings.vectorStore.immutableEdit') }}</p>
|
||||
</div>
|
||||
<div class="setting-control">
|
||||
<VectorStoreBadge
|
||||
:source="props.boundSource"
|
||||
:name="props.boundName"
|
||||
:engine-type="props.boundEngineType"
|
||||
:status="props.boundStatus"
|
||||
/>
|
||||
<p
|
||||
v-if="props.boundStatus === 'unavailable'"
|
||||
class="option-hint change-warning"
|
||||
>
|
||||
<t-icon name="error-circle" class="option-hint-icon" />
|
||||
<span>{{ $t('kbSettings.vectorStore.unavailableHint') }}</span>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, watch, onMounted } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { useUIStore } from '@/stores/ui'
|
||||
import { listVectorStores, type VectorStoreEntity } from '@/api/vector-store'
|
||||
import type { VectorStoreSource, VectorStoreStatus } from '@/api/knowledge-base'
|
||||
import VectorStoreBadge from '@/components/VectorStoreBadge.vue'
|
||||
|
||||
const props = defineProps<{
|
||||
mode: 'create' | 'edit'
|
||||
// create mode — current selection (empty string for env-default)
|
||||
vectorStoreId?: string
|
||||
// edit mode — bound store info already on the KB
|
||||
boundSource?: VectorStoreSource
|
||||
boundName?: string
|
||||
boundEngineType?: string
|
||||
boundStatus?: VectorStoreStatus
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'update:vectorStoreId', id: string): void
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
const uiStore = useUIStore()
|
||||
|
||||
const loading = ref(false)
|
||||
const allStores = ref<VectorStoreEntity[]>([])
|
||||
const localVectorStoreId = ref<string>(props.vectorStoreId || '')
|
||||
|
||||
// Only show user-defined stores in the dropdown. The env store is
|
||||
// surfaced via the explicit "System default" entry at the top of the
|
||||
// list; including it twice would confuse users about which one is the
|
||||
// fallback path.
|
||||
const userStores = computed(() => allStores.value.filter((s) => s.source === 'user'))
|
||||
|
||||
// Engine type for the env store, shown as a tag next to the "System
|
||||
// default" label so users know which storage backend handles unbound
|
||||
// KBs (e.g. "postgres"). When the env-store entry is missing or its
|
||||
// engine type is not populated, the tag is hidden entirely rather than
|
||||
// showing a placeholder.
|
||||
const envEngineType = computed(() => {
|
||||
const envStore = allStores.value.find((s) => s.source === 'env')
|
||||
return envStore?.engine_type || ''
|
||||
})
|
||||
|
||||
watch(
|
||||
() => props.vectorStoreId,
|
||||
(v) => {
|
||||
localVectorStoreId.value = v || ''
|
||||
},
|
||||
)
|
||||
|
||||
const handleChange = (val: string | undefined) => {
|
||||
// t-select's clear emits undefined; normalize to empty string so the
|
||||
// parent treats both as "use system default".
|
||||
emit('update:vectorStoreId', val || '')
|
||||
}
|
||||
|
||||
// Open the global Settings panel directly on the Vector Stores
|
||||
// section. This follows the same pattern as the other KB editor "go
|
||||
// to settings" links (parser, storage, models): it talks to the UI
|
||||
// store rather than navigating via the router, so the host editor
|
||||
// modal stays mounted and can be returned to once the user closes the
|
||||
// settings panel.
|
||||
const goToVectorStoreSettings = () => {
|
||||
uiStore.openSettings('vectorstore')
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
if (props.mode !== 'create') return
|
||||
loading.value = true
|
||||
try {
|
||||
const resp = await listVectorStores()
|
||||
if (resp.success) allStores.value = resp.data || []
|
||||
} catch (e) {
|
||||
// Graceful degradation: if vector-store listing fails the dropdown
|
||||
// simply renders only the "System default" entry, which is exactly
|
||||
// the legacy behavior. The KB editor remains usable.
|
||||
console.warn('[KBVectorStoreSettings] failed to load vector stores', e)
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<style lang="less" scoped>
|
||||
.kb-vector-store-settings {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.section-header {
|
||||
margin-bottom: 20px;
|
||||
|
||||
h2 {
|
||||
font-size: var(--app-text-3xl);
|
||||
font-weight: 600;
|
||||
color: var(--td-text-color-primary);
|
||||
margin: 0 0 6px 0;
|
||||
}
|
||||
|
||||
.section-description {
|
||||
font-size: var(--app-text-base);
|
||||
color: var(--td-text-color-secondary);
|
||||
margin: 0;
|
||||
line-height: 1.5;
|
||||
}
|
||||
}
|
||||
|
||||
.loading-inline {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 16px 0;
|
||||
font-size: var(--app-text-md);
|
||||
color: var(--td-text-color-secondary);
|
||||
}
|
||||
|
||||
.settings-group {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.setting-row {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
padding: 16px 0;
|
||||
border-bottom: 1px solid var(--td-component-stroke);
|
||||
|
||||
&:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
}
|
||||
|
||||
.setting-info {
|
||||
flex: 0 0 40%;
|
||||
max-width: 40%;
|
||||
padding-right: 24px;
|
||||
|
||||
label {
|
||||
font-size: var(--app-text-lg);
|
||||
font-weight: 500;
|
||||
color: var(--td-text-color-primary);
|
||||
display: block;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.desc {
|
||||
font-size: var(--app-text-md);
|
||||
color: var(--td-text-color-secondary);
|
||||
margin: 0;
|
||||
line-height: 1.5;
|
||||
}
|
||||
}
|
||||
|
||||
.setting-control {
|
||||
flex: 0 0 55%;
|
||||
max-width: 55%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.select-option {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.option-hint {
|
||||
font-size: var(--app-text-sm);
|
||||
color: var(--td-text-color-placeholder);
|
||||
margin: 0;
|
||||
line-height: 1.4;
|
||||
|
||||
&.change-warning {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 6px;
|
||||
color: var(--td-warning-color);
|
||||
}
|
||||
|
||||
.option-hint-icon {
|
||||
flex-shrink: 0;
|
||||
margin-top: 1px;
|
||||
font-size: var(--app-text-base);
|
||||
}
|
||||
}
|
||||
|
||||
.go-settings {
|
||||
font-size: var(--app-text-md);
|
||||
color: var(--td-brand-color);
|
||||
margin-top: 8px;
|
||||
text-decoration: none;
|
||||
|
||||
&:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,291 @@
|
||||
// Curated sample texts for the chunking debug drawer. Each preset is sized
|
||||
// to ≈2000–4000 characters and shaped to exercise a distinct tier of the
|
||||
// chunker, so users can quickly see how their config behaves on realistic
|
||||
// content without preparing their own sample.
|
||||
|
||||
export interface ChunkingSample {
|
||||
id: string
|
||||
// i18n key under knowledgeEditor.chunking.debug.samples.<id>
|
||||
labelKey: string
|
||||
text: string
|
||||
}
|
||||
|
||||
const MARKDOWN_SAMPLE = `# WeKnora 知识框架
|
||||
|
||||
WeKnora 是一个基于 LLM 的开源企业知识框架,集 RAG 问答、ReAct 智能体、Wiki 知识图谱于一体。本文介绍其设计动机、架构与典型用法。
|
||||
|
||||
## 设计动机
|
||||
|
||||
企业内部知识散落在 Confluence、飞书、Notion、Git 仓库等多种系统,传统全文检索难以理解语义,单一 LLM 又缺少可信赖的上下文来源。WeKnora 的目标是:
|
||||
|
||||
- **多源接入**:把分散内容统一抽取、清洗、向量化
|
||||
- **多策略检索**:稠密、稀疏、知识图谱多路召回 + RRF 融合
|
||||
- **可解释推理**:ReAct Agent 让推理链条可追踪、可干预
|
||||
- **可观测**:原生集成 Langfuse,每一步推理、每一次工具调用都有 trace
|
||||
|
||||
## 核心特性
|
||||
|
||||
### 多模型支持
|
||||
|
||||
兼容 20+ 主流 LLM:OpenAI、Anthropic、DeepSeek、Qwen、智谱、混元、Gemini,以及本地 Ollama。模型层抽象 \`Provider\` 接口,新增厂商只需实现 \`Chat()\` 方法并注册即可。
|
||||
|
||||
### 多向量库支持
|
||||
|
||||
通过 \`RETRIEVE_DRIVER\` 环境变量切换:
|
||||
|
||||
| 驱动 | 适合场景 |
|
||||
|------|---------|
|
||||
| pgvector | 已有 PostgreSQL,规模 < 1000 万 chunk |
|
||||
| Elasticsearch | 需要混合检索 + 关键词高亮 |
|
||||
| Milvus | 大规模、低延迟 |
|
||||
| Weaviate | 需要混合 BM25 + GraphQL 查询 |
|
||||
| Qdrant | 默认推荐,部署简单、性能均衡 |
|
||||
|
||||
### 数据源连接器
|
||||
|
||||
- **飞书**:自动同步知识库与文档树,支持增量更新
|
||||
- **Notion**:基于 API 抽取 Page / Database
|
||||
- **语雀**:按 Group 拉取,保留多级目录
|
||||
|
||||
每个连接器实现统一的 \`DataSource\` 接口,新增数据源约 200 行代码。
|
||||
|
||||
## 快速开始
|
||||
|
||||
### 环境要求
|
||||
|
||||
- Docker 20.10+ 与 Docker Compose v2
|
||||
- 至少 8GB 内存、20GB 磁盘空间
|
||||
- 如需本地运行 LLM,建议 NVIDIA GPU 24GB 以上显存
|
||||
|
||||
### 启动命令
|
||||
|
||||
\`\`\`bash
|
||||
git clone https://github.com/Tencent/WeKnora && cd WeKnora
|
||||
cp .env.example .env # 修改你的模型与数据库配置
|
||||
make dev-start # 启动 postgres / redis / qdrant
|
||||
make dev-app # 启动后端,热重载
|
||||
make dev-frontend # 启动前端,自动刷新
|
||||
\`\`\`
|
||||
|
||||
打开浏览器访问 http://localhost:5173 即可。
|
||||
|
||||
## 架构概览
|
||||
|
||||
WeKnora 后端采用清晰的分层架构:
|
||||
|
||||
\`\`\`
|
||||
┌────────────────────────┐
|
||||
│ HTTP 层 (Gin) │ 请求路由 / 鉴权 / 限流
|
||||
├────────────────────────┤
|
||||
│ 业务层 (service) │ 核心算法 / 编排
|
||||
├────────────────────────┤
|
||||
│ 数据层 (repository) │ 数据库访问 / 缓存
|
||||
├────────────────────────┤
|
||||
│ 领域模型 (types) │ KnowledgeBase / Chunk / Agent ...
|
||||
└────────────────────────┘
|
||||
\`\`\`
|
||||
|
||||
依赖注入容器(go/dig)在 \`cmd/server/main.go\` 装配所有依赖,handler 通过接口拿到 service,service 通过接口拿到 repository,所有可替换实现都在启动时绑定。
|
||||
|
||||
### 检索流水线
|
||||
|
||||
文档上传 → docreader 服务解析 → 分块(含父子分块) → 嵌入 → 写入向量库与图数据库 → 用户查询时多路召回 → RRF 融合 → 重排 → 返回。
|
||||
|
||||
### Agent 编排
|
||||
|
||||
Agent 引擎执行经典 ReAct 循环:
|
||||
|
||||
1. **Reason**:LLM 根据系统提示和当前观察输出推理
|
||||
2. **Act**:解析工具调用 JSON,分发给内置工具或 MCP 工具
|
||||
3. **Observe**:把工具返回值塞回上下文
|
||||
4. 重复 1-3 直到产出最终答案或达到最大迭代
|
||||
|
||||
每一步都通过 SSE 流式返回前端,并写入 Langfuse trace 便于排查。
|
||||
|
||||
## 进一步阅读
|
||||
|
||||
- API 文档:\`website-docs/04-api/01-api-overview.md\`
|
||||
- 配置项清单:\`config/config.yaml\` 与 \`.env.example\`
|
||||
- 故障排查:\`website-docs/01-getting-started/05-troubleshooting.md\`
|
||||
- 产品介绍:\`website-docs/01-getting-started/01-introduction.md\``
|
||||
|
||||
const FAQ_SAMPLE = `# WeKnora 部署与使用 FAQ
|
||||
|
||||
本文档汇总社区与内部用户最常问到的问题,按"安装 / 配置 / 检索 / 模型 / 性能"分类。
|
||||
|
||||
## 安装与启动
|
||||
|
||||
### Q1: Docker 镜像在哪里下载?
|
||||
官方镜像通过 daocloud 加速分发:
|
||||
|
||||
\`\`\`
|
||||
docker pull docker.m.daocloud.io/wechatopenai/weknora-app:v0.5.0
|
||||
docker pull docker.m.daocloud.io/wechatopenai/weknora-docreader:v0.5.0
|
||||
docker pull docker.m.daocloud.io/wechatopenai/weknora-ui:v0.5.0
|
||||
\`\`\`
|
||||
|
||||
### Q2: 启动后访问 5173 显示旧界面?
|
||||
浏览器缓存了旧版前端资源。Ctrl+Shift+R 强制刷新即可,必要时清空站点存储。
|
||||
|
||||
### Q3: 注册新用户报 500 Internal Server Error
|
||||
通常是后端容器未正常启动。先检查 \`make dev-logs | grep app\`,常见为数据库连接失败或迁移未执行。
|
||||
|
||||
### Q4: 上传文档报 column "xxx" does not exist
|
||||
数据库迁移未完成。运行 \`make migrate-up\`,确认所有迁移成功后重启 app 容器。
|
||||
|
||||
### Q5: 文档上传后状态一直是 processing
|
||||
检查 docreader 容器是否运行(\`docker compose ps\`),并查看其日志中是否有解析报错。常见原因:依赖的 Python 包缺失、PDF 加密、扫描件 OCR 超时。
|
||||
|
||||
## 配置
|
||||
|
||||
### Q6: 如何切换向量库?
|
||||
修改 \`.env\` 中的 \`RETRIEVE_DRIVER\`,可选值:\`qdrant\` (默认) / \`pgvector\` / \`elasticsearch\` / \`milvus\` / \`weaviate\`。切换后需要重新嵌入存量数据。
|
||||
|
||||
### Q7: 如何修改默认 chunk 大小?
|
||||
全局默认在 \`config/config.yaml\` 的 \`knowledge.chunking\` 段;单个知识库可在 UI 的"分块设置"页覆盖。修改后仅对新上传文档生效。
|
||||
|
||||
### Q8: 如何启用多模态?
|
||||
在知识库的"多模态配置"中开启,并选择一个 VLM 模型(如 GPT-4o、Qwen2.5-VL)。开启后,文档中的图片会被 VLM 描述并参与检索。
|
||||
|
||||
### Q9: 如何自定义日志格式?
|
||||
设置 \`WEKNORA_LOG_FORMAT="%d %level %msg" LOG_LEVEL=info\`。模板必须包含 \`%msg\`;留空使用默认格式,\`json\` 不是受支持的格式关键字。
|
||||
|
||||
## 检索与召回
|
||||
|
||||
### Q10: 检索结果为空但确认文档已索引
|
||||
按这个顺序排查:
|
||||
|
||||
1. 确认知识库状态为 \`completed\`,而不是 \`indexing\` 或 \`failed\`
|
||||
2. 检查向量库连接(默认 qdrant:6334),\`docker compose ps\` 看 qdrant 是否健康
|
||||
3. 在管理页"重建索引",确认嵌入模型工作正常
|
||||
4. 查看后端日志中 retriever 是否报 dimension mismatch
|
||||
|
||||
### Q11: 检索结果命中但答非所问
|
||||
通常是 chunk 边界切割了关键句。尝试:
|
||||
|
||||
- 启用父子分块,让向量召回小块、上下文用大块
|
||||
- 调高 chunk overlap 到 chunk size 的 15%-20%
|
||||
- 切换到"按标题切分"或"结构感知"策略
|
||||
|
||||
### Q12: 排序看起来不合理
|
||||
重排(rerank)模型可能未启用。在"模型设置"中配置 BGE-Reranker 或 Cohere Rerank,并在知识库配置中打开重排。
|
||||
|
||||
## 模型与 Token
|
||||
|
||||
### Q13: 调用 OpenAI 超时
|
||||
检查代理网络与 \`OPENAI_BASE_URL\` 配置;本地无外网时切换到 Ollama 或国内大模型。
|
||||
|
||||
### Q14: token 用量在哪里看?
|
||||
开启 Langfuse 后,每个会话、每次推理、每个工具调用的 token 消耗都有完整 trace,可按时间、空间、模型聚合。
|
||||
|
||||
### Q15: 如何接入私有 LLM?
|
||||
实现 \`internal/models/chat/provider/Provider\` 接口,注册到 provider 工厂,配置文件中加一条记录即可,约 100-200 行代码。
|
||||
|
||||
## 性能
|
||||
|
||||
### Q16: 大文档上传慢怎么办?
|
||||
docreader 是 CPU 密集型,建议横向扩容:在 docker-compose 中调高 docreader 服务的 \`deploy.replicas\`,或独立部署到更强的机器。
|
||||
|
||||
### Q17: 嵌入吞吐瓶颈
|
||||
切换到本地 Ollama + GPU 加速,或用商用 API 的批量端点(如 OpenAI 的 batch API)。设置 \`EMBED_BATCH_SIZE=64\` 显著提升吞吐。
|
||||
|
||||
### Q18: 数据库慢查询
|
||||
启用 \`pg_stat_statements\`,定位慢 SQL;常见瓶颈是 chunks 表的元数据 JSONB 查询,可针对热点字段加索引。`
|
||||
|
||||
const CHAPTER_SAMPLE = `第 1 章 引言
|
||||
|
||||
1.1 文档目的
|
||||
|
||||
本文档描述某分布式知识检索平台的整体架构、组件划分与部署方案,面向运维工程师、SRE 与系统架构师。读者应熟悉 Docker、Kubernetes、PostgreSQL 等基础组件。
|
||||
|
||||
1.2 名词约定
|
||||
|
||||
- 网关层(Gateway):负责入口流量调度与协议转换
|
||||
- 业务层(Service):承载领域逻辑与编排
|
||||
- 存储层(Storage):封装持久化与缓存细节
|
||||
- 推理层(Inference):与外部 LLM / 嵌入模型交互的隔离层
|
||||
|
||||
1.3 文档版本
|
||||
|
||||
本版本 v1.4,对应平台代码 v0.5.x 系列。文档随代码同步更新,主要变更见附录 A。
|
||||
|
||||
第 2 章 系统架构
|
||||
|
||||
2.1 总体设计
|
||||
|
||||
平台采用经典的微服务架构,但在边界划分上保持克制——只在确有独立伸缩需求的位置切分服务。当前共 4 个长驻服务:网关、业务后端、文档解析、向量索引。
|
||||
|
||||
2.2 模块划分
|
||||
|
||||
2.2.1 用户与权限
|
||||
|
||||
用户、组织、共享空间、角色与权限规则集中在 user-service 中。RBAC 模型支持继承与覆盖,外部 OIDC 接入通过适配层完成。
|
||||
|
||||
2.2.2 内容与索引
|
||||
|
||||
内容侧负责文档生命周期:上传、解析、分块、嵌入、入库、检索、引用追踪。Chunk 是最细粒度的检索单元,每个 chunk 携带源文档元数据与位置信息。
|
||||
|
||||
2.2.3 推理与编排
|
||||
|
||||
Agent 编排器负责 ReAct 循环,工具调用通过 MCP 协议或内置注册表分发。所有 LLM 调用统一经过模型代理层,方便切换、限流与计费。
|
||||
|
||||
2.3 数据流
|
||||
|
||||
文档上传后依次经过:解析 → 清洗 → 分块 → 嵌入 → 写库。查询路径:rewrite → 多路召回 → fusion → rerank → context 拼接 → LLM 生成。
|
||||
|
||||
第 3 章 部署指南
|
||||
|
||||
3.1 环境要求
|
||||
|
||||
物理资源:8 vCPU / 16 GB 内存 / 100 GB SSD 起步;生产环境建议 16 vCPU / 32 GB / 500 GB。GPU 仅在本地推理时必需。
|
||||
|
||||
3.2 容器编排
|
||||
|
||||
3.2.1 单机 Docker Compose
|
||||
|
||||
适合 PoC 与中小团队(< 100 人,< 100 万 chunk)。一条命令拉起全部服务:
|
||||
|
||||
docker compose up -d
|
||||
|
||||
3.2.2 Kubernetes Helm
|
||||
|
||||
适合规模化部署。Helm chart 在 helm/ 目录,包含 statefulset、配置 secret、ingress 模版。可与现有 PG / Redis 集群对接。
|
||||
|
||||
3.3 配置最佳实践
|
||||
|
||||
- 把外部依赖(数据库、对象存储、向量库)放在配置中心,避免硬编码
|
||||
- 模型 API key 用 Secret 管理,按环境隔离
|
||||
- 日志走 stdout/stderr 由编排平台采集,避免本地落盘
|
||||
|
||||
第 4 章 常见运维场景
|
||||
|
||||
4.1 升级流程
|
||||
|
||||
蓝绿或滚动均可。升级前必看 CHANGELOG 中是否有 schema 变更,迁移先于业务镜像替换。
|
||||
|
||||
4.2 备份与恢复
|
||||
|
||||
PG 全量每日备份 + WAL 增量;MinIO/对象存储依赖云端版本管理。Qdrant 用 snapshot 接口定期落盘到对象存储。
|
||||
|
||||
4.3 故障排查
|
||||
|
||||
按"网关 → 业务 → 存储 → 模型"四个维度逐层排查。每层都有健康检查接口与 Langfuse trace 入口,组合起来可在 5 分钟内定位 80% 问题。`
|
||||
|
||||
const PLAIN_SAMPLE = `知识库的检索质量受多个因素影响,最直接的是切分策略与嵌入模型的匹配度。切分过粗会导致单段语义混杂、相关度被稀释;切分过细则丢失上下文,单独检索某一段无法回答跨段问题。一般建议切分大小落在嵌入模型推荐窗口的 50%–80%,既保证语义完整又留出余量。常见嵌入模型如 BGE、Cohere 的 embed-v3 推荐窗口为 512 tokens,对应字符大致在 300–800 之间,因为中文一个字约 0.5–1.2 个 token,英文一个词约 1.3 个 token。
|
||||
|
||||
除了切分大小,重叠(overlap)也会显著影响召回完整性。重叠为 0 时,跨段问题往往只能召回半句话;重叠 10%–20% 通常就足够覆盖大多数边界情况;重叠超过 30% 会让相邻分块大量同质化,反而增加索引成本而不提升召回。一个简单的判断方法:对你的目标查询,平均答案长度的 1/3 作为 overlap 起点,再根据 A/B 测试微调。
|
||||
|
||||
分隔符的选择应贴合文档真实结构。纯文本可保留默认双换行作为强分隔;Markdown 文档建议保留标题层级,先按标题切,再在大标题内部按段落切;代码与表格混合的内容则需要更精细的策略,例如 Tree-sitter 抽取代码结构、识别表格边界,或者直接用脚本把这两类内容预先分离再走文本切分。如果文档里大量混合中英文,分隔符里务必同时包含中文标点(。!?)和英文标点(. ! ?),否则只对一种语言生效,效果会很差。
|
||||
|
||||
嵌入模型的选择往往被低估。开源里 BGE-large 系列在中文 benchmark 上稳定领先,BGE-M3 同时支持稠密、稀疏、ColBERT 多向量;商用 OpenAI text-embedding-3-large 通用性强、成本不算高,Voyage-3-large 在英文上略胜一筹但中文一般。对长文档场景,注意嵌入模型的最大输入长度——OpenAI 是 8191 tokens,BGE 默认 512,超长输入会被截断或分段嵌入再平均,效果都不好。
|
||||
|
||||
最后,别忽视后处理。重排(rerank)几乎在所有场景都能提升 5%–15% 的端到端效果,代价是每次查询多 100–300ms 延迟。常见 reranker 包括 BGE-Reranker、Cohere Rerank,前者开源、后者付费但效果略好。如果你的检索路径包含关键词召回,强烈建议用 reranker 做第二层过滤,不然 BM25 的纯字面命中会污染上下文。`
|
||||
|
||||
export const CHUNKING_SAMPLES: ChunkingSample[] = [
|
||||
{ id: "markdown", labelKey: "samples.markdown", text: MARKDOWN_SAMPLE },
|
||||
{ id: "faq", labelKey: "samples.faq", text: FAQ_SAMPLE },
|
||||
{ id: "chapter", labelKey: "samples.chapter", text: CHAPTER_SAMPLE },
|
||||
{ id: "plain", labelKey: "samples.plain", text: PLAIN_SAMPLE },
|
||||
];
|
||||
|
||||
export const DEFAULT_SAMPLE_ID = "markdown";
|
||||
@@ -0,0 +1,31 @@
|
||||
// Shared surface tokens for datasource list cards and drawer pickers.
|
||||
|
||||
.ds-surface-card() {
|
||||
border: 1px solid var(--td-component-stroke);
|
||||
border-radius: var(--app-radius-lg);
|
||||
background: var(--td-bg-color-container);
|
||||
transition: border-color 0.18s ease, box-shadow 0.18s ease;
|
||||
}
|
||||
|
||||
.ds-surface-card--interactive() {
|
||||
.ds-surface-card();
|
||||
|
||||
&:hover:not(.disabled):not(:disabled),
|
||||
&:focus-visible {
|
||||
border-color: var(--td-brand-color-3);
|
||||
box-shadow: 0 4px 14px rgba(15, 23, 42, 0.06);
|
||||
outline: none;
|
||||
}
|
||||
|
||||
&:focus-visible {
|
||||
outline: 2px solid var(--td-brand-color);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
}
|
||||
|
||||
// Light inset panel for grouped lists — no outer stroke.
|
||||
.ds-inset-panel() {
|
||||
border-radius: var(--app-radius-md);
|
||||
background: var(--td-bg-color-secondarycontainer);
|
||||
overflow: hidden;
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import feishuIcon from '@/assets/img/datasource-feishu.ico'
|
||||
import gitlabIcon from '@/assets/img/datasource-gitlab.png'
|
||||
import larkIcon from '@/assets/img/datasource-lark.svg'
|
||||
import notionIcon from '@/assets/img/datasource-notion.ico'
|
||||
import yuqueIcon from '@/assets/img/datasource-yuque.ico'
|
||||
import rssIcon from '@/assets/img/datasource-rss.svg'
|
||||
import confluenceIcon from '@/assets/img/datasource-confluence.svg'
|
||||
import dingtalkIcon from '@/assets/img/im/dingtalk.svg'
|
||||
import imaIcon from '@/assets/img/datasource-ima.png'
|
||||
import seafileIcon from '@/assets/img/datasource-seafile.png'
|
||||
|
||||
export const datasourceIconMap: Record<string, string> = {
|
||||
feishu: feishuIcon,
|
||||
lark: larkIcon,
|
||||
// Drive (云盘) connectors reuse the wiki icons - same product, same brand.
|
||||
feishu_drive: feishuIcon,
|
||||
lark_drive: larkIcon,
|
||||
notion: notionIcon,
|
||||
yuque: yuqueIcon,
|
||||
dingtalk: dingtalkIcon,
|
||||
rss: rssIcon,
|
||||
confluence: confluenceIcon,
|
||||
gitlab: gitlabIcon,
|
||||
ima: imaIcon,
|
||||
seafile: seafileIcon,
|
||||
}
|
||||
|
||||
export function getDatasourceIconUrl(type: string): string | undefined {
|
||||
return datasourceIconMap[type]
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import { kbFileTypeVerification } from '@/utils'
|
||||
|
||||
export const UPLOAD_VIDEO_EXTENSIONS = ['mp4', 'mov', 'avi', 'mkv', 'webm', 'wmv', 'flv']
|
||||
|
||||
export function getUploadFileExt(file: File): string {
|
||||
const dot = file.name.lastIndexOf('.')
|
||||
if (dot < 0) return ''
|
||||
return file.name.substring(dot + 1).toLowerCase()
|
||||
}
|
||||
|
||||
export function getUploadFileKey(file: File): string {
|
||||
const path = (file as File & { webkitRelativePath?: string }).webkitRelativePath || ''
|
||||
return `${path || file.name}\0${file.size}`
|
||||
}
|
||||
|
||||
export interface FilterUploadFilesOptions {
|
||||
supportedFileTypes?: Set<string> | string[]
|
||||
fromFolder?: boolean
|
||||
multiFile?: boolean
|
||||
}
|
||||
|
||||
export interface FilterUploadFilesResult {
|
||||
validFiles: File[]
|
||||
skippedCount: number
|
||||
videoFilteredCount: number
|
||||
hiddenFileCount: number
|
||||
}
|
||||
|
||||
export function filterUploadFiles(
|
||||
files: FileList | File[],
|
||||
options: FilterUploadFilesOptions = {},
|
||||
): FilterUploadFilesResult {
|
||||
const list = Array.from(files)
|
||||
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
|
||||
let videoFilteredCount = 0
|
||||
let hiddenFileCount = 0
|
||||
const multiFile = options.multiFile ?? list.length > 1
|
||||
|
||||
for (const file of list) {
|
||||
if (options.fromFolder) {
|
||||
const relativePath = (file as File & { webkitRelativePath?: string }).webkitRelativePath || file.name
|
||||
if (relativePath.split('/').some(part => part.startsWith('.'))) {
|
||||
hiddenFileCount++
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
const fileExt = getUploadFileExt(file)
|
||||
if (UPLOAD_VIDEO_EXTENSIONS.includes(fileExt)) {
|
||||
videoFilteredCount++
|
||||
continue
|
||||
}
|
||||
|
||||
if (kbFileTypeVerification(file, multiFile, dynamicTypes)) {
|
||||
skippedCount++
|
||||
continue
|
||||
}
|
||||
|
||||
validFiles.push(file)
|
||||
}
|
||||
|
||||
return { validFiles, skippedCount, videoFilteredCount, hiddenFileCount }
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,172 @@
|
||||
<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="popupOverlayClass" @visible-change="onVisibleChange">
|
||||
<span :class="['wiki-directory-action', 'wiki-directory-action--reveal', { 'is-open': open }]"
|
||||
:title="t('knowledgeEditor.wikiBrowser.folderActions')" @click.stop @dragstart.prevent.stop>
|
||||
<t-icon name="more" />
|
||||
</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>
|
||||
|
||||
<div v-else-if="mode === 'create'" class="anchored-form-popup-inner">
|
||||
<div class="anchored-form-popup-title">{{ t('knowledgeEditor.wikiBrowser.newSubfolder') }}</div>
|
||||
<t-input
|
||||
ref="inputRef"
|
||||
v-model="nameInput"
|
||||
:placeholder="t('knowledgeEditor.wikiBrowser.folderNamePlaceholder')"
|
||||
@enter="submitName"
|
||||
/>
|
||||
<div class="anchored-form-popup-footer">
|
||||
<t-button variant="outline" @click="open = false">
|
||||
{{ t('common.cancel') }}
|
||||
</t-button>
|
||||
<t-button theme="primary" :disabled="!nameInput.trim()" @click="submitName">
|
||||
{{ t('common.confirm') }}
|
||||
</t-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-else class="anchored-form-popup-inner">
|
||||
<div class="anchored-form-popup-title">{{ t('knowledgeEditor.wikiBrowser.deleteFolder') }}</div>
|
||||
<div class="anchored-form-popup-body">
|
||||
{{
|
||||
deletable
|
||||
? t('knowledgeEditor.wikiBrowser.deleteFolderConfirm', { name })
|
||||
: t('knowledgeEditor.wikiBrowser.deleteFolderNotEmpty')
|
||||
}}
|
||||
</div>
|
||||
<div class="anchored-form-popup-footer">
|
||||
<t-button variant="outline" @click="open = false">
|
||||
{{ deletable ? t('common.cancel') : t('common.confirm') }}
|
||||
</t-button>
|
||||
<t-button v-if="deletable" theme="danger" @click="submitDelete">
|
||||
{{ t('common.confirm') }}
|
||||
</t-button>
|
||||
</div>
|
||||
</div>
|
||||
</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
|
||||
}>(), {
|
||||
name: '',
|
||||
pageCount: 0,
|
||||
hasChildren: false,
|
||||
})
|
||||
|
||||
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)
|
||||
|
||||
const popupOverlayClass = computed(() => (
|
||||
mode.value === 'menu'
|
||||
? 'card-more-popup wiki-folder-action-overlay'
|
||||
: 'anchored-form-popup-overlay'
|
||||
))
|
||||
|
||||
function onVisibleChange(visible: boolean) {
|
||||
if (!visible) {
|
||||
mode.value = 'menu'
|
||||
nameInput.value = ''
|
||||
return
|
||||
}
|
||||
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: var(--app-text-lg);
|
||||
color: var(--td-text-color-placeholder);
|
||||
cursor: pointer;
|
||||
transition: color var(--app-motion-fast), opacity var(--app-motion-fast);
|
||||
|
||||
&:hover {
|
||||
color: var(--td-brand-color);
|
||||
}
|
||||
}
|
||||
|
||||
.wiki-directory-action--reveal {
|
||||
opacity: 0;
|
||||
|
||||
&.is-open {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
<style lang="less">
|
||||
// Menu chrome comes from card-more-popup + .popup-menu in dropdown-menu.less.
|
||||
.wiki-folder-action-overlay {
|
||||
.wiki-folder-menu {
|
||||
min-width: 188px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,867 @@
|
||||
<template>
|
||||
<SettingDrawer v-model:visible="drawerVisible" class="wiki-revision-drawer" :title="drawerTitle" icon="history"
|
||||
width="760px" :min-width="560" :max-width="1280" storage-key="setting-drawer:width:wiki-revision-history"
|
||||
hide-footer>
|
||||
<div class="wiki-rev-layout">
|
||||
<!-- Version list -->
|
||||
<aside class="wiki-rev-list">
|
||||
<div class="wiki-rev-list-items">
|
||||
<div v-if="currentPage" class="wiki-rev-item"
|
||||
:class="{ 'wiki-rev-item--active': selectedVersion === currentPage.version }"
|
||||
@click="selectCurrent">
|
||||
<div class="wiki-rev-item-primary">
|
||||
<span class="wiki-rev-version">v{{ currentPage.version }}</span>
|
||||
<span class="wiki-rev-current-label">{{ t('knowledgeEditor.wikiBrowser.revisionCurrent') }}</span>
|
||||
</div>
|
||||
<div class="wiki-rev-item-secondary">
|
||||
<span>{{ sourceLabel(currentPage.last_edit_source) }}</span>
|
||||
<span class="wiki-rev-time">{{ formatShortTime(currentPage.updated_at) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-for="rev in revisions" :key="rev.id" class="wiki-rev-item"
|
||||
:class="{ 'wiki-rev-item--active': selectedVersion === rev.version }" @click="selectRevision(rev)">
|
||||
<div class="wiki-rev-item-primary">
|
||||
<span class="wiki-rev-version">v{{ rev.version }}</span>
|
||||
</div>
|
||||
<div class="wiki-rev-item-secondary">
|
||||
<span>{{ sourceLabel(rev.edit_source) }}</span>
|
||||
<span class="wiki-rev-time">{{ formatShortTime(rev.edited_at) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="revisions.length < total" class="wiki-rev-load-more">
|
||||
<t-button size="small" variant="outline" theme="default" :loading="loadingList" block @click="loadMore">
|
||||
{{ t('knowledgeEditor.wikiBrowser.loadMoreShort') }}
|
||||
</t-button>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="!loadingList && revisions.length === 0" class="wiki-rev-empty">
|
||||
{{ t('knowledgeEditor.wikiBrowser.revisionEmpty') }}
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<!-- Detail pane -->
|
||||
<div class="wiki-rev-detail">
|
||||
<template v-if="selectedVersion !== null && canShowDiff">
|
||||
<div class="wiki-rev-detail-head">
|
||||
<div class="wiki-rev-detail-context">
|
||||
<div class="wiki-rev-detail-range">{{ versionRangeLabel }}</div>
|
||||
<div v-if="contextHint" class="wiki-rev-detail-sub">{{ contextHint }}</div>
|
||||
</div>
|
||||
<div class="wiki-rev-detail-controls">
|
||||
<div v-if="viewModeOptions.length > 1" class="wiki-rev-view-switch" role="tablist"
|
||||
:aria-label="t('knowledgeEditor.wikiBrowser.revisionViewModeLabel')">
|
||||
<button v-for="option in viewModeOptions" :key="option.value" type="button"
|
||||
class="wiki-rev-view-switch-btn" role="tab" :aria-selected="viewMode === option.value"
|
||||
:class="{ active: viewMode === option.value }" @click="viewMode = option.value">
|
||||
{{ option.label }}
|
||||
</button>
|
||||
</div>
|
||||
<t-popconfirm v-if="canEdit && selectedRevision"
|
||||
:content="t('knowledgeEditor.wikiBrowser.revertConfirm', { ver: selectedRevision.version })"
|
||||
@confirm="doRevert">
|
||||
<t-button size="small" variant="text" theme="warning" :loading="reverting">
|
||||
<template #icon><t-icon name="rollback" /></template>
|
||||
{{ t('knowledgeEditor.wikiBrowser.revertBtn') }}
|
||||
</t-button>
|
||||
</t-popconfirm>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="loadingDetail || diffLoading" class="wiki-rev-detail-loading">
|
||||
<t-loading size="small" />
|
||||
<span>{{ t('knowledgeEditor.wikiBrowser.loading') }}</span>
|
||||
</div>
|
||||
|
||||
<div v-else-if="viewMode !== 'raw'" class="wiki-rev-diff">
|
||||
<div v-if="snapshotMissing" class="wiki-rev-empty-diff">
|
||||
{{ t('knowledgeEditor.wikiBrowser.revisionNotRetained') }}
|
||||
</div>
|
||||
<div v-else-if="diffSections.length === 0" class="wiki-rev-empty-diff">
|
||||
{{ t('knowledgeEditor.wikiBrowser.revisionDiffEmpty') }}
|
||||
</div>
|
||||
<template v-for="section in diffSections" :key="section.field">
|
||||
<div class="wiki-rev-diff-block">
|
||||
<div class="wiki-rev-diff-block-label">{{ revisionDiffFieldLabel(section.field) }}</div>
|
||||
<pre class="wiki-rev-diff-block-body"><span v-for="(line, idx) in section.lines"
|
||||
:key="`${section.field}-${idx}`"
|
||||
:class="['wiki-rev-diff-line', `wiki-rev-diff-line--${line.type}`]">{{ diffPrefix(line.type) }}{{ line.text }}
|
||||
</span></pre>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<div v-else-if="selectedRevision" class="wiki-rev-raw">
|
||||
<pre class="wiki-rev-raw-body">{{ rawRevisionText }}</pre>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<div v-else class="wiki-rev-detail-hint">{{ t('knowledgeEditor.wikiBrowser.revisionSelectHint') }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</SettingDrawer>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { fmtBeijingClock, fmtBeijingTime } from '@/utils/datetime'
|
||||
import { ref, computed, watch } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { MessagePlugin } from 'tdesign-vue-next'
|
||||
import SettingDrawer from '@/components/settings/SettingDrawer.vue'
|
||||
import {
|
||||
listWikiRevisions,
|
||||
getWikiRevision,
|
||||
revertWikiPage,
|
||||
type WikiPage,
|
||||
type WikiPageRevision,
|
||||
} from '@/api/wiki'
|
||||
import { diffWikiRevision, type WikiRevisionDiffField, type WikiRevisionSnapshot } from '@/utils/wikiRevisionDiff'
|
||||
|
||||
type ViewMode = 'incremental' | 'cumulative' | 'raw'
|
||||
|
||||
interface DiffPair {
|
||||
fromVersion: number
|
||||
toVersion: number
|
||||
from: WikiRevisionSnapshot
|
||||
to: WikiRevisionSnapshot
|
||||
// True when the previous version's snapshot is not retained (version
|
||||
// superseded before the revision feature existed, or pruned by retention):
|
||||
// `from` fell back to empty, so the range label and hint must not claim a
|
||||
// real v(from) → v(to) diff.
|
||||
fromMissing?: boolean
|
||||
}
|
||||
|
||||
const props = defineProps<{
|
||||
visible: boolean
|
||||
kbId: string
|
||||
slug: string
|
||||
currentPage: WikiPage | null
|
||||
canEdit?: boolean
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'update:visible', visible: boolean): void
|
||||
(e: 'reverted', page: WikiPage): void
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const drawerVisible = computed({
|
||||
get: () => props.visible,
|
||||
set: (val) => emit('update:visible', val),
|
||||
})
|
||||
|
||||
const drawerTitle = computed(() =>
|
||||
t('knowledgeEditor.wikiBrowser.historyTitle', { title: props.currentPage?.title || props.slug }),
|
||||
)
|
||||
|
||||
const PAGE_SIZE = 50
|
||||
|
||||
const revisions = ref<WikiPageRevision[]>([])
|
||||
const total = ref(0)
|
||||
const loadingList = ref(false)
|
||||
|
||||
const selectedVersion = ref<number | null>(null)
|
||||
const selectedRevision = ref<WikiPageRevision | null>(null)
|
||||
const detailContent = ref('')
|
||||
const loadingDetail = ref(false)
|
||||
const viewMode = ref<ViewMode>('incremental')
|
||||
const reverting = ref(false)
|
||||
const diffLoading = ref(false)
|
||||
const diffPair = ref<DiffPair | null>(null)
|
||||
// True when the selected version's own snapshot is gone (e.g. pruned between
|
||||
// list load and click) — the diff pane shows a hint instead of a diff.
|
||||
const snapshotMissing = ref(false)
|
||||
|
||||
// A null value caches "known not retained" so the 404 is not re-fetched on
|
||||
// every diff reload.
|
||||
const snapshotCache = new Map<number, WikiRevisionSnapshot | null>()
|
||||
|
||||
const currentVersion = computed(() => props.currentPage?.version ?? null)
|
||||
|
||||
const isCurrentSelected = computed(() =>
|
||||
currentVersion.value !== null && selectedVersion.value === currentVersion.value,
|
||||
)
|
||||
|
||||
const canShowDiff = computed(() => {
|
||||
if (selectedVersion.value === null || !props.currentPage) return false
|
||||
if (viewMode.value === 'raw') return true
|
||||
if (viewMode.value === 'cumulative') {
|
||||
return !isCurrentSelected.value && selectedVersion.value! < currentVersion.value!
|
||||
}
|
||||
// incremental: v1 diffs from empty; later versions diff from the previous one
|
||||
return selectedVersion.value! >= 1
|
||||
})
|
||||
|
||||
const viewModeOptions = computed(() => {
|
||||
if (isCurrentSelected.value) return []
|
||||
const ver = selectedVersion.value!
|
||||
const cur = currentVersion.value!
|
||||
const options: Array<{ value: ViewMode; label: string }> = []
|
||||
options.push({ value: 'incremental', label: t('knowledgeEditor.wikiBrowser.revisionDiffIncremental') })
|
||||
if (ver < cur) {
|
||||
options.push({ value: 'cumulative', label: t('knowledgeEditor.wikiBrowser.revisionDiffCumulative') })
|
||||
}
|
||||
options.push({ value: 'raw', label: t('knowledgeEditor.wikiBrowser.revisionRaw') })
|
||||
return options
|
||||
})
|
||||
|
||||
const versionRangeLabel = computed(() => {
|
||||
if (viewMode.value === 'raw') {
|
||||
return selectedRevision.value ? `v${selectedRevision.value.version}` : ''
|
||||
}
|
||||
if (!diffPair.value) return ''
|
||||
if (diffPair.value.fromMissing) {
|
||||
return t('knowledgeEditor.wikiBrowser.revisionNotRetainedRange', { ver: diffPair.value.toVersion })
|
||||
}
|
||||
if (diffPair.value.fromVersion < 1) {
|
||||
return t('knowledgeEditor.wikiBrowser.revisionInitialRange', { ver: diffPair.value.toVersion })
|
||||
}
|
||||
return `v${diffPair.value.fromVersion} → v${diffPair.value.toVersion}`
|
||||
})
|
||||
|
||||
const contextHint = computed(() => {
|
||||
if (viewMode.value === 'raw' && selectedRevision.value) {
|
||||
return [
|
||||
sourceLabel(selectedRevision.value.edit_source),
|
||||
formatShortTime(selectedRevision.value.edited_at),
|
||||
].filter(Boolean).join(' · ')
|
||||
}
|
||||
if (viewMode.value === 'incremental') {
|
||||
if (diffPair.value?.fromMissing) {
|
||||
return t('knowledgeEditor.wikiBrowser.revisionNotRetainedHint', {
|
||||
prev: diffPair.value.fromVersion,
|
||||
ver: diffPair.value.toVersion,
|
||||
})
|
||||
}
|
||||
if ((isCurrentSelected.value && (currentVersion.value ?? 0) <= 1)
|
||||
|| selectedVersion.value === 1) {
|
||||
return t('knowledgeEditor.wikiBrowser.revisionInitialCreationHint')
|
||||
}
|
||||
return isCurrentSelected.value
|
||||
? t('knowledgeEditor.wikiBrowser.revisionLatestChangeHint')
|
||||
: t('knowledgeEditor.wikiBrowser.revisionIncrementalHint', { ver: selectedVersion.value ?? 0 })
|
||||
}
|
||||
if (viewMode.value === 'cumulative') {
|
||||
return t('knowledgeEditor.wikiBrowser.revisionCumulativeHint')
|
||||
}
|
||||
return ''
|
||||
})
|
||||
|
||||
const rawRevisionText = computed(() => {
|
||||
if (!selectedRevision.value) return detailContent.value
|
||||
const parts: string[] = []
|
||||
if (selectedRevision.value.title) parts.push(selectedRevision.value.title)
|
||||
if (selectedRevision.value.summary) {
|
||||
if (parts.length) parts.push('')
|
||||
parts.push(selectedRevision.value.summary)
|
||||
}
|
||||
if (detailContent.value) {
|
||||
if (parts.length) parts.push('')
|
||||
parts.push(detailContent.value)
|
||||
}
|
||||
return parts.join('\n')
|
||||
})
|
||||
|
||||
const diffSections = computed(() => {
|
||||
if (!diffPair.value || viewMode.value === 'raw') return []
|
||||
return diffWikiRevision(diffPair.value.from, diffPair.value.to)
|
||||
})
|
||||
|
||||
watch(
|
||||
() => [props.visible, props.slug] as const,
|
||||
([visible]) => {
|
||||
if (visible && props.slug) {
|
||||
resetAndLoad()
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
watch(
|
||||
() => viewModeOptions.value,
|
||||
(options) => {
|
||||
if (options.length === 0) return
|
||||
if (!options.some((option) => option.value === viewMode.value)) {
|
||||
viewMode.value = options[0].value
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
watch(
|
||||
() => [selectedVersion.value, viewMode.value, props.currentPage?.version, props.currentPage?.content,
|
||||
props.currentPage?.title, props.currentPage?.summary] as const,
|
||||
() => {
|
||||
if (props.visible && viewMode.value !== 'raw') {
|
||||
void loadDiffPair()
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
function snapshotFromPage(page: WikiPage): WikiRevisionSnapshot {
|
||||
return {
|
||||
title: page.title || '',
|
||||
summary: page.summary || '',
|
||||
content: page.content || '',
|
||||
}
|
||||
}
|
||||
|
||||
function snapshotFromRevisionData(data: WikiPageRevision, content: string): WikiRevisionSnapshot {
|
||||
return {
|
||||
title: data.title || '',
|
||||
summary: data.summary || '',
|
||||
content,
|
||||
}
|
||||
}
|
||||
|
||||
// Returns null when the version has no retained snapshot — versions
|
||||
// superseded before the revision feature existed were never snapshotted, and
|
||||
// old machine-authored snapshots get pruned. Both are expected states, not
|
||||
// errors, so callers degrade instead of surfacing a failure.
|
||||
async function loadVersionSnapshot(version: number): Promise<WikiRevisionSnapshot | null> {
|
||||
if (!props.currentPage) {
|
||||
return { title: '', summary: '', content: '' }
|
||||
}
|
||||
if (version === props.currentPage.version) {
|
||||
return snapshotFromPage(props.currentPage)
|
||||
}
|
||||
const cached = snapshotCache.get(version)
|
||||
if (cached !== undefined) return cached
|
||||
try {
|
||||
const res = await getWikiRevision(props.kbId, props.slug, version)
|
||||
const data = (res as any).data || (res as any)
|
||||
const snap = snapshotFromRevisionData(data, data.content || '')
|
||||
snapshotCache.set(version, snap)
|
||||
return snap
|
||||
} catch (e: any) {
|
||||
if (e?.status === 404) {
|
||||
snapshotCache.set(version, null)
|
||||
return null
|
||||
}
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
let diffRequestSeq = 0
|
||||
|
||||
async function loadDiffPair() {
|
||||
const seq = ++diffRequestSeq
|
||||
snapshotMissing.value = false
|
||||
if (!props.currentPage || selectedVersion.value === null || !canShowDiff.value) {
|
||||
diffPair.value = null
|
||||
diffLoading.value = false
|
||||
return
|
||||
}
|
||||
|
||||
const currentVer = props.currentPage.version
|
||||
let fromVer = 0
|
||||
let toVer = 0
|
||||
|
||||
if (viewMode.value === 'incremental') {
|
||||
toVer = isCurrentSelected.value ? currentVer : selectedVersion.value!
|
||||
fromVer = toVer - 1
|
||||
} else {
|
||||
fromVer = selectedVersion.value!
|
||||
toVer = currentVer
|
||||
}
|
||||
|
||||
if (fromVer < 0 || toVer < 1 || fromVer >= toVer) {
|
||||
diffPair.value = null
|
||||
diffLoading.value = false
|
||||
return
|
||||
}
|
||||
|
||||
diffLoading.value = true
|
||||
try {
|
||||
let from: WikiRevisionSnapshot
|
||||
let fromMissing = false
|
||||
if (fromVer < 1) {
|
||||
from = { title: '', summary: '', content: '' }
|
||||
} else {
|
||||
const prev = await loadVersionSnapshot(fromVer)
|
||||
if (seq !== diffRequestSeq) return
|
||||
if (prev) {
|
||||
from = prev
|
||||
} else {
|
||||
// The previous version's snapshot is not retained (pre-revision
|
||||
// history or pruned). Diff from empty so the pane still shows this
|
||||
// version's full content instead of an error toast.
|
||||
from = { title: '', summary: '', content: '' }
|
||||
fromMissing = true
|
||||
}
|
||||
}
|
||||
const to = await loadVersionSnapshot(toVer)
|
||||
if (seq !== diffRequestSeq) return
|
||||
if (!to) {
|
||||
// The selected version's own snapshot vanished (e.g. pruned while the
|
||||
// drawer was open) — nothing to diff, show the hint pane instead of a
|
||||
// misleading "no differences" empty state.
|
||||
snapshotMissing.value = true
|
||||
diffPair.value = null
|
||||
return
|
||||
}
|
||||
diffPair.value = { fromVersion: fromVer, toVersion: toVer, from, to, fromMissing }
|
||||
} catch (e: any) {
|
||||
if (seq !== diffRequestSeq) return
|
||||
diffPair.value = null
|
||||
MessagePlugin.error(e?.message || t('knowledgeEditor.wikiBrowser.revisionLoadFailed'))
|
||||
} finally {
|
||||
if (seq === diffRequestSeq) diffLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function resetAndLoad() {
|
||||
detailRequestSeq++
|
||||
diffRequestSeq++
|
||||
snapshotCache.clear()
|
||||
revisions.value = []
|
||||
total.value = 0
|
||||
selectedVersion.value = props.currentPage?.version ?? null
|
||||
selectedRevision.value = null
|
||||
detailContent.value = ''
|
||||
loadingDetail.value = false
|
||||
diffPair.value = null
|
||||
diffLoading.value = false
|
||||
snapshotMissing.value = false
|
||||
viewMode.value = 'incremental'
|
||||
loadList(0)
|
||||
void loadDiffPair()
|
||||
}
|
||||
|
||||
async function loadList(offset: number) {
|
||||
loadingList.value = true
|
||||
try {
|
||||
const res = await listWikiRevisions(props.kbId, props.slug, { limit: PAGE_SIZE, offset })
|
||||
const data = (res as any).data || (res as any)
|
||||
const items: WikiPageRevision[] = data.revisions || []
|
||||
if (offset === 0) {
|
||||
revisions.value = items
|
||||
} else {
|
||||
// Snapshots are created while the user pages through, which shifts the
|
||||
// newest-first window. Drop versions we already hold so an overlapping
|
||||
// page cannot produce duplicate rows (and duplicate :key values).
|
||||
const seen = new Set(revisions.value.map((r) => r.version))
|
||||
revisions.value = [...revisions.value, ...items.filter((r) => !seen.has(r.version))]
|
||||
}
|
||||
total.value = data.total ?? revisions.value.length
|
||||
} catch (e: any) {
|
||||
MessagePlugin.error(e?.message || t('knowledgeEditor.wikiBrowser.revisionLoadFailed'))
|
||||
} finally {
|
||||
loadingList.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function loadMore() {
|
||||
if (loadingList.value) return
|
||||
loadList(revisions.value.length)
|
||||
}
|
||||
|
||||
function selectCurrent() {
|
||||
detailRequestSeq++
|
||||
selectedVersion.value = props.currentPage?.version ?? null
|
||||
selectedRevision.value = null
|
||||
detailContent.value = ''
|
||||
loadingDetail.value = false
|
||||
viewMode.value = 'incremental'
|
||||
}
|
||||
|
||||
// Monotonic token guarding the detail fetch: clicking through the list fires
|
||||
// overlapping requests, and a slow earlier one must not overwrite the body of
|
||||
// the revision the user is actually looking at.
|
||||
let detailRequestSeq = 0
|
||||
|
||||
async function selectRevision(rev: WikiPageRevision) {
|
||||
const seq = ++detailRequestSeq
|
||||
selectedVersion.value = rev.version
|
||||
selectedRevision.value = rev
|
||||
detailContent.value = ''
|
||||
viewMode.value = 'incremental'
|
||||
loadingDetail.value = true
|
||||
try {
|
||||
const res = await getWikiRevision(props.kbId, props.slug, rev.version)
|
||||
if (seq !== detailRequestSeq) return
|
||||
const data = (res as any).data || (res as any)
|
||||
selectedRevision.value = { ...rev, ...data }
|
||||
detailContent.value = data.content || ''
|
||||
snapshotCache.set(rev.version, snapshotFromRevisionData(data, data.content || ''))
|
||||
} catch (e: any) {
|
||||
if (seq !== detailRequestSeq) return
|
||||
// 404 = snapshot not retained (pre-revision history or pruned); the raw
|
||||
// server message is English and gives the user nothing actionable.
|
||||
MessagePlugin.error(e?.status === 404
|
||||
? t('knowledgeEditor.wikiBrowser.revisionNotRetained')
|
||||
: (e?.message || t('knowledgeEditor.wikiBrowser.revisionLoadFailed')))
|
||||
} finally {
|
||||
if (seq === detailRequestSeq) loadingDetail.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function doRevert() {
|
||||
if (!selectedRevision.value) return
|
||||
reverting.value = true
|
||||
try {
|
||||
const res = await revertWikiPage(props.kbId, props.slug, selectedRevision.value.version)
|
||||
const updated = ((res as any).data || (res as any)) as WikiPage
|
||||
MessagePlugin.success(t('knowledgeEditor.wikiBrowser.revertSuccess', { ver: selectedRevision.value.version }))
|
||||
emit('reverted', updated)
|
||||
// Stay open: reload so the just-created snapshot of the pre-revert
|
||||
// version shows up and the "current" entry reflects the new version.
|
||||
resetAndLoad()
|
||||
} catch (e: any) {
|
||||
MessagePlugin.error(e?.message || t('knowledgeEditor.wikiBrowser.revertFailed'))
|
||||
} finally {
|
||||
reverting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function diffPrefix(type: 'same' | 'add' | 'del'): string {
|
||||
return type === 'add' ? '+ ' : type === 'del' ? '- ' : ' '
|
||||
}
|
||||
|
||||
function revisionDiffFieldLabel(field: WikiRevisionDiffField): string {
|
||||
switch (field) {
|
||||
case 'title':
|
||||
return t('knowledgeEditor.wikiBrowser.revisionDiffTitle')
|
||||
case 'summary':
|
||||
return t('knowledgeEditor.wikiBrowser.revisionDiffSummary')
|
||||
default:
|
||||
return t('knowledgeEditor.wikiBrowser.revisionDiffContent')
|
||||
}
|
||||
}
|
||||
|
||||
function sourceLabel(source?: string): string {
|
||||
switch (source) {
|
||||
case 'user':
|
||||
return t('knowledgeEditor.wikiBrowser.editSourceUser')
|
||||
case 'agent':
|
||||
return t('knowledgeEditor.wikiBrowser.editSourceAgent')
|
||||
case 'revert':
|
||||
return t('knowledgeEditor.wikiBrowser.editSourceRevert')
|
||||
default:
|
||||
return t('knowledgeEditor.wikiBrowser.editSourcePipeline')
|
||||
}
|
||||
}
|
||||
|
||||
function formatShortTime(iso?: string): string {
|
||||
if (!iso) return ''
|
||||
const d = new Date(iso)
|
||||
if (Number.isNaN(d.getTime())) return iso
|
||||
const now = new Date()
|
||||
if (d.toDateString() === now.toDateString()) {
|
||||
return fmtBeijingClock(d)
|
||||
}
|
||||
return fmtBeijingTime(d)
|
||||
}
|
||||
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.wiki-rev-layout {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
height: 100%;
|
||||
align-items: stretch;
|
||||
}
|
||||
|
||||
.wiki-rev-list {
|
||||
width: 220px;
|
||||
flex-shrink: 0;
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
padding: 12px 0;
|
||||
border-right: 1px solid var(--td-component-stroke);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background: var(--td-bg-color-container);
|
||||
}
|
||||
|
||||
.wiki-rev-list-items {
|
||||
flex: 0 0 auto;
|
||||
overflow-y: auto;
|
||||
min-height: 0;
|
||||
padding: 0 8px 0 14px;
|
||||
}
|
||||
|
||||
.wiki-rev-item {
|
||||
border: none;
|
||||
border-radius: var(--app-radius-sm);
|
||||
padding: 6px 10px 6px 14px;
|
||||
cursor: pointer;
|
||||
transition: background var(--app-motion-fast) ease, color var(--app-motion-fast) ease;
|
||||
}
|
||||
|
||||
.wiki-rev-item:hover,
|
||||
.wiki-rev-item--active {
|
||||
background: var(--td-bg-color-container-hover);
|
||||
}
|
||||
|
||||
.wiki-rev-item--active .wiki-rev-version,
|
||||
.wiki-rev-item--active .wiki-rev-current-label {
|
||||
color: var(--td-brand-color);
|
||||
}
|
||||
|
||||
.wiki-rev-item-primary {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.wiki-rev-version {
|
||||
font-weight: 400;
|
||||
font-size: var(--app-text-base);
|
||||
line-height: 20px;
|
||||
font-family: var(--td-font-family-mono);
|
||||
color: var(--td-text-color-primary);
|
||||
transition: color var(--app-motion-fast) ease;
|
||||
}
|
||||
|
||||
.wiki-rev-current-label {
|
||||
font-size: var(--app-text-sm);
|
||||
line-height: 16px;
|
||||
color: var(--td-text-color-placeholder);
|
||||
transition: color var(--app-motion-fast) ease;
|
||||
}
|
||||
|
||||
.wiki-rev-item-secondary {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
margin-top: 2px;
|
||||
min-width: 0;
|
||||
font-size: var(--app-text-xs);
|
||||
line-height: 16px;
|
||||
color: var(--td-text-color-placeholder);
|
||||
}
|
||||
|
||||
.wiki-rev-time {
|
||||
font-size: var(--app-text-xs);
|
||||
color: var(--td-text-color-placeholder);
|
||||
white-space: nowrap;
|
||||
flex-shrink: 0;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.wiki-rev-load-more {
|
||||
padding: 8px 0 4px;
|
||||
}
|
||||
|
||||
.wiki-rev-empty {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 16px 14px;
|
||||
text-align: center;
|
||||
font-size: var(--app-text-sm);
|
||||
line-height: 1.5;
|
||||
color: var(--td-text-color-placeholder);
|
||||
}
|
||||
|
||||
.wiki-rev-detail {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
padding: 14px 18px 18px;
|
||||
}
|
||||
|
||||
.wiki-rev-detail-head {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
margin-bottom: 14px;
|
||||
padding-bottom: 14px;
|
||||
border-bottom: 1px solid var(--td-component-stroke);
|
||||
}
|
||||
|
||||
.wiki-rev-detail-context {
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.wiki-rev-detail-range {
|
||||
font-family: var(--td-font-family-mono);
|
||||
font-size: var(--app-text-lg);
|
||||
font-weight: 600;
|
||||
line-height: 1.4;
|
||||
color: var(--td-text-color-primary);
|
||||
}
|
||||
|
||||
.wiki-rev-detail-sub {
|
||||
margin-top: 4px;
|
||||
font-size: var(--app-text-sm);
|
||||
line-height: 1.5;
|
||||
color: var(--td-text-color-placeholder);
|
||||
}
|
||||
|
||||
.wiki-rev-detail-controls {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.wiki-rev-view-switch {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
padding: 2px;
|
||||
border-radius: var(--app-radius-md);
|
||||
background: var(--td-bg-color-secondarycontainer);
|
||||
}
|
||||
|
||||
.wiki-rev-view-switch-btn {
|
||||
padding: 5px 10px;
|
||||
border: 0;
|
||||
border-radius: var(--app-radius-sm);
|
||||
background: transparent;
|
||||
color: var(--td-text-color-secondary);
|
||||
font-size: var(--app-text-sm);
|
||||
line-height: 1.4;
|
||||
white-space: nowrap;
|
||||
cursor: pointer;
|
||||
transition: background var(--app-motion-fast) ease, color var(--app-motion-fast) ease;
|
||||
}
|
||||
|
||||
.wiki-rev-view-switch-btn:hover {
|
||||
color: var(--td-text-color-primary);
|
||||
}
|
||||
|
||||
.wiki-rev-view-switch-btn.active {
|
||||
color: var(--td-brand-color);
|
||||
background: var(--td-bg-color-container);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.wiki-rev-detail-hint {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: var(--td-text-color-placeholder);
|
||||
padding: 24px;
|
||||
text-align: center;
|
||||
font-size: var(--app-text-md);
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.wiki-rev-detail-loading {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
color: var(--td-text-color-placeholder);
|
||||
font-size: var(--app-text-md);
|
||||
}
|
||||
|
||||
.wiki-rev-diff {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.wiki-rev-empty-diff {
|
||||
padding: 24px 0;
|
||||
text-align: center;
|
||||
font-size: var(--app-text-md);
|
||||
color: var(--td-text-color-placeholder);
|
||||
}
|
||||
|
||||
.wiki-rev-diff-block {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.wiki-rev-diff-block-label {
|
||||
font-size: var(--app-text-sm);
|
||||
font-weight: 500;
|
||||
color: var(--td-text-color-placeholder);
|
||||
}
|
||||
|
||||
.wiki-rev-diff-block-body {
|
||||
overflow: auto;
|
||||
margin: 0;
|
||||
padding: 10px 12px;
|
||||
background: var(--td-bg-color-secondarycontainer);
|
||||
border-radius: var(--app-radius-md);
|
||||
font-size: var(--app-text-sm);
|
||||
line-height: 1.7;
|
||||
font-family: var(--td-font-family-mono);
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.wiki-rev-raw {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.wiki-rev-raw-body {
|
||||
margin: 0;
|
||||
padding: 12px 14px;
|
||||
background: var(--td-bg-color-secondarycontainer);
|
||||
border-radius: var(--app-radius-md);
|
||||
font-size: var(--app-text-md);
|
||||
line-height: 1.7;
|
||||
font-family: var(--td-font-family-mono);
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.wiki-rev-diff-line {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.wiki-rev-diff-line--add {
|
||||
background: color-mix(in srgb, var(--td-brand-color) 8%, transparent);
|
||||
color: var(--td-text-color-primary);
|
||||
}
|
||||
|
||||
.wiki-rev-diff-line--del {
|
||||
background: rgba(213, 73, 65, 0.06);
|
||||
color: var(--td-text-color-secondary);
|
||||
}
|
||||
</style>
|
||||
|
||||
<style lang="less">
|
||||
.wiki-revision-drawer {
|
||||
.t-drawer__content-wrapper,
|
||||
.t-drawer__content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.t-drawer__body {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.setting-drawer__body {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
padding: 0;
|
||||
gap: 0;
|
||||
animation: none;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,169 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { createRequire } from 'node:module'
|
||||
import test from 'node:test'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { runInNewContext } from 'node:vm'
|
||||
import { compileScript, parse } from '@vue/compiler-sfc'
|
||||
import ts from 'typescript'
|
||||
import { createRenderer, nextTick } from 'vue'
|
||||
|
||||
const require = createRequire(import.meta.url)
|
||||
const filename = fileURLToPath(new URL('./WikiBrowser.vue', import.meta.url))
|
||||
const { descriptor } = parse(readFileSync(filename, 'utf8'), { filename })
|
||||
const script = compileScript(descriptor, { id: 'wiki-backlink-browser-test' }).content
|
||||
.replace('__expose();', '')
|
||||
.replace('return __returned__', '__expose(__returned__); return __returned__')
|
||||
const compiled = ts.transpileModule(script, {
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 },
|
||||
}).outputText
|
||||
|
||||
function page(slug: string, titles: Record<string, string> = {}) {
|
||||
return { id: slug, slug, title: slug, content: '', version: 1, in_links: Object.keys(titles), in_link_titles: titles }
|
||||
}
|
||||
|
||||
async function fixture() {
|
||||
const calls: { name: string; args: any[] }[] = []
|
||||
const errors: unknown[][] = []
|
||||
let response: any = page('first')
|
||||
let failure: Error | undefined
|
||||
const api = {
|
||||
getWikiPage: async (...args: any[]) => {
|
||||
calls.push({ name: 'getWikiPage', args })
|
||||
if (failure) throw failure
|
||||
return { data: response }
|
||||
},
|
||||
updateWikiPage: async (...args: any[]) => {
|
||||
calls.push({ name: 'updateWikiPage', args })
|
||||
const { in_link_titles, ...updated } = response
|
||||
return { data: { ...updated, ...args[2], version: updated.version + 1 } }
|
||||
},
|
||||
listWikiIssues: async () => [],
|
||||
listWikiPages: async () => ({ pages: [], total: 0 }),
|
||||
listWikiFolders: async () => ({ folders: [] }),
|
||||
getWikiIndex: async () => ({ groups: [] }),
|
||||
getWikiStats: async () => ({}),
|
||||
}
|
||||
const exports: any = {}
|
||||
runInNewContext(compiled, {
|
||||
exports, console: { error: (...args: unknown[]) => errors.push(args) },
|
||||
setTimeout, clearTimeout, setInterval, clearInterval,
|
||||
localStorage: { getItem: () => null, setItem() {} },
|
||||
require(name: string) {
|
||||
if (name === 'vue' || name === 'marked') return require(name)
|
||||
if (name === 'vue-router') return { useRouter: () => ({}), useRoute: () => ({ query: {} }) }
|
||||
if (name === 'vue-i18n') return { useI18n: () => ({ t: (key: string) => key }) }
|
||||
if (name === '@/stores/assistant') return { useAssistantStore: () => ({ visible: false }) }
|
||||
if (name === '@/composables/useAssistantPageContext') return { useAssistantPageContext() {} }
|
||||
if (name === '@/utils/assistantDataChange') return { useAssistantDataChange() {} }
|
||||
if (name === '@/stores/settings') return { useSettingsStore: () => ({}) }
|
||||
if (name === '@/api/wiki') return api
|
||||
if (name === 'tdesign-vue-next') return { MessagePlugin: { success() {}, error() {} } }
|
||||
// DOM sanitization has separate tests; this fixture exercises the actual
|
||||
// component's title resolution and Markdown caller before that boundary.
|
||||
if (name === '@/utils/security') return { sanitizeMarkdownHTML: (html: string) => html, hydrateProtectedFileImages: async () => {} }
|
||||
if (name.startsWith('./wiki')) return require(`${name}.ts`)
|
||||
if (name === '@/utils/markedLiteralTilde') return require('../../../utils/markedLiteralTilde.ts')
|
||||
if (name.endsWith('.vue') || ['vue-virtual-scroller', '@/api/knowledge-base', '@/api/chat'].includes(name)) return { default: {} }
|
||||
throw new Error(`Unexpected component dependency: ${name}`)
|
||||
},
|
||||
})
|
||||
exports.default.render = () => null
|
||||
const renderer = createRenderer<any, any>({
|
||||
createElement: () => ({}), createText: () => ({}), createComment: () => ({}),
|
||||
insert() {}, remove() {}, setElementText() {}, setText() {}, patchProp() {},
|
||||
parentNode: () => null, nextSibling: () => null,
|
||||
})
|
||||
const app = renderer.createApp(exports.default, { knowledgeBaseId: 'kb-1' })
|
||||
const vm: any = app.mount({})
|
||||
await new Promise(resolve => setImmediate(resolve))
|
||||
await nextTick()
|
||||
return {
|
||||
vm, calls, errors,
|
||||
respond(value: any) { response = value; failure = undefined },
|
||||
fail() { failure = new Error('page lookup failed') },
|
||||
close: () => app.unmount(),
|
||||
}
|
||||
}
|
||||
|
||||
test('page navigation consumes all response titles without a separate title request', async () => {
|
||||
const f = await fixture()
|
||||
try {
|
||||
const titles = Object.fromEntries(Array.from({ length: 2507 }, (_, i) => [`concept/${i}-${'a'.repeat(200)}`, `标题 ${i}`]))
|
||||
f.respond(page('first', titles))
|
||||
await f.vm.selectPage({ id: 'first', slug: 'first' })
|
||||
await nextTick()
|
||||
for (const [slug, title] of Object.entries(titles)) assert.equal(f.vm.slugDisplayName(slug), title)
|
||||
assert.equal(f.calls.length, 1)
|
||||
assert.deepEqual(f.calls[0], { name: 'getWikiPage', args: ['kb-1', 'first'] })
|
||||
assert.equal(f.errors.length, 0)
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
test('navigation, same-page refresh, history and clearing use the matching page map', async () => {
|
||||
const f = await fixture()
|
||||
try {
|
||||
f.respond(page('first', { 'concept/shared': 'First title' }))
|
||||
await f.vm.selectPage({ id: 'first', slug: 'first' })
|
||||
f.respond(page('second', { 'concept/shared': 'Second title' }))
|
||||
await f.vm.navigateToSlug('second')
|
||||
assert.equal(f.vm.slugDisplayName('concept/shared'), 'Second title')
|
||||
f.respond(page('second', { 'concept/shared': 'Refreshed title' }))
|
||||
await f.vm.refreshSelectedPage()
|
||||
assert.equal(f.vm.slugDisplayName('concept/shared'), 'Refreshed title')
|
||||
f.vm.goBack()
|
||||
assert.equal(f.vm.selectedPage.slug, 'first')
|
||||
assert.equal(f.vm.slugDisplayName('concept/shared'), 'First title')
|
||||
f.vm.selectedPage = null
|
||||
assert.equal(f.vm.slugDisplayName('concept/shared'), 'shared')
|
||||
assert.equal(f.errors.length, 0)
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
test('Markdown caller handles prototype names, missing titles and explicit labels', async () => {
|
||||
const f = await fixture()
|
||||
try {
|
||||
f.respond(page('current'))
|
||||
await f.vm.navigateToSlug('current')
|
||||
for (const slug of ['constructor', 'toString', '__proto__', 'hasOwnProperty']) {
|
||||
const html = f.vm.renderMarkdown(`[[${slug}]]`)
|
||||
assert.ok(html.includes(`data-slug="${slug}"`))
|
||||
assert.ok(html.includes(`>${require('marked').marked.parseInline(slug)}</a>`))
|
||||
assert.match(f.vm.renderMarkdown(`[[${slug}|Explicit label]]`), />Explicit label<\/a>/)
|
||||
}
|
||||
f.vm.pages = [{ slug: 'concept/loaded', title: 'Loaded title' }]
|
||||
assert.match(f.vm.renderMarkdown('[[concept/loaded]] [[concept/missing]]'), />Loaded title<\/a>.*>missing<\/a>/)
|
||||
f.respond(page('current', JSON.parse('{"constructor":"构造函数","__proto__":"原型"}')))
|
||||
await f.vm.refreshSelectedPage()
|
||||
assert.match(f.vm.renderMarkdown('[[constructor]] [[__proto__]]'), />构造函数<\/a>.*>原型<\/a>/)
|
||||
assert.equal(f.errors.length, 0)
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
test('saving page edits retains titles omitted from the mutation response', async () => {
|
||||
const f = await fixture()
|
||||
try {
|
||||
f.respond(page('current', { 'concept/unloaded': 'Unloaded title' }))
|
||||
await f.vm.navigateToSlug('current')
|
||||
await nextTick()
|
||||
f.vm.startEditPage()
|
||||
f.vm.editForm.title = 'Edited title'
|
||||
await f.vm.savePageEdit()
|
||||
assert.equal(f.vm.selectedPage.title, 'Edited title')
|
||||
assert.equal(f.vm.slugDisplayName('concept/unloaded'), 'Unloaded title')
|
||||
assert.equal(f.errors.length, 0)
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
test('failed navigation retains the displayed page and reports the failure', async () => {
|
||||
const f = await fixture()
|
||||
try {
|
||||
f.respond(page('first', { 'concept/shared': 'First title' }))
|
||||
await f.vm.navigateToSlug('first')
|
||||
f.fail()
|
||||
await f.vm.navigateToSlug('second')
|
||||
assert.equal(f.vm.selectedPage.slug, 'first')
|
||||
assert.equal(f.vm.slugDisplayName('concept/shared'), 'First title')
|
||||
assert.equal(f.errors.length, 1)
|
||||
} finally { f.close() }
|
||||
})
|
||||
@@ -0,0 +1,45 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import { resolveWikiBacklinkTitle } from './wikiBacklinkTitles.ts'
|
||||
|
||||
test('uses the response title for an unloaded backlink', () => {
|
||||
assert.equal(
|
||||
resolveWikiBacklinkTitle(
|
||||
'concept/gong-si-zi-ben-zhi-du',
|
||||
{ 'concept/gong-si-zi-ben-zhi-du': '公司资本制度' },
|
||||
[],
|
||||
),
|
||||
'公司资本制度',
|
||||
)
|
||||
})
|
||||
|
||||
test('only uses own string titles and preserves fallback for prototype property names', () => {
|
||||
for (const slug of ['constructor', 'toString', '__proto__', 'hasOwnProperty']) {
|
||||
assert.equal(resolveWikiBacklinkTitle(slug, {}, []), slug)
|
||||
assert.equal(resolveWikiBacklinkTitle(slug, {}, [{ slug, title: 'Loaded title' }]), 'Loaded title')
|
||||
const titles = JSON.parse(JSON.stringify({ [slug]: ' 中文标题 ' }))
|
||||
assert.equal(resolveWikiBacklinkTitle(slug, titles, []), '中文标题')
|
||||
}
|
||||
const inherited = Object.create({ 'concept/page': 'Inherited title' })
|
||||
assert.equal(resolveWikiBacklinkTitle('concept/page', inherited, []), 'page')
|
||||
for (const value of [undefined, null, 42, true, {}, [], () => 'title', '', ' ']) {
|
||||
const titles = { 'concept/page': value } as unknown as Record<string, string>
|
||||
assert.equal(resolveWikiBacklinkTitle('concept/page', titles, []), 'page')
|
||||
assert.equal(resolveWikiBacklinkTitle('concept/page', titles, [{ slug: 'concept/page', title: 'Loaded' }]), 'Loaded')
|
||||
}
|
||||
})
|
||||
|
||||
test('prefers the response title and retains hierarchical slug fallback', () => {
|
||||
assert.equal(resolveWikiBacklinkTitle('concept/a', { 'concept/a': ' Current ' }, [{ slug: 'concept/a', title: 'Old' }]), 'Current')
|
||||
assert.equal(resolveWikiBacklinkTitle('concept/a/b', {}, []), 'a/b')
|
||||
assert.equal(resolveWikiBacklinkTitle('', {}, []), '')
|
||||
})
|
||||
|
||||
test('keeps loaded page titles and slug fallback behavior', () => {
|
||||
assert.equal(
|
||||
resolveWikiBacklinkTitle('entity/acme', {}, [{ slug: 'entity/acme', title: 'Acme' }]),
|
||||
'Acme',
|
||||
)
|
||||
assert.equal(resolveWikiBacklinkTitle('concept/unknown-page', {}, []), 'unknown-page')
|
||||
})
|
||||
@@ -0,0 +1,23 @@
|
||||
export interface WikiBacklinkPage {
|
||||
slug: string
|
||||
title: string
|
||||
}
|
||||
|
||||
// Resolve a backlink using the page detail's title map first, then pages
|
||||
// already loaded in the sidebar, and finally the historical slug fallback.
|
||||
export function resolveWikiBacklinkTitle(
|
||||
slug: string,
|
||||
titles: Record<string, string>,
|
||||
pages: WikiBacklinkPage[],
|
||||
): string {
|
||||
if (Object.prototype.hasOwnProperty.call(titles, slug)) {
|
||||
const value = titles[slug]
|
||||
if (typeof value === 'string' && value.trim()) return value.trim()
|
||||
}
|
||||
|
||||
const loadedPage = pages.find(page => page.slug === slug)
|
||||
if (loadedPage?.title) return loadedPage.title
|
||||
|
||||
const parts = slug.split('/')
|
||||
return parts.length > 1 ? parts.slice(1).join('/') : slug
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { dirname, join } from 'node:path'
|
||||
import test from 'node:test'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
import {
|
||||
expandedWikiDirectoryPaths,
|
||||
expandWikiDirectoryPath,
|
||||
} from './wikiDirectoryState.ts'
|
||||
|
||||
test('keeps the current wiki directory path expanded without changing sibling state', () => {
|
||||
const collapsed = new Set([
|
||||
'knowledge:Guides',
|
||||
'knowledge:Guides/Setup',
|
||||
'knowledge:Reference',
|
||||
'summary:Guides',
|
||||
])
|
||||
const touched = new Set(['knowledge:Reference'])
|
||||
|
||||
const state = expandWikiDirectoryPath(
|
||||
'knowledge',
|
||||
['Guides', 'Setup'],
|
||||
collapsed,
|
||||
touched,
|
||||
)
|
||||
|
||||
assert.deepEqual([...state.collapsed].sort(), [
|
||||
'knowledge:Reference',
|
||||
'summary:Guides',
|
||||
])
|
||||
assert.deepEqual([...state.touched].sort(), [
|
||||
'knowledge:Guides',
|
||||
'knowledge:Guides/Setup',
|
||||
'knowledge:Reference',
|
||||
])
|
||||
assert.equal(collapsed.has('knowledge:Guides'), true)
|
||||
assert.equal(touched.has('knowledge:Guides'), false)
|
||||
})
|
||||
|
||||
test('returns expanded wiki paths in parent-first order for a refreshed tree', () => {
|
||||
const paths = expandedWikiDirectoryPaths(
|
||||
'knowledge',
|
||||
new Set(['knowledge:Reference']),
|
||||
new Set([
|
||||
'knowledge:Guides/Setup',
|
||||
'summary:Guides',
|
||||
'knowledge:Reference',
|
||||
'knowledge:Guides',
|
||||
]),
|
||||
)
|
||||
|
||||
assert.deepEqual(paths, [
|
||||
['Guides'],
|
||||
['Guides', 'Setup'],
|
||||
])
|
||||
})
|
||||
|
||||
test('folder creation refreshes data while preserving the current directory state', () => {
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const source = readFileSync(join(here, 'WikiBrowser.vue'), 'utf8')
|
||||
const createFolder = source.slice(
|
||||
source.indexOf('async function createFolder'),
|
||||
source.indexOf('// Inline rename:'),
|
||||
)
|
||||
|
||||
assert.match(createFolder, /expandWikiDirectoryPath/)
|
||||
assert.match(createFolder, /preserveDirectoryState:\s*true/)
|
||||
assert.match(createFolder, /scrollTop/)
|
||||
})
|
||||
@@ -0,0 +1,45 @@
|
||||
export interface WikiDirectoryState {
|
||||
collapsed: Set<string>
|
||||
touched: Set<string>
|
||||
}
|
||||
|
||||
function directoryPathKey(type: string, parts: string[]): string {
|
||||
return `${type}:${parts.join('/')}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep every directory in the current path expanded across a data refresh.
|
||||
* Marking the path as touched prevents default initialization from collapsing
|
||||
* it again when the refreshed folder and page batches arrive.
|
||||
*/
|
||||
export function expandWikiDirectoryPath(
|
||||
type: string,
|
||||
path: string[],
|
||||
collapsed: ReadonlySet<string>,
|
||||
touched: ReadonlySet<string>,
|
||||
): WikiDirectoryState {
|
||||
const nextCollapsed = new Set(collapsed)
|
||||
const nextTouched = new Set(touched)
|
||||
|
||||
for (let depth = 1; depth <= path.length; depth++) {
|
||||
const key = directoryPathKey(type, path.slice(0, depth))
|
||||
nextCollapsed.delete(key)
|
||||
nextTouched.add(key)
|
||||
}
|
||||
|
||||
return { collapsed: nextCollapsed, touched: nextTouched }
|
||||
}
|
||||
|
||||
/** Return expanded, user-touched paths in parent-first order for reloading. */
|
||||
export function expandedWikiDirectoryPaths(
|
||||
type: string,
|
||||
collapsed: ReadonlySet<string>,
|
||||
touched: ReadonlySet<string>,
|
||||
): string[][] {
|
||||
const prefix = `${type}:`
|
||||
return [...touched]
|
||||
.filter(key => key.startsWith(prefix) && !collapsed.has(key))
|
||||
.map(key => key.slice(prefix.length).split('/').filter(Boolean))
|
||||
.filter(path => path.length > 0)
|
||||
.sort((left, right) => left.length - right.length)
|
||||
}
|
||||
@@ -0,0 +1,342 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import {
|
||||
selectGraphAnchors, buildGraphLayout, graphNodeRadius, stepGraphLayout, visibleGraphLabels, initialGraphViewport, graphPointBounds, graphClusterOutline,
|
||||
type ForceNode, type GraphLink, type LayoutInput,
|
||||
} from './wikiGraphLayout.ts'
|
||||
|
||||
function simulate(inputs: LayoutInput[], edges: GraphLink[], prior = new Map<string, { x: number; y: number }>()) {
|
||||
const layout = buildGraphLayout(inputs, edges, 1200, 800, prior)
|
||||
const nodes: ForceNode[] = inputs.map(n => ({
|
||||
slug: n.slug, linkCount: n.link_count, ...layout.placements.get(n.slug)!,
|
||||
vx: 0, vy: 0, pinned: false,
|
||||
}))
|
||||
const retained = new Set(prior.keys())
|
||||
for (let alpha = 1; alpha >= 0.02; alpha *= 0.985) stepGraphLayout(nodes, edges, layout.placements, alpha, retained)
|
||||
return { nodes, layout }
|
||||
}
|
||||
|
||||
test('disconnected groups stay apart and isolated pages distinguish missing visible links', () => {
|
||||
const inputs = [
|
||||
{ slug: 'a', link_count: 1 }, { slug: 'b', link_count: 1 },
|
||||
{ slug: 'c', link_count: 1 }, { slug: 'd', link_count: 1 },
|
||||
{ slug: 'orphan', link_count: 0 }, { slug: 'outside', link_count: 3 },
|
||||
]
|
||||
const edges = [{ source: 'a', target: 'b' }, { source: 'd', target: 'c' }, { source: 'outside', target: 'not-loaded' }]
|
||||
const { nodes, layout } = simulate(inputs, edges)
|
||||
assert.deepEqual(layout.sections.map(s => [s.kind, s.count]), [['offscreen', 1], ['unlinked', 1]])
|
||||
const a = nodes.find(n => n.slug === 'a')!, b = nodes.find(n => n.slug === 'b')!
|
||||
const c = nodes.find(n => n.slug === 'c')!, d = nodes.find(n => n.slug === 'd')!
|
||||
const within = Math.max(Math.hypot(a.x - b.x, a.y - b.y), Math.hypot(c.x - d.x, c.y - d.y))
|
||||
for (const first of [a, b]) for (const second of [c, d]) {
|
||||
assert.ok(Math.hypot(first.x - second.x, first.y - second.y) > within)
|
||||
}
|
||||
for (const section of layout.sections) {
|
||||
const node = nodes.find(n => n.slug === (section.kind === 'unlinked' ? 'orphan' : 'outside'))!
|
||||
assert.ok(node.x > section.left && node.x < section.right && node.y > section.top && node.y < section.bottom)
|
||||
}
|
||||
})
|
||||
|
||||
test('initial positions are stable across API ordering and reverse links', () => {
|
||||
const inputs = Array.from({ length: 20 }, (_, i) => ({ slug: `p${i}`, link_count: 2 }))
|
||||
const edges = inputs.slice(1).map(n => ({ source: 'p0', target: n.slug }))
|
||||
const a = buildGraphLayout(inputs, edges, 900, 600)
|
||||
const b = buildGraphLayout([...inputs].reverse(), [...edges].reverse().map(e => ({ source: e.target, target: e.source })), 900, 600)
|
||||
for (const n of inputs) assert.deepEqual(a.placements.get(n.slug), b.placements.get(n.slug))
|
||||
})
|
||||
|
||||
test('many small components pack without overlap or forming rows', t => {
|
||||
const inputs = Array.from({ length: 500 }, (_, i) => ({ slug: `pair${i}`, link_count: 1 }))
|
||||
const edges = inputs.flatMap((n, i) => i % 2 ? [{ source: `pair${i - 1}`, target: n.slug }] : [])
|
||||
const start = performance.now()
|
||||
const { clusters } = buildGraphLayout(inputs, edges, 1400, 900)
|
||||
t.diagnostic(`250 components packed in ${Math.round(performance.now() - start)} ms`)
|
||||
assert.equal(clusters.length, 250)
|
||||
assert.ok(new Set(clusters.map(c => Math.round(c.y))).size > 100)
|
||||
for (let i = 0; i < clusters.length; i++) for (let j = i + 1; j < clusters.length; j++) {
|
||||
const a = clusters[i]!, b = clusters[j]!
|
||||
assert.ok(a.right <= b.left || a.left >= b.right || a.bottom <= b.top || a.top >= b.bottom)
|
||||
}
|
||||
})
|
||||
|
||||
test('empty and entirely unlinked graphs have finite, nonoverlapping positions', () => {
|
||||
assert.equal(buildGraphLayout([], [], 800, 600).placements.size, 0)
|
||||
const inputs = Array.from({ length: 500 }, (_, i) => ({ slug: `orphan${i}`, link_count: 0 }))
|
||||
const { nodes, layout } = simulate(inputs, [])
|
||||
assert.deepEqual(layout.sections.map(s => [s.kind, s.count]), [['unlinked', 500]])
|
||||
for (let i = 0; i < nodes.length; i++) for (let j = i + 1; j < nodes.length; j++) {
|
||||
assert.ok(Math.hypot(nodes[i]!.x - nodes[j]!.x, nodes[i]!.y - nodes[j]!.y) > 50)
|
||||
}
|
||||
})
|
||||
|
||||
test('500 and 1500 node graphs settle with finite positions and node clearance', t => {
|
||||
for (const count of [500, 1500]) {
|
||||
const inputs = Array.from({ length: count }, (_, i) => ({ slug: `p${i}`, link_count: i % 50 === 0 ? 49 : 1 }))
|
||||
const edges = inputs.flatMap((n, i) => i % 50 ? [{ source: `p${i - i % 50}`, target: n.slug }] : [])
|
||||
const start = performance.now()
|
||||
const { nodes } = simulate(inputs, edges)
|
||||
t.diagnostic(`${count} nodes settled in ${Math.round(performance.now() - start)} ms (pure layout, no DOM)`)
|
||||
for (const n of nodes) {
|
||||
assert.ok(Number.isFinite(n.x) && Number.isFinite(n.y))
|
||||
}
|
||||
for (let i = 0; i < nodes.length; i++) for (let j = i + 1; j < nodes.length; j++) {
|
||||
const a = nodes[i]!, b = nodes[j]!
|
||||
assert.ok(Math.hypot(a.x - b.x, a.y - b.y) >= graphNodeRadius(a.linkCount) + graphNodeRadius(b.linkCount) + 15,
|
||||
`${count}: ${a.slug} overlaps ${b.slug}`)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
test('incremental expansion holds existing nodes and settles new neighbors', () => {
|
||||
const prior = new Map([['a', { x: 111, y: 222 }], ['b', { x: 260, y: 222 }]])
|
||||
const inputs = Array.from({ length: 30 }, (_, i) => ({ slug: i === 0 ? 'a' : i === 1 ? 'b' : `new${i}`, link_count: 1 }))
|
||||
const edges = inputs.slice(1).map(n => ({ source: 'a', target: n.slug }))
|
||||
const { nodes } = simulate(inputs, edges, prior)
|
||||
for (const [slug, point] of prior) {
|
||||
const n = nodes.find(n => n.slug === slug)!
|
||||
assert.deepEqual({ x: n.x, y: n.y }, point)
|
||||
}
|
||||
for (const n of nodes.slice(2)) {
|
||||
assert.ok(Number.isFinite(n.x) && Number.isFinite(n.y))
|
||||
assert.ok(Math.hypot(n.x - 111, n.y - 222) > 32)
|
||||
}
|
||||
})
|
||||
|
||||
test('a large hub with 1499 neighbors settles with node clearance', t => {
|
||||
const inputs = Array.from({ length: 1500 }, (_, i) => ({ slug: `hub${i}`, link_count: i ? 1 : 1499 }))
|
||||
const edges = inputs.slice(1).map(n => ({ source: 'hub0', target: n.slug }))
|
||||
const start = performance.now()
|
||||
const { nodes } = simulate(inputs, edges)
|
||||
t.diagnostic(`1500 nodes in one component settled in ${Math.round(performance.now() - start)} ms (no DOM)`)
|
||||
for (let i = 0; i < nodes.length; i++) for (let j = i + 1; j < nodes.length; j++) {
|
||||
const a = nodes[i]!, b = nodes[j]!
|
||||
assert.ok(Math.hypot(a.x - b.x, a.y - b.y) >= graphNodeRadius(a.linkCount) + graphNodeRadius(b.linkCount) + 14,
|
||||
`${a.slug} overlaps ${b.slug}`)
|
||||
}
|
||||
})
|
||||
|
||||
test('collision separates coincident nodes while respecting a dragged pin', () => {
|
||||
const inputs = [{ slug: 'a', link_count: 10 }, { slug: 'b', link_count: 10 }]
|
||||
const layout = buildGraphLayout(inputs, [{ source: 'a', target: 'b' }], 800, 600)
|
||||
const nodes: ForceNode[] = inputs.map(n => ({ slug: n.slug, linkCount: n.link_count, x: 400, y: 300, vx: 0, vy: 0, pinned: n.slug === 'a' }))
|
||||
for (let i = 0; i < 10; i++) stepGraphLayout(nodes, [], layout.placements, 0.02)
|
||||
assert.equal(nodes[0]!.x, 400)
|
||||
assert.equal(nodes[0]!.y, 300)
|
||||
assert.ok(Math.hypot(nodes[0]!.x - nodes[1]!.x, nodes[0]!.y - nodes[1]!.y) >= graphNodeRadius(10) * 2 + 15)
|
||||
})
|
||||
|
||||
test('overlapping labels favor important nodes, but focused labels always stay readable', () => {
|
||||
const box = { left: 0, right: 100, top: 0, bottom: 20 }
|
||||
const labels = [
|
||||
{ ...box, slug: 'low', priority: 1 }, { ...box, slug: 'high', priority: 20 },
|
||||
{ ...box, left: 200, right: 300, slug: 'separate', priority: 0 },
|
||||
]
|
||||
assert.deepEqual([...visibleGraphLabels(labels)], ['high', 'separate'])
|
||||
assert.deepEqual([...visibleGraphLabels([...labels, { ...box, slug: 'selected', priority: 0, required: true }])], ['selected', 'separate'])
|
||||
})
|
||||
|
||||
|
||||
test('long chains keep their elongated topology and reserve space away from other groups', () => {
|
||||
const inputs = Array.from({ length: 40 }, (_, i) => ({ slug: `chain${String(i).padStart(2, '0')}`, link_count: 2 }))
|
||||
const edges = inputs.flatMap((n, i) => i % 20 ? [{ source: inputs[i - 1]!.slug, target: n.slug }] : [])
|
||||
const { nodes, layout } = simulate(inputs, edges)
|
||||
for (const cluster of layout.clusters) {
|
||||
const members = nodes.filter(n => cluster.slugs.includes(n.slug))
|
||||
const bounds = graphPointBounds(members)
|
||||
const mean = { x: members.reduce((s, n) => s + n.x, 0) / members.length, y: members.reduce((s, n) => s + n.y, 0) / members.length }
|
||||
const xx = members.reduce((s, n) => s + (n.x - mean.x) ** 2, 0)
|
||||
const yy = members.reduce((s, n) => s + (n.y - mean.y) ** 2, 0)
|
||||
const xy = members.reduce((s, n) => s + (n.x - mean.x) * (n.y - mean.y), 0)
|
||||
const delta = Math.hypot(xx - yy, 2 * xy)
|
||||
// Principal axes make this invariant to the chain's heading.
|
||||
assert.ok((xx + yy + delta) / Math.max(1, xx + yy - delta) > 9)
|
||||
assert.ok(Math.hypot(bounds.right - bounds.left, bounds.bottom - bounds.top) > 1500)
|
||||
}
|
||||
const first = nodes.slice(0, 20), second = nodes.slice(20)
|
||||
for (const a of first) for (const b of second) assert.ok(Math.hypot(a.x - b.x, a.y - b.y) > 250)
|
||||
})
|
||||
|
||||
test('large canvases start readable around the focus instead of fitting every node', () => {
|
||||
const points = [{ x: -4000, y: -2000 }, { x: 5000, y: 3000 }]
|
||||
const focus = { x: 300, y: 400 }
|
||||
const view = initialGraphViewport(points, 1200, 800, focus)
|
||||
assert.equal(view.scale, 0.4)
|
||||
assert.equal(focus.x * view.scale + view.x, 600)
|
||||
assert.equal(focus.y * view.scale + view.y, 400)
|
||||
assert.ok(points[1]!.x * view.scale + view.x > 1200)
|
||||
assert.equal(initialGraphViewport([{ x: 0, y: 0 }, { x: 100, y: 100 }], 1200, 800).scale, 0.85)
|
||||
assert.ok(Object.values(initialGraphViewport([], 1200, 800)).every(Number.isFinite))
|
||||
})
|
||||
|
||||
|
||||
test('group outlines follow displaced nodes and handle empty or coincident input', () => {
|
||||
assert.equal(graphClusterOutline([]), '')
|
||||
for (const points of [[{ x: 0, y: 0 }], [{ x: 0, y: 0 }, { x: 0, y: 0 }], [{ x: 0, y: 0 }, { x: 200, y: 10 }, { x: 800, y: 400 }]]) {
|
||||
const path = graphClusterOutline(points)
|
||||
assert.ok(path.startsWith('M') && path.endsWith('Z'))
|
||||
assert.ok(!path.includes('NaN') && !path.includes('Infinity'))
|
||||
assert.equal(graphClusterOutline([...points].reverse()), path)
|
||||
}
|
||||
assert.notEqual(graphClusterOutline([{ x: 0, y: 0 }, { x: 200, y: 0 }]), graphClusterOutline([{ x: 0, y: 0 }, { x: 400, y: 0 }]))
|
||||
})
|
||||
|
||||
|
||||
test('landmarks cover separate dense neighborhoods instead of only the largest one', () => {
|
||||
const sizes = [40, 30, 20]
|
||||
const slugs = sizes.flatMap((size, group) => Array.from({ length: size }, (_, i) => `region${group}-${i}`))
|
||||
const adjacency = new Map(slugs.map(slug => [slug, new Set<string>()]))
|
||||
const link = (a: string, b: string) => { adjacency.get(a)!.add(b); adjacency.get(b)!.add(a) }
|
||||
sizes.forEach((size, group) => {
|
||||
for (let i = 0; i < size; i++) for (let j = i + 1; j < size; j++) link(`region${group}-${i}`, `region${group}-${j}`)
|
||||
})
|
||||
link('region0-0', 'region1-0'); link('region1-0', 'region2-0')
|
||||
const anchors = selectGraphAnchors(slugs, adjacency)
|
||||
assert.equal(anchors.length, 3)
|
||||
assert.equal(new Set(anchors.map(slug => slug.split('-')[0])).size, 3)
|
||||
const reversed = new Map([...adjacency].reverse().map(([slug, neighbors]) => [slug, new Set([...neighbors].reverse())]))
|
||||
assert.deepEqual(selectGraphAnchors([...slugs].reverse(), reversed), anchors)
|
||||
})
|
||||
|
||||
test('one hub does not create artificial extra themes and external neighbors do not affect landmarks', () => {
|
||||
const slugs = Array.from({ length: 200 }, (_, i) => `page${i}`)
|
||||
const adjacency = new Map(slugs.map(slug => [slug, new Set<string>()]))
|
||||
for (const slug of slugs.slice(1)) { adjacency.get('page0')!.add(slug); adjacency.get(slug)!.add('page0') }
|
||||
adjacency.get('page199')!.add('outside-the-component')
|
||||
assert.deepEqual(selectGraphAnchors(slugs, adjacency), ['page0'])
|
||||
assert.deepEqual(selectGraphAnchors([], adjacency), [])
|
||||
})
|
||||
|
||||
test('landmark budgets scale from small to large components with a maximum of five', () => {
|
||||
for (const [size, expected] of [[10, 1], [30, 2], [75, 3], [150, 4], [500, 5]]) {
|
||||
const slugs = Array.from({ length: size! }, (_, i) => `p${i}`)
|
||||
const adjacency = new Map(slugs.map((slug, i) => [slug, new Set([slugs[i - 1], slugs[i + 1]].filter((s): s is string => !!s))]))
|
||||
const anchors = selectGraphAnchors(slugs, adjacency)
|
||||
assert.equal(anchors.length, expected)
|
||||
assert.equal(new Set(anchors).size, expected)
|
||||
if (size! >= 30) {
|
||||
const indices = anchors.map(slug => Number(slug.slice(1)))
|
||||
assert.ok(Math.max(...indices) - Math.min(...indices) > size! * 0.7)
|
||||
}
|
||||
const inputs = slugs.map(slug => ({ slug, link_count: adjacency.get(slug)!.size }))
|
||||
const edges = slugs.slice(1).map((slug, i) => ({ source: slugs[i]!, target: slug }))
|
||||
assert.deepEqual(buildGraphLayout(inputs, edges, 1200, 800).clusters[0]!.anchors, anchors)
|
||||
}
|
||||
})
|
||||
|
||||
test('the main subject leads, and a separate configuration theme is named instead of a second name for the same theme', () => {
|
||||
const names = ['platform', 'enterprise', 'configuration',
|
||||
...Array.from({ length: 12 }, (_, i) => `shared${i}`),
|
||||
...Array.from({ length: 10 }, (_, i) => `platformDetail${i}`),
|
||||
...Array.from({ length: 4 }, (_, i) => `enterpriseDetail${i}`),
|
||||
...Array.from({ length: 6 }, (_, i) => `configurationDetail${i}`)]
|
||||
const adjacency = new Map(names.map(slug => [slug, new Set<string>()]))
|
||||
const edges: GraphLink[] = []
|
||||
const link = (a: string, b: string) => { adjacency.get(a)!.add(b); adjacency.get(b)!.add(a); edges.push({ source: a, target: b }) }
|
||||
for (let i = 0; i < 12; i++) { link('platform', `shared${i}`); link('enterprise', `shared${i}`) }
|
||||
for (let i = 0; i < 10; i++) link('platform', `platformDetail${i}`)
|
||||
for (let i = 0; i < 4; i++) link('enterprise', `enterpriseDetail${i}`)
|
||||
for (let i = 0; i < 6; i++) link('configuration', `configurationDetail${i}`)
|
||||
for (let i = 0; i < 3; i++) link('configuration', `shared${i}`)
|
||||
link('platform', 'enterprise'); link('enterprise', 'configuration')
|
||||
const nodes = names.map(slug => ({ slug, link_count: adjacency.get(slug)!.size,
|
||||
page_type: ['platform', 'enterprise'].includes(slug) ? 'entity' : 'concept' }))
|
||||
const layout = buildGraphLayout(nodes, edges, 1200, 800)
|
||||
// enterprise shares twelve neighbors with platform: one theme, one name.
|
||||
assert.deepEqual(layout.clusters[0]!.anchors, ['platform', 'configuration'])
|
||||
assert.deepEqual(buildGraphLayout([...nodes].reverse(), [...edges].reverse(), 1200, 800).clusters[0]!.anchors, layout.clusters[0]!.anchors)
|
||||
})
|
||||
|
||||
test('a subject linked to most pages of every theme names the component alone', () => {
|
||||
const slugs = ['hub', ...Array.from({ length: 3 }, (_, g) => Array.from({ length: 10 }, (_, i) => `t${g}-${i}`)).flat()]
|
||||
const adjacency = new Map(slugs.map(slug => [slug, new Set<string>()]))
|
||||
const link = (a: string, b: string) => { adjacency.get(a)!.add(b); adjacency.get(b)!.add(a) }
|
||||
for (let g = 0; g < 3; g++) {
|
||||
for (let i = 0; i < 10; i++) for (let j = i + 1; j < 10; j++) link(`t${g}-${i}`, `t${g}-${j}`)
|
||||
// One document: its subject links to nearly every page in each section.
|
||||
for (let i = 0; i < 8; i++) link('hub', `t${g}-${i}`)
|
||||
}
|
||||
assert.deepEqual(selectGraphAnchors(slugs, adjacency), ['hub'])
|
||||
})
|
||||
|
||||
test('a theme is not named again by a page whose title repeats an existing label', () => {
|
||||
const sizes = [30, 20]
|
||||
const slugs = sizes.flatMap((size, g) => Array.from({ length: size }, (_, i) => `r${g}-${i}`))
|
||||
const adjacency = new Map(slugs.map(slug => [slug, new Set<string>()]))
|
||||
const link = (a: string, b: string) => { adjacency.get(a)!.add(b); adjacency.get(b)!.add(a) }
|
||||
sizes.forEach((size, g) => {
|
||||
for (let i = 0; i < size; i++) for (let j = i + 1; j < size; j++) link(`r${g}-${i}`, `r${g}-${j}`)
|
||||
})
|
||||
link('r0-0', 'r1-0')
|
||||
const pages = new Map([
|
||||
['r0-0', { page_type: 'concept', title: '第三代社保卡' }],
|
||||
['r1-0', { page_type: 'entity', title: '北京市第三代社保卡' }],
|
||||
['r1-1', { page_type: 'concept', title: '线上申领' }],
|
||||
])
|
||||
assert.deepEqual(selectGraphAnchors(slugs, adjacency, pages), ['r0-0', 'r1-1'])
|
||||
})
|
||||
|
||||
test('a summary names the document it dominates, but a nearly as central entity still wins', () => {
|
||||
const pages = new Map([
|
||||
['summary', { page_type: 'summary', title: '初中63组语文古诗词高频考点(2).pdf - Summary' }],
|
||||
['subject', { page_type: 'entity', title: '范仲淹' }],
|
||||
])
|
||||
const anchorsWhenSubjectLinks = (details: number) => {
|
||||
const slugs = ['summary', 'subject', ...Array.from({ length: 10 }, (_, i) => `detail${i}`)]
|
||||
const adjacency = new Map(slugs.map(slug => [slug, new Set<string>()]))
|
||||
const link = (a: string, b: string) => { adjacency.get(a)!.add(b); adjacency.get(b)!.add(a) }
|
||||
for (const slug of slugs.slice(1)) link('summary', slug)
|
||||
for (let i = 0; i < details; i++) link('subject', `detail${i}`)
|
||||
return selectGraphAnchors(slugs, adjacency, pages)
|
||||
}
|
||||
assert.deepEqual(anchorsWhenSubjectLinks(5), ['summary'])
|
||||
assert.deepEqual(anchorsWhenSubjectLinks(9), ['subject'])
|
||||
})
|
||||
|
||||
test('a component of several documents also names the page they share', () => {
|
||||
const anchorsWithBridgeDetails = (details: number) => {
|
||||
const slugs: string[] = ['bridge']
|
||||
const adjacency = new Map<string, Set<string>>([['bridge', new Set()]])
|
||||
const link = (a: string, b: string) => {
|
||||
for (const s of [a, b]) if (!adjacency.has(s)) { adjacency.set(s, new Set()); slugs.push(s) }
|
||||
adjacency.get(a)!.add(b); adjacency.get(b)!.add(a)
|
||||
}
|
||||
const pages = new Map<string, { page_type: string; title: string }>([['bridge', { page_type: 'concept', title: '强化学习' }]])
|
||||
for (let d = 0; d < 3; d++) {
|
||||
pages.set(`doc${d}`, { page_type: 'summary', title: `论文${d}.pdf - Summary` })
|
||||
for (let i = 0; i < 8; i++) {
|
||||
link(`doc${d}`, `d${d}-${i}`)
|
||||
if (i > 0) link(`d${d}-${i}`, `d${d}-${i - 1}`)
|
||||
}
|
||||
link('bridge', `doc${d}`)
|
||||
for (let i = 0; i < details; i++) link('bridge', `d${d}-${i}`)
|
||||
}
|
||||
return selectGraphAnchors(slugs, adjacency, pages)
|
||||
}
|
||||
const named = anchorsWithBridgeDetails(1)
|
||||
assert.equal(named.at(-1), 'bridge')
|
||||
assert.ok(named.slice(0, -1).every(slug => slug.startsWith('doc')), named.join())
|
||||
// Shared by every document but barely linked: a detail, not what ties them.
|
||||
assert.ok(!anchorsWithBridgeDetails(0).includes('bridge'))
|
||||
})
|
||||
|
||||
test('an identifier-like file name does not name a theme over a readable page', () => {
|
||||
const slugs = ['summary', 'subject', ...Array.from({ length: 10 }, (_, i) => `detail${i}`)]
|
||||
const adjacency = new Map(slugs.map(slug => [slug, new Set<string>()]))
|
||||
const link = (a: string, b: string) => { adjacency.get(a)!.add(b); adjacency.get(b)!.add(a) }
|
||||
for (const slug of slugs.slice(1)) link('summary', slug)
|
||||
for (let i = 0; i < 5; i++) link('subject', `detail${i}`)
|
||||
const pages = new Map([
|
||||
['summary', { page_type: 'summary', title: '2412.18925v1.pdf - Summary' }],
|
||||
['subject', { page_type: 'entity', title: '香港中文大学(深圳)' }],
|
||||
])
|
||||
assert.deepEqual(selectGraphAnchors(slugs, adjacency, pages), ['subject'])
|
||||
})
|
||||
|
||||
test('entity preference breaks a close ranking without displacing a substantially stronger concept', () => {
|
||||
const inputs = Array.from({ length: 12 }, (_, i) => ({ slug: `page${i}`, link_count: 0, page_type: i === 1 ? 'entity' : 'concept' }))
|
||||
const edges = inputs.slice(1).map(n => ({ source: 'page0', target: n.slug }))
|
||||
assert.deepEqual(buildGraphLayout(inputs, edges, 1200, 800).clusters[0]!.anchors, ['page0'])
|
||||
// Two equally connected pages: the entity is the more useful overview anchor.
|
||||
const pair = [{ slug: 'a-concept', link_count: 1, page_type: 'concept' }, { slug: 'z-entity', link_count: 1, page_type: 'entity' }]
|
||||
assert.deepEqual(buildGraphLayout(pair, [{ source: pair[0]!.slug, target: pair[1]!.slug }], 1200, 800).clusters[0]!.anchors, ['z-entity'])
|
||||
})
|
||||
@@ -0,0 +1,579 @@
|
||||
// Geometry is independent of SVG so dense and disconnected graphs can be
|
||||
// exercised without a browser. Coordinates are world units, not screen pixels.
|
||||
export interface GraphPoint { x: number; y: number }
|
||||
export interface GraphLink { source: string; target: string }
|
||||
export interface LayoutInput { slug: string; link_count: number; page_type?: string; title?: string }
|
||||
export interface GraphBounds { left: number; top: number; right: number; bottom: number }
|
||||
export interface LayoutPlacement extends GraphPoint {
|
||||
center: GraphPoint
|
||||
stationary?: boolean
|
||||
degree?: number
|
||||
}
|
||||
export interface GraphCluster extends GraphPoint, GraphBounds {
|
||||
slugs: string[]
|
||||
representative: string
|
||||
anchors: string[]
|
||||
}
|
||||
export interface GraphSection extends GraphBounds {
|
||||
kind: 'unlinked' | 'offscreen'
|
||||
count: number
|
||||
}
|
||||
|
||||
export function graphNodeRadius(linkCount: number): number {
|
||||
// Square-root scaling keeps leaves small so hubs read as landmarks.
|
||||
return Math.max(5, Math.min(20, 4 + Math.sqrt(Math.max(0, linkCount)) * 1.8))
|
||||
}
|
||||
|
||||
/** Deterministic multi-level Louvain over an undirected, unweighted graph.
|
||||
* Returns a community index per node; callers must pass nodes in a stable
|
||||
* order because ties are resolved by index.
|
||||
*/
|
||||
export function graphCommunities(neighbors: readonly (readonly number[])[]): number[] {
|
||||
const n = neighbors.length
|
||||
let membership = Array.from({ length: n }, (_, i) => i)
|
||||
// Level graph: weighted adjacency between super-nodes plus the weight of
|
||||
// edges already collapsed inside each super-node.
|
||||
let weights: Map<number, number>[] = neighbors.map(list => {
|
||||
const row = new Map<number, number>()
|
||||
for (const j of list) row.set(j, (row.get(j) ?? 0) + 1)
|
||||
return row
|
||||
})
|
||||
let inner = new Array<number>(n).fill(0)
|
||||
for (;;) {
|
||||
const size = weights.length
|
||||
const degree = weights.map((row, i) => [...row.values()].reduce((sum, w) => sum + w, 0) + 2 * inner[i]!)
|
||||
const total = degree.reduce((sum, d) => sum + d, 0)
|
||||
if (!total) break
|
||||
const community = Array.from({ length: size }, (_, i) => i)
|
||||
const tot = [...degree]
|
||||
let movedAny = false
|
||||
for (let pass = 0; pass < 32; pass++) {
|
||||
let moved = false
|
||||
for (let i = 0; i < size; i++) {
|
||||
const own = community[i]!
|
||||
const links = new Map<number, number>()
|
||||
for (const [j, w] of weights[i]!) links.set(community[j]!, (links.get(community[j]!) ?? 0) + w)
|
||||
tot[own] -= degree[i]!
|
||||
let best = own, bestGain = (links.get(own) ?? 0) - tot[own]! * degree[i]! / total
|
||||
for (const c of [...links.keys()].sort((a, b) => a - b)) {
|
||||
const gain = links.get(c)! - tot[c]! * degree[i]! / total
|
||||
if (gain > bestGain + 1e-9) { best = c; bestGain = gain }
|
||||
}
|
||||
tot[best] += degree[i]!
|
||||
if (best !== own) { community[i] = best; moved = true; movedAny = true }
|
||||
}
|
||||
if (!moved) break
|
||||
}
|
||||
if (!movedAny) break
|
||||
const renumber = new Map<number, number>()
|
||||
for (const c of community) if (!renumber.has(c)) renumber.set(c, renumber.size)
|
||||
const next = Array.from({ length: renumber.size }, () => new Map<number, number>())
|
||||
const nextInner = new Array<number>(renumber.size).fill(0)
|
||||
for (let i = 0; i < size; i++) {
|
||||
const ci = renumber.get(community[i]!)!
|
||||
nextInner[ci] += inner[i]!
|
||||
for (const [j, w] of weights[i]!) {
|
||||
const cj = renumber.get(community[j]!)!
|
||||
// Each undirected edge appears in both rows; count it once inside.
|
||||
if (ci === cj) nextInner[ci] += w / 2
|
||||
else next[ci]!.set(cj, (next[ci]!.get(cj) ?? 0) + w)
|
||||
}
|
||||
}
|
||||
membership = membership.map(c => renumber.get(community[c]!)!)
|
||||
weights = next; inner = nextInner
|
||||
if (renumber.size === size) break
|
||||
}
|
||||
return membership
|
||||
}
|
||||
|
||||
/** Landmark caption text: summary pages carry their source file name. */
|
||||
export function graphLandmarkTitle(title: string): string {
|
||||
const name = title.replace(/\s*-\s*Summary$/i, '')
|
||||
.replace(/\.(pdf|docx?|pptx?|xlsx?|csv|md|txt|html?|json|ya?ml|xml|png|jpe?g)$/i, '')
|
||||
.replace(/\s*[((]\d+[))]$/, '').trim()
|
||||
return name || title
|
||||
}
|
||||
|
||||
// A summary is named after its source file, which usually names the document
|
||||
// well, so it only yields near-ties to entities and concepts. Index pages are
|
||||
// navigation and a poor name for a region even when they link to all of it.
|
||||
const anchorTypeQuality: Record<string, number> = {
|
||||
entity: 1.15, concept: 1, synthesis: 0.8, comparison: 0.8, summary: 0.9, index: 0.2,
|
||||
}
|
||||
|
||||
/** Name a connected component and its distinct themes.
|
||||
* The first landmark is the component's most prominent readable page, even
|
||||
* when it bridges every theme. Communities are the themes; each contributes
|
||||
* at most one landmark, chosen by its links inside the theme and how well its
|
||||
* title reads as a name. Themes mostly linked to an existing landmark, and
|
||||
* pages that repeat one, get no extra name. Later picks favor larger themes
|
||||
* far from earlier labels so names spread instead of stacking up. A component
|
||||
* built from several documents also names the page most of them share.
|
||||
*/
|
||||
export function selectGraphAnchors(
|
||||
slugs: string[], adjacency: ReadonlyMap<string, ReadonlySet<string>>,
|
||||
pages: ReadonlyMap<string, Pick<LayoutInput, 'page_type' | 'title'>> = new Map(),
|
||||
): string[] {
|
||||
if (!slugs.length) return []
|
||||
const order = [...new Set(slugs)].sort()
|
||||
const index = new Map(order.map((slug, i) => [slug, i]))
|
||||
const neighbors = order.map(slug => [...(adjacency.get(slug) ?? [])]
|
||||
.flatMap(n => index.has(n) && n !== slug ? [index.get(n)!] : []).sort((a, b) => a - b))
|
||||
const membership = graphCommunities(neighbors)
|
||||
const groups = new Map<number, number[]>()
|
||||
membership.forEach((c, i) => { const group = groups.get(c) ?? []; group.push(i); groups.set(c, group) })
|
||||
|
||||
const quality = (i: number) => {
|
||||
const page = pages.get(order[i]!)
|
||||
const title = graphLandmarkTitle(page?.title ?? '')
|
||||
// An identifier such as an arXiv file name ("2412.18925v1") has no word to read.
|
||||
const readable = /[\u4e00-\u9fff]{2}|[a-z]{3}/i.test(title) ? 1 : 0.3
|
||||
return (anchorTypeQuality[page?.page_type ?? ''] ?? 1) * (title.length > 18 ? 0.6 : 1) * readable
|
||||
}
|
||||
const best = (group: number[], score: (i: number) => number) => group.reduce((top, i) => {
|
||||
const a = score(i), b = score(top)
|
||||
return a > b + 1e-9 || (Math.abs(a - b) <= 1e-9 && neighbors[i]!.length > neighbors[top]!.length) ? i : top
|
||||
})
|
||||
// A theme is named by a page that lives in it; links elsewhere still count
|
||||
// for some prominence.
|
||||
const themes = [...groups.values()].map(group => {
|
||||
const inside = new Set(group)
|
||||
const score = (i: number) => {
|
||||
const internal = neighbors[i]!.filter(j => inside.has(j)).length
|
||||
return (internal + 0.5 * (neighbors[i]!.length - internal) + 1) * quality(i)
|
||||
}
|
||||
const ranked = [...group].sort((a, b) => score(b) - score(a) || neighbors[b]!.length - neighbors[a]!.length || a - b)
|
||||
return { size: group.length, ranked, members: inside }
|
||||
}).sort((a, b) => b.size - a.size || a.ranked[0]! - b.ranked[0]!)
|
||||
|
||||
const name = best(order.map((_, i) => i), i => (neighbors[i]!.length + 1) * quality(i))
|
||||
const home = themes.find(theme => theme.members.has(name))!
|
||||
// Fragments of a theme are not themes of their own.
|
||||
const minimum = Math.max(3, themes[0]!.size * 0.3)
|
||||
const candidates = themes.filter(theme => theme !== home && theme.size >= minimum)
|
||||
// A second name for something already labeled: nearly the same
|
||||
// neighborhood (an author next to their paper) or a title that contains
|
||||
// the other ("北京市第三代社保卡" next to "第三代社保卡").
|
||||
const closed = (i: number) => new Set([i, ...neighbors[i]!])
|
||||
const normalized = (i: number) => graphLandmarkTitle(pages.get(order[i]!)?.title ?? '')
|
||||
.toLowerCase().replace(/[\s《》“”"'‘’()()·・]/g, '')
|
||||
const redundant = (i: number, chosen: number[]) => chosen.some(s => {
|
||||
const a = closed(i), b = closed(s)
|
||||
const shared = [...a].filter(x => b.has(x)).length
|
||||
if (shared / (a.size + b.size - shared) >= 0.5) return true
|
||||
const x = normalized(i), y = normalized(s)
|
||||
return !!x && !!y && (x.includes(y) || y.includes(x))
|
||||
})
|
||||
const budget = order.length < 16 ? 1 : order.length < 50 ? 2 : order.length < 100 ? 3 : order.length < 200 ? 4 : 5
|
||||
const bfs = (start: number) => {
|
||||
const distance = new Array<number>(order.length).fill(Infinity)
|
||||
distance[start] = 0
|
||||
const queue = [start]
|
||||
for (let q = 0; q < queue.length; q++) {
|
||||
for (const j of neighbors[queue[q]!]!) {
|
||||
if (distance[j] !== Infinity) continue
|
||||
distance[j] = distance[queue[q]!]! + 1; queue.push(j)
|
||||
}
|
||||
}
|
||||
return distance
|
||||
}
|
||||
// Labels count as fully separated once they are a fair share of the
|
||||
// component's diameter apart; closer than that, a larger theme still wins.
|
||||
const nearest = bfs(name)
|
||||
const far = nearest.reduce((top, d, i) => d !== Infinity && d > nearest[top]! ? i : top, name)
|
||||
const diameter = Math.max(...bfs(far).filter(Number.isFinite))
|
||||
const reach = Math.max(2, diameter / budget)
|
||||
const selected = [name]
|
||||
const open = new Set(candidates)
|
||||
while (selected.length < budget && open.size) {
|
||||
let pick: { theme: typeof candidates[number]; label: number } | undefined, bestScore = -1
|
||||
for (const theme of open) {
|
||||
// Most of the theme already hangs off an existing label (one document
|
||||
// around its subject): another name would only be a detail page.
|
||||
const covered = selected.some(s => neighbors[s]!.filter(j => theme.members.has(j)).length * 2 >= theme.size)
|
||||
const label = covered ? undefined : theme.ranked.find(i => !redundant(i, selected))
|
||||
if (label === undefined) { open.delete(theme); continue }
|
||||
const score = Math.sqrt(theme.size) * Math.min(nearest[label]!, reach) / reach
|
||||
if (score > bestScore + 1e-9 || (Math.abs(score - bestScore) <= 1e-9 && pick && nearest[label]! > nearest[pick.label]!)) {
|
||||
pick = { theme, label }; bestScore = score
|
||||
}
|
||||
}
|
||||
if (!pick) break
|
||||
open.delete(pick.theme)
|
||||
selected.push(pick.label)
|
||||
bfs(pick.label).forEach((d, i) => { nearest[i] = Math.min(nearest[i]!, d) })
|
||||
}
|
||||
|
||||
// Themes mostly follow documents, so their names say which documents are
|
||||
// here but not why they belong together. A page shared by most of them
|
||||
// says that; it is added unless a label already is one.
|
||||
const documents = new Set(order.flatMap((slug, i) => pages.get(slug)?.page_type === 'summary' ? [i] : []))
|
||||
if (documents.size >= 2) {
|
||||
const spans = (i: number) => documents.has(i) ? 0 : neighbors[i]!.filter(j => documents.has(j)).length
|
||||
const needed = Math.max(2, Math.ceil(documents.size * 2 / 3))
|
||||
if (!selected.some(s => spans(s) >= needed)) {
|
||||
const weakest = Math.min(...selected.map(s => neighbors[s]!.length))
|
||||
const prominence = (i: number) => (neighbors[i]!.length + 1) * quality(i)
|
||||
const bridge = order.map((_, i) => i)
|
||||
.filter(i => spans(i) >= needed && neighbors[i]!.length >= weakest * 0.6 && !redundant(i, selected))
|
||||
.reduce<number | undefined>((top, i) => top === undefined || spans(i) > spans(top)
|
||||
|| (spans(i) === spans(top) && prominence(i) > prominence(top) + 1e-9) ? i : top, undefined)
|
||||
if (bridge !== undefined) selected.push(bridge)
|
||||
}
|
||||
}
|
||||
return selected.map(i => order[i]!)
|
||||
}
|
||||
|
||||
/** Pack connected components separately; singletons get two explicit shelves.
|
||||
* A missing visible edge is not evidence that the page has no links in the KB.
|
||||
*/
|
||||
export function buildGraphLayout(
|
||||
nodes: LayoutInput[], edges: GraphLink[], width: number, height: number,
|
||||
prior: ReadonlyMap<string, GraphPoint> = new Map(),
|
||||
) {
|
||||
const nodeBySlug = new Map(nodes.map(n => [n.slug, n]))
|
||||
const adjacency = new Map(nodes.map(n => [n.slug, new Set<string>()]))
|
||||
for (const e of edges) {
|
||||
if (e.source === e.target || !nodeBySlug.has(e.source) || !nodeBySlug.has(e.target)) continue
|
||||
adjacency.get(e.source)!.add(e.target)
|
||||
adjacency.get(e.target)!.add(e.source)
|
||||
}
|
||||
const components: string[][] = []
|
||||
const unlinked: string[] = []
|
||||
const offscreen: string[] = []
|
||||
const visited = new Set<string>()
|
||||
for (const slug of [...nodeBySlug.keys()].sort()) {
|
||||
if (visited.has(slug)) continue
|
||||
visited.add(slug)
|
||||
if (!adjacency.get(slug)!.size) {
|
||||
;(nodeBySlug.get(slug)!.link_count > 0 ? offscreen : unlinked).push(slug)
|
||||
continue
|
||||
}
|
||||
const component = [slug]
|
||||
for (let i = 0; i < component.length; i++) {
|
||||
for (const neighbor of adjacency.get(component[i]!)!) {
|
||||
if (visited.has(neighbor)) continue
|
||||
visited.add(neighbor)
|
||||
component.push(neighbor)
|
||||
}
|
||||
}
|
||||
components.push(component.sort())
|
||||
}
|
||||
components.sort((a, b) => b.length - a.length || (a[0]! < b[0]! ? -1 : 1))
|
||||
|
||||
// Reserve space from each component's topology, not a circular boundary.
|
||||
// These envelopes only place groups initially; the simulation never clips
|
||||
// nodes to them or pulls individual nodes towards a common center.
|
||||
const aspect = Math.min(1.8, Math.max(0.8, width / Math.max(height, 1)))
|
||||
const stretch = Math.sqrt(aspect)
|
||||
const goldenAngle = Math.PI * (3 - Math.sqrt(5))
|
||||
const clusters: GraphCluster[] = []
|
||||
const seeds = new Map<string, GraphPoint>()
|
||||
const cellSize = 500
|
||||
const cells = new Map<string, GraphCluster[]>()
|
||||
const keysFor = (bounds: GraphBounds) => {
|
||||
const keys: string[] = []
|
||||
for (let gx = Math.floor(bounds.left / cellSize); gx <= Math.floor(bounds.right / cellSize); gx++) {
|
||||
for (let gy = Math.floor(bounds.top / cellSize); gy <= Math.floor(bounds.bottom / cellSize); gy++) keys.push(`${gx},${gy}`)
|
||||
}
|
||||
return keys
|
||||
}
|
||||
for (const slugs of components) {
|
||||
const representative = [...slugs].sort((a, b) => adjacency.get(b)!.size - adjacency.get(a)!.size || (a < b ? -1 : 1))[0]!
|
||||
// Seed a spanning tree from the best-connected page. Branches follow
|
||||
// their parent direction, so chains and trees are not born as disks.
|
||||
const local = new Map<string, GraphPoint & { heading: number }>()
|
||||
local.set(representative, { x: 0, y: 0, heading: 0 })
|
||||
const queue = [representative]
|
||||
for (let cursor = 0; cursor < queue.length; cursor++) {
|
||||
const parentSlug = queue[cursor]!
|
||||
const parent = local.get(parentSlug)!
|
||||
const children = [...adjacency.get(parentSlug)!].filter(slug => !local.has(slug)).sort()
|
||||
children.forEach((slug, i) => {
|
||||
const heading = parent.heading + (cursor === 0 ? i * goldenAngle : ((i + 0.5) / children.length - 0.5) * Math.PI * 0.8)
|
||||
const distance = 150 + (children.length > 6 ? Math.sqrt(i) * 30 : (i % 3) * 12)
|
||||
local.set(slug, { x: parent.x + Math.cos(heading) * distance, y: parent.y + Math.sin(heading) * distance, heading })
|
||||
queue.push(slug)
|
||||
})
|
||||
}
|
||||
const mean = { x: 0, y: 0 }
|
||||
for (const point of local.values()) { mean.x += point.x / local.size; mean.y += point.y / local.size }
|
||||
for (const [slug, point] of local) seeds.set(slug, { x: point.x - mean.x, y: point.y - mean.y })
|
||||
const extent = graphPointBounds(slugs.map(slug => seeds.get(slug)!))
|
||||
// Room for repulsion and the caption; this is spacing, not a force limit.
|
||||
const padding = 160
|
||||
let x = 0, y = 0, bounds: GraphBounds
|
||||
for (let attempt = 0; ; attempt++) {
|
||||
const distance = Math.sqrt(attempt) * 48
|
||||
x = Math.cos(attempt * goldenAngle) * distance * stretch
|
||||
y = Math.sin(attempt * goldenAngle) * distance / stretch
|
||||
bounds = { left: x + extent.left - padding, right: x + extent.right + padding,
|
||||
top: y + extent.top - padding, bottom: y + extent.bottom + padding }
|
||||
const neighbors = new Set(keysFor(bounds).flatMap(key => cells.get(key) ?? []))
|
||||
if ([...neighbors].every(c => bounds.right <= c.left || bounds.left >= c.right || bounds.bottom <= c.top || bounds.top >= c.bottom)) break
|
||||
}
|
||||
const cluster = { x, y, ...bounds, slugs, representative, anchors: selectGraphAnchors(slugs, adjacency, nodeBySlug) }
|
||||
clusters.push(cluster)
|
||||
for (const key of keysFor(bounds)) {
|
||||
const bucket = cells.get(key) ?? []
|
||||
bucket.push(cluster); cells.set(key, bucket)
|
||||
}
|
||||
}
|
||||
const left = Math.min(0, ...clusters.map(c => c.left))
|
||||
const top = Math.min(0, ...clusters.map(c => c.top))
|
||||
const placements = new Map<string, LayoutPlacement>()
|
||||
const sections: GraphSection[] = []
|
||||
let right = 0, bottom = 0
|
||||
for (const cluster of clusters) {
|
||||
cluster.x -= left; cluster.y -= top
|
||||
cluster.left -= left; cluster.right -= left; cluster.top -= top; cluster.bottom -= top
|
||||
const center = { x: cluster.x, y: cluster.y }
|
||||
for (const slug of cluster.slugs) {
|
||||
const point = seeds.get(slug)!
|
||||
placements.set(slug, { x: center.x + point.x, y: center.y + point.y,
|
||||
center, degree: adjacency.get(slug)!.size })
|
||||
}
|
||||
right = Math.max(right, cluster.right)
|
||||
bottom = Math.max(bottom, cluster.bottom)
|
||||
}
|
||||
const gap = 80
|
||||
// Independent pages stay on a readable grid rather than accumulating at a
|
||||
// shared force center. The shelves are not semantic clusters.
|
||||
for (const [kind, slugs] of [['offscreen', offscreen], ['unlinked', unlinked]] as const) {
|
||||
if (!slugs.length) continue
|
||||
const shelfWidth = right || Math.sqrt(slugs.length * 180 * 100 * aspect)
|
||||
const columns = Math.min(slugs.length, Math.max(3, Math.floor(shelfWidth / 180)))
|
||||
const top = bottom ? bottom + gap : 0
|
||||
const sectionWidth = columns * 180
|
||||
const sectionHeight = Math.ceil(slugs.length / columns) * 100 + 50
|
||||
const left = Math.max(0, (right - sectionWidth) / 2)
|
||||
slugs.forEach((slug, i) => {
|
||||
const point = { x: left + (i % columns) * 180 + 90, y: top + 70 + Math.floor(i / columns) * 100 }
|
||||
placements.set(slug, { ...point, center: point, stationary: true })
|
||||
})
|
||||
sections.push({ kind, count: slugs.length, left, top, right: left + sectionWidth, bottom: top + sectionHeight })
|
||||
bottom = top + sectionHeight
|
||||
right = Math.max(right, left + sectionWidth)
|
||||
}
|
||||
|
||||
const dx = (width - right) / 2, dy = (height - bottom) / 2
|
||||
for (const placement of placements.values()) {
|
||||
placement.x += dx; placement.y += dy
|
||||
// Centers are shared by a component; translate them only once below.
|
||||
}
|
||||
for (const center of new Set([...placements.values()].map(p => p.center))) { center.x += dx; center.y += dy }
|
||||
for (const cluster of clusters) {
|
||||
cluster.x += dx; cluster.y += dy
|
||||
cluster.left += dx; cluster.right += dx; cluster.top += dy; cluster.bottom += dy
|
||||
}
|
||||
for (const section of sections) {
|
||||
section.left += dx; section.right += dx; section.top += dy; section.bottom += dy
|
||||
}
|
||||
|
||||
// During expansion, keep the existing mental map. New nodes start near an
|
||||
// already visible neighbor; old nodes are held still by the simulation.
|
||||
if (prior.size) {
|
||||
for (const slugs of components) {
|
||||
const existing = slugs.flatMap(slug => prior.has(slug) ? [prior.get(slug)!] : [])
|
||||
if (!existing.length) continue
|
||||
const center = { x: existing.reduce((sum, p) => sum + p.x, 0) / existing.length, y: existing.reduce((sum, p) => sum + p.y, 0) / existing.length }
|
||||
slugs.forEach((slug, i) => {
|
||||
const neighbor = [...adjacency.get(slug)!].find(nb => prior.has(nb))
|
||||
const anchor = prior.get(slug) ?? (neighbor ? prior.get(neighbor)! : center)
|
||||
const angle = i * Math.PI * (3 - Math.sqrt(5))
|
||||
const point = prior.has(slug) ? anchor : { x: anchor.x + Math.cos(angle) * 90, y: anchor.y + Math.sin(angle) * 90 }
|
||||
placements.set(slug, { ...point, center, degree: adjacency.get(slug)!.size })
|
||||
})
|
||||
}
|
||||
for (const [slug, point] of prior) {
|
||||
const placement = placements.get(slug)
|
||||
if (placement) { placement.x = point.x; placement.y = point.y }
|
||||
}
|
||||
}
|
||||
return { placements, sections: prior.size ? [] : sections, clusters: prior.size ? [] : clusters }
|
||||
}
|
||||
|
||||
export interface ForceNode extends GraphPoint {
|
||||
slug: string; vx: number; vy: number; linkCount: number; pinned: boolean
|
||||
}
|
||||
|
||||
/** Local repulsion uses a 2D spatial grid; collision includes outer rings. */
|
||||
export function stepGraphLayout(
|
||||
nodes: ForceNode[], edges: GraphLink[], placements: ReadonlyMap<string, LayoutPlacement>,
|
||||
alpha: number, retained: ReadonlySet<string> = new Set(),
|
||||
) {
|
||||
const fixed = (n: ForceNode) => n.pinned || retained.has(n.slug) || !!placements.get(n.slug)?.stationary
|
||||
if (nodes.every(fixed)) return
|
||||
const reach = 300
|
||||
const buckets = new Map<string, ForceNode[]>()
|
||||
const nodeMap = new Map(nodes.map(n => [n.slug, n]))
|
||||
for (const n of nodes) {
|
||||
const cx = Math.floor(n.x / reach), cy = Math.floor(n.y / reach)
|
||||
for (let gx = cx - 1; gx <= cx + 1; gx++) for (let gy = cy - 1; gy <= cy + 1; gy++) {
|
||||
for (const other of buckets.get(`${gx},${gy}`) ?? []) {
|
||||
let dx = n.x - other.x, dy = n.y - other.y
|
||||
let distance = Math.hypot(dx, dy)
|
||||
if (distance > reach) continue
|
||||
if (distance < 0.001) { dx = 1; dy = 0; distance = 1 }
|
||||
const force = 12000 * alpha / Math.max(distance * distance, 100)
|
||||
const fx = dx / distance * force, fy = dy / distance * force
|
||||
if (!fixed(n)) { n.vx += fx; n.vy += fy }
|
||||
if (!fixed(other)) { other.vx -= fx; other.vy -= fy }
|
||||
}
|
||||
}
|
||||
const key = `${cx},${cy}`
|
||||
const bucket = buckets.get(key) ?? []
|
||||
bucket.push(n); buckets.set(key, bucket)
|
||||
}
|
||||
// A reciprocal Wiki link is one visual spring, not double attraction.
|
||||
const pairs = new Set<string>()
|
||||
for (const edge of edges) {
|
||||
const s = nodeMap.get(edge.source), t = nodeMap.get(edge.target)
|
||||
if (!s || !t || s === t) continue
|
||||
const key = JSON.stringify([s.slug, t.slug].sort())
|
||||
if (pairs.has(key)) continue
|
||||
pairs.add(key)
|
||||
const dx = t.x - s.x, dy = t.y - s.y, distance = Math.hypot(dx, dy) || 1
|
||||
// Dense pages should not pull a whole group into a solid ball. Normalize
|
||||
// attraction by the visible degrees rather than the KB-wide link count.
|
||||
const degree = Math.min(placements.get(s.slug)?.degree ?? 1, placements.get(t.slug)?.degree ?? 1)
|
||||
const force = (distance - 140) * 0.003 * alpha / Math.sqrt(Math.max(1, degree))
|
||||
if (!fixed(s)) { s.vx += dx / distance * force; s.vy += dy / distance * force }
|
||||
if (!fixed(t)) { t.vx -= dx / distance * force; t.vy -= dy / distance * force }
|
||||
}
|
||||
for (const n of nodes) {
|
||||
if (fixed(n)) continue
|
||||
n.vx *= 0.6
|
||||
n.vy *= 0.6
|
||||
const speed = Math.hypot(n.vx, n.vy)
|
||||
if (speed > 20) { n.vx *= 20 / speed; n.vy *= 20 / speed }
|
||||
n.x += n.vx; n.y += n.vy
|
||||
}
|
||||
// Resolve overlaps after integration, even when the force has cooled. Use
|
||||
// X pruning here since the collision radius is small (at most 64 units).
|
||||
for (let pass = 0; pass < 3; pass++) {
|
||||
const sorted = [...nodes].sort((a, b) => a.x - b.x)
|
||||
for (let i = 0; i < sorted.length; i++) {
|
||||
const a = sorted[i]!
|
||||
for (let j = i + 1; j < sorted.length; j++) {
|
||||
const b = sorted[j]!
|
||||
if (b.x - a.x > 64) break
|
||||
let dx = b.x - a.x, dy = b.y - a.y
|
||||
let distance = Math.hypot(dx, dy)
|
||||
const minimum = graphNodeRadius(a.linkCount) + graphNodeRadius(b.linkCount) + 16
|
||||
if (distance >= minimum || (fixed(a) && fixed(b))) continue
|
||||
if (distance < 0.001) { dx = 1; dy = 0; distance = 1 }
|
||||
const shift = (minimum - distance) / (fixed(a) || fixed(b) ? 1 : 2)
|
||||
if (!fixed(a)) { a.x -= dx / distance * shift; a.y -= dy / distance * shift }
|
||||
if (!fixed(b)) { b.x += dx / distance * shift; b.y += dy / distance * shift }
|
||||
}
|
||||
}
|
||||
}
|
||||
// Correct only whole-component drift. The same translation is applied to
|
||||
// every member; no node is attracted to a shared center or clipped to a
|
||||
// circle. Pinned/retained components keep their user's coordinates intact.
|
||||
const groups = new Map<GraphPoint, ForceNode[]>()
|
||||
for (const node of nodes) {
|
||||
const center = placements.get(node.slug)?.center
|
||||
if (!center) continue
|
||||
const group = groups.get(center) ?? []
|
||||
group.push(node); groups.set(center, group)
|
||||
}
|
||||
for (const [center, group] of groups) {
|
||||
if (group.some(fixed)) continue
|
||||
const dx = (center.x - group.reduce((sum, n) => sum + n.x, 0) / group.length) * 0.03 * alpha
|
||||
const dy = (center.y - group.reduce((sum, n) => sum + n.y, 0) / group.length) * 0.03 * alpha
|
||||
for (const n of group) { n.x += dx; n.y += dy }
|
||||
}
|
||||
}
|
||||
|
||||
export interface GraphLabel extends GraphBounds { slug: string; priority: number; required?: boolean }
|
||||
/** Greedy screen-space label placement. Focused labels are never suppressed. */
|
||||
export function visibleGraphLabels(labels: GraphLabel[]): Set<string> {
|
||||
const visible = new Set<string>()
|
||||
const occupied = new Map<string, GraphLabel[]>()
|
||||
const cells = (label: GraphLabel) => {
|
||||
const keys: string[] = []
|
||||
for (let x = Math.floor(label.left / 160); x <= Math.floor(label.right / 160); x++) {
|
||||
for (let y = Math.floor(label.top / 32); y <= Math.floor(label.bottom / 32); y++) keys.push(`${x},${y}`)
|
||||
}
|
||||
return keys
|
||||
}
|
||||
for (const label of [...labels].sort((a, b) => Number(!!b.required) - Number(!!a.required) || b.priority - a.priority)) {
|
||||
const keys = cells(label)
|
||||
const overlaps = keys.some(key => (occupied.get(key) ?? []).some(other => label.left < other.right && label.right > other.left && label.top < other.bottom && label.bottom > other.top))
|
||||
if (overlaps && !label.required) continue
|
||||
visible.add(label.slug)
|
||||
for (const key of keys) {
|
||||
const bucket = occupied.get(key) ?? []
|
||||
bucket.push(label); occupied.set(key, bucket)
|
||||
}
|
||||
}
|
||||
return visible
|
||||
}
|
||||
|
||||
|
||||
export function graphPointBounds(points: GraphPoint[]): GraphBounds {
|
||||
if (!points.length) return { left: 0, top: 0, right: 0, bottom: 0 }
|
||||
return {
|
||||
left: Math.min(...points.map(p => p.x)), right: Math.max(...points.map(p => p.x)),
|
||||
top: Math.min(...points.map(p => p.y)), bottom: Math.max(...points.map(p => p.y)),
|
||||
}
|
||||
}
|
||||
|
||||
/** Start at a readable scale. Fitting the entire graph is an explicit action. */
|
||||
export function initialGraphViewport(points: GraphPoint[], width: number, height: number, focus?: GraphPoint) {
|
||||
const bounds = graphPointBounds(points)
|
||||
const fit = Math.min(Math.max(100, width - 120) / Math.max(100, bounds.right - bounds.left),
|
||||
Math.max(100, height - 120) / Math.max(100, bounds.bottom - bounds.top))
|
||||
const scale = Math.max(0.4, Math.min(0.85, fit))
|
||||
const center = fit < 0.4 && focus ? focus : { x: (bounds.left + bounds.right) / 2, y: (bounds.top + bounds.bottom) / 2 }
|
||||
return { scale, x: width / 2 - center.x * scale, y: height / 2 - center.y * scale }
|
||||
}
|
||||
|
||||
|
||||
/** Smooth envelope of the node disks with a stable screen-space gutter.
|
||||
* The hull is taken over disks already grown by the gutter, then traced with
|
||||
* a closed spline whose tangents are limited by the adjacent segment length,
|
||||
* so it bows outwards from the hull without loops or cusps.
|
||||
*/
|
||||
export function graphClusterOutline(points: (GraphPoint & { radius?: number })[], scale = 1): string {
|
||||
if (!points.length) return ''
|
||||
const zoom = Number.isFinite(scale) && scale > 0 ? scale : 1
|
||||
// Capped in world units so far-out zoom levels do not merge separate groups.
|
||||
const padding = Math.min(22 / zoom, 60)
|
||||
const samples = 24
|
||||
const expanded = points.flatMap(p => {
|
||||
const radius = Math.max(0, p.radius ?? 0) + padding
|
||||
return Array.from({ length: samples }, (_, i) => ({
|
||||
x: p.x + Math.cos(i * 2 * Math.PI / samples) * radius,
|
||||
y: p.y + Math.sin(i * 2 * Math.PI / samples) * radius,
|
||||
}))
|
||||
}).sort((a, b) => a.x - b.x || a.y - b.y)
|
||||
const unique = expanded.filter((p, i) => !i || p.x !== expanded[i - 1]!.x || p.y !== expanded[i - 1]!.y)
|
||||
const cross = (o: GraphPoint, a: GraphPoint, b: GraphPoint) => (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x)
|
||||
const half = (list: GraphPoint[]) => {
|
||||
const hull: GraphPoint[] = []
|
||||
for (const point of list) {
|
||||
while (hull.length > 1 && cross(hull[hull.length - 2]!, hull[hull.length - 1]!, point) <= 0) hull.pop()
|
||||
hull.push(point)
|
||||
}
|
||||
hull.pop()
|
||||
return hull
|
||||
}
|
||||
const hull = [...half(unique), ...half([...unique].reverse())]
|
||||
const at = (i: number) => hull[(i + hull.length) % hull.length]!
|
||||
const fmt = (p: GraphPoint) => `${Math.round(p.x * 10) / 10},${Math.round(p.y * 10) / 10}`
|
||||
const tangent = (from: GraphPoint, to: GraphPoint, length: number) => {
|
||||
const dx = to.x - from.x, dy = to.y - from.y, norm = Math.hypot(dx, dy) || 1
|
||||
return { x: dx / norm * length, y: dy / norm * length }
|
||||
}
|
||||
const path = [`M${fmt(hull[0]!)}`]
|
||||
hull.forEach((p, i) => {
|
||||
const next = at(i + 1)
|
||||
const reach = Math.hypot(next.x - p.x, next.y - p.y) * 0.36
|
||||
const out = tangent(at(i - 1), next, reach), into = tangent(p, at(i + 2), reach)
|
||||
path.push(`C${fmt({ x: p.x + out.x, y: p.y + out.y })} ${fmt({ x: next.x - into.x, y: next.y - into.y })} ${fmt(next)}`)
|
||||
})
|
||||
return path.join(' ') + ' Z'
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import test from 'node:test'
|
||||
import { runInNewContext } from 'node:vm'
|
||||
import ts from 'typescript'
|
||||
import { graphClusterOutline, visibleGraphLabels } from './wikiGraphLayout.ts'
|
||||
|
||||
// Execute the component's real viewport controller with a deterministic frame
|
||||
// clock. No Vue template or browser layout is needed to count SVG mutations.
|
||||
const source = readFileSync(new URL('./WikiBrowser.vue', import.meta.url), 'utf8')
|
||||
const start = source.indexOf('function setupPanZoom(')
|
||||
const end = source.indexOf('// ─── Hover Highlight', start)
|
||||
const controller = ts.transpileModule(source.slice(start, end), {
|
||||
compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS },
|
||||
}).outputText
|
||||
|
||||
class ElementFixture {
|
||||
attributes = new Map<string, string>()
|
||||
writes: string[] = []
|
||||
style: Record<string, string> = {}
|
||||
listeners = new Map<string, (event: any) => void>()
|
||||
classList = { toggle() {} }
|
||||
setAttribute(name: string, value: string) { this.attributes.set(name, value); this.writes.push(name) }
|
||||
getAttribute(name: string) { return this.attributes.get(name) ?? null }
|
||||
addEventListener(name: string, handler: (event: any) => void) { this.listeners.set(name, handler) }
|
||||
removeEventListener(name: string) { this.listeners.delete(name) }
|
||||
getBoundingClientRect() { return { left: 0, top: 0 } }
|
||||
closest() { return null }
|
||||
}
|
||||
|
||||
function fixture(scale = 1) {
|
||||
const frames = new Map<number, FrameRequestCallback>()
|
||||
let nextFrame = 0, labelPasses = 0, outlines = 0, edgeUpdates = 0
|
||||
const svg = new ElementFixture(), root = new ElementFixture(), window = new ElementFixture()
|
||||
const nodes = [
|
||||
{ slug: 'first', x: 0, y: 0, linkCount: 10, labelWidth: 80 },
|
||||
{ slug: 'second', x: 500, y: 0, linkCount: 1, labelWidth: 80 },
|
||||
{ slug: 'colliding', x: 0, y: 0, linkCount: 0, labelWidth: 80 },
|
||||
]
|
||||
const nodeEls = nodes.map(node => ({ node, text: new ElementFixture() }))
|
||||
const state: any = {
|
||||
svg, root, window, Element: ElementFixture, performance: { now: () => 0 },
|
||||
requestAnimationFrame: (callback: FrameRequestCallback) => { frames.set(++nextFrame, callback); return nextFrame },
|
||||
cancelAnimationFrame: (id: number) => frames.delete(id),
|
||||
graphNodes: nodes, graphNodeElsRef: nodeEls, graphEdgeElsRef: [],
|
||||
graphSectionEls: [], graphContourEls: [], graphClusterEls: [],
|
||||
graphFocusedSlugs: new Set(), graphImportantSlugs: new Set(),
|
||||
graphSelectedSlug: { value: null }, graphHighlightSlug: { value: null },
|
||||
graphDrawerVisible: { value: false }, graphFocusGroup: { value: null },
|
||||
graphEdgeMarkersVisible: true, showArrows: { value: true },
|
||||
graphPanZoomRef: null, disposeGraphPanZoom() {}, refreshGraphLabels() {},
|
||||
clearHighlight() {}, exitGraphFocus() {},
|
||||
graphNodeRadius: () => 8,
|
||||
setEdgePositions: () => { edgeUpdates++ },
|
||||
visibleGraphLabels: (...args: Parameters<typeof visibleGraphLabels>) => { labelPasses++; return visibleGraphLabels(...args) },
|
||||
graphClusterOutline: (...args: Parameters<typeof graphClusterOutline>) => { outlines++; return graphClusterOutline(...args) },
|
||||
}
|
||||
runInNewContext(`${controller}\nsetupPanZoom(svg, root, { scale: ${scale}, x: 0, y: 0 })`, state)
|
||||
function flush(time = 16) {
|
||||
const callbacks = [...frames.values()]
|
||||
frames.clear()
|
||||
for (const callback of callbacks) callback(time)
|
||||
}
|
||||
flush()
|
||||
return {
|
||||
svg, root, window, nodes, nodeEls, state, frames, flush,
|
||||
passes: () => labelPasses, outlines: () => outlines, edgeUpdates: () => edgeUpdates,
|
||||
wheel(deltaY = -120) { svg.listeners.get('wheel')!({ preventDefault() {}, deltaY, clientX: 100, clientY: 50 }) },
|
||||
}
|
||||
}
|
||||
|
||||
test('wheel bursts update the cursor-anchored transform immediately and lay out labels once per frame', () => {
|
||||
const f = fixture()
|
||||
const initialPasses = f.passes()
|
||||
for (let i = 0; i < 8; i++) f.wheel()
|
||||
const scale = 1.08 ** 8
|
||||
assert.ok(Math.abs(f.state.graphPanZoomRef.getScale() - scale) < 1e-10)
|
||||
const { x, y } = f.state.graphPanZoomRef.getTranslate()
|
||||
assert.ok(Math.abs(x - 100 * (1 - scale)) < 1e-10)
|
||||
assert.ok(Math.abs(y - 50 * (1 - scale)) < 1e-10)
|
||||
assert.match(f.root.getAttribute('transform')!, /scale\(/)
|
||||
assert.equal(f.passes(), initialPasses, 'wheel events must not synchronously lay out labels')
|
||||
assert.equal(f.frames.size, 1)
|
||||
f.flush()
|
||||
assert.equal(f.passes(), initialPasses + 1)
|
||||
assert.equal(f.frames.size, 0)
|
||||
})
|
||||
|
||||
test('collision-rejected labels leave SVG layout and receive no font or position writes', () => {
|
||||
const f = fixture()
|
||||
const hidden = f.nodeEls[2]!.text
|
||||
assert.equal(hidden.style.display, 'none')
|
||||
assert.equal(hidden.getAttribute('font-size'), null)
|
||||
assert.equal(hidden.getAttribute('dy'), null)
|
||||
f.wheel()
|
||||
f.flush()
|
||||
assert.equal(hidden.style.display, 'none')
|
||||
assert.equal(hidden.getAttribute('font-size'), null)
|
||||
assert.equal(hidden.getAttribute('dy'), null)
|
||||
assert.equal(f.nodeEls[0]!.text.style.display, '')
|
||||
assert.equal(f.nodeEls[1]!.text.style.display, '')
|
||||
})
|
||||
|
||||
test('pan-only transforms do not recompute labels, even during mouse dragging', () => {
|
||||
const f = fixture()
|
||||
const before = f.passes()
|
||||
f.state.graphPanZoomRef.setTranslate(10, 20)
|
||||
f.state.graphPanZoomRef.apply()
|
||||
f.svg.listeners.get('mousedown')!({ button: 0, target: f.svg, clientX: 0, clientY: 0 })
|
||||
f.window.listeners.get('mousemove')!({ clientX: 40, clientY: 50 })
|
||||
f.flush()
|
||||
assert.equal(f.passes(), before)
|
||||
assert.match(f.root.getAttribute('transform')!, /translate\(50,70\)/)
|
||||
})
|
||||
|
||||
test('hover and selection reveal hidden labels with current zoom metrics, then hide them again', () => {
|
||||
const f = fixture(0.2)
|
||||
const text = f.nodeEls[1]!.text
|
||||
assert.equal(text.style.display, 'none')
|
||||
f.state.graphHighlightSlug.value = 'second'
|
||||
f.state.refreshGraphLabels()
|
||||
f.state.refreshGraphLabels()
|
||||
f.flush()
|
||||
assert.equal(text.style.display, '')
|
||||
assert.equal(text.getAttribute('font-size'), '60')
|
||||
assert.equal(text.getAttribute('dy'), '88')
|
||||
f.state.graphSelectedSlug.value = 'second'
|
||||
f.state.graphHighlightSlug.value = null
|
||||
f.state.refreshGraphLabels()
|
||||
f.flush()
|
||||
assert.equal(text.style.display, '')
|
||||
f.state.graphSelectedSlug.value = null
|
||||
f.state.refreshGraphLabels()
|
||||
f.flush()
|
||||
assert.equal(text.style.display, 'none')
|
||||
})
|
||||
|
||||
test('contours coalesce zooms, retain their pan cache, and invalidate after node movement', () => {
|
||||
const f = fixture()
|
||||
f.state.graphContourEls.push({ path: new ElementFixture(), cluster: { slugs: ['first', 'second'], representative: 'first' } })
|
||||
f.state.refreshGraphLabels()
|
||||
f.flush()
|
||||
assert.equal(f.outlines(), 1)
|
||||
for (let i = 0; i < 5; i++) f.wheel()
|
||||
assert.equal(f.outlines(), 1)
|
||||
f.flush()
|
||||
assert.equal(f.outlines(), 2)
|
||||
f.state.graphPanZoomRef.setTranslate(100, 200)
|
||||
f.state.graphPanZoomRef.apply()
|
||||
f.flush()
|
||||
assert.equal(f.outlines(), 2)
|
||||
f.nodes[0]!.x += 10
|
||||
f.state.refreshGraphLabels()
|
||||
f.flush()
|
||||
assert.equal(f.outlines(), 3)
|
||||
})
|
||||
|
||||
test('marker thresholds and arrow toggles still update edge endpoints', () => {
|
||||
const f = fixture(0.7)
|
||||
f.state.graphEdgeElsRef.push({ line: new ElementFixture(), source: 'first', target: 'second' })
|
||||
f.state.graphPanZoomRef.setScale(1)
|
||||
f.state.graphPanZoomRef.apply()
|
||||
f.flush()
|
||||
assert.equal(f.state.graphEdgeMarkersVisible, true)
|
||||
assert.equal(f.edgeUpdates(), 1)
|
||||
f.state.showArrows.value = false
|
||||
f.state.refreshGraphLabels()
|
||||
f.flush()
|
||||
assert.equal(f.state.graphEdgeMarkersVisible, false)
|
||||
assert.equal(f.edgeUpdates(), 2)
|
||||
})
|
||||
|
||||
test('cluster captions leave layout when hidden and retain keyboard access when revealed', () => {
|
||||
const f = fixture(0.4)
|
||||
const group = new ElementFixture()
|
||||
const cluster = { slugs: ['first', 'second'], anchors: ['first'], representative: 'first' }
|
||||
f.state.graphClusterEls.push({ group, cluster, anchorSlug: 'first', labelWidth: 80, priority: 100000 })
|
||||
f.state.refreshGraphLabels()
|
||||
f.flush()
|
||||
assert.equal(group.style.display, '')
|
||||
assert.equal(group.getAttribute('tabindex'), '0')
|
||||
assert.equal(f.nodeEls[0]!.text.style.display, 'none', 'caption replaces its ordinary label')
|
||||
f.state.graphPanZoomRef.setScale(1.3)
|
||||
f.state.graphPanZoomRef.apply()
|
||||
f.flush()
|
||||
assert.equal(group.style.display, 'none')
|
||||
assert.equal(group.getAttribute('tabindex'), '-1')
|
||||
assert.equal(f.nodeEls[0]!.text.style.display, '')
|
||||
// Outside groups retain a focus-switching caption even at detail zoom.
|
||||
f.state.graphFocusedSlugs.add('second')
|
||||
f.state.refreshGraphLabels()
|
||||
f.flush()
|
||||
assert.equal(group.style.display, '')
|
||||
assert.equal(group.getAttribute('tabindex'), '0')
|
||||
})
|
||||
|
||||
test('same-scale hover refreshes do not rewrite visible label geometry', () => {
|
||||
const f = fixture()
|
||||
const text = f.nodeEls[1]!.text
|
||||
text.writes.length = 0
|
||||
f.state.graphHighlightSlug.value = 'second'
|
||||
f.state.refreshGraphLabels()
|
||||
f.flush()
|
||||
assert.deepEqual(text.writes, [])
|
||||
})
|
||||
|
||||
test('animated focus reaches its final transform and updates labels at the final scale', () => {
|
||||
const f = fixture()
|
||||
f.state.graphPanZoomRef.flyTo(200, 300, 2, 100)
|
||||
f.flush(50)
|
||||
f.flush(100)
|
||||
f.flush(116)
|
||||
assert.equal(f.root.getAttribute('transform'), 'translate(200,300) scale(2)')
|
||||
assert.equal(f.nodeEls[1]!.text.getAttribute('font-size'), '6')
|
||||
assert.equal(f.frames.size, 0)
|
||||
})
|
||||
|
||||
test('disposing a viewport cancels queued label work and animated navigation', () => {
|
||||
const f = fixture()
|
||||
const before = f.passes()
|
||||
f.wheel()
|
||||
f.state.graphPanZoomRef.flyTo(100, 100, 2)
|
||||
assert.ok(f.frames.size > 0)
|
||||
f.state.disposeGraphPanZoom()
|
||||
f.flush()
|
||||
assert.equal(f.passes(), before)
|
||||
assert.equal(f.frames.size, 0)
|
||||
assert.equal(f.window.listeners.size, 0)
|
||||
})
|
||||
@@ -0,0 +1,24 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import { shouldRefreshWikiStatusAfterKnowledgePoll } from './wikiStatusRefresh.ts'
|
||||
|
||||
test('refreshes wiki status when a polled document leaves an in-flight state', () => {
|
||||
assert.equal(
|
||||
shouldRefreshWikiStatusAfterKnowledgePoll(
|
||||
{ parse_status: 'finalizing', summary_status: 'processing' },
|
||||
{ parse_status: 'completed', summary_status: 'completed' },
|
||||
),
|
||||
true,
|
||||
)
|
||||
})
|
||||
|
||||
test('does not refresh wiki status for ordinary in-flight polling updates', () => {
|
||||
assert.equal(
|
||||
shouldRefreshWikiStatusAfterKnowledgePoll(
|
||||
{ parse_status: 'pending' },
|
||||
{ parse_status: 'processing' },
|
||||
),
|
||||
false,
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,21 @@
|
||||
export type KnowledgePollStatus = {
|
||||
parse_status?: string
|
||||
summary_status?: string
|
||||
}
|
||||
|
||||
export function isKnowledgeParseInFlight(status?: string): boolean {
|
||||
return status === 'pending' || status === 'processing' || status === 'finalizing'
|
||||
}
|
||||
|
||||
export function knowledgeNeedsStatusPolling(item: KnowledgePollStatus): boolean {
|
||||
if (isKnowledgeParseInFlight(item.parse_status)) return true
|
||||
return item.parse_status === 'completed' &&
|
||||
(item.summary_status === 'pending' || item.summary_status === 'processing')
|
||||
}
|
||||
|
||||
export function shouldRefreshWikiStatusAfterKnowledgePoll(
|
||||
before: KnowledgePollStatus,
|
||||
after: KnowledgePollStatus,
|
||||
): boolean {
|
||||
return knowledgeNeedsStatusPolling(before) && !knowledgeNeedsStatusPolling(after)
|
||||
}
|
||||
Reference in new issue
Block a user