Vitral 0.2.18
Formulário

Editor

Texto rico com motor próprio e sem dependências: títulos, listas, tabelas, imagens, links e atalhos de Markdown, ligado como HTML sanitizado.

Importação

main.ts
import { Editor } from '@vitral/vue';

Padrão

Release notes

This editor writes semantic HTML, keeps undo history and understands Markdown as you type. Try ## , - or **bold**.

  • Paste from Word or Google Docs

  • Select text and press Ctrl+K for a link

Nothing pasted can run a script: only what the schema knows survives.

Texto formatado. Alt+F10 vai para a barra de ferramentas e Esc volta. Ctrl+K edita um link, Alt+Enter abre o que está sob o cursor, Ctrl+F localiza e Ctrl+H substitui. Atalhos Markdown como # e - funcionam no início da linha.
<script setup lang="ts">import { Editor, Label, StackPanel } from '@vitral/vue';import { ref } from 'vue'; const article = ref(    '<h2>Release notes</h2><p>This editor writes <strong>semantic HTML</strong>, keeps <em>undo</em> history and understands <code>Markdown</code> as you type. Try <code>## </code>, <code>- </code> or <code>**bold**</code>.</p>' +        '<ul data-type="taskList"><li data-type="taskItem" data-checked="true"><p>Paste from Word or Google Docs</p></li><li data-type="taskItem" data-checked="false"><p>Select text and press Ctrl+K for a link</p></li></ul>' +        '<blockquote><p>Nothing pasted can run a script: only what the schema knows survives.</p></blockquote>');</script> <template>    <StackPanel spacing="0.375rem" style="width: 100%">        <Label for="ed-article">Article</Label>        <Editor id="ed-article" v-model="article" placeholder="Write something…" />    </StackPanel></template>

Barra de ferramentas personalizada

`toolbar` recebe grupos de nomes de itens; o slot `toolbar` substitui a barra por peças suas.

Only the basics here.

Texto formatado. Alt+F10 vai para a barra de ferramentas e Esc volta. Ctrl+K edita um link, Alt+Enter abre o que está sob o cursor, Ctrl+F localiza e Ctrl+H substitui. Atalhos Markdown como # e - funcionam no início da linha.


Texto formatado. Alt+F10 vai para a barra de ferramentas e Esc volta. Ctrl+K edita um link, Alt+Enter abre o que está sob o cursor, Ctrl+F localiza e Ctrl+H substitui. Atalhos Markdown como # e - funcionam no início da linha.
<script setup lang="ts">import { Editor, EditorButton, EditorToolbar, EditorToolbarGroup, StackPanel } from '@vitral/vue';import { ref } from 'vue'; const note = ref('<p>Only the basics here.</p>');</script> <template>    <StackPanel spacing="1rem" style="width: 100%">        <Editor v-model="note" :toolbar="[['bold', 'italic', 'strike'], ['bulletList', 'orderedList'], ['link', 'undo', 'redo']]" aria-label="Note" />        <Editor aria-label="Minimal" placeholder="The toolbar slot">            <template #toolbar>                <EditorToolbar>                    <EditorToolbarGroup>                        <EditorButton command="heading2" />                        <EditorButton command="bold" />                        <EditorButton command="italic" />                    </EditorToolbarGroup>                    <EditorToolbarGroup>                        <EditorButton command="clear" show-label />                    </EditorToolbarGroup>                </EditorToolbar>            </template>        </Editor>    </StackPanel></template>

Menu de barra e ações de bloco

Digite `/` no começo de uma palavra e os blocos são oferecidos, filtrados enquanto você digita; Enter ou um clique insere um. Ao lado do bloco em que está o cursor há uma alça, que abre duplicar, mover, transformar em texto e excluir. `slash-menu` e `block-menu` recebem entradas suas, ou `false` para nenhuma.

Type a slash on the empty line under this one.


Texto formatado. Alt+F10 vai para a barra de ferramentas e Esc volta. Ctrl+K edita um link, Alt+Enter abre o que está sob o cursor, Ctrl+F localiza e Ctrl+H substitui. Atalhos Markdown como # e - funcionam no início da linha.

This one offers three commands of its own.


Texto formatado. Alt+F10 vai para a barra de ferramentas e Esc volta. Ctrl+K edita um link, Alt+Enter abre o que está sob o cursor, Ctrl+F localiza e Ctrl+H substitui. Atalhos Markdown como # e - funcionam no início da linha.
<script setup lang="ts">import { Editor, StackPanel } from '@vitral/vue';import { ref } from 'vue'; const blocks = ref('<p>Type a slash on the empty line under this one.</p><p></p>');const custom = ref('<p>This one offers three commands of its own.</p><p></p>'); // A slash command is data: a name, a line about it, and either a command the// editor knows or a `run` of your own.const slashCommands = [    { id: 'heading2', label: 'Section', description: 'A heading for a section', icon: 'heading2', command: ['toggleHeading', 2] as const },    { id: 'taskList', label: 'Checklist', description: 'Things to tick off', icon: 'listChecks', command: ['toggleTaskList'] as const },    {        id: 'today',        label: "Today's date",        description: 'Puts the date in, as text',        icon: 'calendar',        keywords: ['date', 'now'],        run: (editor: { run: (name: string, ...args: unknown[]) => boolean }) => editor.run('insertText', new Date().toLocaleDateString())    }];</script> <template>    <StackPanel spacing="1rem" style="width: 100%">        <Editor v-model="blocks" aria-label="Slash menu example" :toolbar="[['blockType'], ['bold', 'italic']]" />        <Editor            v-model="custom"            aria-label="Own slash commands"            :toolbar="false"            :slash-menu="slashCommands"            :block-menu="[{ id: 'delete', label: 'Delete', icon: 'trash', run: (editor) => editor.run('deleteBlock') }]"        />    </StackPanel></template>

