Skip to content

Editor ​

A document editor with blocks, tables and files that saves the text as HTML or JSON.

Oslo armchair

A soft armchair on a solid oak frame. The cover comes off and washes at 30 °C.

  • 31 in wide, 33 in deep, 36 in high

  • Seat height 16.5 in

  • Holds up to 265 lb

Keep the chair away from radiators: oak dries out and cracks.

Upholstery

FabricPriceIn stock
Gray linen249
Dark linen259
Blue velvet289

Cover care

Wash the cover apart from colored laundry and dry it flat.

Type / at the start of a line to turn it into another block, or press + in the top bar to insert one below.

Installation ​

ts
import { NuiEditor } from '@numior/kit/editor';import type { DocJSON } from '@numior/kit/editor-core';

@numior/kit/editor-core holds the document model: the DocJSON type and functions such as fromHTML. @numior/kit/content describes the blocks and renders a finished document, and @numior/kit/table draws the tables inside it.

Save the document ​

Bind the document with v-model. By default the model holds an HTML string.

Set format="json" to keep the document as an object:


The description is not saved yet

An HTML model updates 300 ms after the last edit, and a JSON model after every edit. Both update at once when the editor loses focus or its form is submitted.

The change event fires after every edit with the document as JSON, whatever the format of the model.

Choose the toolbar ​

Pick a mode above the editor to compare the bars:

The customer asks to deliver the armchair after 6 PM and carry it up to the fifth floor: the elevator is out of order.

By default the editor shows both bars: formatting on top and a bar over the selected text. The block type, such as a heading or a code block, is picked in the bar over the selection.

Touch screens have no bar over the selection, so there the block type moves to the top bar. It sits there with toolbar="fixed" as well. On a phone, the top bar docks above the on-screen keyboard while you type.

With none, there are no bars: text is styled with shortcuts, Markdown and the slash menu.

Mention a teammate ​

Pass a search function to mentions:

The customer wants both armchairs reupholstered in dark linen.

Typing @ opens the list at the caret. The editor waits for a short pause before it calls the function and aborts a stale call through signal. A mention keeps the person's id and name in the document.

type NuiEditorMentions = (query: string, context: { readonly signal: AbortSignal;}) => Promise<readonly NuiEditorMention[]>;
interface NuiEditorMention { readonly id: string; readonly label: string; readonly description?: string | undefined; readonly avatar?: string | undefined;}

Markdown shortcuts ​

Type a marker and a space at the start of a line to change the block:

You typeYou get
# to ######Heading of levels 1 to 6
>Quote
- or *Bulleted list
1.Numbered list that starts from this number
[ ] or [x]To-do list, with the item checked after x
Three backticksCode block; a language name after them sets its language

Typing --- at the start of a line adds a divider. A style applies when you type the closing marker after a word:

You typeYou get
**bold**Bold
*italic*Italic
~~strike~~Strikethrough
`code`Inline code

Read only ​

Set readonly to show the document without editing: the text can still be selected and copied. To show a finished document on a page, render it with NuiContent, which loads no editor code.

During server rendering, the editor outputs the document as plain content. It turns into an editor once it mounts in the browser.

Control the editor from code ​

Take the editor object from a template ref to call the editor from your code:

vue
<template> <NuiEditor ref="editor" v-model="document" aria-label="Product description" /></template><script setup lang="ts">import { ref, useTemplateRef } from 'vue';import { useHotkey } from '@numior/kit';import { NuiEditor, type NuiEditorApi } from '@numior/kit/editor';import { saveDescription } from './api';const editor = useTemplateRef<{ editor: NuiEditorApi }>('editor');const document = ref('<p>A soft armchair on a solid oak frame.</p>');const save = () => { editor.value?.editor.flush(); void saveDescription(document.value);};useHotkey('mod+s', save);</script>

flush() writes the latest edits to the model at once, so the shortcut saves what is on the screen. run applies a command from @numior/kit/editor-core, and revealNode scrolls to a block by its id.

coordsAt, posAt, contentBox and watchLayout help you draw your own layer in the overlay slot, such as the carets of co-authors.

interface NuiEditorApi { state(): EditorState | undefined; run(command: Command): boolean; focus(): void; flush(): void; coordsAt(pos: number): CaretRect | undefined; posAt(x: number, y: number): number | undefined; contentBox(): DOMRect | undefined; revealNode(id: string): void; watchLayout(listener: () => void): () => void;}

Accessibility ​

