RichContent
Displays HTML or default-slot content using HandyUI themes, locales, typography and image previews. It does not edit content, participate in a form model or expose instance methods.
Import
Install the following dependencies to use @nscode/handy-ui/editor. This entry provides both rich text display and editing. Keep the Tiptap dependencies on the same version.
pnpm add @floating-ui/dom@^1 dompurify@^3.4.18 @tiptap/core@3.34.0 @tiptap/pm@3.34.0 @tiptap/vue-3@3.34.0 @tiptap/starter-kit@3.34.0 @tiptap/extensions@3.34.0 @tiptap/extension-text-style@3.34.0 @tiptap/extension-text-align@3.34.0 @tiptap/extension-table@3.34.0 @tiptap/extension-image@3.34.0 @tiptap/extension-file-handler@3.34.0
Use the same Vue and @nscode/handy-ui instances throughout the application. Load the core theme and this package's stylesheet at the application entry, then import the component where needed:
import '@nscode/handy-ui/style.css'
import { HuiRichContent } from '@nscode/handy-ui/editor'
The core stylesheet includes the theme. This component uses the .hui-prose typography class. These stylesheet paths target package output; source-based hosts must configure the corresponding aliases.
Examples
Basic content
Pass the content through html. Headings, paragraphs, lists, quotations, code and tables use the existing typography theme. Component names and Vue directives inside an HTML string are not compiled as Vue components.
<script setup lang="ts">
import { HuiRichContent } from '@nscode/handy-ui/editor'
const html = [
'<h2>Release notes</h2>',
'<p>Content can include <strong>highlights</strong>, <em>explanations</em> and <code>version</code>.</p>',
'<ul><li>Check the content</li><li>Confirm the result</li></ul>',
'<blockquote>Keep a complete content snapshot before publishing.</blockquote>',
'<pre><code>const total = 3</code></pre>',
'<table><thead><tr><th>Item</th><th>Status</th></tr></thead>',
'<tbody><tr><td>Documentation</td><td>Updated</td></tr></tbody></table>'
].join('')
</script>
<template>
<HuiRichContent :html="html" aria-label="Release notes content" />
</template>
Default slot and empty HTML
When html is omitted, the real default slot is rendered and its Vue events work normally. Providing html="" renders empty HTML rather than falling back to the slot. Set html back to undefined to restore the slot. Default-slot content does not pass through the HTML sanitizer; the application's Vue template owns it.
<script setup lang="ts">
import { computed, ref } from 'vue'
import { HuiButton, HuiSpace } from '@nscode/handy-ui'
import { HuiRichContent } from '@nscode/handy-ui/editor'
const mode = ref<'slot' | 'empty' | 'html'>('slot')
const clicks = ref(0)
const html = computed(() =>
mode.value === 'slot'
? undefined
: mode.value === 'empty'
? ''
: '<p>HTML content is currently selected.</p>'
)
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<HuiButton @click="mode = 'slot'">Use the default slot</HuiButton>
<HuiButton @click="mode = 'empty'">Explicit empty HTML</HuiButton>
<HuiButton @click="mode = 'html'">Use HTML</HuiButton>
</HuiSpace>
<p>Mode: {{ mode }}; slot button clicks: {{ clicks }}</p>
<HuiRichContent :html="html" tag="section" aria-label="HTML and slot precedence">
<p>This is the default slot.</p>
<HuiButton @click="clicks++">Slot button</HuiButton>
</HuiRichContent>
</HuiSpace>
</template>
Three text sizes
small, default and large select a body-text size, rather than a form-control size. The default is default; automatic text-size inheritance from Form or ConfigProvider is not part of this component's contract.
<script setup lang="ts">
import { HuiSpace } from '@nscode/handy-ui'
import { HuiRichContent } from '@nscode/handy-ui/editor'
const sizes = ['small', 'default', 'large'] as const
const html =
'<p>This paragraph contains <strong>highlighted text</strong> and <code>inline code</code>.</p>'
</script>
<template>
<HuiSpace direction="vertical" fill>
<div v-for="size in sizes" :key="size">
<p>size={{ size }}</p>
<HuiRichContent :size="size" :html="html" />
</div>
</HuiSpace>
</template>
Root tag, styles and native attributes
tag selects the actual typography root element. class, style, id, ARIA attributes and native listeners reach that root and can be replaced or removed dynamically. No extra display wrapper is added. Choose a native tag appropriate for the content; this example compares article, section and div.
<script setup lang="ts">
import { computed, ref } from 'vue'
import { HuiButton, HuiSpace } from '@nscode/handy-ui'
import { HuiRichContent } from '@nscode/handy-ui/editor'
const tag = ref('article')
const named = ref(true)
const clicks = ref(0)
const target = ref('Not clicked yet')
const attributes = computed(() =>
named.value
? { 'aria-label': 'Project description', title: 'Click the content to inspect its root' }
: {}
)
const onClick = (event: MouseEvent) => {
clicks.value++
target.value = (event.currentTarget as HTMLElement).tagName.toLowerCase()
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<HuiButton v-for="value in ['article', 'section', 'div']" :key="value" @click="tag = value">
tag={{ value }}
</HuiButton>
<HuiButton @click="named = !named">{{
named ? 'Remove name attributes' : 'Restore name attributes'
}}</HuiButton>
</HuiSpace>
<HuiRichContent
v-bind="attributes"
:tag="tag"
class="rich-content-root-example"
style="padding: var(--hui-spacing-4); border: var(--hui-border-width) solid var(--hui-border-color)"
html="<p>Click <strong>this content</strong>; native events still bubble from the actual child.</p>"
@click="onClick"
/>
<p role="status">Native clicks: {{ clicks }}; currentTarget: {{ target }}</p>
</HuiSpace>
</template>
Default sanitization
sanitize defaults to true and uses DOMPurify. The onclick="return false" attribute and unsafe URL scheme below demonstrate filtering; the example does not execute alerts or make requests. Default rules remove event attributes, unsafe links, scripts, style elements and form controls, and keep only typographic declarations in style attributes, while preserving ordinary typography. Use “Inspect sanitized content” to read the actual DOM.
<script setup lang="ts">
import { nextTick, onMounted, ref } from 'vue'
import { HuiButton, HuiSpace } from '@nscode/handy-ui'
import { HuiRichContent } from '@nscode/handy-ui/editor'
const host = ref<HTMLElement>()
const status = ref('Waiting for client mounting')
const html = [
'<p data-sample="content" onclick="return false">The event attribute is removed; <strong>bold content</strong> remains.</p>',
'<p><a href="javascript:void(0)">Only the text remains for the unsafe URL</a></p>',
'<input value="This form control is removed">'
].join('')
const inspect = async () => {
await nextTick()
const body = host.value?.querySelector('.hui-rich-content')
status.value = body
? 'onclick retained: ' +
body.hasAttribute('onclick') +
'; descendant event attributes: ' +
!!body.querySelector('[onclick]') +
'; link href: ' +
(body.querySelector('a')?.getAttribute('href') ?? 'removed') +
'; input retained: ' +
!!body.querySelector('input')
: 'The content has not mounted yet'
}
onMounted(inspect)
</script>
<template>
<HuiSpace direction="vertical" fill>
<div ref="host"><HuiRichContent :html="html" aria-label="Default sanitizer example" /></div>
<HuiButton @click="inspect">Inspect sanitized content</HuiButton>
<p role="status">{{ status }}</p>
<pre>{{ html }}</pre>
</HuiSpace>
</template>
Disabling sanitization for trusted HTML
sanitize=false uses trusted HTML unchanged. The following example contains only local static content and no executable event attributes; compare whether the native button remains. Disabling sanitization does not establish that content is safe. Do not share this switch with the previous example's untrusted input.
<script setup lang="ts">
import { HuiSpace } from '@nscode/handy-ui'
import { HuiRichContent } from '@nscode/handy-ui/editor'
const html =
'<p>Local static content.</p><button type="button" data-trusted="yes">Local HTML button</button>'
</script>
<template>
<HuiSpace direction="vertical" fill>
<div>
<p>Default filtering: removes the native button</p>
<HuiRichContent :html="html" />
</div>
<div>
<p>sanitize=false: keeps the local static button</p>
<HuiRichContent :html="html" :sanitize="false" />
</div>
</HuiSpace>
</template>
Extending the sanitizer rules
allowTags and allowAttrs add to the default rules rather than replace the entire allowlist. forbidTags adds forbidden tags, and prohibitions take precedence. These options apply only to default sanitization. The example keeps a custom tag and attribute and switches whether strong is retained; its text remains available either way.
<script setup lang="ts">
import { computed, nextTick, onMounted, ref } from 'vue'
import { HuiButton, HuiCheckbox, HuiSpace } from '@nscode/handy-ui'
import { HuiRichContent } from '@nscode/handy-ui/editor'
import type { RichContentSanitizeOptions } from '@nscode/handy-ui/editor'
const blockStrong = ref(true)
const host = ref<HTMLElement>()
const status = ref('Waiting for inspection')
const html =
'<custom-note note-id="42"><strong>Important content</strong>, <em>Additional information</em>.</custom-note>'
const options = computed<RichContentSanitizeOptions>(() => ({
allowTags: ['custom-note'],
allowAttrs: ['note-id'],
forbidTags: blockStrong.value ? ['strong'] : []
}))
const inspect = async () => {
await nextTick()
const note = host.value?.querySelector('custom-note')
status.value =
'custom-note: ' +
!!note +
'; note-id: ' +
(note?.getAttribute('note-id') ?? 'none') +
'; strong: ' +
!!note?.querySelector('strong')
}
onMounted(inspect)
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiCheckbox v-model="blockStrong">Forbid the strong tag</HuiCheckbox>
<div ref="host"><HuiRichContent :html="html" :sanitize-options="options" /></div>
<HuiButton @click="inspect">Inspect the current structure</HuiButton>
<p role="status">{{ status }}</p>
</HuiSpace>
</template>
Style filtering
Default sanitization keeps only typographic declarations in style: color, background color, font size, font family, font weight, font style, line height, letter spacing, alignment, text decoration, text indent, vertical alignment, white space, word breaking, list markers, width and height, borders and padding. Everything the editor writes is covered. Declarations such as position, z-index, transform, margin, display and opacity, which can move content out of the body or cover the page, are removed so that content cannot lay a transparent layer over the whole page to hijack clicks. Values containing url() are always removed. When nothing is left, the whole style attribute is removed. Add properties you really need with allowStyles; entries match by prefix, so ['margin'] also allows margin-top and the other longhands. The example below toggles whether margin is added and reads the filtered styles.
<script setup lang="ts">
import { computed, nextTick, onMounted, ref, watch } from 'vue'
import { HuiButton, HuiCheckbox, HuiSpace } from '@nscode/handy-ui'
import { HuiRichContent } from '@nscode/handy-ui/editor'
import type { RichContentSanitizeOptions } from '@nscode/handy-ui/editor'
const allowMargin = ref(false)
const host = ref<HTMLElement>()
const status = ref('Waiting to read')
const html = [
'<p data-sample="mixed" style="color: #c0392b; text-align: center; margin: 16px 0; position: relative; top: 8px; z-index: 10">Color and alignment are kept; margin depends on the option; position and z-index are removed.</p>',
'<p data-sample="layout" style="position: relative; left: 24px; z-index: 10">Only position and z-index here, so the whole style attribute is removed.</p>'
].join('')
const options = computed<RichContentSanitizeOptions>(() => ({
allowStyles: allowMargin.value ? ['margin'] : []
}))
const inspect = async () => {
await nextTick()
const read = (name: string) =>
host.value?.querySelector(`[data-sample="${name}"]`)?.getAttribute('style') ?? '(no style)'
status.value = 'First paragraph: ' + read('mixed') + '; second paragraph: ' + read('layout')
}
watch(allowMargin, inspect)
onMounted(inspect)
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiCheckbox v-model="allowMargin">Add margin</HuiCheckbox>
<div ref="host"><HuiRichContent :html="html" :sanitize-options="options" /></div>
<HuiButton @click="inspect">Read filtered styles</HuiButton>
<p role="status">{{ status }}</p>
</HuiSpace>
</template>
Synchronous replacement sanitizer and empty output on failure
A sanitize function receives the HTML to filter and completely replaces default sanitization; sanitizeOptions no longer participates. Without legacyFormat, the function receives the original input; with it, the function receives converted HTML. It must return a string synchronously. Throwing or returning another type produces empty content and a development diagnostic. The example constructs a fixed summary from the input length without inserting the source into the output. This summary function is not a general-purpose security sanitizer.
<script setup lang="ts">
import { computed, ref } from 'vue'
import { HuiButton, HuiCheckbox, HuiSpace } from '@nscode/handy-ui'
import { HuiRichContent } from '@nscode/handy-ui/editor'
const html = ref('<h2>Original content</h2><p>Used to construct a summary.</p>')
const fail = ref(false)
const filter = computed(() => (original: string): string => {
if (fail.value) throw new Error('Demonstration of synchronous sanitizer failure')
return (
'<p data-summary="yes">Received the source HTML with ' + original.length + ' characters.</p>'
)
})
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiCheckbox v-model="fail">Throw from the sanitizer; content remains empty</HuiCheckbox>
<HuiButton @click="html += '<p>New paragraph.</p>'">Update the source HTML</HuiButton>
<p>Input length: {{ html.length }}; failure mode: {{ fail }}</p>
<HuiRichContent :html="html" :sanitize="filter" aria-label="Synchronous summary result" />
</HuiSpace>
</template>
Link events, cancellation and native events
The href in linkClick(event, href) is the current link attribute. Call event.preventDefault() to cancel the same browser navigation. A link whose href was removed by default sanitization does not produce a misleading notification. Native click still bubbles from the actual child to the typography root and does not replace the component event. This example uses only a local page anchor, without requesting an external address.
<script setup lang="ts">
import { ref, useId } from 'vue'
import { HuiCheckbox, HuiSpace } from '@nscode/handy-ui'
import { HuiRichContent } from '@nscode/handy-ui/editor'
const destination = useId()
const cancel = ref(true)
const status = ref('No link clicked yet')
const nativeClicks = ref(0)
const html = '<p><a href="#' + destination + '"><strong>Target on this page</strong></a></p>'
const onLinkClick = (event: MouseEvent, href: string) => {
if (cancel.value) event.preventDefault()
status.value = 'href=' + href + '; cancelled=' + event.defaultPrevented
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiCheckbox v-model="cancel">Cancel default anchor navigation</HuiCheckbox>
<HuiRichContent :html="html" @link-click="onLinkClick" @click="nativeClicks++" />
<p role="status">{{ status }}; native click: {{ nativeClicks }}</p>
<p :id="destination" tabindex="-1">This is the target paragraph for this example.</p>
</HuiSpace>
</template>
Image previews, cancellation and dynamic content
All images use local SVG data. The index in imageClick(event, src, index) follows the image nodes currently inside this container, so duplicate URLs still have separate positions. preventDefault() cancels the preview. With previewImage disabled, clicks still notify listeners, but no automatic preview keyboard entry is added. Select “Replace content in three seconds”, then open an image to observe the old preview becoming invalid when the content changes. The timer is cleared on unmount.
<script setup lang="ts">
import { computed, onBeforeUnmount, ref } from 'vue'
import { HuiButton, HuiCheckbox, HuiSpace } from '@nscode/handy-ui'
import { HuiRichContent } from '@nscode/handy-ui/editor'
const picture = (title: string, color: string) =>
'data:image/svg+xml;charset=utf-8,' +
encodeURIComponent(
'<svg xmlns="http://www.w3.org/2000/svg" width="240" height="120">' +
'<rect width="240" height="120" fill="' +
color +
'"/>' +
'<text x="120" y="68" text-anchor="middle" fill="white" font-size="24">' +
title +
'</text></svg>'
)
const first = picture('Diagram one', '#409eff')
const second = picture('Diagram two', '#67c23a')
const version = ref(1)
const preview = ref(true)
const cancel = ref(false)
const status = ref('Click an image, or focus it with Tab and press Enter / Space.')
const updateStatus = ref('No update scheduled')
const html = computed(
() =>
'<p>Content version ' +
version.value +
'</p>' +
'<img src="' +
first +
'" alt="Process diagram one">' +
'<img src="' +
second +
'" alt="Process diagram two">' +
'<img src="' +
first +
'" alt="Repeated occurrence of process diagram one">'
)
let alive = true
let timer: ReturnType<typeof setTimeout> | undefined
const onImageClick = (event: MouseEvent, src: string, index: number) => {
if (cancel.value) event.preventDefault()
status.value =
'index=' +
index +
'; local SVG=' +
src.startsWith('data:image/svg+xml') +
'; cancelled=' +
event.defaultPrevented
}
const schedule = () => {
if (timer !== undefined) clearTimeout(timer)
updateStatus.value = 'Updating in three seconds; you can open a preview now.'
timer = setTimeout(() => {
timer = undefined
if (!alive) return
version.value++
updateStatus.value = 'Content updated; the old preview is no longer valid.'
}, 3000)
}
onBeforeUnmount(() => {
alive = false
if (timer !== undefined) clearTimeout(timer)
})
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<HuiCheckbox v-model="preview">Enable default image previews</HuiCheckbox>
<HuiCheckbox v-model="cancel">Cancel this image preview</HuiCheckbox>
<HuiButton @click="schedule">Replace content in three seconds</HuiButton>
</HuiSpace>
<p role="status">{{ status }}; {{ updateStatus }}</p>
<HuiRichContent :html="html" :preview-image="preview" @image-click="onImageClick" />
</HuiSpace>
</template>
Legacy content and standalone conversion
After client mounting, legacyFormat="quill" converts the old format before applying the default or custom sanitizer. sanitize=false skips sanitization, not conversion. This example constructs alignment, indentation, lists and code blocks locally. Its button displays the result of the public convertQuillHtml() function as text. The utility converts formatting only; it does not filter scripts, event attributes or URLs. Calling it directly without DOMParser throws an environment error in Chinese.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiSpace } from '@nscode/handy-ui'
import { convertQuillHtml, HuiRichContent } from '@nscode/handy-ui/editor'
const html = [
'<p class="ql-align-center ql-size-large">Legacy heading</p>',
'<p class="ql-indent-2">Indented content.</p>',
'<ol><li data-list="bullet">First item</li>',
'<li data-list="bullet" class="ql-indent-1">Nested item</li>',
'<li data-list="ordered">First step</li></ol>',
'<div class="ql-code-block-container"><div class="ql-code-block">const total = 1</div>',
'<div class="ql-code-block">total + 1</div></div>'
].join('')
const converted = ref('Read after clicking; DOMParser is not called on the server.')
const convert = () => {
converted.value = convertQuillHtml(html)
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiRichContent :html="html" legacy-format="quill" aria-label="Legacy content" />
<HuiButton @click="convert">Inspect the format-conversion result</HuiButton>
<pre>{{ converted }}</pre>
</HuiSpace>
</template>
Props
| Property | Type | Default | Description |
|---|---|---|---|
| html | string | undefined | HTML content; omission renders the default slot, while an empty string takes precedence over the slot |
| sanitize | boolean | ((html: string) => string) | true | DOMPurify by default; false is for trusted HTML; a synchronous function completely replaces default filtering |
| sanitizeOptions | RichContentSanitizeOptions | — | Additional tags and attributes, and forbidden tags, for default sanitization |
| previewImage | boolean | true | Enables default image previews; false still retains the imageClick notification |
| size | 'small' | 'default' | 'large' | 'default' | Body-text size |
| tag | string | 'div' | Actual typography root tag |
| legacyFormat | 'quill' | undefined | Converts the legacy format after mounting, then follows sanitize |
RichContentSanitizeOptions
| Field | Type | Description |
|---|---|---|
| allowTags | string[] | Adds allowed tags to the default rules |
| allowAttrs | string[] | Adds allowed attributes to the default rules |
| forbidTags | string[] | Adds forbidden tags; takes precedence over allowed tags |
| allowStyles | string[] | Adds properties to the default style allowlist; entries also match longhands by prefix |
This is not the complete DOMPurify configuration object and does not accept a persistent instance. Default sanitization also retains target and data-indent, and forbids the style/form/input/button/textarea/select tags. The style attribute keeps only typographic declarations, and values containing url() are removed (see Style filtering). Any link (a or area) whose target is not _self, _parent or _top has opener removed and noopener/noreferrer added. This includes named windows such as target="report", so the opened page cannot use window.opener to redirect the original page. These default adjustments do not apply when sanitization is disabled or replaced by a custom function.
Events
| Event | Arguments | Description |
|---|---|---|
| linkClick | (event: MouseEvent, href: string) | Click on the current link; preventDefault cancels default navigation |
| imageClick | (event: MouseEvent, src: string, index: number) | Click on an image in this container; preventDefault cancels the default preview |
Use @link-click and @image-click in templates. The component emits no selected value, change event or preview-close event. Listen for native click, keydown and similar events as native attributes. Clicking an image inside a link handles the image first; default preview takes over the same navigation without also notifying the link listener.
Slots
| Slot | Description |
|---|---|
| default | Actual Vue content when html is omitted; no scope arguments |
Methods
There are no public instance methods. convertQuillHtml(html: string): string is a standalone format-conversion function imported from @nscode/handy-ui/editor, not a component-ref method.
Types
import type {
RichContentProps,
RichContentSanitizeOptions,
RichContentEmits,
RichContentSlots
} from '@nscode/handy-ui/editor'