Localizar e substituir

Ctrl+F (⌘F) abre a barra sobre o texto e Ctrl+H (⌘⌥F) abre com a linha de substituir; o item `find` da barra de ferramentas também. Cada resultado fica em amarelo e o atual em laranja, pintados com highlights em vez de escritos no documento, então o desfazer, o cursor e um leitor de tela veem só o texto. Diferenciar maiúsculas, palavra inteira e expressão regular — onde `$1` funciona na substituição — são botões ao lado do campo. Enter vai ao próximo resultado e Shift+Enter ao anterior; uma substituição mantém a formatação das palavras que substitui, e Substituir tudo é um passo só para desfazer. `:find="false"` deixa as teclas para o navegador.

Release notes

The colour tokens are now grouped by colour role, and every colour a chart uses is a token of its own.

Colour contrast was checked against WCAG AA in both colour schemes.

--vt-chart-1: colour-1;
Texto formatado. Alt+F10 vai para a barra de ferramentas e Esc volta. Ctrl+K edita um link, Alt+Enter abre o que está sob o cursor, Ctrl+F localiza e Ctrl+H substitui. Atalhos Markdown como # e - funcionam no início da linha.
<script setup lang="ts">import { Editor } from '@vitral/vue';import { ref } from 'vue'; const text = ref(    '<h3>Release notes</h3><p>The <strong>colour</strong> tokens are now grouped by colour role, and every colour a chart uses is a token of its own.</p><p>Colour contrast was checked against WCAG AA in both colour schemes.</p><pre><code>--vt-chart-1: colour-1;</code></pre>');</script> <template>    <Editor v-model="text" :toolbar="[['bold', 'italic', 'link'], ['undo', 'redo'], ['find']]" aria-label="Release notes" style="width: 100%" /></template>

Chips inline

Um chip é uma peça só na linha — uma pessoa, uma tag, uma variável — que o cursor contorna e que um Backspace remove. `chips` recebe um gatilho por tipo: digite @ ou # e escolha na lista, que `items` pode preencher depois, a partir de um servidor. `run('insertChip', { id, label, kind })` insere um pelo código. O HTML guarda o que cada chip representa, em `data-chip`.

Ask Ana Souza about the release, and tag it urgent. Type @ or # on the line below.


Texto formatado. Alt+F10 vai para a barra de ferramentas e Esc volta. Ctrl+K edita um link, Alt+Enter abre o que está sob o cursor, Ctrl+F localiza e Ctrl+H substitui. Atalhos Markdown como # e - funcionam no início da linha.
<script setup lang="ts">import { Button, Editor, type ChipTrigger } from '@vitral/vue';import { ref } from 'vue'; const text = ref(    '<p>Ask <span data-chip="u1" data-kind="mention" contenteditable="false">Ana Souza</span> about the release, and tag it <span data-chip="t-urgent" data-kind="tag" contenteditable="false">urgent</span>. Type @ or # on the line below.</p><p></p>');const editor = ref<InstanceType<typeof Editor> | null>(null); const people = [    { id: 'u1', label: 'Ana Souza', description: 'Product designer' },    { id: 'u2', label: 'Bruno Lima', description: 'Engineer' },    { id: 'u3', label: 'Carla Dias', description: 'Support' }]; // One trigger a kind. `items` can answer at once, or later — here the tags// stand in for a search on the server.const chips: ChipTrigger[] = [    { char: '@', kind: 'mention', items: (q) => people.filter((p) => p.label.toLowerCase().includes(q.toLowerCase())) },    {        char: '#',        kind: 'tag',        items: (q) =>            new Promise((resolve) =>                setTimeout(() => resolve(['urgent', 'design', 'backend', q].filter((t, i, all) => t && all.indexOf(t) === i && t.includes(q.toLowerCase())).map((t) => ({ id: `t-${t}`, label: t }))), 150)            )    }]; // A chip can be put in from code too: a variable a template fills in later.function insertVariable(name: string) {    editor.value?.editor?.run('insertChip', { id: name, label: name, kind: 'variable' });    editor.value?.focus();}</script> <template>    <div style="display: flex; flex-direction: column; gap: 0.5rem; width: 100%">        <div style="display: flex; flex-wrap: wrap; gap: 0.5rem">            <Button label="first_name" icon="plus" size="small" variant="outlined" severity="secondary" @click="insertVariable('first_name')" />            <Button label="order_id" icon="plus" size="small" variant="outlined" severity="secondary" @click="insertVariable('order_id')" />        </div>        <Editor ref="editor" v-model="text" :chips="chips" aria-label="Inline chips" style="width: 100%" />    </div></template>

Fórmulas

Uma fórmula é escrita em LaTeX — `\frac{a}{b}`, `\sqrt{x}`, `x^2` — e desenhada. O botão Σ na barra de ferramentas e `/fórmula` abrem o painel: o código numa caixa, a fórmula desenhada acima dela enquanto você digita, e as mais comuns prontas em botões. No texto, clique num número ou numa letra de uma fórmula e ele é editado ali mesmo, com a fórmula redesenhada ao redor a cada tecla; Tab vai para o próximo valor, Enter confirma, Escape desfaz. Um clique em qualquer outro ponto da fórmula abre o painel com aquele trecho selecionado. O desenho é feito de contornos posicionados pelo Vitral, não de texto montado pelo navegador, então é igual em todos os navegadores e imprime como aparece; o HTML guarda o código em `data-math`.

