WeKnora/frontend/src/utils/markdownEditing.ts

116 lines
4.1 KiB
TypeScript
Raw Normal View History

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
2026-09-20 08:16:28 +00:00
/**
* 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,
}
}