Passa al contenuto principale

Esempi

Gli esempi seguenti usano esportazioni e nomi delle opzioni effettivamente disponibili. Importa @powerduck/md-editor/dist/style.css una sola volta prima di eseguirli. Crea nella pagina gli elementi contenitore indicati e fornisci un endpoint di caricamento per gli esempi che lo richiedono.

1. Editor di base con le opzioni comuni​

Un MarkdownEditor in JavaScript puro, in modalità complex, con le opzioni comuni configurate:

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. Componente React con valore controllato​

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 e onChange non provocano la ricreazione dell’istanza, quindi la digitazione non distrugge l’istanza di CodeMirror.

3. Barra degli strumenti personalizzata (array e oggetto)​

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

I 22 nomi di azione validi sono elencati in Funzionalità.

4. Integrazione del caricamento immagini​

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

Incolla o trascina un file immagine nell’editor: l’hook viene chiamato automaticamente. Il Markdown generato viene inserito nella posizione del cursore.

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

Digitando @ si apre il menu a discesa. Selezionando un elemento viene inserito [@label](mention:id), visualizzato come badge formattato nell’anteprima.

6. Uso autonomo di 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 restituisce una stringa e non monta un editor. Le mappe mentali vengono emesse come segnaposto <div> inerti; chiama direttamente Renderer.hydrate se servono diagrammi interattivi fuori dall’editor.

7. Modalità semplice (senza barra degli strumenti)​

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

La modalità simple non include barra degli strumenti, barra di stato o numeri di riga. Puoi comunque passare a complex durante l’esecuzione con editor.setMode('complex').

Passi successivi​