Quadratic equations

The roots of are

The mean of a sample is , and the area of a circle is . Press the 4, the 2 or a letter above to change it where it stands; press the fraction bar to open the whole formula.

Texto formatado. Alt+F10 vai para a barra de ferramentas e Esc volta. Ctrl+K edita um link, Alt+Enter abre o que está sob o cursor, Ctrl+F localiza e Ctrl+H substitui. Atalhos Markdown como # e - funcionam no início da linha.
<script setup lang="ts">import { Button, Editor } from '@vitral/vue';import { ref } from 'vue'; // A formula is its LaTeX, in `data-math`. The drawing around it is made from// that, here and in the HTML the editor hands back.const text = ref(    '<h2>Quadratic equations</h2>' +        '<p>The roots of <span data-math="ax^2 + bx + c = 0"></span> are <span data-math="x = \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a}" data-display="true"></span></p>' +        '<p>The mean of a sample is <span data-math="\\overline{x} = \\frac{1}{n} \\sum_{i=1}^{n} x_i"></span>, and the area of a circle is <span data-math="\\pi r^2"></span>. Press the 4, the 2 or a letter above to change it where it stands; press the fraction bar to open the whole formula.</p>');const editor = ref<InstanceType<typeof Editor> | null>(null); // From code: a formula is put in where the caret is.function insert(latex: string) {    editor.value?.editor?.run('insertMath', { latex });    editor.value?.focus();} // The HTML carries the formulas as drawings, so it prints as it looks: into a// frame of its own, and the browser's print dialog saves it as a PDF.function print() {    const frame = document.createElement('iframe');    frame.style.cssText = 'position:fixed;width:0;height:0;border:0';    frame.srcdoc = `<!doctype html><meta charset="utf-8"><title>Document</title><style>body{font:16px/1.6 system-ui,sans-serif;margin:2rem;color:#111}</style>${editor.value?.getHTML() ?? ''}`;    frame.onload = () => {        frame.contentWindow?.print();        setTimeout(() => frame.remove(), 1000);    };    document.body.appendChild(frame);}</script> <template>    <div style="display: flex; flex-direction: column; gap: 0.5rem; width: 100%">        <div style="display: flex; flex-wrap: wrap; gap: 0.5rem">            <Button label="Pythagoras" icon="plus" size="small" variant="outlined" severity="secondary" @click="insert('a^2 + b^2 = c^2')" />            <Button label="Fraction" icon="plus" size="small" variant="outlined" severity="secondary" @click="insert('\\frac{1}{2}')" />            <Button label="Print or save as PDF" icon="download" size="small" variant="text" @click="print" />        </div>        <Editor ref="editor" v-model="text" aria-label="Formulas" style="width: 100%" />    </div></template>

Fórmulas: as suas, ou nenhuma

`math` recebe `{ templates, inlineEdit }`: as fórmulas prontas que o painel oferece, e se um valor é editado onde está (`false` abre o painel no lugar). `:math="false"` continua desenhando as fórmulas que o documento tem e tira todas as formas de criar ou alterar uma: sem botão, sem entrada no menu de barra, sem clique.

Formulas of your own, edited in the panel

Water is , and it forms by .

Texto formatado. Alt+F10 vai para a barra de ferramentas e Esc volta. Ctrl+K edita um link, Alt+Enter abre o que está sob o cursor, Ctrl+F localiza e Ctrl+H substitui. Atalhos Markdown como # e - funcionam no início da linha.
Formulas switched off

The answer sheet: . The text around the formula can be changed; the formula cannot.

Texto formatado. Alt+F10 vai para a barra de ferramentas e Esc volta. Ctrl+K edita um link, Alt+Enter abre o que está sob o cursor, Ctrl+F localiza e Ctrl+H substitui. Atalhos Markdown como # e - funcionam no início da linha.
<script setup lang="ts">import { Editor, type EditorMathOptions } from '@vitral/vue';import { ref } from 'vue'; // The formulas a chemistry class writes, in place of the usual ones; and a// press on a value opens the panel rather than a box over it.const chemistry: EditorMathOptions = {    templates: [        { id: 'water', label: 'Water', latex: 'H_2O' },        { id: 'reaction', label: 'Reaction', latex: '2H_2 + O_2 \\to 2H_2O' },        { id: 'concentration', label: 'Concentration', latex: 'C = \\frac{n}{V}' },        { id: 'ph', label: 'pH', latex: '\\text{pH} = -\\log \\left[ H^+ \\right]' }    ],    inlineEdit: false}; const lesson = ref('<p>Water is <span data-math="H_2O"></span>, and it forms by <span data-math="2H_2 + O_2 \\to 2H_2O"></span>.</p>');const fixed = ref('<p>The answer sheet: <span data-math="x = \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a}"></span>. The text around the formula can be changed; the formula cannot.</p>');</script> <template>    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(18rem, 1fr)); gap: 1rem; width: 100%">        <div style="display: flex; flex-direction: column; gap: 0.375rem">            <span id="ed-math-own">Formulas of your own, edited in the panel</span>            <Editor v-model="lesson" :math="chemistry" aria-labelledby="ed-math-own" />        </div>        <div style="display: flex; flex-direction: column; gap: 0.375rem">            <span id="ed-math-off">Formulas switched off</span>            <Editor v-model="fixed" :math="false" aria-labelledby="ed-math-off" />        </div>    </div></template>

