示例
以下示例使用真实的导出和选项名称。运行前请统一导入一次 @powerduck/md-editor/dist/style.css。在页面中创建示例引用的容器元素,并为上传示例提供自己的上传接口。
1. 配置常用选项的基础编辑器
使用原生 JS 创建 complex 模式的 MarkdownEditor,并配置常用选项:
import { MarkdownEditor, type MarkdownEditorOptions } from '@powerduck/md-editor';
import '@powerduck/md-editor/dist/style.css';
const options: MarkdownEditorOptions = {
value: '# Hello\n\nStart writing here...',
mode: 'complex',
theme: 'light',
math: true,
mindmap: true,
codeHighlight: true,
tips: true,
preview: true,
autoPreview: true,
renderDebounce: false, // render synchronously for this demo
onChange: (value) => console.log('changed:', value.length, 'chars'),
onImageUpload: async (file) => {
const formData = new FormData();
formData.append('file', file);
const res = await fetch('/api/upload', { method: 'POST', body: formData });
if (!res.ok) throw new Error('Upload failed');
const data = await res.json();
return data.url as string;
},
toolbar: ['heading', 'bold', 'italic', 'link', 'image', 'code'],
};
const editor = new MarkdownEditor('#editor', options);
// Call editor.destroy() when removing this editor from the page.
document.querySelector('#save')?.addEventListener('click', () => {
console.log(editor.getValue());
});
2. 受控值 React 组件
import { useRef, useState } from 'react';
import { MarkdownEditorReact, type MarkdownEditorHandle } from '@powerduck/md-editor/react';
import '@powerduck/md-editor/dist/style.css';
function NoteEditor() {
const [value, setValue] = useState('# Draft\n\nWrite something...');
const handleRef = useRef<MarkdownEditorHandle>(null);
return (
<div>
<button onClick={() => handleRef.current?.getHtml()}>Render HTML</button>
<MarkdownEditorReact
ref={handleRef}
value={value}
onChange={setValue}
mode="complex"
theme="light"
/>
</div>
);
}
export default NoteEditor;
value 和 onChange 不会触发实例重建,因此输入时不会销毁 CodeMirror 实例。
3. 自定义工具栏(数组和映射形式)
import { MarkdownEditor } from '@powerduck/md-editor';
import '@powerduck/md-editor/dist/style.css';
// Array form: an include-list. Actions retain the built-in toolbar order.
new MarkdownEditor('#editor-array', {
mode: 'complex',
toolbar: ['bold', 'italic', 'link', 'code', 'math'],
});
// Record form: per-item overrides. Everything not listed stays visible.
new MarkdownEditor('#editor-record', {
mode: 'complex',
toolbar: {
bold: { label: 'Make bold' },
image: { show: false },
youtube: { show: false },
theme: { icon: '<svg>...</svg>' },
},
});
有效的操作名称见功能中列出的 22 项。
4. 集成图片上传
import { MarkdownEditor } from '@powerduck/md-editor';
import '@powerduck/md-editor/dist/style.css';
const editor = new MarkdownEditor('#editor', {
mode: 'complex',
onImageUpload: async (file: File): Promise<string> => {
const form = new FormData();
form.append('file', file);
const res = await fetch('/api/upload', { method: 'POST', body: form });
if (!res.ok) throw new Error('Upload failed');
const { url } = await res.json();
return url; // inserted as 
},
});
将图片文件粘贴或拖入编辑器会自动调用上传钩子,生成的 Markdown 将插入光标位置。
5. 集成 @mention
import { MarkdownEditor, type MentionItem } from '@powerduck/md-editor';
import '@powerduck/md-editor/dist/style.css';
const USERS: MentionItem[] = [
{ id: '1', label: 'Alice', avatar: 'https://example.com/a.png', description: 'alice@example.com' },
{ id: '2', label: 'Bob', description: 'bob@example.com' },
];
new MarkdownEditor('#editor', {
mode: 'complex',
mention: {
onMentionSearch: async (query) =>
USERS.filter((u) => u.label.toLowerCase().includes(query.toLowerCase())),
onMentionSelect: (item) => `[@${item.label}](mention:${item.id})`,
minChars: 0,
maxItems: 8,
},
});
输入 @ 会打开下拉列表。选择条目后插入 [@label](mention:id) 文本,并在预览中显示为带样式的徽标。
6. 独立使用 renderMarkdown
import { renderMarkdown } from '@powerduck/md-editor';
import '@powerduck/md-editor/dist/style.css';
const source = [
'# Hello',
'',
'Inline: $E=mc^2$.',
'',
'```ts',
'const x: number = 1;',
'```',
'',
':::tip',
'Callout block.',
':::',
].join('\n');
const html = renderMarkdown(source, { math: true, tips: true });
document.getElementById('output')!.innerHTML = html;
renderMarkdown 返回字符串,不会挂载编辑器。思维导图以尚未激活的 <div> 占位符输出;如需在编辑器外显示交互式图形,请自行调用 Renderer.hydrate。
7. 简洁模式(无工具栏)
import { MarkdownEditor } from '@powerduck/md-editor';
import '@powerduck/md-editor/dist/style.css';
const editor = new MarkdownEditor('#editor', {
value: '# Minimal editor\n\nNo toolbar, no status bar.',
mode: 'simple', // default; pure edit + preview
theme: 'dark',
preview: true,
});
simple 模式没有工具栏、状态栏和行号。仍可在运行时通过 editor.setMode('complex') 切换为 complex 模式。