Gathering detailed insights and metrics for trix
Gathering detailed insights and metrics for trix
Gathering detailed insights and metrics for trix
Gathering detailed insights and metrics for trix
npm install trix
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
19,139 Stars
3,039 Commits
1,118 Forks
247 Watching
22 Branches
81 Contributors
Updated on 28 Nov 2024
Minified
Minified + Gzipped
JavaScript (97.21%)
SCSS (1.96%)
HTML (0.48%)
Shell (0.35%)
Cumulative downloads
Total Downloads
Last day
-5.6%
36,673
Compared to previous day
Last week
5.1%
205,068
Compared to previous week
Last month
-1.6%
893,710
Compared to previous month
Last year
16.7%
10,192,428
Compared to previous year
23
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 3.
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.
Trix is built with established web standards, notably Custom Elements, Element Internals, Mutation Observer, and Promises.
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:
1<head> 2 … 3 <link rel="stylesheet" type="text/css" href="https://unpkg.com/trix@2.0.8/dist/trix.css"> 4 <script type="text/javascript" src="https://unpkg.com/trix@2.0.8/dist/trix.umd.min.js"></script> 5</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:
1import Trix from "trix" 2 3document.addEventListener("trix-before-initialize", () => { 4 // Change Trix.config if you need 5})
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.
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:
1<main> 2 <trix-toolbar id="my_toolbar"></trix-toolbar> 3 <div class="more-stuff-inbetween"></div> 4 <trix-editor toolbar="my_toolbar" input="my_input"></trix-editor> 5</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:
1<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 meta+b
If the attribute is defined in Trix.config.blockAttributes
, Trix will apply the attribute to the current block of text.
1<button type="button" class="quote" data-trix-attribute="quote"></button>
Clicking the quote button toggles whether the block should be rendered with <blockquote>
.
Trix will integrate <trix-editor>
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
:
1import Trix from "trix"
2
3Trix.elements.TrixEditorElement.formAssociated = false
Internal actions are defined in controllers/editor_controller.js
and consist of:
1<button type="button" class="block-level decrease" data-trix-action="decreaseBlockLevel"></button>
If you want to add a button to the toolbar and have it invoke an external action, you can prefix your action name with x-
. 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 be data-trix-action="x-log"
1<button id="log-button" type="button" data-trix-action="x-log"></button>
To respond to the action, listen for trix-action-invoke
. The event's target
property returns a reference to the <trix-editor>
element, its invokingElement
property returns a reference to the <button>
element, and its actionName
property returns the value of the [data-trix-action]
attribute. Use the value of the actionName
property to detect which external action was invoked.
1document.addEventListener("trix-action-invoke", function(event) { 2 const { target, invokingElement, actionName } = event 3 4 if (actionName === "x-log") { 5 console.log(`Custom ${actionName} invoked from ${invokingElement.id} button on ${target.id} trix-editor`) 6 } 7})
To submit the contents of a <trix-editor>
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.
1<form …> 2 <input id="x" type="hidden" name="content"> 3 <trix-editor input="x"></trix-editor> 4</form>
Trix will automatically update the value of the hidden input field with each change to the editor.
To populate a <trix-editor>
with stored content, include that content in the associated input element’s value
attribute.
1<form …> 2 <input id="x" value="Editor content goes here" type="hidden" name="content"> 3 <trix-editor input="x"></trix-editor> 4</form>
Always use an associated input element to safely populate an editor. Trix won’t load any HTML content inside a <trix-editor>…</trix-editor>
tag.
Out of the box, <trix-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:
1<input id="x" value="" type="hidden" name="content"> 2<trix-editor input="x" required></trix-editor>
Since the <trix-editor>
element is [required]
, it is invalid when its value
is empty:
1const editor = document.querySelector("trix-editor") 2 3editor.validity.valid // => false 4editor.validity.valueMissing // => true 5editor.matches(":valid") // => false 6editor.matches(":invalid") // => true 7 8editor.value = "A value that isn't empty" 9 10editor.validity.valid // => true 11editor.validity.valueMissing // => false 12editor.matches(":valid") // => true 13editor.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:
1<input id="x" value="" type="hidden" name="content"> 2<trix-editor input="x"></trix-editor>
Custom validation can occur at any time. For example, validation can occur after
a trix-change
event fired after the editor's contents change:
1addEventListener("trix-change", (event) => { 2 const editorElement = event.target 3 const trixDocument = editorElement.editor.getDocument() 4 const isValid = (trixDocument) => { 5 // determine the validity based on your custom criteria 6 return true 7 } 8 9 if (isValid(trixDocument)) { 10 editorElement.setCustomValidity("") 11 } else { 12 editorElement.setCustomValidity("The document is not valid.") 13 } 14}
To disable the <trix-editor>
, render it with the [disabled]
attribute:
1<trix-editor disabled></trix-editor>
Disabled editors are not editable, cannot receive focus, and their values will
be ignored when their related <form>
element is submitted.
To change whether or not an editor is disabled, either toggle the [disabled]
attribute or assign a boolean to the .disabled
property:
1<trix-editor id="editor" disabled></trix-editor> 2 3<script> 4 const editor = document.getElementById("editor") 5 6 editor.toggleAttribute("disabled", false) 7 editor.disabled = true 8</script>
When disabled, the editor will match the :disabled CSS pseudo-class.
Like other form controls, <trix-editor>
elements should have an accessible name. The <trix-editor>
element integrates with <label>
elements and The <trix-editor>
supports two styles of integrating with <label>
elements:
<trix-editor>
element with an [id]
attribute that the <label>
element references through its [for]
attribute:1<label for="editor">Editor</label> 2<trix-editor id="editor"></trix-editor>
<trix-editor>
element as a child of the <label>
element:1<trix-toolbar id="editor-toolbar"></trix-toolbar> 2<label> 3 Editor 4 5 <trix-editor toolbar="editor-toolbar"></trix-editor> 6</label>
[!WARNING] When 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 <label>
elements, <trix-editor>
elements support [aria-label]
and [aria-labelledby]
attributes.
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 <trix-editor>
element, and to a containing element when you render stored Trix content for display in your application.
1<trix-editor class="trix-content"></trix-editor>
1<div class="trix-content">Stored content here</div>
The default trix.css
file includes styles for basic formatted content—including bulleted and numbered lists, code blocks, and block quotes—under the class name trix-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 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 trix-attachment-add
event. Upload the attached files with XMLHttpRequest yourself and set the attachment’s URL attribute upon completion. See the attachment example for detailed information.
If you don’t want to accept dropped or pasted files, call preventDefault()
on the trix-file-accept
event, which Trix dispatches just before the trix-attachment-add
event.
You can manipulate a Trix editor programmatically through the Trix.Editor
interface, available on each <trix-editor>
element through its editor
property.
1var element = document.querySelector("trix-editor") 2element.editor // is a Trix.Editor instance
The formatted content of a Trix editor is known as a document, and is represented as an instance of the Trix.Document
class. To get the editor’s current document, use the editor.getDocument
method.
1element.editor.getDocument() // is a Trix.Document instance
You can convert a document to an unformatted JavaScript string with the document.toString
method.
1var document = element.editor.getDocument() 2document.toString() // is a JavaScript string
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 document.isEqualTo
method.
1var document = element.editor.getDocument() 2document.isEqualTo(element.editor.getDocument()) // true
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 editor.getSelectedRange
method, which returns a two-element array containing the start and end positions.
1element.editor.getSelectedRange() // [0, 0]
You can set the editor’s current selection by passing a range array to the editor.setSelectedRange
method.
1// Select the first character in the document 2element.editor.setSelectedRange([0, 1])
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 setSelectedRange
are equivalent when working with collapsed selections:
1element.editor.setSelectedRange(1) 2element.editor.setSelectedRange([1]) 3element.editor.setSelectedRange([1, 1])
To programmatically move the cursor or selection through the document, call the editor.moveCursorInDirection
or editor.expandSelectionInDirection
methods with a direction argument. The direction can be either "forward"
or "backward"
.
1// Move the cursor backward one character 2element.editor.moveCursorInDirection("backward") 3 4// Expand the end of the selection forward by one character 5element.editor.expandSelectionInDirection("forward")
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 editor.getClientRectAtPosition
method with a position argument to get a DOMRect
instance representing the left and top offsets, width, and height of the character at the given position.
1var rect = element.editor.getClientRectAtPosition(0) 2[rect.left, rect.top] // [17, 49]
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.
To insert unformatted text into the document, call the editor.insertString
method.
1// Insert “Hello” at the beginning of the document 2element.editor.setSelectedRange([0, 0]) 3element.editor.insertString("Hello")
To insert HTML into the document, call the editor.insertHTML
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.
1// Insert a bold “Hello” at the beginning of the document 2element.editor.setSelectedRange([0, 0]) 3element.editor.insertHTML("<strong>Hello</strong>")
To insert a DOM File
object into the document, call the editor.insertFile
method. Trix will insert a pending attachment for the file as if you had dragged and dropped it onto the editor.
1// Insert the selected file from the first file input element 2var file = document.querySelector("input[type=file]").file 3element.editor.insertFile(file)
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 Trix.Attachment
with a content
attribute and call the editor.insertAttachment
method. The HTML inside a content attachment is not subject to Trix’s document conversion rules and will be rendered as-is.
1var attachment = new Trix.Attachment({ content: '<span class="mention">@trix</span>' })
2element.editor.insertAttachment(attachment)
To insert a line break, call the editor.insertLineBreak
method, which is functionally equivalent to pressing the return key.
1// Insert “Hello\n” 2element.editor.insertString("Hello") 3element.editor.insertLineBreak()
If the current selection is collapsed, you can simulate deleting text before or after the cursor with the editor.deleteInDirection
method.
1// “Backspace” the first character in the document 2element.editor.setSelectedRange([1, 1]) 3element.editor.deleteInDirection("backward") 4 5// Delete the second character in the document 6element.editor.setSelectedRange([1, 1]) 7element.editor.deleteInDirection("forward")
To delete a range of text, first set the selected range, then call editor.deleteInDirection
with either direction as the argument.
1// Delete the first five characters 2element.editor.setSelectedRange([0, 4]) 3element.editor.deleteInDirection("forward")
Trix represents formatting as sets of attributes applied across ranges of a document.
By default, Trix supports the inline attributes bold
, italic
, href
, and strike
, and the block-level attributes heading1
, quote
, code
, bullet
, and number
.
To apply formatting to the current selection, use the editor.activateAttribute
method.
1element.editor.insertString("Hello") 2element.editor.setSelectedRange([0, 5]) 3element.editor.activateAttribute("bold")
To set the href
attribute, pass a URL as the second argument to editor.activateAttribute
.
1element.editor.insertString("Trix") 2element.editor.setSelectedRange([0, 4]) 3element.editor.activateAttribute("href", "https://trix-editor.org/")
Use the editor.deactivateAttribute
method to remove formatting from a selection.
1element.editor.setSelectedRange([2, 4]) 2element.editor.deactivateAttribute("bold")
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 editor.insertString
.
1element.editor.activateAttribute("italic") 2element.editor.insertString("This is italic")
To adjust the nesting level of quotes, bulleted lists, or numbered lists, call the editor.increaseNestingLevel
and editor.decreaseNestingLevel
methods.
1element.editor.activateAttribute("quote") 2element.editor.increaseNestingLevel() 3element.editor.decreaseNestingLevel()
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 editor.undo
and editor.redo
methods to perform an undo or redo operation.
1element.editor.undo() 2element.editor.redo()
Changes you make through the editor interface will not automatically record undo entries. You can save your own undo entries by calling the editor.recordUndoEntry
method with a description argument.
1element.editor.recordUndoEntry("Insert Text") 2element.editor.insertString("Hello")
Serialize an editor’s state with JSON.stringify
and restore saved state with the editor.loadJSON
method. The serialized state includes the document and current selection, but does not include undo history.
1// Save editor state to local storage 2localStorage["editorState"] = JSON.stringify(element.editor) 3 4// Restore editor state from local storage 5element.editor.loadJSON(JSON.parse(localStorage["editorState"]))
The <trix-editor>
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 its editor
object. If you need to use a custom Trix configuration you can change Trix.config
here.
trix-initialize
fires when the <trix-editor>
element is attached to the DOM and its editor
object is ready for use.
trix-change
fires whenever the editor’s contents have changed.
trix-paste
fires whenever text is pasted into the editor. The paste
property on the event contains the pasted string
or html
, and the range
of the inserted text.
trix-selection-change
fires any time the selected range changes in the editor.
trix-focus
and trix-blur
fire 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 DOM File
object through the file
property on the event. Call preventDefault
on 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 the attachment
property on the event. If the attachment
object has a file
property, you should store this file remotely and set the attachment’s URL attribute. See the attachment example for detailed information.
trix-attachment-remove
fires when an attachment is removed from the document. You can access the Trix attachment object through the attachment
property 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's target
property, the element responsible for invoking the action through the invokingElement
property, and the action's name through the actionName
property. The trix-action-invoke
event will only fire for custom actions and not for built-in.
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.
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
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.html
to see a Trix debugger inspector, or /test.html
to 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
You can also run the test in a headless mode with:
$ yarn test
© 37signals, LLC.
The latest stable version of the package.
Stable Version
3
6.5/10
Summary
Trix has a cross-site Scripting vulnerability on copy & paste
Affected Versions
< 2.1.4
Patched Versions
2.1.4
5.4/10
Summary
Trix Editor Arbitrary Code Execution Vulnerability
Affected Versions
>= 0.9.0, < 1.3.2
Patched Versions
1.3.2
5.4/10
Summary
Trix Editor Arbitrary Code Execution Vulnerability
Affected Versions
>= 2.0.0, < 2.1.1
Patched Versions
2.1.1
Reason
no dangerous workflow patterns detected
Reason
20 commit(s) and 1 issue activity found in the last 90 days -- score normalized to 10
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
Found 7/17 approved changesets -- score normalized to 4
Reason
SAST tool is not run on all commits -- score normalized to 4
Details
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
15 existing vulnerabilities detected
Details
Score
Last Scanned on 2024-11-25
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More