Fórmulas: o que sai

O HTML é por onde as fórmulas de um documento saem com ele. Por padrão cada uma vai com o seu desenho dentro, então o HTML as mostra em qualquer página e imprime como aparece — o botão abre o diálogo de impressão do navegador, que salva em PDF. `:math="{ output: 'source' }"` grava só o LaTeX: uma fração do tamanho para armazenar, e `renderMathIn(element)`, do `@vitral/core`, desenha onde o documento é exibido. `getHTML({ math })` pede um ou outro a qualquer momento, `renderMathHTML(html, 'drawing' | 'source')` converte um HTML armazenado de um para o outro sem precisar de página, e `editorFormulas(doc)` lista as fórmulas como strings. JSON, texto puro e Markdown levam o LaTeX.

Mathematics — test 3

1. Solve and say which root is the larger.

2. Simplify

3. The mean of the marks is . Find it for 6, 8 and 10.

Texto formatado. Alt+F10 vai para a barra de ferramentas e Esc volta. Ctrl+K edita um link, Alt+Enter abre o que está sob o cursor, Ctrl+F localiza e Ctrl+H substitui. Atalhos Markdown como # e - funcionam no início da linha.
The model (v-model), 0.3 KB
<h2>Mathematics — test 3</h2><p>1. Solve <span data-math="x^2 - 5x + 6 = 0"></span> and say which root is the larger.</p><p>2. Simplify <span data-math="\frac{6a^2 b}{3ab}" data-display="true"></span></p><p>3. The mean of the marks is <span data-math="\overline{x} = \frac{1}{n} \sum_{i=1}^{n} x_i"></span>. Find it for 6, 8 and 10.</p>
With drawings: 9.9 KB · source alone: 0.5 KB
The formulas, as strings
x^2 - 5x + 6 = 0
\frac{6a^2 b}{3ab}
\overline{x} = \frac{1}{n} \sum_{i=1}^{n} x_i
A page without the editor

Mathematics — test 3

1. Solve and say which root is the larger.

2. Simplify

3. The mean of the marks is . Find it for 6, 8 and 10.

The source-only HTML, drawn with renderMathIn
<script setup lang="ts">import { editorFormulas, loadMath, renderMathIn } from '@vitral/core';import { Button, Editor, SelectButton, type EditorMathOptions } from '@vitral/vue';import { computed, nextTick, onMounted, ref, watch } from 'vue'; // An exam, with its formulas given as their source alone: that is all the// editor needs to be handed.const text = ref(    '<h2>Mathematics — test 3</h2>' +        '<p>1. Solve <span data-math="x^2 - 5x + 6 = 0"></span> and say which root is the larger.</p>' +        '<p>2. Simplify <span data-math="\\frac{6a^2 b}{3ab}" data-display="true"></span></p>' +        '<p>3. The mean of the marks is <span data-math="\\overline{x} = \\frac{1}{n} \\sum_{i=1}^{n} x_i"></span>. Find it for 6, 8 and 10.</p>'); // How the model's HTML carries a formula: with its drawing, or as its source.const output = ref<'drawing' | 'source'>('drawing');const math = computed<EditorMathOptions>(() => ({ output: output.value })); const editor = ref<InstanceType<typeof Editor> | null>(null);const page = ref<HTMLElement | null>(null);const formulas = ref<string[]>([]);const sizes = ref({ drawing: 0, source: 0 }); async function read() {    const instance = editor.value;    if (!instance?.editor) return;    // The formulas as strings: what a search index, a marking script or another system wants.    formulas.value = editorFormulas(instance.editor.state.doc).map((formula) => formula.latex);    // Either HTML can be asked for, whatever the model holds. The drawings need the renderer, which    // the first formula shown sends for: waiting on it here covers a document read before it has come.    await loadMath();    sizes.value = { drawing: instance.getHTML({ math: 'drawing' }).length, source: instance.getHTML({ math: 'source' }).length };    // A page that shows the document without the editor: the small HTML goes in, and its formulas are drawn from their source.    if (page.value) {        page.value.innerHTML = instance.getHTML({ math: 'source' });        await renderMathIn(page.value);    }} onMounted(() => nextTick(read));watch([text, output], () => nextTick(read)); const kb = (characters: number) => `${(characters / 1024).toFixed(1)} KB`; // The HTML with the drawings prints as it looks: into a frame of its own, and// the browser's print dialog saves it as a PDF.function print() {    const frame = document.createElement('iframe');    frame.style.cssText = 'position:fixed;width:0;height:0;border:0';    frame.srcdoc = `<!doctype html><meta charset="utf-8"><title>Test</title><style>body{font:16px/1.7 system-ui,sans-serif;margin:2.5rem;color:#111}</style>${editor.value?.getHTML({ math: 'drawing' }) ?? ''}`;    frame.onload = () => {        frame.contentWindow?.print();        setTimeout(() => frame.remove(), 1000);    };    document.body.appendChild(frame);}</script> <template>    <div style="display: flex; flex-direction: column; gap: 0.75rem; width: 100%">        <div style="display: flex; flex-wrap: wrap; align-items: center; gap: 0.75rem">            <SelectButton v-model="output" :options="['drawing', 'source']" label="How the model's HTML carries a formula" :allow-empty="false" />            <Button label="Print or save as PDF" icon="download" size="small" variant="outlined" severity="secondary" @click="print" />        </div>        <Editor ref="editor" v-model="text" :math="math" aria-label="Exam" style="width: 100%" />        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(17rem, 1fr)); gap: 1rem; width: 100%">            <div style="display: flex; flex-direction: column; gap: 0.375rem; min-width: 0">                <strong style="font-size: 0.8125rem">The model (v-model), {{ kb(text.length) }}</strong>                <pre class="demo-output" aria-label="The model's HTML" tabindex="0" style="margin: 0; max-height: 14rem; overflow: auto; white-space: pre-wrap; word-break: break-all; font-size: 0.6875rem">{{ text }}</pre>                <small style="color: var(--vt-text-muted-color)">With drawings: {{ kb(sizes.drawing) }} · source alone: {{ kb(sizes.source) }}</small>            </div>            <div style="display: flex; flex-direction: column; gap: 0.375rem; min-width: 0">                <strong style="font-size: 0.8125rem">The formulas, as strings</strong>                <pre class="demo-output" aria-label="The formulas as LaTeX" tabindex="0" style="margin: 0; max-height: 14rem; overflow: auto; white-space: pre-wrap; font-size: 0.75rem">{{ formulas.join('\n') }}</pre>            </div>            <div style="display: flex; flex-direction: column; gap: 0.375rem; min-width: 0">                <strong style="font-size: 0.8125rem">A page without the editor</strong>                <div ref="page" aria-label="The document, shown without the editor" style="padding: 0.75rem 1rem; border: 1px solid var(--vt-content-border-color); border-radius: 0.5rem; max-height: 14rem; overflow: auto; line-height: 1.7" />                <small style="color: var(--vt-text-muted-color)">The source-only HTML, drawn with renderMathIn</small>            </div>        </div>    </div></template>

