Selection
Read and set the editor selection, a value that is a caret or range, one inline block, or a set of blocks, and stage pending marks.
The selection is a value stored on edytor.selection. It is independent from the browser’s DOM selection: the editor derives it from what the user does, and draws it back into the page after each render. Read it to build toolbars and menus; set it to move the caret from code.
The selection value
edytor.selection.value is one of four shapes:
import type { DocAnchor } from 'edytor/crdt/edytor';
type SelectionValue =
| { kind: 'none' }
| { kind: 'text'; anchor: DocAnchor; focus: DocAnchor; pending?: Record<string, unknown> }
| { kind: 'atom'; blockId: string; atomId: string; from: 'before' | 'after' }
| { kind: 'blocks'; ids: readonly string[] };
| Kind | When |
|---|---|
none |
Nothing is selected. Typing, an IME composition, Backspace, Delete and Enter then do nothing (Notion), even where the browser parked a caret of its own (after a drop or a column resize the editor holds the keys with no caret, and an undo, a redo, Escape or a closed menu can leave no selection); a click, a tap or a focus from outside (Tab) places the caret. |
text |
A caret (anchor equals focus) or a text range, possibly across blocks. anchor is where it started, focus where it ends. |
atom |
One inline block is selected, for example after clicking a mention (a click on its left or right edge places the caret beside it instead). The caret a browser places for that click (Chromium parks one at the editor’s start) never replaces it. from is the side the selection was made from. |
blocks |
Whole blocks are selected, for example after clicking a block handle or pressing Mod+A repeatedly. |
Text anchors (DocAnchor) are bound to characters, not to numeric offsets. When a collaborator types before your caret, your caret stays next to the same character. They are plain JSON, so you can store or send them.
The value is reactive, so $derived(edytor.selection.value.kind) updates with the selection. It is read-only: select() and setCaret() replace it, and keep the selected and focused blocks with it.
The caret
edytor.selection.caret is the collapsed text caret as { block, offset }: the Block handle and the offset in its content, where an inline atom counts as 1. It is null when the selection is not a caret (a range, an atom, blocks, none). These block offsets are the ones the document’s operations (edytor.insertText(…), edytor.insertInline(…)) take, an input rule’s and a trigger’s context reads (Input rules and triggers) and dispatcher.caret takes.
const caret = edytor.selection.caret;
if (caret) {
const { block, offset } = caret;
// The same caret, two characters on (clamped to the block's content).
edytor.selection.setCaret({ block, offset: offset + 2 });
// Writes take the same block offsets.
edytor.insertText(block.id, offset, '→ ');
}
selection.setCaret({ block, offset }) selects a caret there; a block that shows no text (a divider) keeps the selection as it was. block.textAtOffset(offset) answers the text segment that shows a block offset and the offset inside it (a boundary before an inline atom reads the text before it).
Reading positions: projection
Anchors are not offsets. For offsets, read selection.projection, computed from the value at the current document version. It is reactive and read-only, and speaks in block ids and block offsets:
| Field | Meaning |
|---|---|
start, end |
{ block, offset } in document order, or null. An inline block counts as 1 in the offset. |
isCollapsed, isReversed |
A caret; a selection made backwards. |
blocks |
Ids of the blocks from start to end, in document order. For a block selection this spans the whole range; selection.selectedBlocks holds exactly the selected blocks. |
isAtStartOfBlock, isAtEndOfBlock, isAtStartOfText, isAtEndOfText |
Edge checks for the start point. |
isTextSpanning, isBlockSpanning |
The range crosses text segments; crosses blocks. |
islandRoot, voidRoot |
The id of the island or void block the selection is in, or null. |
marks |
The marks at the caret (those of the character before it), or at the start of a range. |
content |
The selected text, as a string. |
For handles, look the ids up with edytor.idToBlock.get(id), and a block offset’s text segment with block.textAtOffset(offset):
const { start, isCollapsed, marks } = edytor.selection.projection;
const block = start && edytor.idToBlock.get(start.block);
if (isCollapsed && block && marks.bold === true) console.log(`a bold caret in ${block.type}`);
Setting the selection
selection.setCaret({ block, offset }) selects a caret (The caret); selection.select(value) sets any value. Build text anchors with edytor.document.anchorAt(blockId, offset, affinity). Bind a range start to the 'right' and its end or a caret to the 'left', so text typed at the boundary stays outside the range:
const anchor = edytor.document.anchorAt(blockId, 0, 'right');
const focus = edytor.document.anchorAt(blockId, 5, 'left');
if (anchor && focus) edytor.selection.select({ kind: 'text', anchor, focus });
edytor.selection.select({ kind: 'blocks', ids: [blockId] });
edytor.selection.select({ kind: 'none' });
selection.textValue(startText, startOffset, endText, endOffset, isReversed) builds the same text value from text segments and the offsets in them (endText and endOffset default to a caret), the anchors bound that way:
const block = edytor.idToBlock.get('intro');
const [first, last] = [block?.firstText, block?.lastText];
// The whole block's text, selected backwards.
if (first && last) edytor.selection.select(edytor.selection.textValue(first, 0, last, last.length, true));
To add a block to a block selection, or remove one, select the value’s ids with it or without it:
const { value } = edytor.selection;
const ids = value.kind === 'blocks' ? value.ids : [];
edytor.selection.select({ kind: 'blocks', ids: [...ids, blockId] });
edytor.selection.select({ kind: 'blocks', ids: ids.filter((id) => id !== blockId) });
No caret or range end rests in a block that shows no content of its own (a divider, a list, a code block): select, setCaret or a peer’s change that would put one there moves it to the nearest shown line. A caret goes to a list’s first item, else the next line, else the end of the line before. A range’s start goes to the block’s first shown line and its end to its last (a list’s first and last items); at a divider both pass on as a caret does. With no line anywhere, the selection stays as it was.
Showing it
select and setCaret change the value immediately. The browser selection is drawn after the next render, and only when the editor has focus (or nothing else does). When you set the selection from outside the editor, such as a menu button, focus the editor too:
edytor.selection.setCaret({ block, offset: 0 });
edytor.focus();
edytor.focus() keeps the selection; with none, it puts the caret at the start of the first text.
Block selection
A block selection is exactly its members:
- Clicking a block handle selects that block, not its children. A list and a code block are the exception, as they show nothing but their items or lines: a selected list stands for all of its items, as its highlight shows. Deleting, cutting, copying, pasting or typing over it, Turn into and the formatting keys act on the list with its items, and after Turn into the converted items stay selected. Moving, duplicating and the block menu’s Copy link take it as one block, whole.
- Shift+↑/↓ from a selected block adds each block it passes, nested blocks included; a columns layout and its columns are passed over (from a column’s last block the next column’s first is added), and a selection holding every block of a layout stands for the layout. ↑/↓ over one selected block move it the same way.
- A mouse drag that starts in a column and enters another column of the same layout selects blocks: every block from where it started to the one under the pointer, in reading order. Back in its own column it is a text selection again; released, the blocks stay selected.
- Mod+A selects the text of the current block, then the block, then every block in the document; with nothing selected, every block at once (Notion).
- With nothing selected, the arrows, Home/End and their word, document and Shift variants do nothing (Notion): the browser places no caret of its own. PageUp/PageDown still scroll the page.
- Escape leaves block selection and puts the caret at the end of the first selected block’s line (first in document order; for a list, its last shown line; for an image, its caption; a divider passes to the next selected block). Over selected dividers alone it goes to the start of the next line, else to the end of the line before; with no line anywhere they stay selected. Enter and Shift+Enter do the same, as in Notion: they remove nothing (over selected dividers alone, they add a line after them). Typing, a composition or a paste replaces the selected blocks: a composition (Japanese, Chinese or Korean input) starts in the one empty block that takes their place (a paragraph; inside a list, an item), and writes nowhere else.
- Formatting keys (Mod+B and the others) format exactly the selected blocks’ own text, a selected list’s or code block’s items included, and keep them selected. The hidden body of a closed toggle stays as it is, even inside a selected list; deleting a selected closed toggle keeps its body too, while deleting a selected list takes everything in it.
- The navigation keys (Home/End, the word keys, PageUp/PageDown, and on macOS Ctrl+A/E) read a block selection from its first shown line’s start to its last shown line’s end: each selected block’s own line, never a nested child that is not selected; for a block with no line of its own, such as a list or a code block, its first or last nested line. Going back the caret lands at the start, going forward at the end, and with Shift the selection grows from that edge in the key’s direction (Ctrl+A/E have no Shift variant). Ctrl+B/F leave a block selection as it is. Over selected dividers alone they keep the dividers selected, except PageUp/PageDown (and Mod+↑/↓), which go to the document’s start or end.
- Deleting or cutting every block leaves the caret in the emptied document’s paragraph; when only blocks without a line (a divider) are left, the one beside the deleted blocks is selected.
- Deleting a selection removes only the selected blocks, a selected list or code block with everything in it. A selected parent’s unselected children move into its place (undo puts them back). The caret goes to the start of the first child that takes their place, else to the end of the nearest line before the deleted blocks, or to the start of the nearest line after them when nothing comes before. The block menu’s Delete puts it in the same place.
- In a code block, the first Mod+A selects the code’s text; deleting or cutting it leaves one empty line in the code block.
- A press anywhere outside the editor and its own menus, handles and toolbar ends a block selection (the selection becomes
none), as in Notion. Shift or Mod held at the press keeps it. So does a press inside an element markeddata-edytor-keep-selection: put it on your own toolbar or sidebar when its buttons act on the selected blocks. A text selection is left as the browser leaves it. - Copying a block selection copies only the selected blocks, a selected list or code block with everything in it.
Selected blocks have the data-edytor-selected attribute, and the editor’s root has data-edytor-selection="blocks" while the selection is a block selection (the browser’s own text highlight is hidden under it). edytor.selection.selectedBlocks is a reactive, read-only Set<Block> of the blocks as clicked: a grip-selected list is one block there. edytor.selection.selectedMembers is what a command over the selection acts on, in document order: the selected blocks, a selected list or code block with its whole subtree (hidden toggle bodies included). Pass it to your own commands, such as edytor.deleteBlocks(edytor.selection.selectedMembers.map((block) => block.id)). focusedBlocks holds the blocks a text selection is in (data-edytor-focused).
Pending marks
With a caret, formatting has nothing to apply to yet. The marks you toggle are staged on the caret as pending marks, and the next text typed there takes them:
edytor.selection.pending; // e.g. { bold: true, color: 'red' }, or undefined
// Stage the complete set of marks the next insertion gets.
edytor.selection.stage({ ...edytor.selection.projection.marks, italic: true });
// Clear them.
edytor.selection.stage(undefined);
- Pending marks are the full set the next insertion takes, values included (links, colors), not a diff.
- Moving the caret clears them; inserting text at the caret consumes them.
stageonly applies to atextvalue.
With the rich text plugin, Mod+B at a caret stages bold this way. richTextOperations(edytor).setMarkAtRange('bold') does the same from code.
Reacting to changes
onSelectionChange (on the component or in a plugin) runs when the value changes. A remote edit that shifts where your selection is shown does not change the value, so it does not fire:
<script lang="ts">
import { Edytor } from 'edytor';
let toolbarVisible = $state(false);
</script>
<Edytor
onSelectionChange={(selection) => {
toolbarVisible = selection.value.kind === 'text' && !selection.projection.isCollapsed;
}}
/>
Each view publishes its selection to the document’s awareness, and other people’s selections render as colored carets and highlights. See Collaboration.