Repository: basecamp/trix
Stars: 19934
README.md
Trix
A Rich Text Editor for Everyday Writing
Compose beautifully formatted text in your web application. Trix is a WYSIWYG editor for writing messages, comments, articles, and lists—the simple documents most web apps are made of. It features a sophisticated document model, support for embedded attachments, and outputs terse and consistent HTML.
Trix is an open-source project from 37signals, the creators of Ruby on Rails. Millions of people trust their text to us, and we built Trix to give them the best possible editing experience. See Trix in action in Basecamp.
Different By Design
When Trix was designed in 2014, most WYSIWYG editors were wrappers around HTML’s contenteditable and execCommand APIs, designed by Microsoft to support live editing of web pages in Internet Explorer 5.5, and eventually reverse-engineered and copied by other browsers.
Because these APIs were not fully specified or documented, and because WYSIWYG HTML editors are enormous in scope, each browser’s implementation has its own set of bugs and quirks, and JavaScript developers are left to resolve the inconsistencies.
Trix sidestepped these inconsistencies by treating contenteditable as an I/O device: when input makes its way to the editor, Trix converts that input into an editing operation on its internal document model, then re-renders that document back into the editor. This gives Trix complete control over what happens after every keystroke, and avoids the need to use execCommand at all.
This is the approach that all modern, production ready, WYSIWYG editors now take.
Built on Web standards
<details><summary>Trix supports all evergreen, self-updating desktop and mobile browsers.</summary><img src="https://app.saucelabs.com/browser-matrix/basecamp_trix.svg"></details>
Trix is built with established web standards, notably Custom Elements, Element Internals, Mutation Observer, and Promises.
Getting Started
Trix comes bundled in ESM and UMD formats and works with any asset packaging system.
The easiest way to start with Trix is including it from an npm CDN in the <head> of your page:
<head>
…
<link rel="stylesheet" type="text/css" href="https://unpkg.com/[email protected]/dist/trix.css">
<script type="text/javascript" src="https://unpkg.com/[email protected]/dist/trix.umd.min.js"></script>
</head>trix.css includes default styles for the Trix toolbar, editor, and attachments. Skip this file if you prefer to define these styles yourself.
Alternatively, you can install the npm package and import it in your application:
import Trix from "trix"document.addEventListener("trix-before-initialize", () => {
// Change Trix.config if you need
})
Creating an Editor
Place an empty <trix-editor></trix-editor> tag on the page. Trix will automatically insert a separate <trix-toolbar> before the editor.
Like an HTML <textarea>, <trix-editor> accepts autofocus and placeholder attributes. Unlike a <textarea>, <trix-editor> automatically expands vertically to fit its contents.
Creating a Toolbar
Trix automatically will create a toolbar for you and attach it right before the <trix-editor> element. If you'd like to place the toolbar in a different place you can use the toolbar attribute:
<main>
<trix-toolbar id="my_toolbar"></trix-toolbar>
<div class="more-stuff-inbetween"></div>
<trix-editor toolbar="my_toolbar" input="my_input"></trix-editor>
</main>To change the toolbar without modifying Trix, you can overwrite the Trix.config.toolbar.getDefaultHTML() function. The default toolbar HTML is in config/toolbar.js. Trix uses data attributes to determine how to respond to a toolbar button click.
Toggle Attribute
With data-trix-attribute="<attribute name>", you can add an attribute to the current selection.
For example, to apply bold styling to the selected text the button is:
`` If the attribute is defined in Trix will integrate html
<button type="button" class="bold" data-trix-attribute="bold" data-trix-key="b"></button>Trix will determine that a range of text is selected and will apply the formatting defined in Trix.config.textAttributes (found in config/text_attributes.js).data-trix-key="b" tells Trix that this attribute should be applied when you use <kbd>meta</kbd>+<kbd>b</kdb>.Trix.config.blockAttributes, Trix will apply the attribute to the current block of text.
<button type="button" class="quote" data-trix-attribute="quote"></button>Clicking the quote button toggles whether the block should be rendered with <blockquote>.<trix-editor>Integrating with Element Internals
elements with forms depending on the browser's support for Element Internals. If there is a need to disable support for ElementInternals, set Trix.elements.TrixEditorElement.formAssociated = false:
import Trix from "trix"
Trix.elements.TrixEditorElement.formAssociated = false
When Trix is configured to be compatible withElementInternals, it is also<input type="hidden">
capable of functioning without anelement. To configure<trix-editor>
aelement to skip creating its<input type="hidden">, set thewillCreateInput = false
element's:
addEventListener("before-trix-initialize", (event) => {
const trixEditor = event.target
trixEditor.willCreateInput = false
})
[input]NOTETrix will always use an associated <input type="hidden">
element when theattribute is set. To migrate to<input>-free support, setwillCreateInput = false, then render the<trix-editor>without the[input]attribute.<form>WARNINGIn the absence of an <input type="hidden">
element, the<trix-editor>element's value will not be included inelement submissions unless it[name]is rendered with aattribute. Set the[name]attribute to the same<input type="hidden">value that theelement would have.controllers/editor_controller.jsInvoking Internal Trix Actions
Internal actions are defined in
and consist of:* undo
* redo
* link
* increaseBlockLevel
* decreaseBlockLevel
<button type="button" class="block-level decrease" data-trix-action="decreaseBlockLevel"></button>
x-Invoking External Custom Actions
If you want to add a button to the toolbar and have it invoke an external action, you can prefix your action name with
. For example, if I want to print a log statement any time my new button is clicked, I would set by button's data attribute to bedata-trix-action="x-log"
<button id="log-button" type="button" data-trix-action="x-log"></button>
To respond to the action, listen fortrix-action-invoke. The event'stargetproperty returns a reference to the<trix-editor>element, itsinvokingElementproperty returns a reference to the<button>element, and itsactionNameproperty returns the value of the[data-trix-action]attribute. Use the value of theactionNameproperty to detect which external action was invoked.
document.addEventListener("trix-action-invoke", function(event) {
const { target, invokingElement, actionName } = event
if (actionName === "x-log") { To submit the contents of a To populate a When a <trix-editor> Out of the box,
console.log(Custom ${actionName} invoked from ${invokingElement.id} button on ${target.id} trix-editor)
}
})<trix-editor>Integrating With Forms
with a form, first define a hidden input field in the form and assign it an id. Then reference that id in the editor’s input attribute.
<form …>
<input id="x" type="hidden" name="content">
<trix-editor input="x"></trix-editor>
</form>Trix will automatically update the value of the hidden input field with each change to the editor.<trix-editor>Populating With Stored Content
with stored content, include that content in the associated input element’s value attribute.
<form …>
<input id="x" value="Editor content goes here" type="hidden" name="content">
<trix-editor input="x"></trix-editor>
</form>Use an associated input element to initially populate an editor. When an associated input element is absent, Trix will safely sanitize then load any HTML content inside a <trix-editor>…</trix-editor> tag.
<form …>
<trix-editor>Editor content goes here</trix-editor>
</form><trix-editor> element initially connects with both HTML content andan associated input element, Trix will always disregard the HTML content and
load its initial content from the associated input element.
Validating the Editor
elements support browsers' built-in [Constraint
validation][]. When rendered with the [required][] attribute, editors will be
invalid when they're completely empty. For example, consider the following HTML:
<input id="x" value="" type="hidden" name="content">
<trix-editor input="x" required></trix-editor>Since the <trix-editor> element is [required], it is invalid when its value
is empty:
const editor = document.querySelector("trix-editor")
editor.validity.valid // => false
editor.validity.valueMissing // => true
editor.matches(":valid") // => false
editor.matches(":invalid") // => true
editor.value = "A value that isn't empty"
editor.validity.valid // => true
editor.validity.valueMissing // => false
editor.matches(":valid") // => true
editor.matches(":invalid") // => false
In addition to the built-in[required]attribute,<trix-editor>
elements support custom validation through their [setCustomValidity][] method.
For example, consider the following HTML:
<input id="x" value="" type="hidden" name="content">
<trix-editor input="x"></trix-editor>
Custom validation can occur at any time. For example, validation can occur aftertrix-change
aevent fired after the editor's contents change:
addEventListener("trix-change", (event) => {
const editorElement = event.target
const trixDocument = editorElement.editor.getDocument()
const isValid = (trixDocument) => {
// determine the validity based on your custom criteria
return true
}
if (isValid(trixDocument)) {
editorElement.setCustomValidity("")
} else {
editorElement.setCustomValidity("The document is not valid.")
}
}
[Constraint validation]: https://developer.mozilla.org/en-US/docs/Web/HTML/Constraint_validation<trix-editor>
[required]: https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/required
[setCustomValidity]: https://developer.mozilla.org/en-US/docs/Web/API/HTMLObjectElement/setCustomValidityDisabling the Editor
To disable the
, render it with the[disabled]attribute:
<trix-editor disabled></trix-editor>
Disabled editors are not editable, cannot receive focus, and their values will<form>
be ignored when their relatedelement is submitted.[disabled]To change whether or not an editor is disabled, either toggle the
.disabled
attribute or assign a boolean to theproperty:
<trix-editor id="editor" disabled></trix-editor>
<script>
const editor = document.getElementById("editor")
editor.toggleAttribute("disabled", false)
editor.disabled = true
</script>
When disabled, the editor will match the [:disabled CSS<trix-editor>
pseudo-class][:disabled].[:disabled]: https://developer.mozilla.org/en-US/docs/Web/CSS/:disabled
Providing an Accessible Name
Like other form controls,
elements should have an accessible name. The<trix-editor>element integrates with<label>elements. It supports two styles of integrating with<label>elements:<trix-editor>1. render the
element with an[id]attribute that the<label>element references through its[for]attribute:
<label for="editor">Editor</label>
<trix-editor id="editor"></trix-editor>
2. render the<trix-editor>element as a child of the<label>element:
<trix-toolbar id="editor-toolbar"></trix-toolbar>
<label>
Editor
<trix-editor toolbar="editor-toolbar"></trix-editor>
</label>
<label>WARNINGWhen rendering the <trix-editor>
element as a child of the<label>element, explicitly render the corresponding<trix-toolbar>element outside of the<label>element.In addition to integrating with
elements,<trix-editor>elements support[aria-label]and[aria-labelledby]attributes.<trix-editor>Styling Formatted Content
To ensure what you see when you edit is what you see when you save, use a CSS class name to scope styles for Trix formatted content. Apply this class name to your
element, and to a containing element when you render stored Trix content for display in your application.
<trix-editor class="trix-content"></trix-editor>
<div class="trix-content">Stored content here</div>
The defaulttrix.cssfile includes styles for basic formatted content—including bulleted and numbered lists, code blocks, and block quotes—under the class nametrix-content. We encourage you to use these styles as a starting point by copying them into your application’s CSS with a different class name.trix-attachment-addStoring Attached Files
Trix automatically accepts files dragged or pasted into an editor and inserts them as attachments in the document. Each attachment is considered _pending_ until you store it remotely and provide Trix with a permanent URL.
To store attachments, listen for the
event. Upload the attached files with XMLHttpRequest yourself and set the attachment’s URL attribute upon completion. See the attachment example for detailed information.preventDefault()If you don’t want to accept dropped or pasted files, call
on thetrix-file-acceptevent, which Trix dispatches just before thetrix-attachment-addevent.image/gifPreviewing Attached Files
Trix automatically previews attached image files. To determine whether or not to preview an attached file, Trix compares the file's content type against the Trix.Attachment.previewablePattern. By default, Trix will preview the following content types:
*
image/png
*image/webp
*image/jpg
*image/jpeg
*trix-attachment-addTo customize an attachment's preview, listen for the
event. When handling the event, set the attachment'spreviewableattribute, then change its preview URL by callingsetPreviewURL:
addEventListener("trix-attachment-add", (event) => {
if (event.attachment.file instanceof File) {
event.attachment.setAttribute("previewable", true)
event.attachment.setPreviewURL("...")
}
})
Trix.EditorEditing Text Programmatically
You can manipulate a Trix editor programmatically through the
interface, available on each<trix-editor>element through itseditorproperty.
var element = document.querySelector("trix-editor")
element.editor // is a Trix.Editor instance
Trix.DocumentUnderstanding the Document Model
The formatted content of a Trix editor is known as a _document_, and is represented as an instance of the
class. To get the editor’s current document, use theeditor.getDocumentmethod.
element.editor.getDocument() // is a Trix.Document instance
You can convert a document to an unformatted JavaScript string with thedocument.toStringmethod.
var document = element.editor.getDocument()
document.toString() // is a JavaScript string
document.isEqualToImmutability and Equality
Documents are immutable values. Each change you make in an editor replaces the previous document with a new document. Capturing a snapshot of the editor’s content is as simple as keeping a reference to its document, since that document will never change over time. (This is how Trix implements undo.)
To compare two documents for equality, use the
method.
var document = element.editor.getDocument()
document.isEqualTo(element.editor.getDocument()) // true
editor.getSelectedRangeGetting and Setting the Selection
Trix documents are structured as sequences of individually addressable characters. The index of one character in a document is called a _position_, and a start and end position together make up a _range_.
To get the editor’s current selection, use the
method, which returns a two-element array containing the start and end positions.
element.editor.getSelectedRange() // [0, 0]
You can set the editor’s current selection by passing a range array to theeditor.setSelectedRangemethod.
// Select the first character in the document
element.editor.setSelectedRange([0, 1])
setSelectedRangeCollapsed Selections
When the start and end positions of a range are equal, the range is said to be _collapsed_. In the editor, a collapsed selection appears as a blinking cursor rather than a highlighted span of text.
For convenience, the following calls to
are equivalent when working with collapsed selections:
element.editor.setSelectedRange(1)
element.editor.setSelectedRange([1])
element.editor.setSelectedRange([1, 1])
editor.moveCursorInDirectionDirectional Movement
To programmatically move the cursor or selection through the document, call the
oreditor.expandSelectionInDirectionmethods with a _direction_ argument. The direction can be either"forward"or"backward".
// Move the cursor backward one character
element.editor.moveCursorInDirection("backward")
// Expand the end of the selection forward by one character
element.editor.expandSelectionInDirection("forward")
editor.getClientRectAtPositionConverting Positions to Pixel Offsets
Sometimes you need to know the _x_ and _y_ coordinates of a character at a given position in the editor. For example, you might want to absolutely position a pop-up menu element below the editor’s cursor.
Call the
method with a position argument to get aDOMRectinstance representing the left and top offsets, width, and height of the character at the given position.
var rect = element.editor.getClientRectAtPosition(0)
[rect.left, rect.top] // [17, 49]
editor.insertStringInserting and Deleting Text
The editor interface provides methods for inserting, replacing, and deleting text at the current selection.
To insert or replace text, begin by setting the selected range, then call one of the insertion methods below. Trix will first remove any selected text, then insert the new text at the start position of the selected range.
Inserting Plain Text
To insert unformatted text into the document, call the
method.
// Insert “Hello” at the beginning of the document
element.editor.setSelectedRange([0, 0])
element.editor.insertString("Hello")
editor.insertHTMLInserting HTML
To insert HTML into the document, call the
method. Trix will first convert the HTML into its internal document model. During this conversion, any formatting that cannot be represented in a Trix document will be lost.
// Insert a bold “Hello” at the beginning of the document
element.editor.setSelectedRange([0, 0])
element.editor.insertHTML("<strong>Hello</strong>")
FileInserting a File
object into the document, call theeditor.insertFilemethod. Trix will insert a pending attachment for the file as if you had dragged and dropped it onto the editor.
// Insert the selected file from the first file input element
var file = document.querySelector("input[type=file]").file
element.editor.insertFile(file)
Trix.AttachmentInserting a Content Attachment
Content attachments are self-contained units of HTML that behave like files in the editor. They can be moved or removed, but not edited directly, and are represented by a single character position in the document model.
To insert HTML as an attachment, create a
with acontentattribute and call theeditor.insertAttachmentmethod. The HTML inside a content attachment is not subject to Trix’s document conversion rules and will be rendered as-is.
var attachment = new Trix.Attachment({ content: '<span class="mention">@trix</span>' })
element.editor.insertAttachment(attachment)
editor.insertLineBreakInserting a Line Break
To insert a line break, call the
method, which is functionally equivalent to pressing the return key.
// Insert “Hello\n”
element.editor.insertString("Hello")
element.editor.insertLineBreak()
editor.deleteInDirectionDeleting Text
If the current selection is collapsed, you can simulate deleting text before or after the cursor with the
method.
// “Backspace” the first character in the document
element.editor.setSelectedRange([1, 1])
element.editor.deleteInDirection("backward")
// Delete the second character in the document
element.editor.setSelectedRange([1, 1])
element.editor.deleteInDirection("forward")
To delete a range of text, first set the selected range, then calleditor.deleteInDirectionwith either direction as the argument.
// Delete the first five characters
element.editor.setSelectedRange([0, 4])
element.editor.deleteInDirection("forward")
boldWorking With Attributes and Nesting
Trix represents formatting as sets of _attributes_ applied across ranges of a document.
By default, Trix supports the inline attributes
,italic,href, andstrike, and the block-level attributesheading1,quote,code,bullet, andnumber.editor.activateAttributeApplying Formatting
To apply formatting to the current selection, use the
method.
element.editor.insertString("Hello")
element.editor.setSelectedRange([0, 5])
element.editor.activateAttribute("bold")
To set thehrefattribute, pass a URL as the second argument toeditor.activateAttribute.
element.editor.insertString("Trix")
element.editor.setSelectedRange([0, 4])
element.editor.activateAttribute("href", "https://trix-editor.org/")
editor.deactivateAttributeRemoving Formatting
Use the
method to remove formatting from a selection.
element.editor.setSelectedRange([2, 4])
element.editor.deactivateAttribute("bold")
editor.insertStringFormatting With a Collapsed Selection
If you activate or deactivate attributes when the selection is collapsed, your formatting changes will apply to the text inserted by any subsequent calls to
.
element.editor.activateAttribute("italic")
element.editor.insertString("This is italic")
editor.increaseNestingLevelAdjusting the Nesting Level
To adjust the nesting level of quotes, bulleted lists, or numbered lists, call the
andeditor.decreaseNestingLevelmethods.
element.editor.activateAttribute("quote")
element.editor.increaseNestingLevel()
element.editor.decreaseNestingLevel()
editor.undoUsing Undo and Redo
Trix editors support unlimited undo and redo. Successive typing and formatting changes are consolidated together at five-second intervals; all other input changes are recorded individually in undo history.
Call the
andeditor.redomethods to perform an undo or redo operation.
element.editor.undo()
element.editor.redo()
Changes you make through the editor interface will not automatically record undo entries. You can save your own undo entries by calling theeditor.recordUndoEntrymethod with a description argument.
element.editor.recordUndoEntry("Insert Text")
element.editor.insertString("Hello")
JSON.stringifyLoading and Saving Editor State
Serialize an editor’s state with
and restore saved state with theeditor.loadJSONmethod. The serialized state includes the document and current selection, but does not include undo history.
// Save editor state to local storage
localStorage["editorState"] = JSON.stringify(element.editor)
// Restore editor state from local storage
element.editor.loadJSON(JSON.parse(localStorage["editorState"]))
Trix.config.dompurifyHTML Sanitization
Trix uses DOMPurify to sanitize the editor content. You can set the DOMPurify config via
.For example if you want to keep a custom tag, you can access do that with:
Trix.config.dompurify.ADD_TAGS = [ "my-custom-tag" ]
<trix-editor>HTML Rendering
Trix renders changes to editor content by replacing existing nodes with new nodes.
To customize how Trix renders changes, set the
element'srenderproperty to a function that accepts a<trix-editor>instance and a
[DocumentFragment][]:
document.addEventListener("trix-before-render", (event) => {
const defaultRender = event.render
event.render = function(editorElement, documentFragment) {
// modify the documentFragment…
customize(documentFragment)
// render it with the default rendering function
defaultRender(editorElement, documentFragment)
}
})
<trix-editor>CAUTIONBy the time that render(editorElement, documentFragment)
isinvoked, Trix will have finalized modifications to the HTML content (like HTMLsanitization, for example). If you make further modifications to the content,be sure that they are safe.[DocumentFragment]: https://developer.mozilla.org/en-US/docs/Web/API/DocumentFragment
Observing Editor Changes
The
element emits several events which you can use to observe and respond to changes in editor state.trix-before-initialize*
fires when the<trix-editor>element is attached to the DOM just before Trix installs itseditorobject. If you need to use a custom Trix configuration you can changeTrix.confighere.trix-initialize*
fires when the<trix-editor>element is attached to the DOM and itseditorobject is ready for use.trix-change*
fires whenever the editor’s contents have changed.trix-before-render*
fires before the editor’s new contents are rendered. You can override the function used to render the content through therenderproperty on the event. Therenderfunction expects two positional arguments: the<trix-editor>element that will render and a DocumentFragment instance that contains the new content. Read HTML Rendering to learn more.trix-before-paste*
fires just before text is pasted into the editor. You can use this to modify the content being pasted or prevent the paste event from happening at all. Thepasteproperty on the event contains the pastedstringorhtml, and therangeof the inserted text.trix-paste*
fires whenever text is pasted into the editor. Thepasteproperty on the event contains the pastedstringorhtml, and therangeof the inserted text.trix-selection-change*
fires any time the selected range changes in the editor.trix-focus*
andtrix-blurfire when the editor gains or loses focus, respectively.trix-file-accept*
fires when a file is dropped or inserted into the editor. You can access the DOMFileobject through thefileproperty on the event. CallpreventDefaulton the event to prevent attaching the file to the document.trix-attachment-add*
fires after an attachment is added to the document. You can access the Trix attachment object through theattachmentproperty on the event. If theattachmentobject has afileproperty, you should store this file remotely and set the attachment’s URL attribute. See the attachment example for detailed information.trix-attachment-edit*
fires after an attachment is edited in the document. You can access the Trix attachment object through theattachmentproperty on the event.trix-attachment-remove*
fires when an attachment is removed from the document. You can access the Trix attachment object through theattachmentproperty on the event. You may wish to use this event to clean up remotely stored files.trix-action-invoke*
fires when a Trix action is invoked. You can access the<trix-editor>element through the event'stargetproperty, the element responsible for invoking the action through theinvokingElementproperty, and the action's name through theactionNameproperty. Thetrix-action-invokeevent will only fire for custom actions and not for built-in.Contributing to Trix
Trix is open-source software, freely distributable under the terms of an MIT-style license. The source code is hosted on GitHub.
We welcome contributions in the form of bug reports, pull requests, or thoughtful discussions in the GitHub issue tracker. Please see the Code of Conduct for our pledge to contributors.
Trix was created by Javan Makhmali and Sam Stephenson, with development sponsored by 37signals.
Building From Source
Trix uses Yarn to manage dependencies and Rollup to bundle its source.
Install development dependencies with:
$ yarn install
To generate distribution files run:$ yarn build
Developing In-Browser
You can run a watch process to automatically generate distribution files when your source file change:
$ yarn watch
When the watch process is running you can run a web server to serve the compiled assets:$ yarn dev
With the development server running, you can visit/index.htmlto see a Trix debugger inspector, or/test.htmlto run the tests on a browser.For easier development, you can watch for changes to the JavaScript and style files, and serve the results in a browser, with a single command:
$ yarn start
Running Tests
You can also run the test in a headless mode with:
$ yarn test
``
---
© 37signals, LLC.