Fórmulas: uma sozinha

Fora do editor, uma fórmula é uma função do seu código. `renderMath(latex, { fontSize, color, display })`, do `@vitral/core`, devolve o SVG como arquivo: com tamanho em pixels e cor própria, que é o que uma biblioteca de PDF desenha (o `svg` do pdfmake, o pdfkit e o jsPDF com seus plugins de SVG) e o que um servidor consegue gerar sem navegador. `renderMathDataUri` devolve o mesmo como endereço para um `<img>`, e `renderMathPng` uma imagem, no navegador, para o que só aceita imagens. Sem `fontSize`, o desenho é o trecho de linha que uma página quer, dimensionado pelo texto ao redor.

x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}
<svg xmlns="http://www.w3.org/2000/svg" role="img" aria-label="x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}" viewBox="-40 -2047.9 8559.4 2770.9" width="239.66" height="77.59" fill="#111827"><g transform="translate(0 0)"><g transform="translate(0 0)"><path d="M0 0 232-276 116-536H205L288-338L445-536H547L324-272L447 0H358L267-208L102 0Z"/></g></g><g transform="translate(798 0)"><g transform="translate(0 0)"><path d="M51-342V-413H521V-342ZM51-143V-214H521V-143Z"/></g></g><g transform="translate(1648 0)"><g transform="translate(110 -704)"><g transform="translate(0 0)"><g transform="translate(0 0)"><path d="M51-242V-313H521V-242Z"/></g></g><g transform="translate(572 0)"><g transform="translate(0 0)"><path d="M269 10Q215 10 182-18Q148-45 132-82H127L94 0H28L189-760H277L239-580Q232-546 224-514Q215-481 209-460Q203-438 202-436H206Q242-480 284-512Q327-545 383-545Q449-545 490-499Q530-453 530-363Q530-290 512-223Q494-156 460-104Q426-51 378-20Q330 10 269 10ZM262-63Q302-63 335-88Q368-114 392-157Q415-200 428-254Q440-308 440-364Q440-472 355-472Q322-472 288-448Q253-423 224-380Q195-338 178-284Q160-230 160-171Q160-123 185-93Q210-63 262-63Z"/></g></g><g transform="translate(1373 0)"><g transform="translate(0 0)"><path d="M250-36V-242H51V-313H250V-520H322V-313H521V-242H322V-36ZM51-36V-107H521V-36Z"/></g></g><g transform="translate(2167 0)"><g transform="translate(0 186.1)"><path d="M315 0 138-580H50V-650H196L351-121L706-1419H780L389 0Z"/></g><rect x="746" y="-1232.9" width="3698.4" height="71"/><g transform="translate(746 0)"><g transform="translate(0 0)"><g transform="translate(0 0)"><g transform="translate(0 0)"><path d="M269 10Q215 10 182-18Q148-45 132-82H127L94 0H28L189-760H277L239-580Q232-546 224-514Q215-481 209-460Q203-438 202-436H206Q242-480 284-512Q327-545 383-545Q449-545 490-499Q530-453 530-363Q530-290 512-223Q494-156 460-104Q426-51 378-20Q330 10 269 10ZM262-63Q302-63 335-88Q368-114 392-157Q415-200 428-254Q440-308 440-364Q440-472 355-472Q322-472 288-448Q253-423 224-380Q195-338 178-284Q160-230 160-171Q160-123 185-93Q210-63 262-63Z"/></g></g><g transform="translate(609 -390)"><g transform="translate(0 0)"><path d="M48 0V-73L235-262Q289-316 326-358Q363-400 382-440Q401-481 401-529Q401-588 366-618Q331-649 275-649Q223-649 184-631Q144-613 103-581L56-640Q98-675 152-700Q207-724 275-724Q375-724 433-674Q491-623 491-534Q491-478 468-430Q445-381 404-333Q363-285 308-231L159-84V-80H520V0Z" transform="scale(0.7 0.7)"/></g></g></g><g transform="translate(1271.4 0)"><g transform="translate(0 0)"><path d="M51-242V-313H521V-242Z"/></g></g><g transform="translate(2065.4 0)"><g transform="translate(0 0)"><path d="M363 0V-162H21V-237L357-718H448V-241H552V-162H448V0ZM107-241H363V-466Q363-518 364-554Q366-591 368-624H364Q356-605 344-583Q332-561 321-546Z"/></g></g><g transform="translate(2637.4 0)"><g transform="translate(0 0)"><path d="M197 10Q125 10 84-30Q44-71 44-129Q44-196 84-237Q124-278 190-298Q257-318 337-320L429-323L436-355Q438-363 439-373Q440-383 440-400Q440-432 416-453Q392-474 340-474Q315-474 270-468Q226-461 169-433L150-495Q193-521 246-533Q298-545 345-545Q409-545 448-526Q488-506 506-473Q525-440 525-400Q525-378 523-362Q521-345 517-328L446 0H382L381-76H377Q333-32 292-11Q251 10 197 10ZM214-61Q260-61 300-86Q341-110 370-148Q399-187 408-229L415-262L335-259Q279-257 234-245Q188-233 162-207Q135-181 135-136Q135-103 158-82Q180-61 214-61Z"/></g></g><g transform="translate(3205.4 0)"><g transform="translate(0 0)"><path d="M247 10Q158 10 103-40Q48-90 48-190Q48-262 68-326Q87-391 124-440Q160-489 212-518Q264-546 328-546Q363-546 398-539Q433-532 461-520L436-447Q416-456 388-464Q361-472 329-472Q272-472 229-434Q186-395 162-331Q138-267 138-191Q138-130 170-96Q201-63 256-63Q291-63 322-73Q354-83 385-96V-22Q357-8 322 1Q288 10 247 10Z"/></g></g></g></g></g><rect x="0" y="-313.5" width="6831.4" height="71"/><g transform="translate(2845.7 673)"><g transform="translate(0 0)"><g transform="translate(0 0)"><path d="M48 0V-73L235-262Q289-316 326-358Q363-400 382-440Q401-481 401-529Q401-588 366-618Q331-649 275-649Q223-649 184-631Q144-613 103-581L56-640Q98-675 152-700Q207-724 275-724Q375-724 433-674Q491-623 491-534Q491-478 468-430Q445-381 404-333Q363-285 308-231L159-84V-80H520V0Z"/></g></g><g transform="translate(572 0)"><g transform="translate(0 0)"><path d="M197 10Q125 10 84-30Q44-71 44-129Q44-196 84-237Q124-278 190-298Q257-318 337-320L429-323L436-355Q438-363 439-373Q440-383 440-400Q440-432 416-453Q392-474 340-474Q315-474 270-468Q226-461 169-433L150-495Q193-521 246-533Q298-545 345-545Q409-545 448-526Q488-506 506-473Q525-440 525-400Q525-378 523-362Q521-345 517-328L446 0H382L381-76H377Q333-32 292-11Q251 10 197 10ZM214-61Q260-61 300-86Q341-110 370-148Q399-187 408-229L415-262L335-259Q279-257 234-245Q188-233 162-207Q135-181 135-136Q135-103 158-82Q180-61 214-61Z"/></g></g></g></g></svg>
<script setup lang="ts">import { renderMath, renderMathDataUri, renderMathPng } from '@vitral/core';import { Button, InputNumber, InputText, Label } from '@vitral/vue';import { ref, watch } from 'vue'; // A formula with no editor around it: from its source to a drawing that// stands on its own, for whatever builds the PDF of an exam.const latex = ref('x = \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a}');const fontSize = ref(28);const color = ref('#111827'); const image = ref('');const svg = ref(''); watch(    [latex, fontSize, color],    async () => {        const options = { display: true, fontSize: fontSize.value || 16, color: color.value };        // The drawing as a file: a size in pixels and a colour of its own.        svg.value = await renderMath(latex.value, options);        // The same, as an address an <img> takes.        image.value = await renderMathDataUri(latex.value, options);    },    { immediate: true }); function save(name: string, blob: Blob) {    const link = document.createElement('a');    link.href = URL.createObjectURL(blob);    link.download = name;    link.click();    setTimeout(() => URL.revokeObjectURL(link.href), 1000);} const saveSvg = () => save('formula.svg', new Blob([svg.value], { type: 'image/svg+xml' }));// A picture, for what does not take drawings: three pixels for each one, so it prints sharp.const savePng = async () => save('formula.png', await renderMathPng(latex.value, { display: true, fontSize: fontSize.value || 16, color: color.value, scale: 3, background: '#ffffff' }));const copy = () => navigator.clipboard?.writeText(latex.value);</script> <template>    <div style="display: flex; flex-direction: column; gap: 0.75rem; width: 100%">        <div style="display: flex; flex-wrap: wrap; align-items: end; gap: 0.75rem">            <div style="display: flex; flex-direction: column; gap: 0.375rem; flex: 1 1 18rem">                <Label for="fx-latex">Formula, in LaTeX</Label>                <InputText id="fx-latex" v-model="latex" fluid spellcheck="false" />            </div>            <div style="display: flex; flex-direction: column; gap: 0.375rem">                <Label for="fx-size">Size, in pixels</Label>                <InputNumber id="fx-size" v-model="fontSize" :min="8" :max="96" style="width: 7rem" />            </div>            <div style="display: flex; flex-direction: column; gap: 0.375rem">                <Label for="fx-color">Colour</Label>                <InputText id="fx-color" v-model="color" style="width: 7rem" spellcheck="false" />            </div>        </div>        <!-- An ordinary image: the formula is a file now, and has nothing of the page in it. -->        <div style="display: flex; align-items: center; justify-content: center; min-height: 6rem; padding: 1rem; overflow: auto; background: #ffffff; border: 1px solid var(--vt-content-border-color); border-radius: 0.5rem">            <img v-if="image" :src="image" :alt="latex" />        </div>        <div style="display: flex; flex-wrap: wrap; gap: 0.5rem">            <Button label="Download SVG" icon="download" size="small" @click="saveSvg" />            <Button label="Download PNG" icon="download" size="small" variant="outlined" @click="savePng" />            <Button label="Copy LaTeX" icon="copy" size="small" variant="text" severity="secondary" @click="copy" />        </div>        <pre class="demo-output" aria-label="The SVG" tabindex="0" style="margin: 0; max-height: 8rem; overflow: auto; white-space: pre-wrap; word-break: break-all; font-size: 0.6875rem">{{ svg }}</pre>    </div></template>

