Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

feat(chat): rework the saved-answer Markdown editor (#3467)

lyingbug7fa6f028fcea
diff --git a/frontend/src/components/manual-knowledge-editor.vue b/frontend/src/components/manual-knowledge-editor.vue
index 455009148..432f0a091 100644
--- a/frontend/src/components/manual-knowledge-editor.vue
+++ b/frontend/src/components/manual-knowledge-editor.vue
@@ -2,7 +2,7 @@
import { ref, reactive, computed, watch, nextTick, onBeforeUnmount } from 'vue'
import SettingDrawer from '@/components/settings/SettingDrawer.vue'
import { marked } from 'marked'
-import { MessagePlugin } from 'tdesign-vue-next'
+import { DialogPlugin, MessagePlugin } from 'tdesign-vue-next'
import { useUIStore } from '@/stores/ui'
import {
listKnowledgeBases,
@@ -15,6 +15,7 @@ import { useUploadConfirmStore } from '@/stores/uploadConfirm'
import { useOrganizationStore } from '@/stores/organization'
import type { KnowledgeProcessOverrides } from '@/types/knowledgeProcess'
import { sanitizeHTML, safeMarkdownToHTML, hydrateProtectedFileImages } from '@/utils/security'
+import { continueListOnEnter, countContent, indentOnTab } from '@/utils/markdownEditing'
import { useI18n } from 'vue-i18n'
interface KnowledgeBaseOption {
@@ -85,72 +86,85 @@ const kbLoading = ref(false)
const contentLoading = ref(false)
const saving = ref(false)
const savingAction = ref<ManualStatus>('draft')
-const activeTab = ref<'edit' | 'preview'>('edit')
const lastUpdatedAt = ref<string>('')
-const textareaComponent = ref<any>(null)
-const textareaElement = ref<HTMLTextAreaElement | null>(null)
-const selectionRange = reactive({ start: 0, end: 0 })
-const selectionEvents = ['select', 'keyup', 'click', 'mouseup', 'input']
-
-const resolveTextareaElement = (): HTMLTextAreaElement | null => {
- const component = textareaComponent.value as any
- if (!component) return null
- if (component.textareaRef) {
- return component.textareaRef as HTMLTextAreaElement
- }
- if (component.$el) {
- const el = component.$el.querySelector('textarea')
- if (el) {
- return el as HTMLTextAreaElement
- }
- }
- return null
-}
+// ---------- view mode ----------
+type ViewMode = 'edit' | 'split' | 'preview'
+const VIEW_MODE_STORAGE_KEY = 'manual-editor:view-mode'
+/** Below this the two panes would each be too narrow to write or read in. */
+const SPLIT_MIN_WIDTH = 820
-const handleTextareaSelectionEvent = () => {
- const textarea = textareaElement.value ?? resolveTextareaElement()
- if (!textarea) {
- return
+const readStoredViewMode = (): ViewMode => {
+ try {
+ const stored = window.localStorage.getItem(VIEW_MODE_STORAGE_KEY)
+ if (stored === 'edit' || stored === 'split' || stored === 'preview') return stored
+ } catch {
+ // localStorage can throw in private mode / quota errors.
}
- selectionRange.start = textarea.selectionStart ?? 0
- selectionRange.end = textarea.selectionEnd ?? 0
-}
+ return 'split'
+}
+
+const viewMode = ref<ViewMode>(readStoredViewMode())
+const editorAreaRef = ref<HTMLElement | null>(null)
+const editorAreaWidth = ref(SPLIT_MIN_WIDTH)
+const canSplit = computed(() => editorAreaWidth.value >= SPLIT_MIN_WIDTH)
+/**
+ * Narrow-layout switch, driven from the same measurement rather than a
+ * `@container` query: this project's scoped-style pipeline drops `@container`
+ * blocks, so those rules never reach the page.
+ */
+const NARROW_WIDTH = 620
+const isNarrow = computed(() => editorAreaWidth.value > 0 && editorAreaWidth.value < NARROW_WIDTH)
+/** Split silently falls back to edit-only while the drawer is too narrow for it. */
+const activeView = computed<ViewMode>(() =>
+ viewMode.value === 'split' && !canSplit.value ? 'edit' : viewMode.value,
+)
+const showEditor = computed(() => activeView.value !== 'preview')
+const showPreview = computed(() => activeView.value !== 'edit')
-const detachTextareaListeners = () => {
- if (!textareaElement.value) {
- return
+const setViewMode = (mode: ViewMode) => {
+ if (mode === 'split' && !canSplit.value) return
+ viewMode.value = mode
+ try {
+ window.localStorage.setItem(VIEW_MODE_STORAGE_KEY, mode)
+ } catch {
+ // Ignore: remembering the layout is a convenience, not a requirement.
}
- selectionEvents.forEach((eventName) => {
- textareaElement.value?.removeEventListener(eventName, handleTextareaSelectionEvent)
- })
- textareaElement.value = null
}
-const attachTextareaListeners = () => {
- nextTick(() => {
- const textarea = resolveTextareaElement()
- if (!textarea) {
- return
- }
- if (textareaElement.value === textarea) {
- return
- }
- detachTextareaListeners()
- textareaElement.value = textarea
- selectionEvents.forEach((eventName) => {
- textarea.addEventListener(eventName, handleTextareaSelectionEvent)
- })
- handleTextareaSelectionEvent()
+let editorAreaObserver: ResizeObserver | null = null
+
+watch(editorAreaRef, (el) => {
+ editorAreaObserver?.disconnect()
+ editorAreaObserver = null
+ if (!el) return
+ // Measure straight away: waiting for the observer's first callback would
+ // paint a split editor for a frame before collapsing it on a narrow drawer.
+ editorAreaWidth.value = el.clientWidth
+ if (typeof ResizeObserver === 'undefined') return
+ editorAreaObserver = new ResizeObserver((entries) => {
+ editorAreaWidth.value = entries[0]?.contentRect.width ?? 0
})
+ editorAreaObserver.observe(el)
+})
+
+// ---------- textarea selection ----------
+const textareaEl = ref<HTMLTextAreaElement | null>(null)
+const selectionRange = reactive({ start: 0, end: 0 })
+
+const syncSelection = () => {
+ const textarea = textareaEl.value
+ if (!textarea) return
+ selectionRange.start = textarea.selectionStart ?? 0
+ selectionRange.end = textarea.selectionEnd ?? 0
}
const setSelectionRange = (start: number, end: number) => {
selectionRange.start = start
selectionRange.end = end
nextTick(() => {
- const textarea = resolveTextareaElement()
- if (!textarea || activeTab.value !== 'edit') {
+ const textarea = textareaEl.value
+ if (!textarea || !showEditor.value) {
return
}
// Initialization can finish while the drawer is still sliding in. A plain
@@ -340,77 +354,220 @@ type ToolbarButton = {
action: ToolbarAction
icon: string
}
+/**
+ * A group of related actions behind one labelled trigger. Headings and the
+ * block inserts are one-per-document choices, so they cost more toolbar room
+ * than they earn as separate icons.
+ */
+type ToolbarMenu = {
+ key: string
+ label: string
+ options: Array<{ content: string; value: string }>
+ actions: Record<string, ToolbarAction>
+}
type ToolbarGroup = {
key: string
buttons: ToolbarButton[]
+ menu?: ToolbarMenu
}
-const toolbarGroups = computed<ToolbarGroup[]>(() => [
- {
- key: 'format',
- buttons: [
- { key: 'bold', icon: 'textformat-bold', tooltip: t('manualEditor.toolbar.bold'), action: () => wrapSelection('**', '**', t('manualEditor.placeholders.bold')) },
- { key: 'italic', icon: 'textformat-italic', tooltip: t('manualEditor.toolbar.italic'), action: () => wrapSelection('*', '*', t('manualEditor.placeholders.italic')) },
- { key: 'strike', icon: 'textformat-strikethrough', tooltip: t('manualEditor.toolbar.strike'), action: () => wrapSelection('~~', '~~', t('manualEditor.placeholders.strike')) },
- { key: 'inline-code', icon: 'code', tooltip: t('manualEditor.toolbar.inlineCode'), action: () => wrapSelection('`', '`', t('manualEditor.placeholders.inlineCode')) },
- ],
- },
- {
+const toolbarGroups = computed<ToolbarGroup[]>(() => {
+ const headingMenu: ToolbarMenu = {
key: 'heading',
- buttons: [
- { key: 'h1', icon: 'numbers-1', tooltip: t('manualEditor.toolbar.heading1'), action: () => applyHeading(1) },
- { key: 'h2', icon: 'numbers-2', tooltip: t('manualEditor.toolbar.heading2'), action: () => applyHeading(2) },
- { key: 'h3', icon: 'numbers-3', tooltip: t('manualEditor.toolbar.heading3'), action: () => applyHeading(3) },
- ],
- },
- {
- key: 'list',
- buttons: [
- { key: 'ul', icon: 'view-list', tooltip: t('manualEditor.toolbar.bulletList'), action: applyBulletList },
- { key: 'ol', icon: 'list-numbered', tooltip: t('manualEditor.toolbar.orderedList'), action: applyOrderedList },
- { key: 'task', icon: 'check-rectangle', tooltip: t('manualEditor.toolbar.taskList'), action: applyTaskList },
- { key: 'quote', icon: 'quote', tooltip: t('manualEditor.toolbar.blockquote'), action: applyBlockquote },
+ label: t('manualEditor.toolbar.headingGroup'),
+ options: [
+ { content: t('manualEditor.toolbar.heading1'), value: 'h1' },
+ { content: t('manualEditor.toolbar.heading2'), value: 'h2' },
+ { content: t('manualEditor.toolbar.heading3'), value: 'h3' },
],
- },
- {
+ actions: {
+ h1: () => applyHeading(1),
+ h2: () => applyHeading(2),
+ h3: () => applyHeading(3),
+ },
+ }
+
+ const insertMenu: ToolbarMenu = {
key: 'insert',
- buttons: [
- { key: 'codeblock', icon: 'code-1', tooltip: t('manualEditor.toolbar.codeBlock'), action: insertCodeBlock },
- { key: 'link', icon: 'link', tooltip: t('manualEditor.toolbar.link'), action: insertLink },
- { key: 'image', icon: 'image', tooltip: t('manualEditor.toolbar.image'), action: insertImage },
- { key: 'table', icon: 'table', tooltip: t('manualEditor.toolbar.table'), action: insertTable },
- { key: 'hr', icon: 'component-divider-horizontal', tooltip: t('manualEditor.toolbar.horizontalRule'), action: insertHorizontalRule },
+ label: t('manualEditor.toolbar.insertGroup'),
+ options: [
+ { content: t('manualEditor.toolbar.blockquote'), value: 'quote' },
+ { content: t('manualEditor.toolbar.codeBlock'), value: 'codeblock' },
+ { content: t('manualEditor.toolbar.table'), value: 'table' },
+ { content: t('manualEditor.toolbar.image'), value: 'image' },
+ { content: t('manualEditor.toolbar.horizontalRule'), value: 'hr' },
],
- },
-])
+ actions: {
+ quote: applyBlockquote,
+ codeblock: insertCodeBlock,
+ table: insertTable,
+ image: insertImage,
+ hr: insertHorizontalRule,
+ },
+ }
+
+ return [
+ {
+ key: 'format',
+ buttons: [
+ { key: 'bold', icon: 'textformat-bold', tooltip: t('manualEditor.toolbar.bold'), action: () => wrapSelection('**', '**', t('manualEditor.placeholders.bold')) },
+ { key: 'italic', icon: 'textformat-italic', tooltip: t('manualEditor.toolbar.italic'), action: () => wrapSelection('*', '*', t('manualEditor.placeholders.italic')) },
+ { key: 'strike', icon: 'textformat-strikethrough', tooltip: t('manualEditor.toolbar.strike'), action: () => wrapSelection('~~', '~~', t('manualEditor.placeholders.strike')) },
+ { key: 'inline-code', icon: 'code', tooltip: t('manualEditor.toolbar.inlineCode'), action: () => wrapSelection('`', '`', t('manualEditor.placeholders.inlineCode')) },
+ ],
+ },
+ { key: 'heading', buttons: [], menu: headingMenu },
+ {
+ key: 'list',
+ buttons: [
+ { key: 'ul', icon: 'view-list', tooltip: t('manualEditor.toolbar.bulletList'), action: applyBulletList },
+ { key: 'ol', icon: 'list-numbered', tooltip: t('manualEditor.toolbar.orderedList'), action: applyOrderedList },
+ { key: 'task', icon: 'check-rectangle', tooltip: t('manualEditor.toolbar.taskList'), action: applyTaskList },
+ ],
+ },
+ {
+ key: 'insert',
+ buttons: [
+ { key: 'link', icon: 'link', tooltip: t('manualEditor.toolbar.link'), action: insertLink },
+ ],
+ menu: insertMenu,
+ },
+ ]
+})
+
+/** TDesign hands the clicked item's `value` (or the item itself in older builds). */
+const handleToolbarMenuSelect = (menu: ToolbarMenu, selected: unknown) => {
+ const key =
+ selected && typeof selected === 'object'
+ ? String((selected as { value?: unknown }).value ?? '')
+ : String(selected ?? '')
+ const action = menu.actions[key]
+ if (action) handleToolbarAction(action)
+}
const previewRoot = ref<HTMLElement | null>(null)
-const isPreviewMode = computed(() => activeTab.value === 'preview')
-const viewToggleIcon = computed(() => (isPreviewMode.value ? 'edit-1' : 'browse'))
-const viewToggleLabel = computed(() =>
- isPreviewMode.value ? t('manualEditor.view.editLabel') : t('manualEditor.view.previewLabel'),
-)
+
+const viewOptions = computed(() => [
+ { value: 'edit' as ViewMode, icon: 'edit-1', label: t('manualEditor.view.edit'), disabled: false, tooltip: t('manualEditor.view.edit') },
+ {
+ value: 'split' as ViewMode,
+ icon: 'column-layout',
+ label: t('manualEditor.view.split'),
+ disabled: !canSplit.value,
+ tooltip: canSplit.value ? t('manualEditor.view.split') : t('manualEditor.view.splitUnavailable'),
+ },
+ { value: 'preview' as ViewMode, icon: 'browse', label: t('manualEditor.view.preview'), disabled: false, tooltip: t('manualEditor.view.preview') },
+])
const handleToolbarAction = (action: ToolbarAction) => {
if (saving.value) {
return
}
- if (activeTab.value !== 'edit') {
- activeTab.value = 'edit'
- nextTick(() => {
- attachTextareaListeners()
- action()
- })
+ // Formatting acts on the textarea, so bring it back into view first.
+ if (!showEditor.value) {
+ setViewMode(canSplit.value ? 'split' : 'edit')
+ nextTick(action)
} else {
- attachTextareaListeners()
action()
}
}
-const toggleEditorView = () => {
- activeTab.value = isPreviewMode.value ? 'edit' : 'preview'
+// ---------- keyboard ----------
+const isApplePlatform =
+ typeof navigator !== 'undefined' && /Mac|iPhone|iPad|iPod/.test(navigator.platform || navigator.userAgent)
+const modifierLabel = computed(() => (isApplePlatform ? '⌘' : 'Ctrl+'))
+
+const SHORTCUT_ACTIONS: Record<string, () => void> = {
+ b: () => wrapSelection('**', '**', t('manualEditor.placeholders.bold')),
+ i: () => wrapSelection('*', '*', t('manualEditor.placeholders.italic')),
+ k: insertLink,
+}
+
+const applyPatch = (patch: { value: string; start: number; end: number }) => {
+ form.content = patch.value
+ setSelectionRange(patch.start, patch.end)
}
+/** Read the live caret off the event target — it is ahead of our cached range. */
+const readEditorState = (event: KeyboardEvent) => {
+ const textarea = event.currentTarget instanceof HTMLTextAreaElement ? event.currentTarget : null
+ return {
+ value: form.content ?? '',
+ start: textarea?.selectionStart ?? selectionRange.start,
+ end: textarea?.selectionEnd ?? selectionRange.end,
+ }
+}
+
+/**
+ * Shortcuts an author expects from any Markdown editor, plus list/indent
+ * behaviour a bare <textarea> does not provide.
+ */
+const handleEditorKeydown = (event: KeyboardEvent) => {
+ // Never steal a key from an IME mid-composition (Chinese/Japanese input).
+ if (event.isComposing || event.keyCode === 229) return
+
+ const modifier = isApplePlatform ? event.metaKey : event.ctrlKey
+ if (modifier && !event.altKey) {
+ const key = event.key.toLowerCase()
+ if (key === 'enter') {
+ event.preventDefault()
+ handleSave('publish')
+ return
+ }
+ if (key === 's') {
+ event.preventDefault()
+ handleSave('draft')
+ return
+ }
+ if (saving.value) return
+ const shortcut = SHORTCUT_ACTIONS[key]
+ if (shortcut) {
+ event.preventDefault()
+ syncSelection()
+ shortcut()
+ return
+ }
+ }
+
+ if (saving.value) return
+ const state = readEditorState(event)
+
+ if (event.key === 'Enter' && !event.shiftKey && !modifier) {
+ const patch = continueListOnEnter(state)
+ if (patch) {
+ event.preventDefault()
+ applyPatch(patch)
+ }
+ return
+ }
+
+ if (event.key === 'Tab') {
+ const patch = indentOnTab(state, event.shiftKey)
+ if (patch) {
+ event.preventDefault()
+ applyPatch(patch)
+ }
+ }
+}
+
+const contentStats = computed(() => countContent(form.content))
+const counterText = computed(() =>
+ t('manualEditor.status.counter', {
+ chars: contentStats.value.characters,
+ lines: contentStats.value.lines,
+ }),
+)
+/** Rows behind the status bar's keyboard button — a full list, not a cropped line. */
+const shortcutRows = computed(() => [
+ { keys: `${modifierLabel.value}B`, label: t('manualEditor.toolbar.bold') },
+ { keys: `${modifierLabel.value}I`, label: t('manualEditor.toolbar.italic') },
+ { keys: `${modifierLabel.value}K`, label: t('manualEditor.toolbar.link') },
+ { keys: `${modifierLabel.value}S`, label: t('manualEditor.actions.saveDraft') },
+ { keys: `${modifierLabel.value}\u21B5`, label: t('manualEditor.actions.publish') },
+ { keys: 'Enter', label: t('manualEditor.shortcuts.continueList') },
+ { keys: 'Tab', label: t('manualEditor.shortcuts.indent') },
+])
+
marked.use({})
const previewHTML = computed(() => {
@@ -422,9 +579,9 @@ const previewHTML = computed(() => {
return sanitizeHTML(html)
})
-watch([previewHTML, activeTab, () => form.kbId], async () => {
+watch([previewHTML, activeView, () => form.kbId], async () => {
await nextTick()
- if (activeTab.value === 'preview') await hydrateProtectedFileImages(previewRoot.value,
+ if (showPreview.value) await hydrateProtectedFileImages(previewRoot.value,
mode.value === 'edit' && form.kbId ? { mode: 'knowledgeBase', kbId: form.kbId } : undefined)
})
@@ -562,7 +719,6 @@ const resetForm = () => {
form.title = uiStore.manualEditorInitialTitle || ''
form.content = uiStore.manualEditorInitialContent || ''
form.status = uiStore.manualEditorInitialStatus || 'draft'
- activeTab.value = 'edit'
lastUpdatedAt.value = ''
initialLoaded.value = false
manualTagIds.value = mode.value === 'create' ? [...uiStore.selectedTagIds] : []
@@ -595,6 +751,7 @@ const initialize = async () => {
}
initialLoaded.value = true
+ markPristine()
}
const validateForm = (targetStatus: ManualStatus): boolean => {
@@ -697,6 +854,7 @@ const handleSave = async (targetStatus: ManualStatus) => {
status: targetStatus,
})
}
+ markPristine()
uiStore.closeManualEditor()
} else {
const message = response?.message || t('manualEditor.error.saveFailed')
@@ -710,8 +868,33 @@ const handleSave = async (targetStatus: ManualStatus) => {
}
}
+// ---------- unsaved-changes guard ----------
+const pristineSnapshot = ref('')
+
+const snapshot = () => JSON.stringify({ kbId: form.kbId, title: form.title, content: form.content })
+const markPristine = () => {
+ pristineSnapshot.value = snapshot()
+}
+const isDirty = () => initialLoaded.value && snapshot() !== pristineSnapshot.value
+
const handleClose = () => {
- uiStore.closeManualEditor()
+ if (!isDirty()) {
+ uiStore.closeManualEditor()
+ return
+ }
+ // An accidental overlay click used to throw the whole draft away.
+ const dialog = DialogPlugin.confirm({
+ header: t('common.unsavedChanges.title'),
+ body: t('common.unsavedChanges.body'),
+ theme: 'warning',
+ confirmBtn: { content: t('common.unsavedChanges.discard'), theme: 'danger' },
+ cancelBtn: t('common.unsavedChanges.keepEditing'),
+ onConfirm: () => {
+ dialog.destroy()
+ uiStore.closeManualEditor()
+ },
+ onClose: () => dialog.destroy(),
+ })
}
watch(visible, async (val) => {
@@ -719,39 +902,29 @@ watch(visible, async (val) => {
await nextTick()
await initialize()
await nextTick()
- attachTextareaListeners()
const length = form.content ? form.content.length : 0
setSelectionRange(length, length)
} else {
- detachTextareaListeners()
resetForm()
}
})
-watch(activeTab, (val) => {
- if (val === 'edit') {
- nextTick(() => {
- attachTextareaListeners()
- })
- } else {
- detachTextareaListeners()
- }
-})
-
onBeforeUnmount(() => {
- detachTextareaListeners()
+ editorAreaObserver?.disconnect()
+ editorAreaObserver = null
})
</script>
<template>
<SettingDrawer
+ class="manual-editor-drawer"
:visible="visible"
:title="dialogTitle"
- :description="$t('manualEditor.description')"
icon="edit-1"
- width="760px"
- :min-width="560"
- :max-width="1280"
+ width="960px"
+ :min-width="600"
+ :max-width="1440"
+ maximizable
storage-key="setting-drawer:width:manual-markdown-editor"
:hide-footer="!initialLoaded"
@update:visible="(v: boolean) => { visible = v }"
@@ -764,6 +937,7 @@ onBeforeUnmount(() => {
<t-tag size="small" theme="success" variant="light" v-else>
{{ $t('manualEditor.status.publishedTag') }}
</t-tag>
+ <span class="manual-editor-footer-count">{{ counterText }}</span>
</div>
</template>
@@ -798,110 +972,148 @@ onBeforeUnmount(() => {
</div>
</template>
- <div class="manual-editor" v-if="initialLoaded">
- <section class="setting-drawer__section">
- <h4 class="setting-drawer__section-title">{{ $t('manualEditor.section.basic') }}</h4>
-
- <div class="form-item">
- <label class="form-label required">{{ $t('manualEditor.form.titleLabel') }}</label>
- <t-input
- v-model="form.title"
- maxlength="100"
- :placeholder="$t('manualEditor.form.titlePlaceholder')"
- showLimitNumber
- />
+ <div class="manual-editor" :class="{ 'manual-editor--narrow': isNarrow }" v-if="initialLoaded">
+ <!-- Document head: the title reads as the document's title, not as a form
+ field, and the destination is a sentence instead of a labelled row. -->
+ <div class="doc-head">
+ <t-input
+ id="manual-editor-title"
+ class="doc-title"
+ v-model="form.title"
+ maxlength="100"
+ borderless
+ :placeholder="$t('manualEditor.form.titlePlaceholder')"
+ :aria-label="$t('manualEditor.form.titleLabel')"
+ />
+ <div class="doc-meta">
+ <t-tooltip :content="$t('manualEditor.form.knowledgeBaseLabel')" placement="top">
+ <t-icon name="folder" class="doc-meta__icon" />
+ </t-tooltip>
+ <t-select
+ class="doc-meta__kb"
+ v-model="form.kbId"
+ size="small"
+ auto-width
+ :disabled="kbDisabled"
+ :loading="kbLoading"
+ :options="kbOptions"
+ :placeholder="$t('manualEditor.form.knowledgeBasePlaceholder')"
+ :aria-label="$t('manualEditor.form.knowledgeBaseLabel')"
+ :popup-props="{ attach: 'body', zIndex: 2600 }"
+ >
+ <template #empty>
+ <div class="kb-empty">{{ $t('manualEditor.noDocumentKnowledgeBases') }}</div>
+ </template>
+ </t-select>
+ <span v-if="lastUpdatedText" class="doc-meta__time">{{ lastUpdatedText }}</span>
</div>
+ </div>
- <div class="form-item">
- <label class="form-label required">{{ $t('manualEditor.form.knowledgeBaseLabel') }}</label>
- <div class="kb-row">
- <t-select
- v-model="form.kbId"
- :disabled="kbDisabled"
- :loading="kbLoading"
- :options="kbOptions"
- :placeholder="$t('manualEditor.form.knowledgeBasePlaceholder')"
- :popup-props="{ attach: 'body', zIndex: 2600 }"
- >
- <template #empty>
- <div style="padding: 20px; text-align: center; color: var(--td-text-color-placeholder);">
- {{ $t('manualEditor.noDocumentKnowledgeBases') }}
- </div>
- </template>
- </t-select>
- <div class="status-row" v-if="mode === 'edit'">
- <t-tag size="small" theme="warning" variant="light" v-if="form.status === 'draft'">
- {{ $t('manualEditor.status.draftTag') }}
- </t-tag>
- <t-tag size="small" theme="success" variant="light" v-else>
- {{ $t('manualEditor.status.publishedTag') }}
- </t-tag>
- </div>
+ <div class="editor-area" ref="editorAreaRef" :class="`editor-area--${activeView}`">
+ <div class="editor-toolbar">
+ <div class="editor-toolbar__format">
+ <template v-for="(group, groupIndex) in toolbarGroups" :key="group.key">
+ <div class="toolbar-group">
+ <template v-for="btn in group.buttons" :key="btn.key">
+ <t-tooltip :content="btn.tooltip" placement="top">
+ <button
+ type="button"
+ class="toolbar-btn"
+ :aria-label="btn.tooltip"
+ @mousedown.prevent
+ @click="handleToolbarAction(btn.action)"
+ >
+ <t-icon :name="btn.icon" size="18px" />
+ </button>
+ </t-tooltip>
+ </template>
+ <t-dropdown
+ v-if="group.menu"
+ :options="group.menu.options"
+ trigger="click"
+ :min-column-width="132"
+ :popup-props="{ attach: 'body', zIndex: 2600 }"
+ @click="(selected: unknown) => handleToolbarMenuSelect(group.menu!, selected)"
+ >
+ <button type="button" class="toolbar-menu-btn" @mousedown.prevent>
+ <span>{{ group.menu.label }}</span>
+ <t-icon name="chevron-down" class="toolbar-menu-btn__caret" />
+ </button>
+ </t-dropdown>
+ </div>
+ <div
+ v-if="groupIndex < toolbarGroups.length - 1"
+ class="toolbar-divider"
+ ></div>
+ </template>
</div>
- <p v-if="lastUpdatedText" class="form-desc">{{ lastUpdatedText }}</p>
- </div>
- </section>
-
- <section class="setting-drawer__section editor-section">
- <h4 class="setting-drawer__section-title">{{ $t('manualEditor.section.content') }}</h4>
-
- <div class="editor-area">
- <div class="editor-toolbar">
- <div class="editor-toolbar__format">
- <template v-for="(group, groupIndex) in toolbarGroups" :key="group.key">
- <div class="toolbar-group">
- <template v-for="btn in group.buttons" :key="btn.key">
- <t-tooltip :content="btn.tooltip" placement="top">
- <button
- type="button"
- class="toolbar-btn"
- :class="`btn-${btn.key}`"
- @mousedown.prevent
- @click="handleToolbarAction(btn.action)"
- >
- <t-icon :name="btn.icon" size="18px" />
- </button>
- </t-tooltip>
- </template>
+ <div class="editor-toolbar__view">
+ <t-tooltip placement="top-right" :show-arrow="false">
+ <template #content>
+ <div class="shortcut-sheet">
+ <div class="shortcut-sheet__title">{{ $t('manualEditor.shortcuts.title') }}</div>
+ <div v-for="row in shortcutRows" :key="row.keys" class="shortcut-sheet__row">
+ <kbd>{{ row.keys }}</kbd>
+ <span>{{ row.label }}</span>
+ </div>
</div>
- <div
- v-if="groupIndex < toolbarGroups.length - 1"
- class="toolbar-divider"
- ></div>
</template>
- </div>
- <div class="editor-toolbar__view">
- <t-button
- variant="text"
- theme="primary"
- size="small"
- :class="['toggle-view-btn', { 'is-preview': isPreviewMode }]"
- :disabled="saving"
- @click="toggleEditorView"
+ <button
+ type="button"
+ class="toolbar-shortcuts"
+ :aria-label="$t('manualEditor.shortcuts.title')"
+ @mousedown.prevent
>
- <template #icon><t-icon :name="viewToggleIcon" /></template>
- {{ viewToggleLabel }}
- </t-button>
+ <t-icon name="keyboard" />
+ </button>
+ </t-tooltip>
+ <div class="view-switch" role="group" :aria-label="$t('manualEditor.view.groupLabel')">
+ <t-tooltip v-for="option in viewOptions" :key="option.value" :content="option.tooltip" placement="top">
+ <!-- aria-disabled, not disabled: a disabled button swallows hover,
+ and the tooltip is the only place that explains why split is off. -->
+ <button
+ type="button"
+ class="view-switch__btn"
+ :class="{ 'is-active': activeView === option.value, 'is-disabled': option.disabled }"
+ :aria-disabled="option.disabled"
+ :aria-pressed="activeView === option.value"
+ @mousedown.prevent
+ @click="setViewMode(option.value)"
+ >
+ <t-icon :name="option.icon" />
+ <span class="view-switch__label">{{ option.label }}</span>
+ </button>
+ </t-tooltip>
</div>
</div>
+ </div>
- <div class="editor-pane" v-show="activeTab === 'edit'">
- <t-textarea
- ref="textareaComponent"
+ <div class="editor-body">
+ <div class="editor-pane editor-pane--edit" v-show="showEditor">
+ <textarea
v-if="!contentLoading"
+ ref="textareaEl"
v-model="form.content"
- :placeholder="$t('manualEditor.form.contentPlaceholder')"
class="editor-textarea"
- />
+ spellcheck="false"
+ :placeholder="$t('manualEditor.form.contentPlaceholder')"
+ :aria-label="$t('manualEditor.section.content')"
+ @keydown="handleEditorKeydown"
+ @select="syncSelection"
+ @click="syncSelection"
+ @keyup="syncSelection"
+ @input="syncSelection"
+ ></textarea>
<div v-else class="loading-placeholder">
<t-loading size="small" :text="$t('manualEditor.loading.content')" />
</div>
</div>
- <div class="editor-pane editor-pane--preview" v-show="activeTab === 'preview'">
+ <div class="editor-pane editor-pane--preview" v-show="showPreview">
<div ref="previewRoot" class="preview-container" v-html="previewHTML" />
</div>
</div>
- </section>
+
+ </div>
</div>
<div v-else class="loading-wrapper">
<t-loading size="medium" :text="$t('manualEditor.loading.preparing')" />
@@ -913,8 +1125,11 @@ onBeforeUnmount(() => {
/* 复用模型管理同款 SettingDrawer:分组 section / header 图标 / footer 按钮 / 拖拽调宽。
这里只负责本编辑器特有的内容样式。内容内联渲染(无 teleport),scoped 生效。 */
.manual-editor {
+ flex: 1;
+ min-height: 0;
display: flex;
flex-direction: column;
+ gap: 14px;
}
.manual-editor-footer-meta {
@@ -923,6 +1138,18 @@ onBeforeUnmount(() => {
align-items: center;
gap: 8px;
color: var(--td-text-color-placeholder);
+
+ /* 状态标签保持整行,窄抽屉里让后面的时间先省略 */
+ :deep(.t-tag) {
+ flex-shrink: 0;
+ white-space: nowrap;
+ }
+}
+
+.manual-editor-footer-count {
+ font-size: var(--app-text-sm);
+ color: var(--td-text-color-placeholder);
+ white-space: nowrap;
}
.manual-editor-footer-actions {
@@ -940,7 +1167,8 @@ onBeforeUnmount(() => {
border-color: transparent;
background: var(--td-bg-color-secondarycontainer);
color: var(--td-text-color-secondary);
- transition: background 0.18s ease, border-color 0.18s ease, color 0.18s ease;
+ transition: background var(--app-motion-base) ease, border-color var(--app-motion-base) ease,
+ color var(--app-motion-base) ease;
&:hover {
border-color: var(--td-component-stroke);
@@ -949,53 +1177,135 @@ onBeforeUnmount(() => {
}
}
-.form-item {
+/* ---------- 文档头:标题 + 存入位置 ---------- */
+.doc-head {
+ flex-shrink: 0;
display: flex;
- flex-direction: column;
- gap: 6px;
+ align-items: center;
+ gap: 12px;
}
-.form-label {
- font-size: var(--app-text-md);
- font-weight: 500;
- color: var(--td-text-color-primary);
+/* 标题按“文档标题”排版,不做成表单控件;hover/聚焦才显出输入框的边界 */
+:deep(.doc-title) {
+ flex: 1 1 auto;
+ min-width: 0;
+ padding: 0;
+ background: transparent;
+ /* 负外边距抵掉内边距:文字和下方编辑卡左对齐,hover 底色仍有呼吸空间 */
+ margin: 0 -8px;
+
+ .t-input {
+ padding: 4px 8px;
+ border-radius: var(--app-radius-sm);
+ background: transparent;
+ transition: background var(--app-motion-fast) ease;
+ }
+
+ .t-input__inner {
+ font-size: var(--app-text-xl);
+ font-weight: 600;
+ line-height: 1.4;
+ color: var(--td-text-color-primary);
+ }
+
+ &:hover .t-input {
+ background: var(--td-bg-color-container-hover);
+ }
- &.required::after {
- content: '*';
- margin-left: 4px;
- color: var(--td-error-color);
+ .t-input.t-is-focused {
+ background: var(--td-bg-color-container-hover);
}
}
-.form-desc {
- margin: 2px 0 0;
+.doc-meta {
+ flex: 0 0 auto;
+ display: flex;
+ align-items: center;
+ gap: 4px;
font-size: var(--app-text-sm);
color: var(--td-text-color-placeholder);
}
-.kb-row {
- display: flex;
- align-items: center;
- gap: 12px;
+.doc-meta__icon {
+ flex-shrink: 0;
+ font-size: var(--app-text-md);
+}
- :deep(.t-select) {
- flex: 1;
- min-width: 0;
+:deep(.doc-meta__kb) {
+ /* TDesign 的 select 根节点是块级;这里让它收到内容宽度,
+ 否则框比文字宽,箭头够不到右边缘,看着就是没对齐 */
+ flex: 0 1 auto;
+ width: auto;
+ min-width: 0;
+ max-width: 260px;
+
+ .t-input {
+ border-color: transparent;
+ background: transparent;
+ padding-left: 4px;
+ padding-right: 4px;
+ }
+
+ .t-input__inner {
+ color: var(--td-text-color-secondary);
+ }
+
+ &:hover .t-input {
+ border-color: var(--td-component-border);
+ background: var(--td-bg-color-container);
}
}
-.status-row {
- display: flex;
- align-items: center;
- gap: 6px;
- flex-shrink: 0;
+.doc-meta__time {
+ overflow: hidden;
+ text-overflow: ellipsis;
white-space: nowrap;
}
-/* 内容分组:让编辑区占满,无需依赖父级 flex 链路,直接用视口高度,稳健 */
-.editor-section {
+.kb-empty {
+ padding: 20px;
+ text-align: center;
+ color: var(--td-text-color-placeholder);
+}
+
+/* 窄抽屉:与其让工具栏折行(视图切换会悬在第二行),不如把视图切换收成图标,
+ 一行仍然装得下。文字含义由 tooltip 兜底。 */
+.manual-editor--narrow {
+ .view-switch__btn {
+ padding: 0 6px;
+ }
+
+ .view-switch__label {
+ display: none;
+ }
+
+ /* 极窄时的兜底:真放不下才换行,而不是把按钮藏进隐藏的滚动条里 */
+ .editor-toolbar {
+ flex-wrap: wrap;
+ }
+
+ .editor-toolbar__format {
+ flex-wrap: wrap;
+ overflow-x: visible;
+ }
+}
+
+/* ---------- 编辑区 ---------- */
+.editor-area {
flex: 1;
- min-height: 0;
+ /* 视口很矮时不再继续压缩,改由抽屉主体滚动 */
+ min-height: 260px;
+ display: flex;
+ flex-direction: column;
+ border: 1px solid var(--td-component-stroke);
+ border-radius: var(--app-radius-md);
+ overflow: hidden;
+ background: var(--td-bg-color-container);
+ transition: border-color var(--app-motion-base) ease, box-shadow var(--app-motion-base) ease;
+
+ &:focus-within {
+ border-color: var(--td-component-border);
+ }
}
.editor-toolbar {
@@ -1028,43 +1338,84 @@ onBeforeUnmount(() => {
flex-shrink: 0;
display: flex;
align-items: center;
+ gap: 6px;
padding-left: 8px;
border-left: 1px solid var(--td-component-stroke);
}
-.toggle-view-btn {
- min-width: 92px;
- height: 30px;
- padding: 0 10px;
+/* 编辑 / 分屏 / 预览:一组分段控件,当前视图一眼可见 */
+.view-switch {
+ display: flex;
+ align-items: center;
+ gap: 2px;
+ padding: 2px;
+ border-radius: var(--app-radius-sm);
+ background: var(--td-bg-color-component-disabled);
border: 1px solid var(--td-component-stroke);
- border-radius: 7px;
- background: var(--td-bg-color-container);
+}
+
+.view-switch__btn {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ height: 24px;
+ padding: 0 8px;
+ border: none;
+ border-radius: var(--app-radius-xs);
+ background: transparent;
color: var(--td-text-color-secondary);
+ font-size: var(--app-text-sm);
font-weight: 500;
- box-shadow: 0 1px 2px rgba(15, 23, 42, 0.04);
- transition: background 0.18s ease, border-color 0.18s ease, color 0.18s ease, box-shadow 0.18s ease;
+ white-space: nowrap;
+ cursor: pointer;
+ transition: background var(--app-motion-fast) ease, color var(--app-motion-fast) ease;
- &:hover {
- border-color: color-mix(in srgb, var(--td-brand-color) 45%, transparent);
- background: color-mix(in srgb, var(--td-brand-color) 6%, transparent);
- color: var(--td-brand-color);
- box-shadow: 0 2px 6px color-mix(in srgb, var(--td-brand-color) 10%, transparent);
+ &:hover:not(.is-disabled) {
+ background: var(--td-bg-color-container-hover);
+ color: var(--td-text-color-primary);
}
- &.is-preview {
- border-color: color-mix(in srgb, var(--td-brand-color) 50%, transparent);
- background: color-mix(in srgb, var(--td-brand-color) 10%, transparent);
- color: var(--td-brand-color);
+ &.is-active {
+ background: var(--td-bg-color-container);
+ color: var(--td-text-color-primary);
+ box-shadow: 0 1px 2px rgba(15, 23, 42, 0.08);
}
- &:active {
- transform: translateY(1px);
- box-shadow: none;
+ &.is-disabled {
+ color: var(--td-text-color-disabled);
+ cursor: not-allowed;
}
- :deep(.t-button__icon) {
- margin-right: 5px;
- font-size: var(--app-text-lg);
+ &:focus-visible {
+ outline: none;
+ box-shadow: 0 0 0 2px color-mix(in srgb, var(--td-brand-color) 25%, transparent);
+ }
+}
+
+/* 快捷键速查:和视图切换同处工具栏右端,省掉一整条状态栏 */
+.toolbar-shortcuts {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 26px;
+ height: 26px;
+ padding: 0;
+ border: none;
+ border-radius: var(--app-radius-sm);
+ background: transparent;
+ color: var(--td-text-color-placeholder);
+ font-size: var(--app-text-md);
+ cursor: help;
+ transition: background var(--app-motion-fast) ease, color var(--app-motion-fast) ease;
+
+ &:hover {
+ background: var(--td-bg-color-container-hover);
+ color: var(--td-text-color-secondary);
+ }
+
+ &:focus-visible {
+ outline: none;
+ box-shadow: 0 0 0 2px color-mix(in srgb, var(--td-brand-color) 25%, transparent);
}
}
@@ -1074,6 +1425,38 @@ onBeforeUnmount(() => {
gap: 2px;
}
+.toolbar-menu-btn {
+ display: flex;
+ align-items: center;
+ gap: 2px;
+ height: 28px;
+ padding: 0 6px 0 8px;
+ border: none;
+ border-radius: var(--app-radius-sm);
+ background: transparent;
+ color: var(--td-text-color-secondary);
+ font-size: var(--app-text-sm);
+ font-weight: 500;
+ white-space: nowrap;
+ cursor: pointer;
+ transition: background var(--app-motion-base) ease, color var(--app-motion-base) ease;
+
+ &:hover {
+ background: var(--td-bg-color-container-hover);
+ color: var(--td-text-color-primary);
+ }
+
+ &:focus-visible {
+ outline: none;
+ box-shadow: 0 0 0 2px color-mix(in srgb, var(--td-brand-color) 25%, transparent);
+ }
+}
+
+.toolbar-menu-btn__caret {
+ font-size: var(--app-text-sm);
+ opacity: 0.7;
+}
+
.toolbar-divider {
width: 1px;
height: 18px;
@@ -1090,11 +1473,11 @@ onBeforeUnmount(() => {
border: none;
background: transparent;
cursor: pointer;
- transition: all var(--app-motion-base) ease;
+ transition: background var(--app-motion-base) ease, color var(--app-motion-base) ease;
display: flex;
align-items: center;
justify-content: center;
-
+
.t-icon {
color: var(--td-text-color-secondary);
font-size: var(--app-text-xl);
@@ -1104,20 +1487,11 @@ onBeforeUnmount(() => {
}
.toolbar-btn:hover {
- background: color-mix(in srgb, var(--td-brand-color) 8%, transparent);
- color: var(--td-brand-color);
-
- .t-icon {
- color: var(--td-brand-color);
- }
-}
+ background: var(--td-bg-color-container-hover);
+ color: var(--td-text-color-primary);
-.toolbar-btn.active {
- background: color-mix(in srgb, var(--td-brand-color) 12%, transparent);
- color: var(--td-brand-color);
-
.t-icon {
- color: var(--td-brand-color);
+ color: var(--td-text-color-primary);
}
}
@@ -1127,31 +1501,20 @@ onBeforeUnmount(() => {
}
.toolbar-btn:active {
- background: color-mix(in srgb, var(--td-brand-color) 15%, transparent);
+ background: var(--td-bg-color-container-active);
transform: translateY(0.5px);
}
-.editor-area {
- /* 抽屉为整屏高,减去 header/footer/基本信息分组的大致高度,
- 让编辑区占据剩余空间且不必撑满父级 flex 链路。 */
- height: calc(100vh - 360px);
- min-height: 280px;
+.editor-body {
+ flex: 1;
+ min-height: 0;
display: flex;
- flex-direction: column;
- border: 1px solid var(--td-component-stroke);
- border-radius: var(--app-radius-md);
- overflow: hidden;
- background: var(--td-bg-color-container);
- transition: border-color var(--app-motion-base) ease, box-shadow var(--app-motion-base) ease;
-
- &:focus-within {
- border-color: var(--td-brand-color);
- box-shadow: 0 0 0 2px color-mix(in srgb, var(--td-brand-color) 10%, transparent);
- }
+ align-items: stretch;
}
.editor-pane {
flex: 1;
+ min-width: 0;
min-height: 0;
display: flex;
flex-direction: column;
@@ -1159,33 +1522,37 @@ onBeforeUnmount(() => {
background: var(--td-bg-color-container);
}
-:deep(.editor-textarea) {
- flex: 1;
- min-height: 0;
- display: flex;
- flex-direction: column;
- height: 100%;
-
- .t-textarea__inner {
- flex: 1;
- height: 100% !important;
- resize: none;
- border: none;
- border-radius: 0;
- padding: 14px 16px;
- font-family: var(--app-font-family-mono);
- font-size: var(--app-text-base);
- line-height: 1.7;
- background: var(--td-bg-color-container);
+/* 分屏时两栏之间给一道分隔线,预览栏底色略沉,区分“源码 / 成稿” */
+.editor-area--split {
+ .editor-pane--preview {
+ border-left: 1px solid var(--td-component-stroke);
+ background: var(--td-bg-color-secondarycontainer);
+ }
- &:focus {
- box-shadow: none;
- }
+ .preview-container {
+ background: var(--td-bg-color-secondarycontainer);
}
}
-.editor-pane--preview {
+.editor-textarea {
+ flex: 1;
+ min-height: 0;
+ width: 100%;
+ padding: 14px 16px;
+ border: none;
+ outline: none;
+ resize: none;
+ box-sizing: border-box;
+ font-family: var(--app-font-family-mono);
+ font-size: var(--app-text-base);
+ line-height: 1.7;
+ color: var(--td-text-color-primary);
background: var(--td-bg-color-container);
+ tab-size: 2;
+
+ &::placeholder {
+ color: var(--td-text-color-placeholder);
+ }
}
.preview-container {
@@ -1220,17 +1587,21 @@ onBeforeUnmount(() => {
overflow: auto;
}
+ /* 与 chat-markdown.less 的引用块一致:中性描边、无底色 */
:deep(blockquote) {
- border-left: 4px solid var(--td-brand-color);
- padding-left: 12px;
+ border-left: 2px solid var(--td-component-stroke);
+ padding: 6px 0 6px 14px;
color: var(--td-text-color-secondary);
- margin: 16px 0;
- background: color-mix(in srgb, var(--td-brand-color) 8%, transparent);
+ margin: 12px 0;
}
:deep(a) {
color: var(--td-brand-color);
}
+
+ :deep(img) {
+ max-width: 100%;
+ }
}
.loading-wrapper,
@@ -1247,3 +1618,69 @@ onBeforeUnmount(() => {
color: var(--td-text-color-placeholder);
}
</style>
+
+<!--
+ Non-scoped: the editor wants the drawer's full height instead of the body's
+ natural scroll, so the flex chain has to start at TDesign's own body wrapper.
+ Namespaced under .manual-editor-drawer so no other SettingDrawer is affected.
+-->
+<style lang="less">
+/* Tooltip content is teleported out of the component, so its rules cannot be scoped. */
+.shortcut-sheet {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ padding: 2px 0;
+}
+
+.shortcut-sheet__title {
+ font-weight: 600;
+ margin-bottom: 2px;
+}
+
+.shortcut-sheet__row {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ white-space: nowrap;
+
+ kbd {
+ min-width: 42px;
+ font-family: var(--app-font-family-mono);
+ font-size: var(--app-text-xs);
+ opacity: 0.9;
+ }
+}
+
+.manual-editor-drawer {
+ /* 没有副标题的抽屉不需要 65px 的头:收一圈内边距、缩小图标徽章,
+ 把高度还给正文。只作用于本抽屉,不动共用的 SettingDrawer。 */
+ .t-drawer__header {
+ /* TDesign 给 header 兜了 56px 的 min-height,不解开就只是白留一圈空 */
+ min-height: 0;
+ padding: 9px 18px;
+ }
+
+ .setting-drawer__header {
+ padding: 0;
+ }
+
+ .setting-drawer__header-icon {
+ width: 26px;
+ height: 26px;
+ border-radius: var(--app-radius-sm);
+ font-size: var(--app-text-md);
+ }
+
+ .t-drawer__body {
+ display: flex;
+ flex-direction: column;
+ overflow: auto;
+ }
+
+ .setting-drawer__body {
+ flex: 1;
+ min-height: 0;
+ }
+}
+</style>
diff --git a/frontend/src/components/settings/SettingDrawer.vue b/frontend/src/components/settings/SettingDrawer.vue
index a6c02b328..11b30e479 100644
--- a/frontend/src/components/settings/SettingDrawer.vue
+++ b/frontend/src/components/settings/SettingDrawer.vue
@@ -1,6 +1,6 @@
<template>
<teleport to="body">
- <div v-if="drawerVisible && resizable" class="setting-drawer-resize-handle"
+ <div v-if="drawerVisible && resizable && !maximized" class="setting-drawer-resize-handle"
:class="{ 'setting-drawer-resize-handle--active': drawerResizing }"
:style="{ right: `${drawerWidthPx}px`, '--setting-drawer-travel': `${drawerWidthPx}px` }"
role="separator" aria-orientation="vertical" @mousedown.prevent="onResizeStart">
@@ -31,7 +31,20 @@
<slot name="subtitle">{{ description }}</slot>
</div>
</div>
- <div :id="headerActionsId" class="setting-drawer__header-actions"><slot name="header-actions" /></div>
+ <div class="setting-drawer__header-tools">
+ <div :id="headerActionsId" class="setting-drawer__header-actions"><slot name="header-actions" /></div>
+ <t-tooltip v-if="maximizable" :content="maximized ? t('common.exitFullscreen') : t('common.fullscreen')" placement="bottom">
+ <button
+ type="button"
+ class="setting-drawer__maximize"
+ :aria-label="maximized ? t('common.exitFullscreen') : t('common.fullscreen')"
+ :aria-pressed="maximized"
+ @click="maximized = !maximized"
+ >
+ <t-icon :name="maximized ? 'fullscreen-exit' : 'fullscreen'" />
+ </button>
+ </t-tooltip>
+ </div>
</div>
<div v-if="$slots['header-extra']" class="setting-drawer__header-extra">
<slot name="header-extra" />
@@ -74,7 +87,7 @@ export const SETTING_DRAWER_HEADER_ACTIONS_ID: InjectionKey<string> = Symbol('se
</script>
<script setup lang="ts">
-import { ref, computed, provide, useAttrs, useId, onMounted, onUnmounted } from 'vue'
+import { ref, computed, provide, useAttrs, useId, onMounted, onUnmounted, watch } from 'vue'
import { useI18n } from 'vue-i18n'
interface Props {
@@ -96,6 +109,12 @@ interface Props {
/** Min/max bounds for the drag-resize, in px. */
minWidth?: number
maxWidth?: number
+ /**
+ * Show a maximize toggle in the header. Content-heavy drawers (the Markdown
+ * editor) need more room than `maxWidth` allows; while maximized the drawer
+ * spans the viewport and the drag handle steps aside.
+ */
+ maximizable?: boolean
/**
* localStorage key used to remember the user's chosen width. Set to '' to
* disable persistence. Default key is namespaced per-consumer using the
@@ -120,6 +139,7 @@ const props = withDefaults(defineProps<Props>(), {
resizable: true,
minWidth: 480,
maxWidth: 1200,
+ maximizable: false,
storageKey: '',
confirmLoading: false,
cancelDisabled: false,
@@ -195,7 +215,18 @@ const drawerWidthPx = computed(() =>
clampWidth(userWidthPx.value ?? parseWidthToPx(props.width)),
)
-const effectiveWidth = computed(() => `${drawerWidthPx.value}px`)
+// ---------- maximize ----------
+const maximized = ref(false)
+
+// Leaving the drawer maximized would surprise the next caller of the same
+// storage key, so the toggle lives for one open.
+watch(drawerVisible, (val) => {
+ if (!val) maximized.value = false
+})
+
+const effectiveWidth = computed(() =>
+ maximized.value ? `${viewportWidth.value}px` : `${drawerWidthPx.value}px`,
+)
const persistWidth = (width: number) => {
const next = clampWidth(width)
@@ -324,11 +355,45 @@ const handleCancel = () => {
min-width: 0;
}
-.setting-drawer__header-actions {
+.setting-drawer__header-tools {
flex-shrink: 0;
display: flex;
align-items: center;
+ gap: 8px;
margin-left: auto;
+}
+
+.setting-drawer__maximize {
+ flex-shrink: 0;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 28px;
+ height: 28px;
+ padding: 0;
+ border: none;
+ border-radius: var(--app-radius-sm);
+ background: transparent;
+ color: var(--td-text-color-secondary);
+ font-size: var(--app-text-lg);
+ cursor: pointer;
+ transition: background var(--app-motion-fast) ease, color var(--app-motion-fast) ease;
+
+ &:hover {
+ background: var(--td-bg-color-container-hover);
+ color: var(--td-text-color-primary);
+ }
+
+ &:focus-visible {
+ outline: none;
+ box-shadow: 0 0 0 2px color-mix(in srgb, var(--td-brand-color) 25%, transparent);
+ }
+}
+
+.setting-drawer__header-actions {
+ flex-shrink: 0;
+ display: flex;
+ align-items: center;
&:empty {
display: none;
diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts
index cae7aed56..8cc98768d 100755
--- a/frontend/src/i18n/locales/en-US.ts
+++ b/frontend/src/i18n/locales/en-US.ts
@@ -2483,6 +2483,8 @@ export default {
discard: 'Discard changes',
keepEditing: 'Keep editing',
},
+ fullscreen: 'Full screen',
+ exitFullscreen: 'Exit full screen',
save: 'Save',
delete: 'Delete',
edit: 'Edit',
@@ -2585,11 +2587,21 @@ export default {
link: 'Insert link',
image: 'Insert image',
table: 'Insert table',
- horizontalRule: 'Horizontal rule'
+ horizontalRule: 'Horizontal rule',
+ headingGroup: 'Heading',
+ insertGroup: 'Insert'
+ },
+ shortcuts: {
+ title: 'Shortcuts',
+ continueList: 'Continue the list',
+ indent: 'Indent / Shift+Tab to outdent'
},
view: {
- editLabel: 'Back to edit',
- previewLabel: 'Preview content'
+ edit: 'Edit',
+ split: 'Split',
+ preview: 'Preview',
+ splitUnavailable: 'Widen the drawer or go full screen to split the view',
+ groupLabel: 'Editor view'
},
preview: {
empty: 'No content yet'
@@ -2598,9 +2610,7 @@ export default {
edit: 'Edit Markdown Knowledge',
create: 'Create Markdown Knowledge'
},
- description: 'Write knowledge in Markdown with live preview',
section: {
- basic: 'Basic Info',
content: 'Content'
},
labels: {
@@ -2622,9 +2632,9 @@ export default {
published: 'Knowledge published and indexing started'
},
form: {
- knowledgeBaseLabel: 'Target knowledge base',
knowledgeBasePlaceholder: 'Select knowledge base',
titleLabel: 'Knowledge title',
+ knowledgeBaseLabel: 'Target knowledge base',
titlePlaceholder: 'Enter title',
contentPlaceholder: 'Supports Markdown. Use # headings, lists, code blocks, etc.'
},
@@ -2632,7 +2642,8 @@ export default {
status: {
draftTag: 'Status: Draft',
publishedTag: 'Status: Published',
- lastUpdated: 'Last updated: {time}'
+ lastUpdated: 'Last updated: {time}',
+ counter: '{chars} characters · {lines} lines'
},
loading: {
content: 'Loading content...',
@@ -3797,6 +3808,7 @@ export default {
processError: 'Processing error',
sessionExcerpt: 'Session Excerpt',
noAnswerContent: '(No answer content)',
+ manualSourcesHeading: 'Sources',
noMatchFound: 'No matching content found',
deleteSessionFailed: 'Delete failed, please try again later!',
imageTooMany: 'Maximum 5 images allowed',
diff --git a/frontend/src/i18n/locales/ja-JP.ts b/frontend/src/i18n/locales/ja-JP.ts
index 6d4cb9c5b..138557e10 100644
--- a/frontend/src/i18n/locales/ja-JP.ts
+++ b/frontend/src/i18n/locales/ja-JP.ts
@@ -2483,6 +2483,8 @@ export default {
discard: '変更を破棄',
keepEditing: '編集を続ける',
},
+ fullscreen: '全画面',
+ exitFullscreen: '全画面を終了',
save: '保存',
delete: '削除',
edit: '編集',
@@ -2585,11 +2587,21 @@ export default {
link: 'リンクを挿入',
image: '画像を挿入',
table: '表を挿入',
- horizontalRule: '水平線'
+ horizontalRule: '水平線',
+ headingGroup: '見出し',
+ insertGroup: '挿入'
+ },
+ shortcuts: {
+ title: 'ショートカット',
+ continueList: 'リストを続ける',
+ indent: 'インデント / Shift+Tab で解除'
},
view: {
- editLabel: '編集に戻る',
- previewLabel: '内容をプレビュー'
+ edit: '編集',
+ split: '分割',
+ preview: 'プレビュー',
+ splitUnavailable: '幅が足りません。ドロワーを広げるか全画面にすると分割できます',
+ groupLabel: 'エディタ表示'
},
preview: {
empty: 'まだ内容がありません'
@@ -2598,9 +2610,7 @@ export default {
edit: 'Markdownナレッジを編集',
create: 'Markdownナレッジを作成'
},
- description: 'Markdownでナレッジを記述し、リアルタイムでプレビューできます',
section: {
- basic: '基本情報',
content: '内容'
},
labels: {
@@ -2622,9 +2632,9 @@ export default {
published: 'ナレッジを公開し、インデックス作成を開始しました'
},
form: {
- knowledgeBaseLabel: '対象のナレッジベース',
knowledgeBasePlaceholder: 'ナレッジベースを選択',
titleLabel: 'ナレッジのタイトル',
+ knowledgeBaseLabel: '対象のナレッジベース',
titlePlaceholder: 'タイトルを入力',
contentPlaceholder: 'Markdownに対応しています。#見出し、リスト、コードブロックなどが使えます。'
},
@@ -2632,7 +2642,8 @@ export default {
status: {
draftTag: 'ステータス: 下書き',
publishedTag: 'ステータス: 公開済み',
- lastUpdated: '最終更新: {time}'
+ lastUpdated: '最終更新: {time}',
+ counter: '{chars} 文字 · {lines} 行'
},
loading: {
content: '内容を読み込み中...',
@@ -3797,6 +3808,7 @@ export default {
processError: '処理エラー',
sessionExcerpt: 'セッション抜粋',
noAnswerContent: '(回答内容なし)',
+ manualSourcesHeading: '参照元',
noMatchFound: '一致する内容が見つかりません',
deleteSessionFailed: '削除に失敗しました。しばらくしてから再試行してください!',
imageTooMany: '画像は最大5枚までです',
diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts
index ceb4b2307..ccbd54bca 100755
--- a/frontend/src/i18n/locales/ko-KR.ts
+++ b/frontend/src/i18n/locales/ko-KR.ts
@@ -3923,6 +3923,7 @@ export default {
processError: '처리 오류',
sessionExcerpt: '대화 발췌',
noAnswerContent: '(답변 내용 없음)',
+ manualSourcesHeading: '참고 출처',
noMatchFound: '일치하는 내용을 찾을 수 없습니다',
deleteSessionFailed: '삭제 실패, 나중에 다시 시도해주세요!',
imageTooMany: '최대 5장까지 업로드 가능합니다',
@@ -4919,7 +4920,6 @@ export default {
}
},
manualEditor: {
- description: 'Markdown으로 지식을 작성하고 실시간 미리보기 지원',
defaultTitlePrefix: '새 문서',
noDocumentKnowledgeBases: '사용 가능한 문서형 지식베이스가 없습니다. 먼저 문서형 지식베이스를 생성해주세요',
actions: {
@@ -4934,12 +4934,13 @@ export default {
status: {
draftTag: '현재 상태: 임시 저장',
publishedTag: '현재 상태: 게시됨',
- lastUpdated: '최근 업데이트: {time}'
+ lastUpdated: '최근 업데이트: {time}',
+ counter: '{chars}자 · {lines}줄'
},
form: {
- knowledgeBaseLabel: '대상 지식베이스',
knowledgeBasePlaceholder: '지식베이스를 선택해주세요',
titleLabel: '지식 제목',
+ knowledgeBaseLabel: '대상 지식베이스',
titlePlaceholder: '제목을 입력해주세요',
contentPlaceholder: 'Markdown 구문을 지원합니다. # 제목, 목록, 코드 블록 등을 사용할 수 있습니다'
},
@@ -4961,7 +4962,6 @@ export default {
currentKnowledgeBase: '현재 지식베이스'
},
section: {
- basic: '기본 정보',
content: '지식 내용'
},
title: {
@@ -4971,9 +4971,17 @@ export default {
preview: {
empty: '내용 없음'
},
+ shortcuts: {
+ title: '단축키',
+ continueList: '목록 이어쓰기',
+ indent: '들여쓰기 / Shift+Tab 내어쓰기'
+ },
view: {
- editLabel: '편집으로 돌아가기',
- previewLabel: '내용 미리보기'
+ edit: '편집',
+ split: '분할',
+ preview: '미리보기',
+ splitUnavailable: '너비가 부족합니다. 서랍을 넓히거나 전체 화면으로 전환하세요',
+ groupLabel: '편집기 보기'
},
toolbar: {
bold: '굵게',
@@ -4991,7 +4999,9 @@ export default {
link: '링크 삽입',
image: '이미지 삽입',
table: '표 삽입',
- horizontalRule: '구분선'
+ horizontalRule: '구분선',
+ headingGroup: '제목',
+ insertGroup: '삽입'
},
table: {
column1: '열1',
@@ -5037,6 +5047,8 @@ export default {
discard: '변경 사항 버리기',
keepEditing: '계속 편집',
},
+ fullscreen: '전체 화면',
+ exitFullscreen: '전체 화면 종료',
save: '저장',
delete: '삭제',
edit: '편집',
diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts
index 8c77cae7d..29b1f9f2f 100755
--- a/frontend/src/i18n/locales/ru-RU.ts
+++ b/frontend/src/i18n/locales/ru-RU.ts
@@ -3923,6 +3923,7 @@ export default {
processError: 'Ошибка обработки',
sessionExcerpt: 'Выдержка из сессии',
noAnswerContent: '(Нет содержимого ответа)',
+ manualSourcesHeading: 'Источники',
noMatchFound: 'Совпадений не найдено',
deleteSessionFailed: 'Ошибка удаления, попробуйте позже!',
imageTooMany: 'Максимум 5 изображений',
@@ -4919,7 +4920,6 @@ export default {
}
},
manualEditor: {
- description: 'Пишите знания в Markdown с предпросмотром в реальном времени',
defaultTitlePrefix: 'Новый документ',
noDocumentKnowledgeBases: 'Нет доступных баз знаний типа "документ". Пожалуйста, создайте одну сначала',
actions: {
@@ -4934,12 +4934,13 @@ export default {
status: {
draftTag: 'Статус: Черновик',
publishedTag: 'Статус: Опубликовано',
- lastUpdated: 'Последнее обновление: {time}'
+ lastUpdated: 'Последнее обновление: {time}',
+ counter: 'Символов: {chars} · Строк: {lines}'
},
form: {
- knowledgeBaseLabel: 'Целевая база знаний',
knowledgeBasePlaceholder: 'Выберите базу знаний',
titleLabel: 'Заголовок знания',
+ knowledgeBaseLabel: 'Целевая база знаний',
titlePlaceholder: 'Введите заголовок',
contentPlaceholder: 'Поддерживается Markdown. Используйте # заголовки, списки, блоки кода и т.д.'
},
@@ -4961,7 +4962,6 @@ export default {
currentKnowledgeBase: 'Текущая база знаний'
},
section: {
- basic: 'Основная информация',
content: 'Содержимое'
},
title: {
@@ -4971,9 +4971,17 @@ export default {
preview: {
empty: 'Пока нет содержимого'
},
+ shortcuts: {
+ title: 'Горячие клавиши',
+ continueList: 'Продолжить список',
+ indent: 'Отступ / Shift+Tab — назад'
+ },
view: {
- editLabel: 'Вернуться к редактированию',
- previewLabel: 'Предпросмотр'
+ edit: 'Редактор',
+ split: 'Разделить',
+ preview: 'Предпросмотр',
+ splitUnavailable: 'Расширьте панель или включите полный экран, чтобы разделить вид',
+ groupLabel: 'Вид редактора'
},
toolbar: {
bold: 'Жирный',
@@ -4991,7 +4999,9 @@ export default {
link: 'Вставить ссылку',
image: 'Вставить изображение',
table: 'Вставить таблицу',
- horizontalRule: 'Горизонтальная линия'
+ horizontalRule: 'Горизонтальная линия',
+ headingGroup: 'Заголовок',
+ insertGroup: 'Вставить'
},
table: {
column1: 'Колонка 1',
@@ -5037,6 +5047,8 @@ export default {
discard: 'Отменить изменения',
keepEditing: 'Продолжить редактирование',
},
+ fullscreen: 'Полный экран',
+ exitFullscreen: 'Выйти из полного экрана',
save: 'Сохранить',
delete: 'Удалить',
edit: 'Редактировать',
diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts
index 1939eccd0..8ba874f86 100755
--- a/frontend/src/i18n/locales/zh-CN.ts
+++ b/frontend/src/i18n/locales/zh-CN.ts
@@ -3925,6 +3925,7 @@ export default {
processError: '处理出错',
sessionExcerpt: '会话摘录',
noAnswerContent: '(无回答内容)',
+ manualSourcesHeading: '参考来源',
noMatchFound: '未找到匹配的内容',
deleteSessionFailed: '删除失败,请稍后再试!',
imageTooMany: '最多上传5张图片',
@@ -4921,7 +4922,6 @@ export default {
}
},
manualEditor: {
- description: '使用 Markdown 编写知识内容,支持实时预览',
defaultTitlePrefix: '新建文档',
noDocumentKnowledgeBases: '暂无可用的文档型知识库,请先创建一个文档型知识库',
actions: {
@@ -4936,12 +4936,13 @@ export default {
status: {
draftTag: '当前状态:草稿',
publishedTag: '当前状态:已发布',
- lastUpdated: '最近更新:{time}'
+ lastUpdated: '最近更新:{time}',
+ counter: '{chars} 字 · {lines} 行'
},
form: {
- knowledgeBaseLabel: '目标知识库',
knowledgeBasePlaceholder: '请选择知识库',
titleLabel: '知识标题',
+ knowledgeBaseLabel: '目标知识库',
titlePlaceholder: '请输入标题',
contentPlaceholder: '支持 Markdown 语法,可使用 # 标题、列表、代码块等'
},
@@ -4963,7 +4964,6 @@ export default {
currentKnowledgeBase: '当前知识库'
},
section: {
- basic: '基本信息',
content: '知识内容'
},
title: {
@@ -4973,9 +4973,17 @@ export default {
preview: {
empty: '暂无内容'
},
+ shortcuts: {
+ title: '快捷键',
+ continueList: '列表内自动续行',
+ indent: '缩进 / Shift+Tab 反缩进'
+ },
view: {
- editLabel: '返回编辑',
- previewLabel: '预览内容'
+ edit: '编辑',
+ split: '分屏',
+ preview: '预览',
+ splitUnavailable: '宽度不足,拖宽抽屉或全屏后可用分屏',
+ groupLabel: '编辑区视图'
},
toolbar: {
bold: '加粗',
@@ -4993,7 +5001,9 @@ export default {
link: '插入链接',
image: '插入图片',
table: '插入表格',
- horizontalRule: '分割线'
+ horizontalRule: '分割线',
+ headingGroup: '标题',
+ insertGroup: '插入'
},
table: {
column1: '列1',
@@ -5039,6 +5049,8 @@ export default {
discard: '放弃更改',
keepEditing: '继续编辑',
},
+ fullscreen: '全屏',
+ exitFullscreen: '退出全屏',
save: '保存',
delete: '删除',
edit: '编辑',
diff --git a/frontend/src/utils/chatMessageShared.ts b/frontend/src/utils/chatMessageShared.ts
index 3fea40992..96b0b253a 100644
--- a/frontend/src/utils/chatMessageShared.ts
+++ b/frontend/src/utils/chatMessageShared.ts
@@ -1,5 +1,6 @@
import i18n from '@/i18n';
import { buildMermaidBlockHtml, buildMermaidLoadingHtml } from '@/utils/markdownEnhancements';
+import { buildManualDraft, deriveManualTitle } from './manualKnowledgeDraft';
import {
injectCachedMermaidSvg as injectCachedMermaidSvgHtml,
maskMermaidBlocksForStreaming as maskMermaidBlocks,
@@ -67,17 +68,12 @@ export const injectCachedMermaidSvg = (
};
export const formatManualTitle = (question?: string): string => {
- if (!question) {
- return i18n.global.t('chat.sessionExcerpt');
- }
- const condensed = question.replace(/\s+/g, ' ').trim();
- if (!condensed) {
- return i18n.global.t('chat.sessionExcerpt');
- }
- return condensed.length > 40 ? `${condensed.slice(0, 40)}...` : condensed;
+ return deriveManualTitle(question || '', i18n.global.t('chat.sessionExcerpt'));
};
export const buildManualMarkdown = (_question: string, answer: string): string => {
- const safeAnswer = answer?.trim() || i18n.global.t('chat.noAnswerContent');
- return `${safeAnswer}`;
+ return buildManualDraft(answer, {
+ emptyAnswer: i18n.global.t('chat.noAnswerContent'),
+ sourcesHeading: i18n.global.t('chat.manualSourcesHeading'),
+ });
};
diff --git a/frontend/src/utils/citationMarkdown.ts b/frontend/src/utils/citationMarkdown.ts
index 32710dcfb..8f503428a 100644
--- a/frontend/src/utils/citationMarkdown.ts
+++ b/frontend/src/utils/citationMarkdown.ts
@@ -314,3 +314,50 @@ export function preserveCitationTags(contentStr: string): { text: string; tags:
export function restoreCitationTags(text: string, tags: string[]): string {
return text.replace(/\x00TAG(\d+)\x00/g, (_, idx) => tags[Number(idx)] || '')
}
+
+/** A line that holds nothing but `<kb/>` tags, including its line break. */
+const KB_ONLY_LINE_RE = /^[ \t]*(?:<kb\b[^>]*?\/?>[ \t]*)+\n?/gm
+/** An inline `<kb/>` tag together with the space that separated it from the text. */
+const KB_INLINE_TAG_RE = /[ \t]*<kb\b[^>]*?\s*\/?>/g
+
+/**
+ * Strip chat-only citation markup so an answer can live on as standalone
+ * Markdown (e.g. saved into a knowledge base by "add to knowledge").
+ *
+ * `<web/>` becomes a plain Markdown link — the URL still means something
+ * outside the chat. `<kb/>` points at chunk UUIDs that do not, so it is dropped
+ * and its document name is returned instead, for the caller to render as a
+ * source list. Removal stays local to the tags: no whitespace elsewhere in the
+ * answer is touched, so code blocks survive unchanged.
+ */
+export function stripCitationTagsForMarkdown(
+ content: string,
+): { text: string; sources: string[] } {
+ if (!content) return { text: '', sources: [] }
+
+ const sources: string[] = []
+ const seen = new Set<string>()
+ KB_TAG_ATTR_RE.lastIndex = 0
+ for (const match of content.matchAll(KB_TAG_ATTR_RE)) {
+ const doc = (parseTagAttributes(match[1]).doc || '').trim()
+ if (doc && !seen.has(doc)) {
+ seen.add(doc)
+ sources.push(doc)
+ }
+ }
+
+ const text = content
+ .replace(WEB_TAG_ATTR_RE, (_match, attrString: string) => {
+ const attrs = parseTagAttributes(attrString)
+ const url = (attrs.url || '').trim()
+ if (!url) return ''
+ // Brackets inside the label would break the link syntax we emit.
+ const label = (attrs.title || '').trim().replace(/[[\]]/g, ' ').trim() || url
+ return `[${label}](${url})`
+ })
+ .replace(KB_ONLY_LINE_RE, '')
+ .replace(KB_INLINE_TAG_RE, '')
+ .trim()
+
+ return { text, sources }
+}
diff --git a/frontend/src/utils/manualKnowledgeDraft.test.ts b/frontend/src/utils/manualKnowledgeDraft.test.ts
new file mode 100644
index 000000000..9f3ad338f
--- /dev/null
+++ b/frontend/src/utils/manualKnowledgeDraft.test.ts
@@ -0,0 +1,67 @@
+import assert from 'node:assert/strict'
+import test from 'node:test'
+import { buildManualDraft, deriveManualTitle } from './manualKnowledgeDraft'
+
+const labels = { emptyAnswer: '(无内容)', sourcesHeading: '参考来源' }
+
+test('a chat answer loses its <kb/> tags and gains a source list', () => {
+ const answer = [
+ '## 二元技术观',
+ '',
+ '> **"人们陷入非好即坏的二元看法。"** <kb doc="Interview.md" chunk_id="230a27cb-45c8-4ba9-9ba1-babea70bcd95" kb_id="441ee604-a04d-4c9a-a4bd-1c4e198e6226" />',
+ '',
+ '他接着以 Zig 为例 <kb doc="Interview.md" chunk_id="ef18491c-34f0-4563-bb4a-062cacbdfd95" kb_id="441ee604-a04d-4c9a-a4bd-1c4e198e6226" />',
+ ].join('\n')
+
+ const draft = buildManualDraft(answer, labels)
+
+ assert.ok(!draft.includes('<kb'), draft)
+ assert.ok(!draft.includes('chunk_id'), draft)
+ assert.ok(draft.includes('> **"人们陷入非好即坏的二元看法。"**'))
+ assert.ok(draft.endsWith('**参考来源**\n\n- Interview.md\n'), draft)
+})
+
+test('web citations survive as real Markdown links', () => {
+ const draft = buildManualDraft('见 <web url="https://ziglang.org" title="Zig" /> 官网', labels)
+ assert.equal(draft, '见 [Zig](https://ziglang.org) 官网')
+})
+
+test('a tag alone on its line leaves no blank line behind', () => {
+ const draft = buildManualDraft('第一段\n<kb doc="A.md" chunk_id="1" />\n第二段', labels)
+ assert.equal(draft, '第一段\n第二段\n\n---\n\n**参考来源**\n\n- A.md\n')
+})
+
+test('code blocks keep their own spacing while citations are stripped', () => {
+ const answer = '```js\nfn( 1 ) ;\n\n\nconst x = 2\n```\n\n说明 <kb doc="A.md" chunk_id="1" />'
+ const draft = buildManualDraft(answer, labels)
+ assert.ok(draft.startsWith('```js\nfn( 1 ) ;\n\n\nconst x = 2\n```'), draft)
+ assert.ok(draft.includes('\n\n说明\n'), draft)
+})
+
+test('an answer without citations is passed through untouched', () => {
+ assert.equal(buildManualDraft('纯文本回答', labels), '纯文本回答')
+ assert.equal(buildManualDraft(' ', labels), '(无内容)')
+})
+
+test('a long question is cut on a clause boundary, with no trailing ellipsis', () => {
+ const title = deriveManualTitle(
+ '互联网上的人们常常陷入对技术好坏的二元看法,这种看法如何影响了技术的多样性和创新?',
+ '对话摘录',
+ )
+ assert.equal(title, '互联网上的人们常常陷入对技术好坏的二元看法')
+})
+
+test('a short question keeps its wording, minus the question mark', () => {
+ assert.equal(deriveManualTitle('Zig 为什么值得关注?', '对话摘录'), 'Zig 为什么值得关注')
+ assert.equal(deriveManualTitle(' ', '对话摘录'), '对话摘录')
+})
+
+test('a long question with no boundary is cut at the limit', () => {
+ const title = deriveManualTitle('长'.repeat(60), '对话摘录')
+ assert.equal(title, '长'.repeat(32))
+})
+
+test('an English question is cut on a word boundary', () => {
+ const title = deriveManualTitle('How does a binary view of technology hurt diversity?', '对话摘录')
+ assert.equal(title, 'How does a binary view of')
+})
diff --git a/frontend/src/utils/manualKnowledgeDraft.ts b/frontend/src/utils/manualKnowledgeDraft.ts
new file mode 100644
index 000000000..b8298e960
--- /dev/null
+++ b/frontend/src/utils/manualKnowledgeDraft.ts
@@ -0,0 +1,56 @@
+import { stripCitationTagsForMarkdown } from './citationMarkdown'
+
+/** Longest title we derive from a question before cutting it down. */
+const MANUAL_TITLE_MAX = 32
+
+/** A boundary cut has to leave at least this much of the question behind. */
+const MANUAL_TITLE_MIN = 12
+
+/** Punctuation that reads as noise at the end of a document title. */
+const TRAILING_PUNCTUATION_RE = /[??!!。.,,、;;::\s]+$/
+
+/** Clause boundaries we prefer to cut a long question on. */
+const TITLE_BOUNDARIES = [',', '。', ';', ':', '?', '!', '、', ',', ';', ':', ' ']
+
+/**
+ * Turn the asked question into a document title.
+ *
+ * A question mark and a hard cut mid-word ("……的多样性和创新...") both read as
+ * an unfinished sentence in a knowledge list, so we drop the trailing
+ * punctuation and, when the question is too long, cut it on the last clause
+ * boundary instead of appending an ellipsis.
+ */
+export function deriveManualTitle(question: string, fallback: string): string {
+ const condensed = (question || '').replace(/\s+/g, ' ').trim()
+ if (!condensed) return fallback
+
+ const stripped = condensed.replace(TRAILING_PUNCTUATION_RE, '').trim() || condensed
+ if (stripped.length <= MANUAL_TITLE_MAX) return stripped
+
+ const head = stripped.slice(0, MANUAL_TITLE_MAX)
+ const boundary = TITLE_BOUNDARIES.reduce((best, char) => Math.max(best, head.lastIndexOf(char)), -1)
+ // Only honour a boundary that still leaves a meaningful title behind.
+ const cut = boundary >= MANUAL_TITLE_MIN ? head.slice(0, boundary) : head
+ return cut.replace(TRAILING_PUNCTUATION_RE, '').trim() || head.trim()
+}
+
+/**
+ * Build the Markdown body seeded into the manual editor from a chat answer.
+ *
+ * The raw answer carries inline `<kb/>` citation tags whose chunk/kb UUIDs are
+ * meaningless once the text leaves the conversation — they used to land in the
+ * editor verbatim and had to be deleted by hand. Strip them, keep `<web/>`
+ * citations as real links, and list the cited documents once at the bottom so
+ * the provenance survives.
+ */
+export function buildManualDraft(
+ answer: string,
+ labels: { emptyAnswer: string; sourcesHeading: string },
+): string {
+ const { text, sources } = stripCitationTagsForMarkdown(answer || '')
+ const body = text.trim() || labels.emptyAnswer
+ if (!sources.length) return body
+
+ const list = sources.map((source) => `- ${source}`).join('\n')
+ return `${body}\n\n---\n\n**${labels.sourcesHeading}**\n\n${list}\n`
+}
diff --git a/frontend/src/utils/markdownEditing.test.ts b/frontend/src/utils/markdownEditing.test.ts
new file mode 100644
index 000000000..222631bef
--- /dev/null
+++ b/frontend/src/utils/markdownEditing.test.ts
@@ -0,0 +1,49 @@
+import assert from 'node:assert/strict'
+import test from 'node:test'
+import { continueListOnEnter, countContent, indentOnTab } from './markdownEditing'
+
+const caret = (value: string, at: number) => ({ value, start: at, end: at })
+
+test('Enter continues a bullet, a task item and a numbered list', () => {
+ const bullet = continueListOnEnter(caret('- first', 7))
+ assert.deepEqual(bullet, { value: '- first\n- ', start: 10, end: 10 })
+
+ const task = continueListOnEnter(caret('- [x] done', 10))
+ assert.deepEqual(task, { value: '- [x] done\n- [ ] ', start: 17, end: 17 })
+
+ const ordered = continueListOnEnter(caret(' 9. nine', 9))
+ assert.deepEqual(ordered, { value: ' 9. nine\n 10. ', start: 16, end: 16 })
+})
+
+test('Enter on an empty item ends the list instead of stacking markers', () => {
+ const patch = continueListOnEnter(caret('- first\n- ', 10))
+ assert.deepEqual(patch, { value: '- first\n', start: 8, end: 8 })
+})
+
+test('Enter outside a list and over a selection is left to the browser', () => {
+ assert.equal(continueListOnEnter(caret('plain text', 10)), null)
+ assert.equal(continueListOnEnter({ value: '- first', start: 2, end: 7 }), null)
+})
+
+test('Tab indents a list line and Shift+Tab takes it back out', () => {
+ const indented = indentOnTab(caret('- item', 6), false)
+ assert.deepEqual(indented, { value: ' - item', start: 8, end: 8 })
+
+ const outdented = indentOnTab(caret(' - item', 8), true)
+ assert.equal(outdented?.value, '- item')
+})
+
+test('Tab indents every line of a multi-line selection but skips blank ones', () => {
+ const patch = indentOnTab({ value: 'a\n\nb', start: 0, end: 4 }, false)
+ assert.equal(patch?.value, ' a\n\n b')
+ assert.deepEqual([patch?.start, patch?.end], [0, 8])
+})
+
+test('Tab stays a focus move when it would not indent anything', () => {
+ assert.equal(indentOnTab(caret('plain text', 4), false), null)
+})
+
+test('countContent reports characters and lines', () => {
+ assert.deepEqual(countContent('one\ntwo'), { characters: 7, lines: 2 })
+ assert.deepEqual(countContent(''), { characters: 0, lines: 0 })
+})
diff --git a/frontend/src/utils/markdownEditing.ts b/frontend/src/utils/markdownEditing.ts
new file mode 100644
index 000000000..19a342fa5
--- /dev/null
+++ b/frontend/src/utils/markdownEditing.ts
@@ -0,0 +1,115 @@
+/**
+ * Keyboard behaviours a plain <textarea> does not give a Markdown author:
+ * continuing a list on Enter and indenting a block with Tab.
+ *
+ * Everything here is a pure string transform — the component owns the DOM and
+ * only applies the returned value/selection.
+ */
+
+export interface EditorState {
+ value: string
+ start: number
+ end: number
+}
+
+/** A `null` result means "let the browser handle the key normally". */
+export type EditorPatch = EditorState | null
+
+/** Indent unit: two spaces, the width Markdown nests a list item with. */
+const INDENT = ' '
+
+/** `- `, `* `, `+ `, `1. `, `1) `, optionally followed by a `[ ]` checkbox. */
+const LIST_LINE_RE = /^([ \t]*)([-*+]|\d+[.)])[ \t]+(\[[ xX]\][ \t]+)?(.*)$/
+
+const lineStartAt = (value: string, index: number): number => {
+ if (index <= 0) return 0
+ const previousBreak = value.lastIndexOf('\n', index - 1)
+ return previousBreak === -1 ? 0 : previousBreak + 1
+}
+
+const lineEndAt = (value: string, index: number): number => {
+ const nextBreak = value.indexOf('\n', index)
+ return nextBreak === -1 ? value.length : nextBreak
+}
+
+/**
+ * Enter inside a list item keeps the list going.
+ *
+ * An item that is still empty ends the list instead — the same escape hatch
+ * every Markdown editor has, so Enter twice gets you back to a paragraph.
+ */
+export function continueListOnEnter({ value, start, end }: EditorState): EditorPatch {
+ // A range selection replaces text; leave that to the browser.
+ if (start !== end) return null
+
+ const lineStart = lineStartAt(value, start)
+ const match = LIST_LINE_RE.exec(value.slice(lineStart, start))
+ if (!match) return null
+
+ const [, indent, marker, checkbox, content] = match
+ if (!content.trim()) {
+ // Empty item: drop the marker and leave the caret on a clean line.
+ const nextValue = value.slice(0, lineStart) + value.slice(start)
+ return { value: nextValue, start: lineStart, end: lineStart }
+ }
+
+ const nextMarker = /^\d+[.)]$/.test(marker)
+ ? `${parseInt(marker, 10) + 1}${marker.slice(-1)}`
+ : marker
+ const prefix = `\n${indent}${nextMarker} ${checkbox ? '[ ] ' : ''}`
+ const caret = start + prefix.length
+ return { value: value.slice(0, start) + prefix + value.slice(start), start: caret, end: caret }
+}
+
+const hasLineBreak = (value: string, start: number, end: number) =>
+ value.slice(start, end).includes('\n')
+
+/** Rewrite every line the selection touches, keeping it selected. */
+function mapSelectedLines(
+ { value, start, end }: EditorState,
+ transform: (line: string) => string,
+): EditorState {
+ const blockStart = lineStartAt(value, start)
+ const blockEnd = lineEndAt(value, end)
+ const rewritten = value.slice(blockStart, blockEnd).split('\n').map(transform).join('\n')
+ return {
+ value: value.slice(0, blockStart) + rewritten + value.slice(blockEnd),
+ start: blockStart,
+ end: blockStart + rewritten.length,
+ }
+}
+
+/**
+ * Tab indents, Shift+Tab outdents.
+ *
+ * Only claimed when it would actually mean something — a multi-line selection,
+ * or a caret sitting in a list item. Anywhere else Tab still moves focus, which
+ * is the only way out of the textarea for keyboard users.
+ */
+export function indentOnTab(state: EditorState, outdent: boolean): EditorPatch {
+ const { value, start, end } = state
+ const multiLine = hasLineBreak(value, start, end)
+ const lineStart = lineStartAt(value, start)
+ const inList = LIST_LINE_RE.test(value.slice(lineStart, lineEndAt(value, end)))
+ if (!multiLine && !inList) return null
+
+ if (outdent) {
+ return mapSelectedLines(state, (line) => line.replace(/^(?: {1,2}|\t)/, ''))
+ }
+ if (multiLine) {
+ return mapSelectedLines(state, (line) => (line.trim() ? INDENT + line : line))
+ }
+ // Single list line: indent the line, not the caret position inside it.
+ const indented = mapSelectedLines(state, (line) => INDENT + line)
+ const caret = start + INDENT.length
+ return { ...indented, start: caret, end: caret + (end - start) }
+}
+
+/** Reading stats shown next to the draft tag in the footer. */
+export function countContent(value: string): { characters: number; lines: number } {
+ const text = value ?? ''
+ return {
+ characters: text.length,
+ lines: text ? text.split('\n').length : 0,
+ }
+}