SvRichText
A lightweight WYSIWYG editor: a formatting toolbar over a contentEditable
region that emits HTML through a bindable value.
SvRichText covers the common editing commands - bold, italic, underline,
strikethrough, headings, lists, quote, code block, alignment, links, and
undo/redo - in a compact toolbar you can reorder or trim. It emits an HTML string
via bind:value and reflects the active formatting state (bold/italic and list
buttons light up with the caret). It uses document.execCommand, the pragmatic
approach for a component-kit editor. All color comes from the --sg-* tokens.
value goes through sanitizeHtml on its way in and out, so a stored string
cannot run a script: event attributes, javascript: links and any style but a
text alignment are removed.
Four more tools can be listed in tools for page and article editing: image
(uploaded through onImageUpload), table, hr and source (the HTML itself).
With name, the editor posts its value with a plain form.
Related: Inputs overview · SvForm · Navigation & rich overview
Installation
Add it with the CLI - this drops a ready-to-edit SvRichText starter into your app:
Prefer to see it first? npx @svgrid/ui try rich-text opens it in a throwaway sandbox - no project needed.
Or install the package and import it directly. SvRichText ships free in
@svgrid/grid (dependency-free):
The examples on this page import from @svgrid/grid:
<script lang="ts">
import { SvButton, SvRichText } from '@svgrid/grid'
</script>
import { SvRichText } from '@svgrid/grid'
Example
<script lang="ts">
import { SvRichText } from '@svgrid/grid'
let html = $state('<p>Hello</p>')
</script>
<SvRichText bind:value={html} placeholder="Write something…" />
Props
| Prop | Type | Default | Description |
|---|---|---|---|
value |
string |
'' |
HTML string (bindable). |
onChange |
(html: string) => void |
- | Fires with the HTML on every edit. |
placeholder |
string |
'' |
Shown when the editor is empty. |
disabled |
boolean |
false |
Dims the editor and blocks all input. |
readonly |
boolean |
false |
Hides the toolbar and makes the body non-editable. |
minHeight |
string |
160px |
Minimum height of the editable body (any CSS length). |
tools |
RichTextTool[] |
full default set | Toolbar tools and their order; use '|' for a separator. |
ariaLabel |
string |
Rich text editor |
Accessible name for the editable region. |
messages |
Partial<RichTextMessages> |
- | Any toolbar label or prompt, for localization. |
onImageUpload |
(file: File) => Promise<string | null> |
- | The image tool's upload: resolve to the URL to insert. Without it, the tool asks for a URL. |
sanitize |
(html: string) => string |
sanitizeHtml |
Replaces the sanitizer both ways, for content the app trusts. |
name |
string |
- | Posts the value with a native form, as a hidden input. |
RichTextTool (exported) is one of:
'bold' | 'italic' | 'underline' | 'strike' | 'h1' | 'h2' | 'h3' | 'p' | 'ul' | 'ol' | 'quote' | 'code' | 'alignLeft' | 'alignCenter' | 'alignRight' | 'link' | 'clear' | 'undo' | 'redo' | 'image' | 'table' | 'hr' | 'source' | '|'.
The '|' entry draws a visual separator between tool groups. The default
toolbar is every tool up to redo; image, table, hr and source appear
only when listed.
Examples
A trimmed toolbar
Pass just the tools you need; group them with '|' separators:
<SvRichText
bind:value={note}
tools={['bold', 'italic', '|', 'ul', 'ol', '|', 'link']}
/>
Pages and articles: images, tables, the HTML
For a CMS page or a blog post, list the extra tools, upload images to your
server and post the editor with the rest of the form. sanitize is replaced
only because the administrators who write these pages are trusted to use
inline styles; keep the default for anything a visitor can write.
<script lang="ts">
import { SvRichText } from '@svgrid/grid'
async function upload(file: File) {
const body = new FormData()
body.append('image', file)
const answer = await (await fetch('/api/upload', { method: 'POST', body })).json()
return answer.url ?? null
}
</script>
<form method="post">
<SvRichText
name="content"
value={page.content}
tools={['bold', 'italic', 'h2', 'h3', '|', 'ul', 'ol', '|', 'link', 'image', 'table', 'hr', '|', 'source', 'undo', 'redo']}
onImageUpload={upload}
sanitize={(html) => html.replace(/<script[\s\S]*?<\/script>/gi, '')}
/>
<button>Save</button>
</form>
source swaps the body for a text area with the HTML; the other tools wait
until it is switched off, and what was typed there goes through sanitize.
Read-only rendering
Set readonly to show formatted content without a toolbar - useful for previews
of the same HTML the editor produced:
<SvRichText value={savedHtml} readonly />
Reacting to edits
Persist on change instead of only on blur:
<SvRichText bind:value={html} onChange={(h) => queueSave(h)} />
A field bound to a record, with preview
Bind value straight to a field on your state object so edits flow back into the
model. Track a dirty flag from onChange to gate the Save button, then flip to
readonly to preview the exact HTML the editor produced:
<script lang="ts">
import { SvRichText, SvButton } from '@svgrid/grid'
let ticket = $state({ id: 42, notes: '<p>Initial triage notes.</p>' })
let editing = $state(true)
let dirty = $state(false)
function save() {
fetch(`/api/tickets/${ticket.id}`, {
method: 'PATCH',
body: JSON.stringify({ notes: ticket.notes }),
})
dirty = false
editing = false
}
</script>
{#if editing}
<SvRichText
bind:value={ticket.notes}
tools={['bold', 'italic', '|', 'ul', 'ol', '|', 'link', 'clear']}
minHeight="200px"
placeholder="Add triage notes..."
onChange={() => (dirty = true)}
/>
<SvButton variant="primary" disabled={!dirty} onclick={save}>Save</SvButton>
{:else}
<SvRichText value={ticket.notes} readonly />
<SvButton onclick={() => (editing = true)}>Edit</SvButton>
{/if}
Tip: an external change to value is written into the editor only while it is
not focused - writing innerHTML mid-caret would collapse the selection - so a
value set from elsewhere applies once the field blurs. readonly mode drops the
toolbar and renders the same HTML, making it a zero-cost preview of what you saved.
Accessibility
- The editable region is a
role="textbox"witharia-multilineand anaria-label. - The toolbar is a
role="toolbar"wired to the body viaaria-controls. - Toggle tools (bold, italic, lists) expose
aria-pressedreflecting the current caret state; every button has a descriptive label.
Disabled and read-only
Disabled takes the control out of the tab order; read-only keeps it focusable and copyable. Reach for read-only when the value still matters to the reader.
<script lang="ts">
import { SvRichText } from '@svgrid/grid'
let html = $state('')
</script>
<SvRichText bind:value={html} disabled />
<SvRichText bind:value={html} readonly />
See also
- Navigation overview - the wayfinding family at a glance.
- Inputs overview - the text and value editors.
- SvForm - collect rich text alongside other fields.