Barra de ferramentas flutuante

`bubble-menu` mostra uma barra de ferramentas sobre o texto selecionado; com `:toolbar="false"`, ela é a única.

Select some of this text: a floating toolbar appears over it, with bold, italic, a link and a colour.

Texto formatado. Alt+F10 vai para a barra de ferramentas e Esc volta. Ctrl+K edita um link, Alt+Enter abre o que está sob o cursor, Ctrl+F localiza e Ctrl+H substitui. Atalhos Markdown como # e - funcionam no início da linha.
<script setup lang="ts">import { Editor } from '@vitral/vue';import { ref } from 'vue'; const bubble = ref('<p>Select some of this text: a floating toolbar appears over it, with bold, italic, a link and a colour.</p>');</script> <template>    <Editor v-model="bubble" :toolbar="false" bubble-menu aria-label="Bubble toolbar example" style="width: 100%" /></template>

Somente leitura

Terms

Read-only text can still be selected and copied, and links open.

  1. First

  2. Second

Texto formatado. Alt+F10 vai para a barra de ferramentas e Esc volta. Ctrl+K edita um link, Alt+Enter abre o que está sob o cursor, Ctrl+F localiza e Ctrl+H substitui. Atalhos Markdown como # e - funcionam no início da linha.
<script setup lang="ts">import { Editor } from '@vitral/vue';import { ref } from 'vue'; const terms = ref(    '<h3>Terms</h3><p>Read-only text can still be <mark data-color="yellow">selected and copied</mark>, and <a href="https://example.com" target="_blank">links</a> open.</p><ol><li><p>First</p></li><li><p>Second</p></li></ol>');</script> <template>    <Editor v-model="terms" readonly :toolbar="false" aria-label="Terms" style="width: 100%" /></template>

