Extensions

search

Behaviour takes options 1.37 kB gzipped

Find and replace.

Every match is a decoration, so nothing about searching touches the document, and replacing all of them is one transaction and one undo step.

Matches are recomputed per block and cached on the block node: typing in one paragraph rescans that paragraph and reads every other paragraph's matches back, so a search left open while writing costs the paragraph being written, not the document.

editor.commands.setSearch({ query: 'colour', caseSensitive: false })
editor.commands.nextMatch()
editor.commands.replaceMatch('color')
editor.commands.replaceAllMatches('color')
editor.commands.clearSearch()

1 · Install

One package for every extension · there is no @matrajs/search to install.

npm i @matrajs/core

2 · Add it to the editor

Import it and put it in the extensions array. That array is the whole feature list: what is not in it is not in your bundle and not in the document's schema.

import { createEditor, document, paragraph, text, search } from '@matrajs/core'

const editor = createEditor({
  extensions: [document, paragraph, text, search({ … })],
  element: document.querySelector('#editor'),
})

3 · Use it

Run a command, and give focus back · a click on a button takes it away.

editor.commands.setSearch(…)
editor.focus()

Wired to a button:

const button = document.querySelector('#setSearch')

button.addEventListener('click', () => {
  editor.commands.setSearch(…)
  editor.focus()
})

Options

search is a function · call it with an options object.

Option Type What it does
name string Extension name, and the key `editor.extensionState` reads.
matchClass string Class on every match.
currentClass string Class on the current match, in addition to `matchClass`.

Commands

Every one returns true if it changed the document and false if it could not · a command that does not apply where the caret is says so rather than throwing.

Command Call
setSearch editor.commands.setSearch(query: SearchQuery | string)
clearSearch editor.commands.clearSearch()
nextMatch editor.commands.nextMatch()
previousMatch editor.commands.previousMatch()
replaceMatch editor.commands.replaceMatch(replacement: string)
replaceAllMatches editor.commands.replaceAllMatches(replacement: string)

Styling

This one needs CSS to look right, and ships the minimum as a string rather than a file · nothing loads unless you load it, and you can ignore it and write your own.

import { searchCSS } from '@matrajs/core'

const style = document.createElement('style')
style.textContent = searchCSS
document.head.append(style)

← All 83 extensions

Edit this page on GitHub