The text area is a multiline text box named by label or aria-label. Alt+F10 moves the focus into the formatting bar, the arrow keys walk its buttons, and Escape returns to the text.

In the slash and @ menus the focus stays in the text, and screen readers announce the highlighted option. On a Mac, press ⌘ in place of Ctrl.

Keys
Action
AltF10
Moves the focus into the formatting bar. Escape returns it to the text.
CtrlK
Opens the link field for the selected text.
CtrlU
Makes the text bold, italic or underlined.
CtrlShiftE
Strikes the text through or turns it into inline code.
CtrlShiftY
Undoes and redoes an edit.
CtrlShift↓
Moves the block with the caret up or down.
Ctrl↵
Checks a task list item. In a code block, starts a text line after it.
⇥
Indents and outdents a list item or a code line.
/
At the start of a line or after a space, opens the block menu.
@
Opens the list of people when mentions is set.
ArrowUp / ArrowDown
Moves through the options of the slash and @ menus.
Enter / Tab
Applies the chosen option of the slash or @ menu.
Esc
Closes the slash and @ menus and keeps the typed character as text.

API ​

Props

Name
Type
Default
Description
format
NuiEditorFormat
"html"
What v-model holds: html for a markup string, json for a JSON document.
schema
Schema
contentSchema
Document schema: which blocks and styles are allowed. Defaults to contentSchema from @numior/kit/content.
placeholder
string
—
Text shown in an empty document.
autofocus
boolean
false
Focuses the editor once it is mounted.
toolbar
NuiEditorToolbarMode
"both"
Formatting bar: fixed above the text, bubble over the selection, both, or none. The block type is picked in the bar over the selection, and in the top bar with fixed and with both on touch screens. The + button in the top bar inserts a block below the caret.
selectionActions
readonly NuiEditorSelectionAction[]
—
Your own buttons for selected text, in the bar over the selection and in the toolbar. A button is disabled while its command does not apply. In readonly mode only these are shown: over the selection, or in the toolbar on a touch screen.
colours
readonly string[]
CONTENT_COLOURS
Text colors in the menu, such as red or blue. All nine by default. Colors already in the document stay.
highlights
readonly string[]
CONTENT_COLOURS
Background highlight colors in the menu. All nine by default.
blockHandles
boolean
true
Shows a handle on the block under the pointer, with a block menu and dragging. Ctrl+Shift+Up and Down move the block with the caret.
blocks
readonly NuiEditorBlock[]
editorBlocks
Custom blocks from defineBlock, read once on mount: a component, keys, slash menu items and block menu items. The block context reports a place inside the block with setSpot(part) and leaveSpot(), and peers() returns where others are. This is how the document table shows the cells of co-authors.
highlighter
false | NuiHighlighter
—
Highlighter for code blocks instead of the one set in createNuiConfig or the built-in Shiki. false renders code in one color.
upload
NuiEditorUploadAdapter
—
Upload function (file, { onProgress, signal }) => Promise<{ url }>. With it, files and images can be pasted, dropped or picked in the slash menu and the + menu. Without it, only by link.
embeds
readonly (NuiEmbedProvider | "youtube" | "vimeo" | "loom" | "figma" | "maps" | "codepen")[]
NO_EMBEDS
Links that embed as a frame: youtube, vimeo, loom, figma, maps, codepen or custom rules { id, label, aspect, source(url) }. Without the prop embeds are off.
linkMetadata
NuiEditorLinkMetadata
—
Function (url, { signal }) => Promise<{ title, description, image, icon, site }> for link cards. Without it a card shows only the URL and the domain.
mentions
NuiEditorMentions
—
People search for mentions: (query, { signal }) => Promise<{ id, label, description?, avatar? }[]>. With it, @ opens a list at the caret. Without it, @ is plain text.
accept
string
—
File types that can be uploaded, in the accept attribute format, such as image/*.
maxSize
number
—
Largest upload size in bytes.
maxHeight
string
—
Largest height of the text area (a CSS length): beyond it the document scrolls inside the editor and the toolbar stays put.
plugins
readonly Plugin<unknown>[]
—
Extra core plugins, read on mount. Collaboration connects through it.
ids
IdSource
—
The source of ids for new nodes. Each client has its own in collaboration.
id
string
—
Id of the control. Defaults to the one from NuiField or is generated automatically.
size
NuiSize
"md"
Changes the size of the control: sm, md or lg. The theme density shifts the height of each size.
disabled
boolean
—
Disables the control. Inside NuiField it defaults to the field value.
readonly
boolean
—
Shows the document without editing. The text can still be selected and copied, and the field takes focus. Buttons from selectionActions stay available.
required
boolean
—
Marks the control as required. Inside NuiField it defaults to the field value.
invalid
boolean
—
Shows the error state without a text. With error it turns on by itself.
label
string
—
Label of the control. Inside NuiField the field provides the label.
description
string
—
Hint below the control. Screen readers announce it with the control.
error
string
—
Error text below the control. Puts the control into the error state.
reserveError
boolean
false
Reserves space for the error so the form does not shift when it appears.

Models

Name
Type
Default
Description
v-model
V
—
The document in the format encoding. HTML updates 300 ms after an edit, JSON on the next frame, and both right away on blur, form submit and editor.flush(). A value set from outside resets the undo history.

Events

Name
Payload
Description
focus
[event: FocusEvent]
Fires when the editor gets focus.
blur
[event: FocusEvent]
Fires when the editor loses focus.
change
[document: DocJSON]
Fires after an edit, at most once per frame, with the document as JSON.
paste
[paste: NuiEditorPaste]
Fires on paste. source tells where the content came from: own, word, google-docs, excel, sheets, html or text.

Slots

Name
Slot props
Description
overlay
{}
A layer above the editor text, such as remote cursors in collaboration.

Texts

Key
Russian
English
blockActions
Действия с блоком
Block actions
blockType
Тип блока
Block type
blocks
Блоки
Blocks
bold
Жирный
Bold
bookmark
Закладка
Bookmark
bookmarkEdit
Изменить закладку
Edit bookmark
bulletList
Маркированный список
Bulleted list
callout
Выноска
Callout
calloutTone
({ tone }) => `Тон выноски: ${RU_TONES[tone] ?? tone}`
({ tone }) => `Callout tone: ${EN_TONES[tone] ?? tone}`
chooseFile
Выбрать файлы
Choose files
chooseImage
Выбрать картинку
Choose an image
code
Код в строке
Inline code
codeBlock
Блок кода
Code block
codeCopied
Скопировано
Copied
codeLanguage
Язык кода
Code language
codeLanguageSearch
Найти язык
Search languages
codePlain
Обычный текст
Plain text
collapse
Свернуть
Collapse
colour
Цвет
Color
colourName
({ name }) => RU_COLOURS[name] ?? name
({ name }) => EN_COLOURS[name] ?? name
columnWidth
({ index }) => `Ширина колонки ${String(index)}`
({ index }) => `Column ${String(index)} width`
columns
({ count }) => `${String(count)} колонки`
({ count }) => `${String(count)} columns`
copyCode
Копировать код
Copy code
currentBlock
({ type }) => `Тип блока: ${type}`
({ type }) => `Block type: ${type}`
defaultColour
Обычный
Default
deleteBlock
Удалить
Delete
divider
Разделитель
Divider
done
({ text }) => (text === '' ? 'Выполнено' : `Выполнено: ${text}`)
({ text }) => (text === '' ? 'Done' : `Done: ${text}`)
download
Скачать
Download
duplicate
Дублировать
Duplicate
embed
Встраивание
Embed
embedInvalid
Эту ссылку нельзя встроить
This link cannot be embedded
embedTitle
({ provider }) => `Встраивание ${provider}`
({ provider }) => `${provider} embed`
embedUnavailable
({ provider }) => `Встраивания ${provider} здесь не разрешены`
({ provider }) => `${provider} embeds are not allowed here`
expand
Развернуть
Expand
file
Файл
File
formatting
Форматирование выделения
Selection formatting
heading
({ level }) => `Заголовок ${String(level)}`
({ level }) => `Heading ${String(level)}`
highlight
Выделение
Highlight
image
Картинка
Image
imageAlign
Выравнивание
Alignment
imageAlignCenter
По центру
Center
imageAlignEnd
К концу строки
Align to the line end
imageAlignStart
К началу строки
Align to the line start
imageAlt
Описание
Alt text
imageAltHint
Рассказывает о картинке тем, кто её не видит
Describes the image to people who cannot see it
imageAltSave
Сохранить
Save
imageCaption
Добавьте подпись
Add a caption
imageReplace
Заменить
Replace
imageWidth
Ширина картинки
Image width
imageWrap
Обтекание текстом
Text wrapping
imageWrapBreak
Отдельной строкой
Break text
imageWrapInline
В тексте
In line with text
imageWrapWrap
Обтекание
Wrap text
indent
Сдвинуть вправо
Indent
insert
Вставить
Insert
insertEmpty
Такого блока нет
No such block
insertSearch
Найти блок
Search blocks
italic
Курсив
Italic
link
Ссылка
Link
linkAddress
Адрес ссылки
Link address
linkApply
Готово
Apply
linkDescription
Описание
Description
linkEdit
Изменить ссылку
Edit link
linkInvalid
Такой адрес нельзя сделать ссылкой
This address cannot be linked
linkLoading
Загрузка…
Loading…
linkRefresh
Обновить
Refresh
linkRemove
Убрать ссылку
Remove link
linkSave
Сохранить
Save
linkTitle
Заголовок
Title
mediaAddress
Адрес
Address
mediaDropHint
Или перетащите файлы в редактор либо вставьте их
Or drop files into the editor or paste them
mediaInsert
Вставить
Insert
mediaInvalid
Введите веб-адрес
Enter a web address
mediaLink
По ссылке
By link
mediaUpload
Загрузить
Upload
mentions
Люди
People
mentionsEmpty
Никого не нашли
Nobody found
mentionsFailed
Не удалось загрузить людей
People could not be loaded
mentionsLoading
Ищем…
Searching…
moveDown
Переместить ниже
Move down
moveUp
Переместить выше
Move up
noHighlight
Нет
None
openByDefault
Открыт по умолчанию
Open by default
openLink
Открыть ссылку
Open link
orderedList
Нумерованный список
Numbered list
outdent
Сдвинуть влево
Outdent
pasteAs
Вставить ссылку как
Paste the link as
pasteEmbed
({ provider }) => `Встроить ${provider}`
({ provider }) => `Embed ${provider}`
pasteLink
Оставить ссылкой
Keep as a link
quote
Цитата
Quote
redo
Повторить
Redo
strike
Зачёркнутый
Strikethrough
table
Таблица
Table
tableAddColumn
Колонка
Column
tableAddRow
Строка
Row
tableColumn
({ index }) => `Колонка ${String(index)}`
({ index }) => `Column ${String(index)}`
tableColumnAfter
Вставить колонку после
Insert column after
tableColumnBefore
Вставить колонку перед
Insert column before
tableColumnName
Название колонки
Column name
tableDeleteColumn
Удалить колонку
Delete column
tableDeleteRow
Удалить строку
Delete row
tableRename
Переименовать
Rename
tableRowAbove
Вставить строку выше
Insert row above
tableRowBelow
Вставить строку ниже
Insert row below
tableType
Тип
Type
tableTypeName
({ type }) => RU_TYPES[type] ?? type
({ type }) => EN_TYPES[type] ?? type
text
Текст
Text
textColour
Цвет текста
Text color
toBookmark
Показать закладкой
Show as bookmark
toEmbed
Встроить
Embed
todoList
Список задач
To-do list
toggle
Раскрывающийся блок
Toggle
tone
Тон
Tone
toneName
({ tone }) => RU_TONES[tone] ?? tone
({ tone }) => EN_TONES[tone] ?? tone
toolbar
Форматирование
Formatting
turnInto
Превратить в
Turn into
underline
Подчёркнутый
Underline
undo
Отменить
Undo
uploadCancel
({ name }) => `Отменить загрузку ${name}`
({ name }) => `Cancel the upload of ${name}`
uploadDismiss
Убрать
Remove
uploadFailed
({ name }) => `Не удалось загрузить ${name}`
({ name }) => `Could not upload ${name}`
uploadLost
({ name }) => `${name} загружен, но вставить его некуда`
({ name }) => `${name} is uploaded, but there is no place left for it`
uploadRetry
Повторить
Retry
uploadSize
({ name, size }) => `${name} больше ${size}`
({ name, size }) => `${name} is larger than ${size}`
uploadSizeReason
({ size }) => `Файл больше ${size}`
({ size }) => `The file is larger than ${size}`
uploadType
({ name }) => `${name}: такой тип файла не принимается`
({ name }) => `${name}: this file type is not accepted`
uploadTypeReason
Такой тип файла не принимается
This file type is not accepted
uploadUnavailable
Сюда нельзя загрузить файлы — вставьте их по ссылке
Files cannot be uploaded here; insert them by link
uploaded
({ name }) => `${name} загружен`
({ name }) => `${name} is uploaded`
uploading
({ percent }) => `Загрузка… ${String(percent)} %`
({ percent }) => `Uploading… ${String(percent)}%`
wholeOf
({ type }) => RU_WHOLE[type] ?? 'Весь блок'
({ type }) => EN_WHOLE[type] ?? 'Whole block'

Edit this page

Search

Esc