Com contagem e limite

`max-length` interrompe a digitação e a colagem no limite; a contagem descreve o texto.

Keep it short.

Texto formatado. Alt+F10 vai para a barra de ferramentas e Esc volta. Ctrl+K edita um link, Alt+Enter abre o que está sob o cursor, Ctrl+F localiza e Ctrl+H substitui. Atalhos Markdown como # e - funcionam no início da linha.
<script setup lang="ts">import { Editor, Label, StackPanel } from '@vitral/vue';import { ref } from 'vue'; const bio = ref('<p>Keep it short.</p>');</script> <template>    <StackPanel spacing="0.375rem" style="width: 100%">        <Label for="ed-bio">Bio</Label>        <Editor id="ed-bio" v-model="bio" :max-length="140" :toolbar="[['bold', 'italic', 'link']]" />    </StackPanel></template>

Saída em HTML e JSON

Type here and watch both formats change.

Texto formatado. Alt+F10 vai para a barra de ferramentas e Esc volta. Ctrl+K edita um link, Alt+Enter abre o que está sob o cursor, Ctrl+F localiza e Ctrl+H substitui. Atalhos Markdown como # e - funcionam no início da linha.
<p>Type here and watch <strong>both</strong> formats change.</p>
null
<script setup lang="ts">import { Editor, type EditorJSON } from '@vitral/vue';import { ref } from 'vue'; const output = ref('<p>Type here and watch <strong>both</strong> formats change.</p>');const outputJson = ref<EditorJSON | null>(null);</script> <template>    <Editor v-model="output" v-model:json="outputJson" aria-label="Output example" :toolbar="[['blockType'], ['bold', 'italic', 'color', 'highlight'], ['bulletList', 'link']]" style="width: 100%" />    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(16rem, 1fr)); gap: 1rem; width: 100%">        <pre class="demo-output" aria-label="HTML" tabindex="0" style="margin: 0; max-height: 16rem; overflow: auto; white-space: pre-wrap; font-size: 0.75rem">{{ output }}</pre>        <pre class="demo-output" aria-label="JSON" tabindex="0" style="margin: 0; max-height: 16rem; overflow: auto; font-size: 0.75rem">{{ JSON.stringify(outputJson, null, 2) }}</pre>    </div></template>

Composto por partes

`Editor.Root`, `Editor.Toolbar`, `Editor.Button`, `Editor.Content`, `Editor.BubbleMenu`, `Editor.Footer` e `Editor.Count`, também exportados como `EditorRoot`, `EditorToolbar`… compartilham um só editor; `useEditor()` chega até ele a partir dos seus próprios componentes.

