Lewati ke konten utama

Contoh

Contoh berikut menggunakan ekspor dan nama opsi yang benar-benar tersedia. Impor @powerduck/md-editor/dist/style.css sekali sebelum menjalankannya. Buat elemen kontainer yang dirujuk pada halaman Anda dan sediakan endpoint unggah sendiri untuk contoh unggah berkas.

1. Editor dasar dengan opsi umum​

MarkdownEditor dalam JavaScript biasa, menggunakan mode complex dengan opsi umum yang dikonfigurasi:

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. Komponen React dengan nilai terkontrol​

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 dan onChange tidak memicu pembuatan ulang, sehingga mengetik tidak menghancurkan instans CodeMirror.

3. Bilah alat kustom (bentuk array dan record)​

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

Terdapat 22 nama tindakan valid yang tercantum dalam Fitur.

4. Integrasi unggah gambar​

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 ![filename](url)
},
});

Tempel atau seret berkas gambar ke editor; hook akan dipanggil otomatis. Markdown yang dihasilkan disisipkan pada posisi kursor.

5. Integrasi @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,
},
});

Mengetik @ membuka dropdown. Memilih item menyisipkan teks [@label](mention:id), yang ditampilkan sebagai lencana berformat dalam pratinjau.

6. Penggunaan mandiri 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 mengembalikan string dan tidak memasang editor. Peta pikiran dihasilkan sebagai placeholder <div> yang belum aktif; panggil Renderer.hydrate sendiri jika memerlukan diagram interaktif di luar editor.

7. Mode sederhana (tanpa bilah alat)​

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

Mode simple tidak memiliki bilah alat, bilah status, atau nomor baris. Anda tetap dapat beralih ke complex saat runtime dengan editor.setMode('complex').

Langkah berikutnya​