Rich Text
The RichText field renders a WYSIWYG editor with a configurable toolbar. It submits an HTML string, or null when the editor is empty. The PHP field adds a string rule automatically, so add nullable() to optional editors.
Basic Usage
use InertiaUI\Forms\Fields\RichText;
RichText::make('body')->nullable();This renders an editor with the default toolbar: bold, italic, underline, strike, an H2 heading, lists, links, blockquotes, inline code, undo, and redo.
Toolbar Presets
The toolbar may use one of two presets, or a configuration of your own.
Simple
The simple preset is a minimal toolbar with bold, italic, and link:
RichText::make('bio')->simple();Full
The full preset adds the larger editor controls, including image embeds, task lists, and text alignment:
RichText::make('content')->full();Custom
To build your own toolbar, pass a configuration string to the toolbar method:
RichText::make('notes')
->toolbar('bold italic | bullet ordered ~ link undo redo');You may also pass an array, where each nested array becomes a visual button group:
RichText::make('notes')->toolbar([
['bold', 'italic'],
['bulletList', 'orderedList'],
['link'],
]);A flat array works too:
RichText::make('notes')->toolbar([
'bold', 'italic', '|', 'bulletList', 'orderedList', '|', 'link',
]);Use | as a visual separator between button groups and ~ as a flexible spacer. The string grammar also accepts these aliases: bullet for bulletList, ordered for orderedList, quote for blockquote, hr for horizontalRule, and h1, h2, or h3 for heading.
To get the canonical flat toolbar array without building a field instance, call RichText::normalizeToolbar(), which applies the same normalization.
The h1, h2, and h3 aliases all normalize to the single heading toolbar control. That control toggles an H2 heading. It isn't a heading level picker.
Available Toolbar Items
| Item | Description |
|---|---|
bold | Bold text |
italic | Italic text |
underline | Underlined text |
strike | Strikethrough text |
heading | Toggle an H2 heading |
highlight | Highlighted text |
subscript | Subscript text |
superscript | Superscript text |
bulletList | Unordered list |
orderedList | Numbered list |
taskList | Checkbox list |
link | Hyperlink |
image | Image embed |
blockquote | Block quote |
code | Inline code |
codeBlock | Code block |
horizontalRule | Horizontal divider |
alignLeft | Left alignment |
alignCenter | Center alignment |
alignRight | Right alignment |
undo | Undo |
redo | Redo |
Link Options
The link toolbar item opens a native modal dialog for inserting, editing, and removing links. You may configure the generated link policy from PHP:
RichText::make('body')
->simple()
->linkTargetBlank()
->linkNoopener()
->linkNoreferrer()
->linkAllowedProtocols(['https', 'mailto'])
->linkDefaultProtocol('https');By default, links open in the same tab, and noopener is enabled for links that open in a new tab. The noreferrer option is disabled, while auto-linking and link-on-paste are enabled. The default protocol is http, and the allowed protocols are http, https, mailto, and tel.
To stop converting typed URLs, use autoLink(false). To stop converting a pasted URL, use linkOnPaste(false). These switches don't disable the link dialog.
The linkAllowedProtocols method normalizes and deduplicates protocol names. Removing the current default protocol makes the first allowed protocol the new default. The linkDefaultProtocol method must select a protocol that is already allowed.
By default, authors may toggle "Open in new tab" for each link. To let the field configuration alone decide whether links open in a new tab, use allowLinkTargetOverride(false):
RichText::make('body')
->linkTargetBlank()
->allowLinkTargetOverride(false);The linkRel method adds rel tokens such as nofollow, sponsored, or ugc:
RichText::make('body')
->linkRel(['nofollow', 'ugc']);Protocol options are validated when the form is built. Unsafe or malformed protocols such as javascript: and data: are rejected, and the editor also rejects links whose protocol isn't allowed. This policy applies to links the editor creates or normalizes. It doesn't replace server-side HTML sanitization for untrusted HTML.
Height
You may set a minimum height, a maximum height, or both for the editor area, in pixels:
RichText::make('content')
->minHeight(200)
->maxHeight(600);Image Embeds
By default, the image toolbar item accepts image URLs. To let authors also pick an image file from their device, add imageUploads():
use InertiaUI\Forms\Fields\RichText;
use InertiaUI\Forms\FileUploads\UploadConfig;
RichText::make('body')
->full()
->imageUploads(fn (UploadConfig $uploads) => $uploads
->maxSize(2048)
->maxDimensions(width: 2400, height: 1600));Upload sizes are in kilobytes, and image dimensions are in pixels.
RichText image uploads use the same temporary upload pipeline as the File field. Custom routes, chunking, and direct-to-storage uploads are covered in Choosing an Upload Path. Upload validators and token validation are covered in Validation.
Image helpers such as accept(), maxSize(), minSize(), dimensions(), minDimensions(), and maxDimensions() run during the upload request. The configuration always includes Laravel's image rule. The accept method may narrow the allowed image MIME types, but it doesn't turn this into a general file upload.
The generated companion field is <name>_images, such as body_images. To get that name in application code, call getImageUploadFieldName() on the field or RichTextUploads::imageUploadFieldName(field: 'body'). Both return body_images for the body field.
RichText images don't support storeWithForm(). RichText still submits an HTML string for the field itself. Uploaded images are tracked in a companion token list, so your controller may resolve the temporary uploads and rewrite the HTML before storing it.
Image Resizing
Authors may resize images in the editor with corner handles, whether the image was inserted by URL or uploaded through imageUploads(). The editor stores the resized display size as numeric width and height attributes on the <img> tag, so the submitted value stays regular HTML. RichTextUploads and RichTextContent preserve those attributes when they rewrite temporary upload markers or stored image references.
Storage and rendering callbacks receive the existing image attributes through the RichTextImage builder. To normalize or override the author's display size while storing or rendering an image, use RichTextImage::width(), height(), or dimensions():
// $image is the RichTextImage passed to your storage or rendering callback...
$image->dimensions(width: 720, height: 480);These fluent setters write the rendered <img width height> attributes. They aren't getters, and they don't describe the source image's intrinsic pixel dimensions. To validate the actual uploaded file, use upload validation helpers such as UploadConfig::dimensions() and maxDimensions().
Leave the dimensions unchanged to preserve the size chosen in the editor.
Storing Uploaded Images
Use the validated Form in your controller or form request handler. For public files with stable URLs, store each image on a Laravel filesystem disk and write that URL into the HTML:
use Illuminate\Support\Facades\Storage;
use InertiaUI\Forms\FileUploads\SubmittedUpload;
use InertiaUI\Forms\RichText\RichTextImage;
use RuntimeException;
// $form is the validated form instance...
$storedHtml = $form->richText('body')
->storeImagesUsing(function (SubmittedUpload $upload, RichTextImage $image): RichTextImage {
$path = $upload->store(
path: 'content-images',
options: ['disk' => 'public'],
deleteTemporary: false,
);
if ($path === false) {
throw new RuntimeException('The image could not be stored.');
}
return $image->src(Storage::disk('public')->url($path));
})
->toHtml();SubmittedUpload::store() mirrors Laravel's uploaded file API. It returns the stored path, or false when storage fails. The path argument is the directory on the target disk, while options['disk'] selects Laravel's public filesystem disk.
Setting deleteTemporary: false keeps the staged source available until RichTextUploads has stored every image and rewritten the HTML. The helper then deletes it.
Storage::disk('public')->url($path) turns the stored path into its public URL. Laravel's local public disk also needs the usual php artisan storage:link setup before browsers may reach that URL. Direct-to-storage uploads must stay on their source disk, so use that configured disk instead of public in this workflow.
The richText accessor applies the matching field's imageUploads() policy and verifies the HTML markers against the companion tokens.
RichTextImage may set src(), alt(), title(), width(), height(), or both dimensions together. The attribute and attributes methods set other valid image attributes, and passing null or false removes one. The callback may mutate the supplied builder or return another RichTextImage. Returning null keeps the supplied builder.
Image Upload Validation
Before storage, the Form accessor validates each image against the matching field's MIME type, size, and dimension policy. It rejects fields that are unavailable or don't enable image uploads.
Processing images directly, outside a Form, requires an explicit policy:
use InertiaUI\Forms\FileUploads\UploadConfig;
use InertiaUI\Forms\RichText\RichTextUploads;
// $request is the submitted request and $post is a saved Post model...
$storedHtml = RichTextUploads::from(
request: $request,
field: 'body',
)
->validateUsing(UploadConfig::images()
->maxSize(2048)
->maxDimensions(width: 2400, height: 1600))
->storeImagesInMediaLibrary(
model: $post,
collection: 'content-images',
)
->toHtml();The request argument is the submitted request, and field is the RichText field name. To apply a RichText field's policy outside a Form, you may also use forField($field). RichTextUploads::from() doesn't discover a policy from the current request.
Invalid MIME types, sizes, and dimensions throw a ValidationException before storage.
The withoutImageValidation method accepts any file behind a valid upload token. Only use it when your own pipeline validates the files.
Spatie Media Library
To let Form::save() store the uploaded images and persist the rewritten HTML, declare the Media Library destination on the field:
RichText::make('body')
->imageUploads(fn (UploadConfig $uploads) => $uploads
->maxSize(2048)
->maxDimensions(width: 2400, height: 1600))
->storeImagesInMediaLibrary(
collection: 'content-images',
deleteUnused: true,
);Then save the form in your controller:
namespace App\Http\Controllers;
use App\Forms\PostForm;
use App\Models\Post;
use InertiaUI\Forms\Validate;
class PostController extends Controller
{
public function update(#[Validate] PostForm $form, Post $post)
{
$form->save($post);
return back();
}
}The model must implement Spatie Media Library's HasMedia contract. The storage declaration stays on the server and isn't serialized to the frontend. The collection argument is required, because cleanup works on the complete collection. Prefer a dedicated named collection. You may explicitly choose collection: 'default', but deleteUnused: true is only safe when that collection belongs exclusively to this field.
The storeImagesInMediaLibrary call must follow imageUploads(). To override the collection's configured disk with another Laravel filesystem disk, pass a disk argument such as disk: 's3'.
Form::save() holds the submitted RichText value out of mass assignment, stores its images, saves the rewritten HTML, and only then removes unused media. Raw upload markers are never written to the model.
RichText fields declared directly inside a Repeater or Blocks schema use the same workflow. Every submitted instance of one schema field contributes its stored image references before deleteUnused cleanup runs once for the collection, so one row can't delete images another row still references. The parent model attribute needs an array or JSON-compatible cast. Binding resolves the nested stored HTML for the editor without a RichText cast on each nested value.
A new model is saved once to create the Media Library owner, and again once the deferred RichText values are ready:
// $form is the validated PostForm...
$post = $form->save(new Post);The created event runs during the first save, before the RichText attribute contains its final stored HTML. See Saving Models for the full Eloquent lifecycle and the initial column value requirement.
Manual Processing
For a custom controller workflow, you may call the richText helper directly:
// $form is the validated form instance and $post is a saved Post model...
$storedHtml = $form->richText('body')
->storeImagesInMediaLibrary(
model: $post,
collection: 'content-images',
)
->toHtml();
$post->update(['body' => $storedHtml]);The helper stores every image in the given collection, replaces its temporary src with the Media Library URL, and records a signed image reference for later rendering.
The model must already be saved, so a create workflow should persist the model before moving its RichText images:
use Illuminate\Support\Arr;
$post = Post::create(
Arr::except($form->validated(files: false), 'body'),
);
$post->body = $form->richText('body')
->storeImagesInMediaLibrary(
model: $post,
collection: 'content-images',
)
->toHtml();
$post->save();The validated(files: false) call leaves file-backed values out of mass assignment. Arr::except(..., 'body') also holds back the RichText HTML until its uploaded images have been stored and rewritten.
Loading Stored Images Into The Editor
Stored Media Library images include a signed reference that lets RichText identify their Media records on later submissions. To make a bound RichText field preserve those references automatically, cast the model attribute to RichTextContent:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use InertiaUI\Forms\RichText\RichTextContent;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;
class Post extends Model implements HasMedia
{
use InteractsWithMedia;
protected function casts(): array
{
return [
'body' => RichTextContent::class,
];
}
}The form may then bind the model directly:
namespace App\Forms;
use App\Models\Post;
use InertiaUI\Forms\Form;
class PostForm extends Form
{
// ...
public function forPost(Post $post): static
{
return $this->bind($post);
}
}Eloquent applies the cast while the form reads body. The RichText field then loads the current Media Library URLs and available srcset, and keeps the signed references the editor needs. Other field types aren't converted.
To hydrate the editor manually without a bound cast, use toEditorHtml(). It's equivalent to calling preserveStoredImageReferences() before toHtml(), with a name that states the intent:
// Inside a method of your form class, where $post is a Post model...
return $this->bind([
'body' => RichTextContent::fromModel($post, 'body')->toEditorHtml(),
]);Loading public HTML into the editor loses the Media Library identity. A later submission then treats each image as an ordinary URL image, and with deleteUnused: true, its Media record may be removed as unused.
Rendering Saved Content
The two toHtml() methods sit on different sides of the save operation:
$form->richText('body')returnsRichTextUploads. ItstoHtml()method verifies and stores submitted images, removes temporary upload tokens, and returns HTML for database storage. A signed stored image reference may remain, so later edits can identify the image.$post->bodyreturnsRichTextContentwhen the attribute uses the cast shown above. ItstoHtml()method removes those stored references and returns HTML for public display.
With image uploads enabled, never save the raw submitted body. Pass it through RichTextUploads, so temporary upload tokens are verified and removed.
Store the $storedHtml the upload processor returns, and render only the cast value:
// $post is a Post model with the RichTextContent cast...
$publicHtml = $post->body?->toHtml();The cast uses the same public representation when the model is converted to an array or JSON.
Never render storage or editor HTML
Don't send raw submitted HTML, $storedHtml, toStoredHtml(), toEditorHtml(), or preserveStoredImageReferences()->toHtml() to a user-facing page. Those values may intentionally contain package-owned image references. Use RichTextContent::toHtml() for public output.
Removing the package-owned image attributes doesn't sanitize arbitrary HTML or authorize private image URLs. Sanitize untrusted HTML separately, and authorize the model and viewer before generating private media URLs.
Removing Unused Media
By default, images removed from the editor stay in the collection. To keep an exclusively owned collection in sync with the stored HTML, pass deleteUnused: true:
RichText::make('body')
->imageUploads()
->storeImagesInMediaLibrary(
collection: 'content-images',
deleteUnused: true,
);With Form::save(), cleanup only runs after every new image is stored and the rewritten model attribute is saved. An explicitly submitted empty or null body clears the collection. An absent field leaves both the attribute and its collection untouched. Only valid signed references for the same collection retain media.
Manual processing may enable the same behavior on the upload helper:
// $form is the validated form instance and $post is a saved Post model...
$post->body = $form->richText('body')
->storeImagesInMediaLibrary(
model: $post,
collection: 'content-images',
deleteUnused: true,
)
->toHtml();
$post->save();The helper preserves each original filename. A successful rewrite deletes the staged upload. A failed rewrite removes the newly created Media records and keeps the staged upload available for a retry. The scheduled upload cleanup command remains the safety net for abandoned files.
Model and media writes are not atomic
Form::save() doesn't open a database transaction around Media Library and filesystem changes. A failed model write removes the media created while preparing the RichText value, and keeps its staged uploads for a retry. Unused media cleanup runs after the rewritten attribute is saved, because a database rollback can't restore deleted files.
A cleanup failure may therefore leave the model update and newly referenced media in place while the old unused media cleanup is incomplete. The exception isn't swallowed. A failure after the first save of a new model may leave that model row in place with its ordinary attributes. Multiple media fields are also processed in order, so a later failure doesn't undo an earlier successful field. Use dedicated collections, handle the exception at the application boundary, and rely on the scheduled upload cleanup command for abandoned staging files.
Custom Storage and Deferred URLs
To support a stored URL that may change or must be generated for the current viewer, add a durable identifier. The keepTokenized method requires every newly stored image to receive one:
use Illuminate\Support\Facades\Storage;
use InertiaUI\Forms\FileUploads\SubmittedUpload;
use InertiaUI\Forms\RichText\RichTextImage;
use RuntimeException;
// $form is the validated form instance...
$storedHtml = $form->richText('body')
->keepTokenized()
->storeImagesUsing(function (
SubmittedUpload $upload,
RichTextImage $image,
): RichTextImage {
$path = $upload->store(
path: 'content-images',
options: ['disk' => 'public'],
deleteTemporary: false,
);
if ($path === false) {
throw new RuntimeException('The image could not be stored.');
}
return $image
->src(Storage::disk('public')->url($path))
->identifier($path);
})
->toHtml();The identifier method writes an application-owned identifier and optional metadata in a signed stored reference. Existing references only survive later submissions when their signatures are valid.
Rendering Stored Images
Stored image references let your application refresh image URLs without rewriting the saved RichText HTML. Media Library models use fromModel(), while applications with another storage layer may resolve identifiers themselves.
Media Library Images
A model implementing Spatie Media Library's HasMedia contract may render a RichText attribute directly with the fromModel method:
use InertiaUI\Forms\RichText\RichTextContent;
// $post is a Post model that implements HasMedia...
$publicHtml = RichTextContent::fromModel(
model: $post,
attribute: 'body',
)->toHtml();The helper reads the attribute, resolves its stored images from the media attached to that model, and checks the collection recorded in each reference. It then writes the public Media Library URL and the available srcset. Normal rendering removes the internal stored image references from the returned HTML.
The fromMediaLibrary method writes the full URL and the available srcset, then records the Media Library identifier. Existing editor dimensions are preserved, and images without editor dimensions receive the intrinsic size of the largest responsive variant. The Media name only becomes alt text when the original image has no alt attribute. Editor-bound HTML must keep that identifier, as described in Loading Stored Images Into The Editor.
Customizing Model Images
The withImages method customizes the images a cast attribute resolves. The callback receives the stored reference, a RichTextImage builder already populated from Media Library, and the resolved Media model:
use InertiaUI\Forms\RichText\RichTextImage;
use InertiaUI\Forms\RichText\RichTextStoredImage;
use Spatie\MediaLibrary\MediaCollections\Models\Media;
// $post is a Post model with the RichTextContent cast...
$publicHtml = $post->body?->withImages(function (
RichTextStoredImage $stored,
RichTextImage $image,
Media $media,
): void {
$image
->fromMediaLibrary($media, conversion: 'web')
->attribute('sizes', '(min-width: 768px) 720px, 100vw')
->attribute('loading', 'lazy');
})->toHtml();Mutating the supplied builder is enough, so the callback doesn't need to return it. Returning another RichTextImage or Media instance replaces the supplied builder.
In this example, web is an application-defined Media Library conversion. The sizes value uses a 720-pixel slot from 768 pixels upward, and the viewport width below that breakpoint. The loading attribute enables native lazy loading.
Automatic cast hydration uses Media Library's default URLs. To apply custom image resolution while loading an editor, bind an array and finish the customized content with toEditorHtml():
// Inside a method of your form class, where $post is a Post model...
return $this->bind([
'body' => $post->body?->withImages(function (
RichTextStoredImage $stored,
RichTextImage $image,
Media $media,
): void {
$image->fromMediaLibrary($media, conversion: 'web');
})->toEditorHtml(),
]);Before binding or rendering a collection of models, eager-load their media relation to avoid one Media Library query per model.
Private Media
The fromModel method initially fills the image with Media Library's durable URL and responsive sources. Private media needs a fresh authorized URL each time the content is rendered:
// $post is a Post model that implements HasMedia...
$publicHtml = RichTextContent::fromModel(
model: $post,
attribute: 'body',
)
->requireSignedImages()
->withImages(function (
RichTextStoredImage $stored,
RichTextImage $image,
Media $media,
): void {
$image
->src($media->getTemporaryUrl(now()->addMinutes(5)))
->attribute('srcset', null);
})
->toHtml();Authorize the model for the current tenant and viewer before rendering it. You may also enforce a per-image policy inside the callback. Removing srcset keeps public responsive URLs from remaining beside the private src.
The signed reference contains the application identifier and optional metadata, not the temporary upload token. now()->addMinutes(5) makes each generated URL expire five minutes after rendering.
Custom Image Resolution
The replaceImagesUsing method serves lower-level workflows that resolve their own stored identifiers instead of loading images from a Media Library model. This example matches the filesystem identifier stored in the Custom Storage and Deferred URLs example:
use Illuminate\Support\Facades\Storage;
// $post is a Post model with the RichTextContent cast...
$publicHtml = RichTextContent::from($post->body?->toStoredHtml())
->requireSignedImages()
->replaceImagesUsing(function (
RichTextStoredImage $stored,
RichTextImage $image,
): void {
$image->src(
Storage::disk('public')->url($stored->identifier()),
);
})
->toHtml();The RichTextStoredImage passed to the callback exposes identifier(), all metadata(), a nested meta($key, $default) lookup, and the original image attributes(). The RichTextImage builder is mutable, so the callback doesn't need to return it. Returning a different RichTextImage replaces the builder, while returning null without changing it preserves the original attributes.
By default, rendered HTML has its data-inertia-forms-image attributes removed, including unresolved and malformed references, while ordinary image attributes remain. Replacement callbacks may preserve a reference, remove it with attribute(RichTextImage::STORED_ATTRIBUTE, null), or replace it with identifier().
RichTextContent::toHtml() returns null when its input was null. It assumes RichTextUploads already removed the temporary upload markers, and it doesn't replace processing submitted uploads.
Stored Image Reference Versions
The package owns the data-inertia-forms-* attribute namespace. RichTextUploads removes client-submitted package attributes before storage callbacks run.
RichTextImage::identifier() writes a signed version 2 reference using Laravel's app.key configuration value, which is usually set by APP_KEY. Verification also checks app.previous_keys, so key rotation keeps existing content readable. The keepTokenized method only preserves verified existing references and references the storage callback issued.
Stored image references are signed, not encrypted. Anyone may decode their identifiers and metadata, so they must never contain secrets. Public rendering removes the references from the returned HTML.
A signature proves that the package issued a reference, not that the current user owns its image, so keep authorizing identifiers in the render callback.
To require a valid signature while rendering, call the requireSignedImages method:
use Illuminate\Support\Facades\Storage;
// $post is a Post model with the RichTextContent cast...
$publicHtml = RichTextContent::from($post->body?->toStoredHtml())
->requireSignedImages()
->replaceImagesUsing(
fn (RichTextStoredImage $stored, RichTextImage $image): RichTextImage => $image->src(
Storage::disk('public')->url($stored->identifier()),
),
)
->toHtml();Versions before 1.4 wrote unsigned version 1 references. These remain readable from existing stored HTML as read-only legacy data, and RichTextUploads never trusts an unsigned version 1 reference the browser submits. Signed version 1 references remain valid, and all newly issued references use signed version 2.
Removing package-owned attributes doesn't sanitize the remaining HTML, and neither does image upload validation. Keep sanitizing untrusted HTML before storing or rendering it. A sanitizer that runs before processing should allow src, alt, title, width, height, and data-inertia-forms-upload. Tokenized content also needs data-inertia-forms-image until RichTextContent renders it.
Word and Character Count
Word Count
RichText::make('content')->showWordCount();Character Count
RichText::make('content')->showCharacterCount();Max Length
The maxLength method sets a character limit for the editor text:
RichText::make('content')
->maxLength(5000)
->showCharacterCount();The maxLength method configures Tiptap's visible text limit, and showCharacterCount() displays the current count.
The maxLength method doesn't add a Laravel validation rule, because Laravel's string rules measure the submitted HTML markup, not only its visible text. Add server-side rules for the submitted value:
RichText::make('content')
->maxLength(5000)
->showCharacterCount()
->rules(['nullable', 'string']);To enforce a visible text limit, use a custom rule or a FormRequest hook:
// $request is the current Illuminate\Http\Request...
$request->validate([
'content' => ['nullable', 'string'],
]);
$html = $request->string('content')->toString();
// Sanitize the HTML with your application's approved sanitizer before storing.
// Count text extracted from sanitized HTML when enforcing a visible-text limit.Article Editor
This example combines the options above. The placeholder method sets the prompt of the empty editor:
RichText::make('body')
->label('Article Body')
->placeholder('Start writing...')
->full()
->linkAllowedProtocols(['https', 'mailto'])
->linkDefaultProtocol('https')
->linkTargetBlank()
->linkNoopener()
->minHeight(300)
->maxHeight(800)
->showWordCount()
->showCharacterCount()
->maxLength(10000)
->required();Shared Field APIs
RichText fields also use Form Class for labels and help text, Model Binding for defaults and bound values, and Validation for rules and precognition. They support Conditional Visibility and Authorization, and use Styling for classes, layout, and part classes. Image uploads use the transport setup described in Choosing an Upload Path.
Using the Component Directly
You may render RichText from each stack's richtext subpath with local HTML state, or pass serialized field props during manual form rendering.
<script setup lang="ts">
import { ref } from 'vue'
import {
RichText,
type RichTextLinkOptions,
type RichTextToolbar,
} from '@inertiaui/form-vue/richtext'
const body = ref<string | null>('<p>Draft body</p>')
const locked = ref(false)
const hasError = ref(false)
const toolbar: RichTextToolbar = [
'bold',
'italic',
'|',
'bulletList',
'orderedList',
'|',
'link',
'image',
'|',
'undo',
'redo',
]
const linkOptions: RichTextLinkOptions = {
targetBlank: true,
noopener: true,
noreferrer: true,
rel: ['nofollow'],
allowedProtocols: ['https', 'mailto'],
defaultProtocol: 'https',
autoLink: true,
linkOnPaste: true,
allowTargetOverride: false,
}
const editorParts = {
toolbar: 'border-b border-zinc-200',
toolbarButton: 'data-[active=true]:text-blue-600',
editor: 'min-h-48',
footer: 'text-xs',
dialog: 'max-w-lg',
}
</script>
<template>
<RichText
v-model="body"
id="article-body"
name="body"
label="Article body"
help="Draft the public article body."
placeholder="Start writing..."
:toolbar="toolbar"
:min-height="300"
:max-height="800"
show-word-count
show-character-count
:max-length="10000"
:link-options="linkOptions"
required
precognitive
:disabled="locked"
:invalid="hasError"
:error="hasError ? 'Article body is required.' : null"
badge="Draft"
badge-class="bg-zinc-100 text-zinc-700"
label-trailing="Required"
label-trailing-class="text-zinc-500"
tooltip="Shown on the article page."
help-position="below"
layout="stacked"
control-position="end"
label-class="font-medium"
help-class="text-zinc-500"
error-class="text-red-600"
wrapper-class="max-w-3xl"
control-class="bg-white"
class="font-medium"
:part-classes="editorParts"
/>
</template>import { useState } from 'react'
import {
RichText,
type RichTextLinkOptions,
type RichTextToolbar,
} from '@inertiaui/form-react/richtext'
const toolbar: RichTextToolbar = [
'bold',
'italic',
'|',
'bulletList',
'orderedList',
'|',
'link',
'image',
'|',
'undo',
'redo',
]
const linkOptions: RichTextLinkOptions = {
targetBlank: true,
noopener: true,
noreferrer: true,
rel: ['nofollow'],
allowedProtocols: ['https', 'mailto'],
defaultProtocol: 'https',
autoLink: true,
linkOnPaste: true,
allowTargetOverride: false,
}
const editorParts = {
toolbar: 'border-b border-zinc-200',
toolbarButton: 'data-[active=true]:text-blue-600',
editor: 'min-h-48',
footer: 'text-xs',
dialog: 'max-w-lg',
}
export default function ArticleEditor() {
const [body, setBody] = useState<string | null>('<p>Draft body</p>')
const [locked] = useState(false)
const [hasError] = useState(false)
return (
<RichText
value={body}
onValueChange={setBody}
id="article-body"
name="body"
label="Article body"
help="Draft the public article body."
placeholder="Start writing..."
toolbar={toolbar}
minHeight={300}
maxHeight={800}
showWordCount
showCharacterCount
maxLength={10000}
linkOptions={linkOptions}
required
precognitive
disabled={locked}
invalid={hasError}
error={hasError ? 'Article body is required.' : null}
badge="Draft"
badgeClass="bg-zinc-100 text-zinc-700"
labelTrailing="Required"
labelTrailingClass="text-zinc-500"
tooltip="Shown on the article page."
helpPosition="below"
layout="stacked"
controlPosition="end"
labelClass="font-medium"
helpClass="text-zinc-500"
errorClass="text-red-600"
wrapperClass="max-w-3xl"
controlClass="bg-white"
class="font-medium"
partClasses={editorParts}
/>
)
}RichText is a composite editor, so it doesn't forward arbitrary native attributes to an inner native element. See Native Attributes And Events. The runtime configuration of image uploads uses the props described in Serialized Upload Configuration.
Editor Support Components
The richtext subpath also exports EditorShell, EditorToolbar, and EditorCountFooter with their prop types. These low-level presenters let custom RichText integrations reuse the package shell, toolbar semantics, count footer, native attributes, and styling hooks without pulling Tiptap into the root or components entry points.
This custom editor surface reuses the package shell and count footer:
<script setup lang="ts">
import {
EditorCountFooter,
EditorShell,
type EditorCountFooterState,
} from '@inertiaui/form-vue/richtext'
const footer: EditorCountFooterState = {
show: true,
wordLabel: '12 words',
characterLabel: '74 characters',
characterLimitLabel: '500',
}
</script>
<template>
<EditorShell name="summary">
<div
class="min-h-40 p-3"
contenteditable
role="textbox"
aria-label="Summary"
></div>
<template #footer>
<EditorCountFooter :footer="footer" />
</template>
</EditorShell>
</template>import {
EditorCountFooter,
EditorShell,
type EditorCountFooterState,
} from '@inertiaui/form-react/richtext'
const footer: EditorCountFooterState = {
show: true,
wordLabel: '12 words',
characterLabel: '74 characters',
characterLimitLabel: '500',
}
export default function SummaryEditor() {
return (
<EditorShell name="summary">
<div
className="min-h-40 p-3"
contentEditable
suppressContentEditableWarning
role="textbox"
aria-label="Summary"
/>
<EditorCountFooter footer={footer} />
</EditorShell>
)
}| Component | Public options |
|---|---|
EditorShell | name writes data-editor-name; focused, invalid, and disabled select semantic states; classValue and controlClass extend shell classes. Vue provides toolbar, default, and footer slots. React renders children. Both forward native wrapper attributes. |
EditorToolbar | items is the normalized control/separator/spacer order; buttons supplies each control's label, state, and action; disabled disables every control; dataAttributePrefix changes generated test/data attribute names; classValue and buttonClass extend toolbar styling. React additionally receives an icons map; Vue toolbar buttons carry their icon components. Native wrapper attributes are forwarded. |
EditorCountFooter | footer.show controls rendering; wordLabel, characterLabel, and characterLimitLabel provide already-formatted display text; classValue extends footer styling. Both implementations forward native wrapper attributes. |
For broader presenter customization, copy the shipped RichText presenter and see Customizing Presenters.