A) 前端把 ^[inferred]/^[ambiguous] 渲染成「推测」「存疑」小角标(原先原样显示文本) B) 相关笔记只按"区分性标签"精确匹配(去掉标题/摘要关键词检索——中文分词导致 助手/知识图谱/页面 等泛词误关联,如「AI助手打招呼」被错误拉进 Related); 无区分性标签则不关联、不渲染 ## Related 段 C) LLM 提炼启用但失败时不再静默回退成"原文堆砌": - 回退笔记落为 draft(草稿)而非 approved,便于复核 - capture_thread 记 WARNING 并返回 llm_fallback;router 透出该标志 - llm_extractor 在 JSON 解析失败/无 notes 时补充可诊断的 WARNING 日志 Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
275 lines
12 KiB
TypeScript
275 lines
12 KiB
TypeScript
import React, { useState } from 'react';
|
|
import ReactMarkdown from 'react-markdown';
|
|
import remarkGfm from 'remark-gfm';
|
|
import rehypeRaw from 'rehype-raw';
|
|
import { Check, Copy } from 'lucide-react';
|
|
import { PrismLight as SyntaxHighlighter } from 'react-syntax-highlighter';
|
|
import bash from 'react-syntax-highlighter/dist/esm/languages/prism/bash';
|
|
import css from 'react-syntax-highlighter/dist/esm/languages/prism/css';
|
|
import java from 'react-syntax-highlighter/dist/esm/languages/prism/java';
|
|
import javascript from 'react-syntax-highlighter/dist/esm/languages/prism/javascript';
|
|
import json from 'react-syntax-highlighter/dist/esm/languages/prism/json';
|
|
import jsx from 'react-syntax-highlighter/dist/esm/languages/prism/jsx';
|
|
import markup from 'react-syntax-highlighter/dist/esm/languages/prism/markup';
|
|
import sql from 'react-syntax-highlighter/dist/esm/languages/prism/sql';
|
|
import tsx from 'react-syntax-highlighter/dist/esm/languages/prism/tsx';
|
|
import typescript from 'react-syntax-highlighter/dist/esm/languages/prism/typescript';
|
|
import { oneDark } from 'react-syntax-highlighter/dist/esm/styles/prism';
|
|
|
|
export interface WikiLinkTarget {
|
|
target: string;
|
|
kind: 'note' | 'vault' | 'missing';
|
|
exists: boolean;
|
|
note_id?: string;
|
|
vault_path?: string;
|
|
title?: string;
|
|
}
|
|
|
|
export type WikiLinkMap = Record<string, WikiLinkTarget>;
|
|
|
|
interface MarkdownRendererProps {
|
|
content: string;
|
|
className?: string;
|
|
onCitationClick?: (index: number) => void;
|
|
/** Resolved `[[wikilink]]` targets; when provided, non-numeric `[[...]]` render as links. */
|
|
wikiLinks?: WikiLinkMap;
|
|
onWikiLinkClick?: (link: WikiLinkTarget) => void;
|
|
}
|
|
|
|
const escapeHtmlAttr = (value: string): string =>
|
|
value
|
|
.replace(/&/g, '&')
|
|
.replace(/</g, '<')
|
|
.replace(/>/g, '>')
|
|
.replace(/"/g, '"');
|
|
|
|
SyntaxHighlighter.registerLanguage('bash', bash);
|
|
SyntaxHighlighter.registerLanguage('css', css);
|
|
SyntaxHighlighter.registerLanguage('html', markup);
|
|
SyntaxHighlighter.registerLanguage('java', java);
|
|
SyntaxHighlighter.registerLanguage('javascript', javascript);
|
|
SyntaxHighlighter.registerLanguage('json', json);
|
|
SyntaxHighlighter.registerLanguage('jsx', jsx);
|
|
SyntaxHighlighter.registerLanguage('markup', markup);
|
|
SyntaxHighlighter.registerLanguage('sql', sql);
|
|
SyntaxHighlighter.registerLanguage('tsx', tsx);
|
|
SyntaxHighlighter.registerLanguage('typescript', typescript);
|
|
SyntaxHighlighter.registerLanguage('vue', markup);
|
|
|
|
const extractTextFromNode = (node: React.ReactNode): string => {
|
|
if (typeof node === 'string' || typeof node === 'number') return String(node);
|
|
if (Array.isArray(node)) return node.map(extractTextFromNode).join('');
|
|
if (React.isValidElement<{ children?: React.ReactNode }>(node)) return extractTextFromNode(node.props.children);
|
|
return '';
|
|
};
|
|
|
|
const getLanguageFromClassName = (className = '') => (
|
|
className.match(/language-([\w-]+)/)?.[1]?.toLowerCase() || 'text'
|
|
);
|
|
|
|
const languageLabels: Record<string, string> = {
|
|
js: 'javascript',
|
|
jsx: 'jsx',
|
|
ts: 'typescript',
|
|
tsx: 'tsx',
|
|
vue: 'vue',
|
|
java: 'java',
|
|
py: 'python',
|
|
sh: 'shell',
|
|
bash: 'bash',
|
|
json: 'json',
|
|
css: 'css',
|
|
html: 'html',
|
|
xml: 'xml',
|
|
sql: 'sql',
|
|
text: 'text',
|
|
};
|
|
|
|
const InlineCode: React.FC<{ children: React.ReactNode; className?: string }> = ({ children, className = '' }) => (
|
|
<code
|
|
className={`rounded-md border border-gray-200 bg-gray-100 px-1.5 py-0.5 font-mono text-[0.92em] text-rose-700 dark:border-slate-700 dark:bg-slate-800 dark:text-cyan-200 ${className}`}
|
|
>
|
|
{children}
|
|
</code>
|
|
);
|
|
|
|
const CodeBlock: React.FC<{ children: React.ReactNode; className?: string }> = ({ children, className = '' }) => {
|
|
const [copied, setCopied] = useState(false);
|
|
const codeText = extractTextFromNode(children).replace(/\n$/, '');
|
|
const language = getLanguageFromClassName(className);
|
|
const languageLabel = languageLabels[language] || language;
|
|
|
|
const handleCopy = async () => {
|
|
try {
|
|
await navigator.clipboard.writeText(codeText);
|
|
setCopied(true);
|
|
window.setTimeout(() => setCopied(false), 1500);
|
|
} catch (error) {
|
|
console.error('复制代码失败:', error);
|
|
}
|
|
};
|
|
|
|
return (
|
|
<div className="group relative my-4 overflow-hidden rounded-lg border border-slate-200 bg-[#282c34] shadow-sm dark:border-slate-700">
|
|
<div className="flex items-center justify-between border-b border-white/10 bg-black/20 px-3 py-2">
|
|
<span className="font-mono text-xs font-semibold uppercase tracking-wide text-slate-300">
|
|
{languageLabel}
|
|
</span>
|
|
<button
|
|
type="button"
|
|
onClick={handleCopy}
|
|
className="inline-flex items-center gap-1.5 rounded-md border border-white/10 bg-white/10 px-2.5 py-1.5 text-xs font-medium text-slate-200 transition-colors hover:bg-white/15"
|
|
>
|
|
{copied ? <Check className="h-3.5 w-3.5" /> : <Copy className="h-3.5 w-3.5" />}
|
|
{copied ? '已复制' : '复制'}
|
|
</button>
|
|
</div>
|
|
<SyntaxHighlighter
|
|
language={language}
|
|
style={oneDark}
|
|
PreTag="div"
|
|
customStyle={{
|
|
margin: 0,
|
|
padding: '16px',
|
|
background: 'transparent',
|
|
fontSize: '13px',
|
|
lineHeight: 1.7,
|
|
}}
|
|
codeTagProps={{
|
|
style: {
|
|
fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace',
|
|
},
|
|
}}
|
|
>
|
|
{codeText}
|
|
</SyntaxHighlighter>
|
|
</div>
|
|
);
|
|
};
|
|
|
|
const MarkdownRenderer: React.FC<MarkdownRendererProps> = ({
|
|
content,
|
|
className = '',
|
|
onCitationClick,
|
|
wikiLinks,
|
|
onWikiLinkClick,
|
|
}) => {
|
|
// 1) Non-numeric [[wikilinks]] → clickable (or greyed-out) links, driven by the
|
|
// resolver map. Numeric [[123]] are left untouched here for the citation pass.
|
|
let processed = content;
|
|
if (wikiLinks) {
|
|
processed = processed.replace(
|
|
/\[\[([^\]\n|]+)(?:\|([^\]\n]+))?\]\]/g,
|
|
(match, rawTarget: string, alias?: string) => {
|
|
const target = String(rawTarget).trim();
|
|
if (/^\d+$/.test(target)) return match; // citation badge, handled below
|
|
const resolved = wikiLinks[target];
|
|
const label = (alias?.trim() || resolved?.title || target);
|
|
const safeLabel = escapeHtmlAttr(label);
|
|
const safeTarget = escapeHtmlAttr(target);
|
|
if (resolved && resolved.exists) {
|
|
return `<button type="button" data-wikilink-target="${safeTarget}" class="inline items-center font-medium text-blue-600 dark:text-blue-400 hover:underline cursor-pointer align-baseline">${safeLabel}</button>`;
|
|
}
|
|
return `<span data-wikilink-missing="${safeTarget}" title="页面不存在" class="text-muted-foreground underline decoration-dashed decoration-from-font cursor-not-allowed">${safeLabel}</span>`;
|
|
},
|
|
);
|
|
}
|
|
// 2) wiki-capture provenance markers ^[inferred] / ^[ambiguous] → small badges
|
|
// (otherwise they render as raw text). They mark model-inferred / uncertain
|
|
// statements per the wiki-capture spec.
|
|
processed = processed
|
|
.replace(
|
|
/\s*\^\[inferred\]/g,
|
|
' <sup title="模型推断,非原文直接得出" class="ml-0.5 rounded bg-amber-50 px-1 text-[10px] font-medium text-amber-600 align-super dark:bg-amber-500/15 dark:text-amber-300">推测</sup>',
|
|
)
|
|
.replace(
|
|
/\s*\^\[ambiguous\]/g,
|
|
' <sup title="不确定 / 存在冲突" class="ml-0.5 rounded bg-rose-50 px-1 text-[10px] font-medium text-rose-600 align-super dark:bg-rose-500/15 dark:text-rose-300">存疑</sup>',
|
|
);
|
|
|
|
// 3) Numeric [[123]] citation badges.
|
|
const contentWithCitationBadge = processed.replace(
|
|
/\[\[(\d+)\]\]/g,
|
|
'<button type="button" data-citation-index="$1" class="inline-flex items-center justify-center min-w-[1.5rem] h-6 px-2 mx-0.5 rounded-md border text-xs font-semibold align-middle bg-red-50 text-red-600 border-red-200 dark:bg-slate-700 dark:text-slate-100 dark:border-slate-500 cursor-pointer transition-all hover:opacity-85">[$1]</button>',
|
|
);
|
|
|
|
return (
|
|
<div
|
|
className={`markdown-content ${className}`}
|
|
onClick={(event) => {
|
|
const target = event.target as HTMLElement;
|
|
const wikiButton = target.closest('[data-wikilink-target]') as HTMLElement | null;
|
|
if (wikiButton && onWikiLinkClick && wikiLinks) {
|
|
const key = wikiButton.dataset.wikilinkTarget || '';
|
|
const link = wikiLinks[key];
|
|
if (link) {
|
|
onWikiLinkClick(link);
|
|
return;
|
|
}
|
|
}
|
|
if (!onCitationClick) return;
|
|
const button = target.closest('[data-citation-index]') as HTMLElement | null;
|
|
if (!button) return;
|
|
const index = Number(button.dataset.citationIndex || '0');
|
|
if (Number.isNaN(index) || index <= 0) return;
|
|
onCitationClick(index);
|
|
}}
|
|
>
|
|
<ReactMarkdown
|
|
remarkPlugins={[remarkGfm]}
|
|
rehypePlugins={[rehypeRaw]}
|
|
components={{
|
|
h1: ({ node, ...props }) => <h1 className="mb-4 text-2xl font-bold" {...props} />,
|
|
h2: ({ node, ...props }) => <h2 className="mb-3 text-xl font-bold" {...props} />,
|
|
h3: ({ node, ...props }) => <h3 className="mb-2 text-lg font-bold" {...props} />,
|
|
h4: ({ node, ...props }) => <h4 className="mb-2 text-base font-bold" {...props} />,
|
|
h5: ({ node, ...props }) => <h5 className="mb-2 text-sm font-bold" {...props} />,
|
|
h6: ({ node, ...props }) => <h6 className="mb-2 text-xs font-bold" {...props} />,
|
|
p: ({ node, ...props }) => <p className="mb-4 leading-relaxed" {...props} />,
|
|
ul: ({ node, ...props }) => <ul className="mb-4 ml-4 list-inside list-disc" {...props} />,
|
|
ol: ({ node, ...props }) => <ol className="mb-4 ml-4 list-inside list-decimal" {...props} />,
|
|
li: ({ node, ...props }) => <li className="mb-1" {...props} />,
|
|
code: ({ node, inline, className, children, ...props }: any) => {
|
|
const codeText = extractTextFromNode(children).trim();
|
|
const isShortSingleLineCode = !codeText.includes('\n') && codeText.length <= 80;
|
|
|
|
if (inline || isShortSingleLineCode) {
|
|
return (
|
|
<InlineCode className={className || ''} {...props}>
|
|
{children}
|
|
</InlineCode>
|
|
);
|
|
}
|
|
|
|
return <CodeBlock className={className}>{children}</CodeBlock>;
|
|
},
|
|
pre: ({ node, children }) => <>{children}</>,
|
|
blockquote: ({ node, ...props }) => (
|
|
<blockquote className="my-4 border-l-4 border-gray-300 pl-4 italic dark:border-gray-600" {...props} />
|
|
),
|
|
a: ({ node, ...props }) => (
|
|
<a className="text-blue-600 hover:underline dark:text-blue-400" {...props} />
|
|
),
|
|
table: ({ node, ...props }) => (
|
|
<div className="mb-4 overflow-x-auto">
|
|
<table className="min-w-full border-collapse" {...props} />
|
|
</div>
|
|
),
|
|
thead: ({ node, ...props }) => <thead className="bg-gray-100 dark:bg-gray-800" {...props} />,
|
|
tbody: ({ node, ...props }) => <tbody className="divide-y divide-gray-200 dark:divide-gray-700" {...props} />,
|
|
tr: ({ node, ...props }) => <tr className="hover:bg-gray-50 dark:hover:bg-gray-700" {...props} />,
|
|
th: ({ node, ...props }) => <th className="px-4 py-2 text-left font-semibold" {...props} />,
|
|
td: ({ node, ...props }) => <td className="px-4 py-2" {...props} />,
|
|
hr: ({ node, ...props }) => <hr className="my-4 border-gray-300 dark:border-gray-600" {...props} />,
|
|
strong: ({ node, ...props }) => <strong className="font-bold" {...props} />,
|
|
em: ({ node, ...props }) => <em className="italic" {...props} />,
|
|
}}
|
|
>
|
|
{contentWithCitationBadge}
|
|
</ReactMarkdown>
|
|
</div>
|
|
);
|
|
};
|
|
|
|
export default MarkdownRenderer;
|