This one is built from parts, with a toolbar of its own and a word count.

Texto formatado. Alt+F10 vai para a barra de ferramentas e Esc volta. Ctrl+K edita um link, Alt+Enter abre o que está sob o cursor, Ctrl+F localiza e Ctrl+H substitui. Atalhos Markdown como # e - funcionam no início da linha.
<script setup lang="ts">import { Editor } from '@vitral/vue';import { ref } from 'vue'; const composed = ref('<p>This one is built from parts, with a toolbar of its own and a word count.</p>');const words = ref(0);</script> <template>    <Editor.Root v-model="composed" placeholder="Parts…" aria-label="Composed editor" style="width: 100%" @text-change="words = $event.textValue.split(/\s+/).filter(Boolean).length">        <Editor.Toolbar>            <Editor.ToolbarGroup>                <Editor.BlockSelect :options="['paragraph', 'heading1', 'heading2']" />            </Editor.ToolbarGroup>            <Editor.ToolbarGroup>                <Editor.Button command="bold" />                <Editor.Button command="italic" />                <Editor.ColorPicker kind="highlight" />                <Editor.Button command="link" />            </Editor.ToolbarGroup>            <Editor.ToolbarGroup>                <Editor.Button command="taskList" />                <Editor.ImageButton />                <Editor.TableMenu />            </Editor.ToolbarGroup>        </Editor.Toolbar>        <Editor.Content />        <Editor.BubbleMenu :items="['bold', 'italic', 'link']" />        <Editor.Footer>            <span style="margin-inline-end: auto">Edited words: {{ words }}</span>            <Editor.Count :words="false" />        </Editor.Footer>    </Editor.Root></template>

API

Lido de packages/vue/src/components/Editor/types.ts, então diz o que o componente aceita de fato.

Props

NomeTipoDescrição
placeholder string—
readonly booleanO texto pode ser lido, selecionado e copiado, não alterado.
disabled boolean—
invalid boolean—
variant InputVariantO padrão é o `inputVariant` do plugin.
maxLength numberO máximo de caracteres que o texto pode ter; digitar e colar param aí.
autofocus booleanDá foco ao texto, com o cursor no fim, ao montar.
colors string[]Nomes de cores da paleta que os seletores de cor e de destaque oferecem, em ordem. O padrão é a paleta inteira.
historyDelay numberMilissegundos dentro dos quais digitação seguida conta como um só passo de desfazer. O padrão é 500.
slashMenu boolean | SlashCommand[]O menu que uma `/` abre no início de uma palavra: `true` para os blocos que o editor conhece, os comandos a oferecer, ou `false` para nenhum. O padrão é true.
chips ChipTrigger | ChipTrigger[]Chips inline inseridos ao digitar um gatilho: `{ char: '@', kind: 'mention', items: (q) => people.filter(…) }`, ou vários gatilhos. `items` pode devolver uma promise, para uma busca no servidor.
math boolean | EditorMathOptionsFórmulas, escritas em LaTeX e desenhadas: o botão de fórmula da barra de ferramentas, a entrada do menu de barra, o painel em que uma fórmula é escrita, e a edição de uma com um clique nela no texto. O padrão é true. `false` continua desenhando as fórmulas que o documento tem, e tira todas as formas de criar ou alterar uma. Um objeto escolhe as fórmulas prontas que o painel oferece (`templates`) e se um valor é editado onde está (`inlineEdit`).
find booleanLocalizar e substituir: Ctrl/⌘+F abre a barra sobre o texto, Ctrl+H (⌘+⌥+F no Mac) com a linha de substituir. Precisa de uma parte `<EditorFind>`, que o editor pronto já tem. O padrão é true; `false` deixa as teclas para o navegador.
blockMenu boolean | BlockAction[]A alça ao lado do bloco em que está o cursor: `true` para as ações de sempre, as ações a oferecer, ou `false` para nenhuma. O padrão é true.
toolbar boolean | EditorToolbarItem[][]A barra de ferramentas: `false` para nenhuma, ou grupos de nomes de itens, como em `[['bold', 'italic'], ['link']]`. O slot `toolbar` a substitui por completo.
bubbleMenu boolean | EditorToolbarItem[]Uma barra de ferramentas flutuante sobre o texto selecionado; `true` para os botões padrão, ou os itens a mostrar.
showCount booleanMostra a contagem de palavras e caracteres abaixo do texto. Ligado por padrão quando há `maxLength`.
showWordCount booleanMostra a contagem de palavras ao lado da de caracteres. O padrão é true.
scrollbar ScrollbarModeAs barras das caixas que este componente rola por dentro: `'hover'`, `'always'` ou `'native'`. Por padrão é a opção `scrollbar` da aplicação, que é `'hover'`.

Mais pt, dt e unstyled de BaseProps; veja pass-through e modo sem estilo.

Emits

EventoPayloadDescrição
update:modelValue value: string—
update:json value: EditorJSON—
text-change event: EditorTextChangeEventO conteúdo mudou.
selection-change event: EditorSelectionChangeEvent—
focus event: FocusEvent—
blur event: FocusEvent—
load event: { instance: unknown }O editor está pronto; `instance` é o editor sem framework por trás do componente.

Slots

NomeProps do slotDescrição
toolbar —Substitui a barra de ferramentas. Monte uma com `EditorToolbar`, `EditorButton` e as outras partes.
footer —Substitui o conteúdo do rodapé (a contagem).