feat: 助手引用改为行内标签样式并可自由插入

This commit is contained in:
2026-09-28 10:57:14 +08:00
parent e136084794
commit 59881dcb68
2 changed files with 673 additions and 119 deletions
@@ -1,5 +1,12 @@
<script lang="ts" setup>
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
import {
computed,
nextTick,
onBeforeUnmount,
onMounted,
ref,
watch,
} from 'vue';
import { createIconifyIcon } from '@vben/icons';
import { Tooltip, message } from 'ant-design-vue';
@@ -11,11 +18,13 @@ import { getShopPageApi } from '#/api/ec/shop';
import {
catalogCiteLabel,
stripTrailingMention,
formatInlineCite,
inlineCiteKeysInText,
mentionQueryAt,
parseDraftSegments,
toProductCite,
toShopCite,
toSkuCite,
trailingMentionQuery,
type CatalogCite,
type CatalogCiteKind,
} from './catalog-cite';
@@ -24,7 +33,7 @@ const ArrowUpIcon = createIconifyIcon('lucide:arrow-up');
const ExpandIcon = createIconifyIcon('lucide:maximize-2');
const CollapseIcon = createIconifyIcon('lucide:minimize-2');
/** 包一层 ChatSender:@ 先选分类,选中后在输入行内嵌标签。 */
/** 包一层 ChatSender:contenteditable 行内标签 + 草稿 token 发给模型。 */
const draft = defineModel<string>({ required: true });
const cites = defineModel<CatalogCite[]>('cites', { required: true });
@@ -35,7 +44,7 @@ const props = withDefaults(
placeholder?: string;
}>(),
{
placeholder: '问点什么,或用 @ 引用店铺 / 商品 / SKU',
placeholder: '问点什么,或用 @ 在任意位置引用店铺 / 商品 / SKU',
},
);
@@ -47,6 +56,7 @@ const emit = defineEmits<{
const kinds: CatalogCiteKind[] = ['shop', 'product', 'sku'];
const kind = ref<CatalogCiteKind>('shop');
const rootRef = ref<HTMLElement | null>(null);
const editorRef = ref<HTMLElement | null>(null);
const dismissed = ref(false);
const loadingList = ref(false);
const activeKey = ref('');
@@ -55,20 +65,22 @@ const items = ref<CatalogCite[]>([]);
const expanded = ref(false);
/** 内容是否超过 1 行(用于显示右上角展开按钮) */
const multiLine = ref(false);
/** 草稿光标偏移(与 token 字符串对齐) */
const cursorPos = ref(0);
/** 正在由编辑器写回 draft,避免 watch 重建 DOM 打断输入 */
let syncingFromEditor = false;
let timer: ReturnType<typeof setTimeout> | undefined;
let seq = 0;
const mentionQuery = computed(() => trailingMentionQuery(draft.value));
const mentionHit = computed(() =>
mentionQueryAt(draft.value, cursorPos.value),
);
const mentionQuery = computed(() => mentionHit.value?.query ?? null);
const menuOpen = computed(
() => mentionQuery.value !== null && !dismissed.value,
);
/** 未展开:1~14 行自动增高;展开后再抬高上限 */
const textareaAutosize = computed(() =>
expanded.value
? { minRows: 8, maxRows: 28 }
: { minRows: 1, maxRows: 14 },
);
const editorMaxHeight = computed(() => (expanded.value ? 28 * 24 : 14 * 24));
const showExpandToggle = computed(() => expanded.value || multiLine.value);
@@ -96,7 +108,14 @@ watch(kind, () => {
scheduleSearch(mentionQuery.value);
});
watch(draft, () => {
watch(draft, (text) => {
if (!syncingFromEditor) {
renderEditor(text, cursorPos.value);
}
const keys = inlineCiteKeysInText(text);
if (cites.value.some((c) => !keys.has(c.key))) {
cites.value = cites.value.filter((c) => keys.has(c.key));
}
checkMultiLine();
});
@@ -104,6 +123,10 @@ watch(expanded, () => {
void nextTick(() => checkMultiLine());
});
onMounted(() => {
renderEditor(draft.value, draft.value.length);
});
function scheduleSearch(query: string) {
if (timer) clearTimeout(timer);
loadingList.value = true;
@@ -168,43 +191,292 @@ async function safeList(task: Promise<CatalogCite[]>) {
}
}
/** 按可视行数判断:超过 1 行就稳定显示展开按钮(不依赖 scroll overflow,避免 autosize 时闪烁消失) */
function checkMultiLine() {
const run = () => {
const el = rootRef.value?.querySelector('textarea');
if (!el) {
multiLine.value = false;
function createChipEl(cite: CatalogCite): HTMLSpanElement {
const chip = document.createElement('span');
chip.className = 'cite-chip';
chip.contentEditable = 'false';
chip.dataset.citeKey = cite.key;
const kindEl = document.createElement('span');
kindEl.className = 'cite-chip__kind';
kindEl.textContent = catalogCiteLabel(cite.kind);
const titleEl = document.createElement('span');
titleEl.className = 'cite-chip__title';
titleEl.textContent = cite.title;
const removeBtn = document.createElement('button');
removeBtn.type = 'button';
removeBtn.className = 'cite-chip__remove';
removeBtn.setAttribute('aria-label', '移除引用');
removeBtn.textContent = '×';
removeBtn.addEventListener('mousedown', (event) => {
event.preventDefault();
event.stopPropagation();
});
removeBtn.addEventListener('click', (event) => {
event.preventDefault();
event.stopPropagation();
removeCite(cite.key);
});
chip.append(kindEl, titleEl, removeBtn);
return chip;
}
/** 按草稿 token 重建编辑器 DOM(程序化变更时调用)。 */
function renderEditor(text: string, caret?: number) {
const editor = editorRef.value;
if (!editor) return;
editor.innerHTML = '';
for (const seg of parseDraftSegments(text)) {
if (seg.type === 'text') {
if (seg.value) editor.appendChild(document.createTextNode(seg.value));
} else {
const cite = cites.value.find((c) => c.key === seg.key);
if (cite) editor.appendChild(createChipEl(cite));
}
}
if (caret != null) {
void nextTick(() => setCaretAtDraftOffset(caret));
}
checkMultiLine();
}
function serializeEditor(): string {
const editor = editorRef.value;
if (!editor) return '';
let out = '';
const walk = (node: Node) => {
if (node.nodeType === Node.TEXT_NODE) {
out += node.textContent ?? '';
return;
}
if (expanded.value) {
multiLine.value = true;
if (!(node instanceof HTMLElement)) return;
if (node.dataset.citeKey) {
const cite = cites.value.find((c) => c.key === node.dataset.citeKey);
if (cite) out += formatInlineCite(cite);
return;
}
const text = draft.value || '';
if (!text) {
multiLine.value = false;
if (node.tagName === 'BR') {
out += '\n';
return;
}
// 显式换行
if (text.includes('\n')) {
multiLine.value = true;
return;
// contenteditable 换行常包成 DIV/P
if (
(node.tagName === 'DIV' || node.tagName === 'P') &&
out.length > 0 &&
!out.endsWith('\n')
) {
out += '\n';
}
const style = window.getComputedStyle(el);
const lineHeight = parseFloat(style.lineHeight);
const fontSize = parseFloat(style.fontSize) || 14;
const lh =
Number.isFinite(lineHeight) && lineHeight > 0 ? lineHeight : fontSize * 1.5;
const padY =
(parseFloat(style.paddingTop) || 0) +
(parseFloat(style.paddingBottom) || 0);
// scrollHeight 在 autosize 下仍反映内容总高度
const rows = Math.max(1, Math.round((el.scrollHeight - padY) / lh));
multiLine.value = rows > 1;
node.childNodes.forEach(walk);
};
// 等 autosize 改完高度再量,避免中间态误判
editor.childNodes.forEach(walk);
return out;
}
function tokenLengthForChip(key: string): number {
const cite = cites.value.find((c) => c.key === key);
return cite ? formatInlineCite(cite).length : 0;
}
/** 将浏览器选区映射为草稿 token 偏移。 */
function getDraftOffsetFromSelection(): number {
const editor = editorRef.value;
const sel = window.getSelection();
if (!editor || !sel || sel.rangeCount === 0) return draft.value.length;
const range = sel.getRangeAt(0);
if (!editor.contains(range.startContainer)) return draft.value.length;
let offset = 0;
let done = false;
const walk = (node: Node) => {
if (done) return;
if (node === range.startContainer && node.nodeType === Node.TEXT_NODE) {
offset += range.startOffset;
done = true;
return;
}
if (node.nodeType === Node.TEXT_NODE) {
offset += node.textContent?.length ?? 0;
return;
}
if (!(node instanceof HTMLElement)) return;
if (node.dataset.citeKey) {
if (node === range.startContainer || node.contains(range.startContainer)) {
// 落在 chip 内:算到 chip 末尾(不可编辑原子)
offset += tokenLengthForChip(node.dataset.citeKey);
done = true;
return;
}
offset += tokenLengthForChip(node.dataset.citeKey);
return;
}
if (node.tagName === 'BR') {
if (node === range.startContainer) {
done = true;
return;
}
offset += 1;
return;
}
for (const child of node.childNodes) {
walk(child);
if (done) return;
}
};
for (const child of editor.childNodes) {
walk(child);
if (done) break;
}
return offset;
}
function setCaretAtDraftOffset(target: number) {
const editor = editorRef.value;
if (!editor) return;
editor.focus();
let remaining = Math.max(0, target);
const state: { caret: { node: Text; offset: number } | null } = {
caret: null,
};
let found = false;
const walk = (node: Node) => {
if (found) return;
if (node.nodeType === Node.TEXT_NODE) {
const len = node.textContent?.length ?? 0;
if (remaining <= len) {
state.caret = { node: node as Text, offset: remaining };
found = true;
return;
}
remaining -= len;
return;
}
if (!(node instanceof HTMLElement)) return;
if (node.dataset.citeKey) {
const len = tokenLengthForChip(node.dataset.citeKey);
if (remaining <= len) {
const after = node.nextSibling;
if (after?.nodeType === Node.TEXT_NODE) {
state.caret = { node: after as Text, offset: 0 };
} else {
const spacer = document.createTextNode('');
node.after(spacer);
state.caret = { node: spacer, offset: 0 };
}
found = true;
return;
}
remaining -= len;
return;
}
if (node.tagName === 'BR') {
if (remaining <= 1) {
const after = node.nextSibling;
if (after?.nodeType === Node.TEXT_NODE) {
state.caret = { node: after as Text, offset: 0 };
} else {
const spacer = document.createTextNode('');
node.after(spacer);
state.caret = { node: spacer, offset: 0 };
}
found = true;
return;
}
remaining -= 1;
return;
}
for (const child of node.childNodes) {
walk(child);
if (found) return;
}
};
for (const child of editor.childNodes) {
walk(child);
if (found) break;
}
const sel = window.getSelection();
if (!sel) return;
const range = document.createRange();
const caretHit = state.caret as {
node: Text;
offset: number;
} | null;
if (caretHit) {
const len = caretHit.node.textContent?.length ?? 0;
range.setStart(caretHit.node, Math.min(caretHit.offset, len));
} else {
range.selectNodeContents(editor);
range.collapse(false);
}
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
cursorPos.value = target;
}
function syncDraftFromEditor() {
syncingFromEditor = true;
const next = serializeEditor();
draft.value = next;
cursorPos.value = getDraftOffsetFromSelection();
const keys = inlineCiteKeysInText(next);
if (cites.value.some((c) => !keys.has(c.key))) {
cites.value = cites.value.filter((c) => keys.has(c.key));
}
void nextTick(() => {
requestAnimationFrame(run);
syncingFromEditor = false;
checkMultiLine();
});
}
function onEditorInput() {
syncDraftFromEditor();
}
function syncCursor() {
if (!editorRef.value) return;
cursorPos.value = getDraftOffsetFromSelection();
}
function checkMultiLine() {
void nextTick(() => {
requestAnimationFrame(() => {
const el = editorRef.value;
if (!el) {
multiLine.value = false;
return;
}
if (expanded.value) {
multiLine.value = true;
return;
}
const text = draft.value || '';
if (!text) {
multiLine.value = false;
return;
}
if (text.includes('\n') || el.querySelector('.cite-chip')) {
// 有 chip 时视觉上常超一行;仍按高度判断更准
}
const style = window.getComputedStyle(el);
const lineHeight = parseFloat(style.lineHeight);
const fontSize = parseFloat(style.fontSize) || 14;
const lh =
Number.isFinite(lineHeight) && lineHeight > 0
? lineHeight
: fontSize * 1.5;
const rows = Math.max(1, Math.round(el.scrollHeight / lh));
multiLine.value = rows > 1;
});
});
}
@@ -234,27 +506,67 @@ function onStopClick() {
emit('stop');
}
function onKeydown(event: KeyboardEvent) {
// 光标在输入框开头(或内容为空)时,Backspace 删掉最后一个引用 chip
function onEditorKeydown(event: KeyboardEvent) {
// 菜单打开时由外层 capture 处理方向键/Enter
if (menuOpen.value) return;
if (event.key === 'Enter' && !event.shiftKey && !event.isComposing) {
event.preventDefault();
if (!props.loading && draft.value.trim()) {
emit('send', draft.value);
resetExpandAfterSend();
}
return;
}
// ⌫:若前一个节点是 chip,整段删除
if (
event.key === 'Backspace' &&
!event.isComposing &&
event.keyCode !== 229 &&
cites.value.length > 0
event.keyCode !== 229
) {
const el = rootRef.value?.querySelector('textarea');
if (el) {
const atStart = el.selectionStart === 0 && el.selectionEnd === 0;
if (atStart || !draft.value) {
const sel = window.getSelection();
if (!sel || !sel.isCollapsed || sel.rangeCount === 0) return;
const range = sel.getRangeAt(0);
if (
range.startContainer.nodeType === Node.TEXT_NODE &&
range.startOffset === 0
) {
const prev = range.startContainer.previousSibling;
if (prev instanceof HTMLElement && prev.dataset.citeKey) {
event.preventDefault();
event.stopPropagation();
const last = cites.value[cites.value.length - 1];
if (last) removeCite(last.key);
const key = prev.dataset.citeKey;
prev.remove();
cites.value = cites.value.filter((c) => c.key !== key);
syncDraftFromEditor();
return;
}
}
if (
range.startContainer === editorRef.value &&
range.startOffset > 0
) {
const prev =
editorRef.value?.childNodes[range.startOffset - 1] ?? null;
if (prev instanceof HTMLElement && prev.dataset.citeKey) {
event.preventDefault();
const key = prev.dataset.citeKey;
prev.remove();
cites.value = cites.value.filter((c) => c.key !== key);
syncDraftFromEditor();
}
}
}
}
function onEditorPaste(event: ClipboardEvent) {
event.preventDefault();
const text = event.clipboardData?.getData('text/plain') ?? '';
if (!text) return;
document.execCommand('insertText', false, text);
}
function onKeydown(event: KeyboardEvent) {
if (!menuOpen.value || event.isComposing || event.keyCode === 229) return;
if (event.key === 'ArrowDown') {
event.preventDefault();
@@ -290,48 +602,95 @@ function scrollActiveIntoView() {
const key = activeKey.value;
if (!key || !rootRef.value) return;
rootRef.value
.querySelector(`[data-cite-key="${CSS.escape(key)}"]`)
.querySelector(`[data-menu-cite-key="${CSS.escape(key)}"]`)
?.scrollIntoView({ block: 'nearest' });
}
function applyDraftChange(next: string, caret: number) {
cites.value = cites.value.filter((c) =>
inlineCiteKeysInText(next).has(c.key),
);
draft.value = next;
cursorPos.value = caret;
void nextTick(() => {
renderEditor(next, caret);
});
}
function pick(item: CatalogCite) {
const hit = mentionHit.value;
if (!hit) return;
if (cites.value.some((cite) => cite.key === item.key)) {
message.info('已经引用过了');
draft.value = stripTrailingMention(draft.value);
focusInput();
applyDraftChange(
draft.value.slice(0, hit.start) + draft.value.slice(hit.end),
hit.start,
);
return;
}
if (cites.value.length >= 5) {
message.warning('一条消息最多引用 5 个');
return;
}
const next = stripTrailingMention(draft.value);
const token = formatInlineCite(item);
const next =
draft.value.slice(0, hit.start) +
token +
' ' +
draft.value.slice(hit.end);
cites.value = [...cites.value, item];
draft.value = next;
focusInput();
cursorPos.value = hit.start + token.length + 1;
void nextTick(() => {
renderEditor(next, cursorPos.value);
});
}
function removeCite(key: string) {
cites.value = cites.value.filter((cite) => cite.key !== key);
focusInput();
const token = (() => {
const cite = cites.value.find((c) => c.key === key);
return cite ? formatInlineCite(cite) : '';
})();
cites.value = cites.value.filter((c) => c.key !== key);
if (!token) {
syncDraftFromEditor();
return;
}
const idx = draft.value.indexOf(token);
const next =
idx >= 0
? draft.value.slice(0, idx) + draft.value.slice(idx + token.length)
: draft.value;
applyDraftChange(next, Math.max(0, idx));
}
function insertMention() {
if (trailingMentionQuery(draft.value) === null) {
const text = draft.value;
const gap = text && !/\s$/.test(text) ? ' ' : '';
draft.value = `${text}${gap}@`;
syncCursor();
const pos = cursorPos.value;
const text = draft.value;
if (mentionQueryAt(text, pos)) {
dismissed.value = false;
focusInput(pos);
return;
}
const gap = pos > 0 && !/\s/.test(text[pos - 1] ?? '') ? ' ' : '';
const next = `${text.slice(0, pos)}${gap}@${text.slice(pos)}`;
dismissed.value = false;
focusInput();
const nextPos = pos + gap.length + 1;
draft.value = next;
cursorPos.value = nextPos;
void nextTick(() => renderEditor(next, nextPos));
}
function focusInput(cursor?: number) {
void nextTick(() => {
const el = rootRef.value?.querySelector('textarea');
if (!el) return;
el.focus();
if (cursor != null) el.setSelectionRange(cursor, cursor);
const editor = editorRef.value;
if (!editor) return;
editor.focus();
if (cursor != null) setCaretAtDraftOffset(cursor);
else syncCursor();
});
}
@@ -357,7 +716,6 @@ onBeforeUnmount(() => {
:class="{ 'catalog-cite-sender--expandable': showExpandToggle }"
@keydown.capture="onKeydown"
>
<!-- 展开/收起固定在输入框右上角 -->
<Tooltip
v-if="showExpandToggle"
:title="expanded ? '收起输入框' : '展开输入框'"
@@ -395,7 +753,6 @@ onBeforeUnmount(() => {
{{ catalogCiteLabel(item) }}
</button>
</div>
<!-- 固定高度,避免加载前后弹层跳动 -->
<div class="cite-menu-list h-72 overflow-y-auto py-1">
<div
v-if="loadingList && items.length === 0"
@@ -414,7 +771,7 @@ onBeforeUnmount(() => {
v-for="item in items"
:key="item.key"
type="button"
:data-cite-key="item.key"
:data-menu-cite-key="item.key"
class="flex w-full cursor-pointer flex-col px-3 py-1.5 text-left"
:class="item.key === activeKey ? 'bg-primary/10' : 'hover:bg-muted'"
@mouseenter="activeKey = item.key"
@@ -431,7 +788,7 @@ onBeforeUnmount(() => {
</template>
</div>
<div class="text-muted-foreground border-border border-t px-3 py-1.5 text-[11px]">
↑↓ 选择 · Enter 引用 · Esc 关闭 · ⌫ 删引用
↑↓ 选择 · Enter 引用 · Esc 关闭 · ⌫ 删标签
</div>
</div>
@@ -439,30 +796,32 @@ onBeforeUnmount(() => {
v-model="draft"
class="agent-td-sender"
:loading="loading"
:placeholder="placeholder"
:textarea-props="{ autosize: textareaAutosize }"
placeholder=""
:textarea-props="{ autosize: { minRows: 1, maxRows: 1 } }"
@send="onChatSend"
@stop="emit('stop')"
>
<template #input-prefix>
<div v-if="cites.length" class="cite-inline">
<span
v-for="cite in cites"
:key="cite.key"
class="bg-primary/10 text-primary inline-flex max-w-40 items-center gap-1 rounded-md px-1.5 py-0.5 text-xs"
>
<span class="shrink-0 opacity-70">{{ catalogCiteLabel(cite.kind) }}</span>
<span class="truncate">{{ cite.title }}</span>
<button
type="button"
class="cursor-pointer opacity-60 hover:opacity-100"
aria-label="移除引用"
@mousedown.prevent
@click="removeCite(cite.key)"
>
×
</button>
</span>
<div
class="cite-editor-wrap"
:class="{ 'cite-editor-wrap--expanded': expanded }"
:style="{ maxHeight: `${editorMaxHeight}px` }"
>
<div
ref="editorRef"
class="cite-editor"
contenteditable="true"
role="textbox"
aria-multiline="true"
:data-placeholder="placeholder"
:data-empty="!(draft || '').trim() ? 'true' : 'false'"
@input="onEditorInput"
@keydown="onEditorKeydown"
@keyup="syncCursor"
@click="syncCursor"
@mouseup="syncCursor"
@paste="onEditorPaste"
></div>
</div>
</template>
<template #footer-prefix>
@@ -529,35 +888,99 @@ onBeforeUnmount(() => {
margin-bottom: 0 !important;
}
/* 真实输入改走 contenteditable,隐藏原生 textarea 占位 */
.catalog-cite-sender :deep(.t-textarea) {
flex: 1;
width: auto;
min-width: 0;
flex: 0 0 0 !important;
width: 0 !important;
min-width: 0 !important;
height: 0 !important;
margin: 0 !important;
overflow: hidden !important;
opacity: 0 !important;
pointer-events: none !important;
}
.catalog-cite-sender :deep(.t-textarea__inner) {
padding: 0 !important;
}
.catalog-cite-sender--expandable :deep(.t-textarea__inner) {
/* 给右上角展开按钮留出点击空间,避免文字压住图标 */
padding-right: 28px !important;
height: 0 !important;
min-height: 0 !important;
}
.catalog-cite-sender :deep(.t-chat-sender__footer) {
align-items: center;
}
.cite-inline {
display: flex;
flex-shrink: 0;
flex-wrap: nowrap;
.cite-editor-wrap {
flex: 1;
width: 100%;
min-width: 0;
max-height: v-bind('editorMaxHeight + "px"');
overflow-x: hidden;
overflow-y: auto;
}
.cite-editor-wrap--expanded {
min-height: 192px;
}
.cite-editor {
width: 100%;
min-height: 24px;
padding-right: 28px;
font-size: 14px;
line-height: 24px;
word-break: break-word;
white-space: pre-wrap;
outline: none;
caret-color: hsl(var(--foreground));
}
.cite-editor[data-empty='true']:before {
color: hsl(var(--muted-foreground));
pointer-events: none;
content: attr(data-placeholder);
}
.cite-editor :deep(.cite-chip),
.cite-editor .cite-chip {
display: inline-flex;
max-width: 12rem;
align-items: center;
gap: 4px;
max-width: 60%;
margin-top: 2px;
margin-right: 8px;
overflow-x: auto;
margin: 0 2px;
padding: 0 6px;
vertical-align: baseline;
font-size: 12px;
line-height: 20px;
color: hsl(var(--primary));
white-space: nowrap;
background: hsl(var(--primary) / 0.1);
border-radius: 6px;
user-select: none;
}
.cite-editor .cite-chip__kind {
flex-shrink: 0;
opacity: 0.7;
}
.cite-editor .cite-chip__title {
overflow: hidden;
text-overflow: ellipsis;
}
.cite-editor .cite-chip__remove {
flex-shrink: 0;
padding: 0;
cursor: pointer;
border: none;
opacity: 0.6;
background: transparent;
color: inherit;
}
.cite-editor .cite-chip__remove:hover {
opacity: 1;
}
.sender-expand-corner {
@@ -10,25 +10,100 @@ export interface CatalogCite {
line: string;
}
/** 光标处未完成的 @ 查询区间 */
export interface MentionHit {
start: number;
end: number;
query: string;
}
const KIND_LABEL: Record<CatalogCiteKind, string> = {
shop: '店铺',
product: '商品',
sku: 'SKU',
};
const LABEL_KIND: Record<string, CatalogCiteKind> = {
店铺: 'shop',
商品: 'product',
SKU: 'sku',
};
/** 行内引用:@[店铺#123·名称](每次新建,避免 /g lastIndex 串扰) */
function inlineCitePattern() {
return /@\[(店铺|商品|SKU)#(\d+)·([^\]]*)\]/g;
}
/** 草稿分段:纯文本 / 已选引用(供 contenteditable 渲染标签) */
export type DraftSegment =
| { type: 'text'; value: string }
| { type: 'cite'; key: string };
export function parseDraftSegments(text: string): DraftSegment[] {
const segments: DraftSegment[] = [];
let last = 0;
for (const m of text.matchAll(inlineCitePattern())) {
if (m.index == null) continue;
if (m.index > last) {
segments.push({ type: 'text', value: text.slice(last, m.index) });
}
const label = m[1];
const id = Number(m[2]);
const kind = label ? LABEL_KIND[label] : undefined;
if (kind && Number.isFinite(id)) {
segments.push({ type: 'cite', key: `${kind}:${id}` });
} else {
segments.push({ type: 'text', value: m[0] });
}
last = m.index + m[0].length;
}
if (last < text.length) {
segments.push({ type: 'text', value: text.slice(last) });
}
if (segments.length === 0) {
segments.push({ type: 'text', value: '' });
}
return segments;
}
export function catalogCiteLabel(kind: CatalogCiteKind) {
return KIND_LABEL[kind];
}
/** 输入框末尾的 @ 查询;没有则 null。空字符串表示刚输入 @。 */
export function trailingMentionQuery(text: string): null | string {
const matched = text.match(/(^|\s)@([^\s@]*)$/);
return matched ? matched[2] ?? '' : null;
/** 在光标前查找未完成的 @查询(支持正文任意位置)。 */
export function mentionQueryAt(
text: string,
cursor: number,
): MentionHit | null {
const pos = Math.max(0, Math.min(cursor, text.length));
const before = text.slice(0, pos);
const matched = before.match(/(^|[\s\n])@([^\s@\[]*)$/);
if (!matched) return null;
const index = matched.index;
if (index == null) return null;
const prefix = matched[1] ?? '';
return {
start: index + prefix.length,
end: pos,
query: matched[2] ?? '',
};
}
/** 发送前去掉还没选中的 @查询。 */
/** @deprecated 兼容旧调用:等价于光标在末尾 */
export function trailingMentionQuery(text: string): null | string {
return mentionQueryAt(text, text.length)?.query ?? null;
}
/** 发送前去掉仍未选中的残缺 @查询(末尾)。 */
export function stripTrailingMention(text: string) {
return text.replace(/(^|\s)@[^\s@]*$/, '$1').replace(/\s+$/, '');
return text.replace(/(^|[\s\n])@[^\s@\[]*$/u, '$1').replace(/\s+$/u, '');
}
/** 输入框内展示用标记(嵌 id,发送时按位置展开)。 */
export function formatInlineCite(cite: CatalogCite): string {
const raw = cite.title.trim() || String(cite.id);
const title = raw.length > 24 ? `${raw.slice(0, 23)}…` : raw;
return `@[${KIND_LABEL[cite.kind]}#${cite.id}·${title}]`;
}
export function toShopCite(shop: {
@@ -85,12 +160,68 @@ export function toSkuCite(sku: {
};
}
/** 正文后面附上引用 id。标签只在输入框里显示,不占一行正文。 */
/**
* 按正文中的行内标记位置展开引用;标记不在文中的 cite 仍附在末尾 [引用] 块(兼容旧数据)。
*/
export function composeMessageWithCites(text: string, cites: CatalogCite[]) {
const body = text.trim();
if (cites.length === 0) return body;
const block = ['[引用]', ...cites.map((item) => item.line)].join('\n');
return body ? `${body}\n${block}` : block;
const body = stripTrailingMention(text);
if (!body && cites.length === 0) return '';
const used = new Set<string>();
const expanded = body.replace(
inlineCitePattern(),
(_raw, label: string, idStr: string) => {
const kind = LABEL_KIND[label];
const id = Number(idStr);
if (!kind || !Number.isFinite(id)) return _raw;
const hit =
cites.find((c) => c.kind === kind && c.id === id) ||
cites.find((c) => c.key === `${kind}:${id}`);
if (!hit) return _raw;
used.add(hit.key);
return hit.line;
},
);
const orphans = cites.filter((c) => !used.has(c.key));
if (orphans.length === 0) return expanded.trim();
const block = ['[引用]', ...orphans.map((item) => item.line)].join('\n');
const trimmed = expanded.trim();
return trimmed ? `${trimmed}\n${block}` : block;
}
/** 正文里仍存在的引用 key(用于删字后同步 cites)。 */
export function inlineCiteKeysInText(text: string): Set<string> {
const keys = new Set<string>();
for (const m of text.matchAll(inlineCitePattern())) {
const label = m[1];
const id = Number(m[2]);
const kind = label ? LABEL_KIND[label] : undefined;
if (kind && Number.isFinite(id)) keys.add(`${kind}:${id}`);
}
return keys;
}
/**
* 光标落在某个行内引用上(含紧挨标记末尾)时返回其区间,便于 ⌫ 整段删除。
*/
export function inlineCiteRangeAt(
text: string,
cursor: number,
): { start: number; end: number; key: string } | null {
for (const m of text.matchAll(inlineCitePattern())) {
if (m.index == null) continue;
const start = m.index;
const end = start + m[0].length;
if (cursor > start && cursor <= end) {
const label = m[1];
const id = Number(m[2]);
const kind = label ? LABEL_KIND[label] : undefined;
if (!kind || !Number.isFinite(id)) continue;
return { start, end, key: `${kind}:${id}` };
}
}
return null;
}
function joinLine(kind: string, title: string, id: number, extra: string) {