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

* feat(chat): make the saved-answer Markdown editor usable

Saving a chat answer to a knowledge base dropped the raw answer — citation
tags and all — into a 760px drawer with a single column and a preview
toggle. Every `<kb doc=… chunk_id=… kb_id=…/>` had to be deleted by hand,
and the title arrived hard-cut with an ellipsis.

- strip `<kb/>` tags from the seeded draft and list the cited documents
  once at the bottom; keep `<web/>` citations as real Markdown links
- cut a long question on a clause boundary instead of at 40 chars + "..."
- compact title + knowledge-base row, full-height editor (no more
  calc(100vh - 360px)), and an edit / split / preview switch that starts
  on split whenever the drawer is wide enough for two panes
- opt-in maximize toggle on SettingDrawer for full-width editing
- native textarea in place of t-textarea, with Cmd/Ctrl+B/I/K/S/Enter,
  list continuation on Enter and Tab indenting
- confirm before discarding unsaved changes; show a character/line count

* style(chat): stop painting the Markdown editor green

Brand green was doing decorative work in the editor: a 4px green rule and
an 8% green wash on every blockquote in the preview, a green pill for the
active view, green toolbar hovers, and a green halo around the whole
editor while it had focus. Together they read as noise.

Green now means action only — the publish button, links, keyboard focus
rings. Blockquotes match the chat renderer's own neutral treatment
(2px --td-component-stroke, no fill), the view switch uses a raised
neutral pill, and toolbar hover/active use the container tokens.

* refactor(chat): fold the editor toolbar from 16 buttons to 10

Sixteen same-sized icons gave equal weight to "bold" and "insert
horizontal rule", and at the default drawer width the row already ran out
of space (the overflow scrollbar is hidden, so the last icons simply
vanished).

Headings collapse into one labelled "标题" menu and the block inserts
(quote, code block, table, image, rule) into "插入"; the actions people
reach for mid-sentence — bold/italic/strike/inline code, the three list
kinds, link — stay one click away. The cropped shortcut line in the
status bar becomes a keyboard button whose tooltip lists every binding,
including Cmd+Enter to publish, which was undocumented.

* refactor(chat): collapse the editor into four bands

The drawer stacked seven horizontal strips — header, subtitle, a labelled
title row, a labelled knowledge-base row, toolbar, canvas, status bar —
each with its own rule or tint, and none of them shared a left edge.

The document now has a head (a borderless title that reads as a title,
with "存入 <知识库>" as a sentence under it), one editor card, and a
footer. The header subtitle, the two field labels and the status strip
are gone: word/line counts moved next to the draft tag in the footer and
the shortcut sheet to the toolbar's right end. Title, destination and the
editor card all start on the same left edge.

* refactor(chat): move the destination onto the title row

"存入" was a verb invented for this one screen, and the row it sat on cost
the head a whole line. The destination is now the folder icon this product
already uses for a knowledge base in the @-mention list, followed by the
select, parked at the right end of the title row — so the head is one line
whose two ends line up with the editor card below it.

The narrow layout that stacks them again is now driven by the editor's
ResizeObserver instead of a `@container` query: the scoped-style pipeline
drops `@container` blocks (none of them reach the page), so the previous
rules — stacking and, worse, the toolbar wrap that keeps the last buttons
from silently overflowing — never actually applied.

* style(chat): let the destination select reach the right edge

The select's box sat flush with the editor card, but a 132px min-width
held it open past its content, so the folder icon, the name and the caret
stopped 43px short — the block read as floating rather than aligned. It
now shrinks to its content (up to 260px, then truncates), leaving only the
control's own 5px of inner padding, and stays right-aligned when the
narrow layout stacks it under the title.

* style(chat): keep the narrow toolbar on one row

A narrow drawer wrapped the toolbar into two rows and left the view switch
hanging beside the second one, and the head split into two rows as well.
The view switch now drops its three text labels on narrow (the tooltips
already carry them), which buys back enough room for the whole toolbar —
all ten controls — to stay on one row down to the 600px minimum width.
The head keeps title and destination on one line too, now that the
destination shrank to its content.

* style(chat): shrink the editor drawer's header

The header was sized for a title plus a subtitle; with the subtitle gone
it kept 65px for one 15px line — a 32px badge inside 14px of padding,
propped up by TDesign's 56px min-height. Down to 47px: 26px badge, 9px
padding, min-height released. Scoped to this drawer, so the other
SettingDrawer consumers keep their proportions.

* chore(chat): drop leftovers from the editor rework

- the per-button `btn-<key>` class on toolbar buttons: nothing styled or
  queried it
- `INDENT` was exported but only ever used inside markdownEditing
- a comment still pointed at the status bar that no longer exists
main
lyingbug 2026-09-20 16:16:28 +08:00 committed by GitHub
parent a62a51e6b0
commit 7fa6f028fc
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
13 changed files with 1260 additions and 368 deletions

File diff suppressed because it is too large Load Diff

View File

@ -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-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;
margin-left: auto;
&:empty {
display: none;

View File

@ -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',

View File

@ -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枚までです',

View File

@ -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: '편집',

View File

@ -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: 'Редактировать',

View File

@ -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: '编辑',

View File

@ -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'),
});
};

View File

@ -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 }
}

View File

@ -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')
})

View File

@ -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`
}

View File

@ -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 })
})

View File

@ -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,
}
}