{"id":13393167,"url":"https://github.com/basecamp/trix","last_synced_at":"2025-05-12T18:21:27.580Z","repository":{"id":9838853,"uuid":"11829145","full_name":"basecamp/trix","owner":"basecamp","description":"A rich text editor for everyday writing","archived":false,"fork":false,"pushed_at":"2025-04-29T10:47:44.000Z","size":6138,"stargazers_count":19462,"open_issues_count":165,"forks_count":1134,"subscribers_count":247,"default_branch":"main","last_synced_at":"2025-05-05T15:49:17.889Z","etag":null,"topics":["custom-elements","editor","javascript","rich-text-editor","text-editor","wysiwyg","wysiwyg-editor"],"latest_commit_sha":null,"homepage":"https://trix-editor.org/","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/basecamp.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2013-08-01T22:21:30.000Z","updated_at":"2025-05-05T15:02:47.000Z","dependencies_parsed_at":"2023-02-11T10:15:22.092Z","dependency_job_id":"f4d6929c-fa8d-4047-8f80-22b9ca39b24f","html_url":"https://github.com/basecamp/trix","commit_stats":{"total_commits":2687,"total_committers":54,"mean_commits":49.75925925925926,"dds":"0.33941198362486047","last_synced_commit":"7c727e0276f5ee66b2d30612e7d5db91cc1e4c4f"},"previous_names":[],"tags_count":70,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/basecamp%2Ftrix","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/basecamp%2Ftrix/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/basecamp%2Ftrix/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/basecamp%2Ftrix/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/basecamp","download_url":"https://codeload.github.com/basecamp/trix/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":252752061,"owners_count":21798723,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["custom-elements","editor","javascript","rich-text-editor","text-editor","wysiwyg","wysiwyg-editor"],"created_at":"2024-07-30T17:00:44.482Z","updated_at":"2025-05-12T18:21:27.545Z","avatar_url":"https://github.com/basecamp.png","language":"JavaScript","funding_links":[],"categories":["JavaScript","CoffeeScript","Editor","独立的","Editors","🛠️ Developer Tools","Real World","javascript","Editors [🔝](#readme)","Packages","Programming Languages","Web 前端","text-editor","Repository","Uncategorized","编辑器","Rich-text editors using contenteditable","Standalone"],"sub_categories":["Runner","Components","JavaScript","Editor","Uncategorized","运行器","运行器e2e测试"],"readme":"# Trix\n### A Rich Text Editor for Everyday Writing\n\n**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.\n\nTrix is an open-source project from [37signals](https://37signals.com), the creators of [Ruby on Rails](http://rubyonrails.org/). 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](https://basecamp.com).\n\n### Different By Design\n\nWhen 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](https://blog.whatwg.org/the-road-to-html-5-contenteditable#history) and copied by other browsers.\n\nBecause 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.\n\nTrix 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.\n\nThis is the approach that all modern, production ready, WYSIWYG editors now take.\n\n### Built on Web standards\n\n\u003cdetails\u003e\u003csummary\u003eTrix supports all evergreen, self-updating desktop and mobile browsers.\u003c/summary\u003e\u003cimg src=\"https://app.saucelabs.com/browser-matrix/basecamp_trix.svg\"\u003e\u003c/details\u003e\n\nTrix is built with established web standards, notably [Custom Elements](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements), [Element Internals](https://developer.mozilla.org/en-US/docs/Web/API/ElementInternals), [Mutation Observer](https://dom.spec.whatwg.org/#mutation-observers), and [Promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).\n\n# Getting Started\n\nTrix comes bundled in ESM and UMD formats and works with any asset packaging system.\n\nThe easiest way to start with Trix is including it from an npm CDN in the `\u003chead\u003e` of your page:\n\n```html\n\u003chead\u003e\n  …\n  \u003clink rel=\"stylesheet\" type=\"text/css\" href=\"https://unpkg.com/trix@2.0.8/dist/trix.css\"\u003e\n  \u003cscript type=\"text/javascript\" src=\"https://unpkg.com/trix@2.0.8/dist/trix.umd.min.js\"\u003e\u003c/script\u003e\n\u003c/head\u003e\n```\n\n`trix.css` includes default styles for the Trix toolbar, editor, and attachments. Skip this file if you prefer to define these styles yourself.\n\nAlternatively, you can install the npm package and import it in your application:\n\n```js\nimport Trix from \"trix\"\n\ndocument.addEventListener(\"trix-before-initialize\", () =\u003e {\n  // Change Trix.config if you need\n})\n```\n\n## Creating an Editor\n\nPlace an empty `\u003ctrix-editor\u003e\u003c/trix-editor\u003e` tag on the page. Trix will automatically insert a separate `\u003ctrix-toolbar\u003e` before the editor.\n\nLike an HTML `\u003ctextarea\u003e`, `\u003ctrix-editor\u003e` accepts `autofocus` and `placeholder` attributes. Unlike a `\u003ctextarea\u003e`, `\u003ctrix-editor\u003e` automatically expands vertically to fit its contents.\n\n## Creating a Toolbar\n\nTrix automatically will create a toolbar for you and attach it right before the `\u003ctrix-editor\u003e` element. If you'd like to place the toolbar in a different place you can use the `toolbar` attribute:\n\n```html\n\u003cmain\u003e\n  \u003ctrix-toolbar id=\"my_toolbar\"\u003e\u003c/trix-toolbar\u003e\n  \u003cdiv class=\"more-stuff-inbetween\"\u003e\u003c/div\u003e\n  \u003ctrix-editor toolbar=\"my_toolbar\" input=\"my_input\"\u003e\u003c/trix-editor\u003e\n\u003c/main\u003e\n```\n\nTo 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.\n\n**Toggle Attribute**\n\nWith `data-trix-attribute=\"\u003cattribute name\u003e\"`, you can add an attribute to the current selection.\nFor example, to apply bold styling to the selected text the button is:\n\n``` html\n\u003cbutton type=\"button\" class=\"bold\" data-trix-attribute=\"bold\" data-trix-key=\"b\"\u003e\u003c/button\u003e\n```\n\nTrix 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`).\n\n`data-trix-key=\"b\"` tells Trix that this attribute should be applied when you use \u003ckbd\u003emeta\u003c/kbd\u003e+\u003ckbd\u003eb\u003c/kdb\u003e.\n\nIf the attribute is defined in `Trix.config.blockAttributes`, Trix will apply the attribute to the current block of text.\n\n``` html\n\u003cbutton type=\"button\" class=\"quote\" data-trix-attribute=\"quote\"\u003e\u003c/button\u003e\n```\n\nClicking the quote button toggles whether the block should be rendered with `\u003cblockquote\u003e`.\n\n## Integrating with Element Internals\n\nTrix will integrate `\u003ctrix-editor\u003e` elements with forms depending on the browser's support for [Element Internals](https://developer.mozilla.org/en-US/docs/Web/API/ElementInternals). If there is a need to disable support for `ElementInternals`, set `Trix.elements.TrixEditorElement.formAssociated = false`:\n\n```js\nimport Trix from \"trix\"\n\nTrix.elements.TrixEditorElement.formAssociated = false\n```\n\n## Invoking Internal Trix Actions\n\nInternal actions are defined in `controllers/editor_controller.js` and consist of:\n\n* undo\n* redo\n* link\n* increaseBlockLevel\n* decreaseBlockLevel\n\n``` html\n\u003cbutton type=\"button\" class=\"block-level decrease\" data-trix-action=\"decreaseBlockLevel\"\u003e\u003c/button\u003e\n```\n\n## Invoking External Custom Actions\n\nIf 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\"`\n\n``` html\n\u003cbutton id=\"log-button\" type=\"button\" data-trix-action=\"x-log\"\u003e\u003c/button\u003e\n```\n\nTo respond to the action, listen for `trix-action-invoke`. The event's `target` property returns a reference to the `\u003ctrix-editor\u003e` element, its `invokingElement` property returns a reference to the `\u003cbutton\u003e` 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.\n\n```javascript\ndocument.addEventListener(\"trix-action-invoke\", function(event) {\n  const { target, invokingElement, actionName } = event\n\n  if (actionName === \"x-log\") {\n    console.log(`Custom ${actionName} invoked from ${invokingElement.id} button on ${target.id} trix-editor`)\n  }\n})\n```\n\n## Integrating With Forms\n\nTo submit the contents of a `\u003ctrix-editor\u003e` 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.\n\n```html\n\u003cform …\u003e\n  \u003cinput id=\"x\" type=\"hidden\" name=\"content\"\u003e\n  \u003ctrix-editor input=\"x\"\u003e\u003c/trix-editor\u003e\n\u003c/form\u003e\n```\n\nTrix will automatically update the value of the hidden input field with each change to the editor.\n\n## Populating With Stored Content\n\nTo populate a `\u003ctrix-editor\u003e` with stored content, include that content in the associated input element’s `value` attribute.\n\n```html\n\u003cform …\u003e\n  \u003cinput id=\"x\" value=\"Editor content goes here\" type=\"hidden\" name=\"content\"\u003e\n  \u003ctrix-editor input=\"x\"\u003e\u003c/trix-editor\u003e\n\u003c/form\u003e\n```\n\nAlways use an associated input element to safely populate an editor. Trix won’t load any HTML content inside a `\u003ctrix-editor\u003e…\u003c/trix-editor\u003e` tag.\n\n## Validating the Editor\n\nOut of the box, `\u003ctrix-editor\u003e` elements support browsers' built-in [Constraint\nvalidation][]. When rendered with the [required][] attribute, editors will be\ninvalid when they're completely empty. For example, consider the following HTML:\n\n```html\n\u003cinput id=\"x\" value=\"\" type=\"hidden\" name=\"content\"\u003e\n\u003ctrix-editor input=\"x\" required\u003e\u003c/trix-editor\u003e\n```\n\nSince the `\u003ctrix-editor\u003e` element is `[required]`, it is invalid when its value\nis empty:\n\n```js\nconst editor = document.querySelector(\"trix-editor\")\n\neditor.validity.valid        // =\u003e false\neditor.validity.valueMissing // =\u003e true\neditor.matches(\":valid\")     // =\u003e false\neditor.matches(\":invalid\")   // =\u003e true\n\neditor.value = \"A value that isn't empty\"\n\neditor.validity.valid         // =\u003e true\neditor.validity.valueMissing  // =\u003e false\neditor.matches(\":valid\")      // =\u003e true\neditor.matches(\":invalid\")    // =\u003e false\n```\n\nIn addition to the built-in `[required]` attribute, `\u003ctrix-editor\u003e`\nelements support custom validation through their [setCustomValidity][] method.\nFor example, consider the following HTML:\n\n```js\n\u003cinput id=\"x\" value=\"\" type=\"hidden\" name=\"content\"\u003e\n\u003ctrix-editor input=\"x\"\u003e\u003c/trix-editor\u003e\n```\n\nCustom validation can occur at any time. For example, validation can occur after\na `trix-change` event fired after the editor's contents change:\n\n```js\naddEventListener(\"trix-change\", (event) =\u003e {\n  const editorElement = event.target\n  const trixDocument = editorElement.editor.getDocument()\n  const isValid = (trixDocument) =\u003e {\n    // determine the validity based on your custom criteria\n    return true\n  }\n\n  if (isValid(trixDocument)) {\n    editorElement.setCustomValidity(\"\")\n  } else {\n    editorElement.setCustomValidity(\"The document is not valid.\")\n  }\n}\n```\n\n[Constraint validation]: https://developer.mozilla.org/en-US/docs/Web/HTML/Constraint_validation\n[required]: https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/required\n[setCustomValidity]: https://developer.mozilla.org/en-US/docs/Web/API/HTMLObjectElement/setCustomValidity\n\n## Disabling the Editor\n\nTo disable the `\u003ctrix-editor\u003e`, render it with the `[disabled]` attribute:\n\n```html\n\u003ctrix-editor disabled\u003e\u003c/trix-editor\u003e\n```\n\nDisabled editors are not editable, cannot receive focus, and their values will\nbe ignored when their related `\u003cform\u003e` element is submitted.\n\nTo change whether or not an editor is disabled, either toggle the `[disabled]`\nattribute or assign a boolean to the `.disabled` property:\n\n```html\n\u003ctrix-editor id=\"editor\" disabled\u003e\u003c/trix-editor\u003e\n\n\u003cscript\u003e\n  const editor = document.getElementById(\"editor\")\n\n  editor.toggleAttribute(\"disabled\", false)\n  editor.disabled = true\n\u003c/script\u003e\n```\n\nWhen disabled, the editor will match the [:disabled CSS\npseudo-class][:disabled].\n\n[:disabled]: https://developer.mozilla.org/en-US/docs/Web/CSS/:disabled\n\n## Providing an Accessible Name\n\nLike other form controls, `\u003ctrix-editor\u003e` elements should have an accessible name. The `\u003ctrix-editor\u003e` element integrates with `\u003clabel\u003e` elements. It supports two styles of integrating with `\u003clabel\u003e` elements:\n\n1. render the `\u003ctrix-editor\u003e` element with an `[id]` attribute that the `\u003clabel\u003e` element references through its `[for]` attribute:\n\n```html\n\u003clabel for=\"editor\"\u003eEditor\u003c/label\u003e\n\u003ctrix-editor id=\"editor\"\u003e\u003c/trix-editor\u003e\n```\n\n2. render the `\u003ctrix-editor\u003e` element as a child of the `\u003clabel\u003e` element:\n\n```html\n\u003ctrix-toolbar id=\"editor-toolbar\"\u003e\u003c/trix-toolbar\u003e\n\u003clabel\u003e\n  Editor\n\n  \u003ctrix-editor toolbar=\"editor-toolbar\"\u003e\u003c/trix-editor\u003e\n\u003c/label\u003e\n```\n\n\u003e [!WARNING]\n\u003e When rendering the `\u003ctrix-editor\u003e` element as a child of the `\u003clabel\u003e` element, [explicitly render](#creating-an-editor) the corresponding `\u003ctrix-toolbar\u003e` element outside of the `\u003clabel\u003e` element.\n\nIn addition to integrating with `\u003clabel\u003e` elements, `\u003ctrix-editor\u003e` elements support `[aria-label]` and `[aria-labelledby]` attributes.\n\n## Styling Formatted Content\n\nTo 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 `\u003ctrix-editor\u003e` element, and to a containing element when you render stored Trix content for display in your application.\n\n```html\n\u003ctrix-editor class=\"trix-content\"\u003e\u003c/trix-editor\u003e\n```\n\n```html\n\u003cdiv class=\"trix-content\"\u003eStored content here\u003c/div\u003e\n```\n\nThe 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.\n\n## Storing Attached Files\n\nTrix 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.\n\nTo 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](https://trix-editor.org/js/attachments.js) for detailed information.\n\nIf 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.\n\n# Editing Text Programmatically\n\nYou can manipulate a Trix editor programmatically through the `Trix.Editor` interface, available on each `\u003ctrix-editor\u003e` element through its `editor` property.\n\n```js\nvar element = document.querySelector(\"trix-editor\")\nelement.editor  // is a Trix.Editor instance\n```\n\n## Understanding the Document Model\n\nThe 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.\n\n```js\nelement.editor.getDocument()  // is a Trix.Document instance\n```\n\nYou can convert a document to an unformatted JavaScript string with the `document.toString` method.\n\n```js\nvar document = element.editor.getDocument()\ndocument.toString()  // is a JavaScript string\n```\n\n### Immutability and Equality\n\nDocuments 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.)\n\nTo compare two documents for equality, use the `document.isEqualTo` method.\n\n```js\nvar document = element.editor.getDocument()\ndocument.isEqualTo(element.editor.getDocument())  // true\n```\n\n## Getting and Setting the Selection\n\nTrix 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_.\n\nTo get the editor’s current selection, use the `editor.getSelectedRange` method, which returns a two-element array containing the start and end positions.\n\n```js\nelement.editor.getSelectedRange()  // [0, 0]\n```\n\nYou can set the editor’s current selection by passing a range array to the `editor.setSelectedRange` method.\n\n```js\n// Select the first character in the document\nelement.editor.setSelectedRange([0, 1])\n```\n\n### Collapsed Selections\n\nWhen 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.\n\nFor convenience, the following calls to `setSelectedRange` are equivalent when working with collapsed selections:\n\n```js\nelement.editor.setSelectedRange(1)\nelement.editor.setSelectedRange([1])\nelement.editor.setSelectedRange([1, 1])\n```\n\n### Directional Movement\n\nTo 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\"`.\n\n```js\n// Move the cursor backward one character\nelement.editor.moveCursorInDirection(\"backward\")\n\n// Expand the end of the selection forward by one character\nelement.editor.expandSelectionInDirection(\"forward\")\n```\n\n### Converting Positions to Pixel Offsets\n\nSometimes 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.\n\nCall the `editor.getClientRectAtPosition` method with a position argument to get a [`DOMRect`](https://drafts.fxtf.org/geometry/#DOMRect) instance representing the left and top offsets, width, and height of the character at the given position.\n\n```js\nvar rect = element.editor.getClientRectAtPosition(0)\n[rect.left, rect.top]  // [17, 49]\n```\n\n## Inserting and Deleting Text\n\nThe editor interface provides methods for inserting, replacing, and deleting text at the current selection.\n\nTo 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.\n\n### Inserting Plain Text\n\nTo insert unformatted text into the document, call the `editor.insertString` method.\n\n```js\n// Insert “Hello” at the beginning of the document\nelement.editor.setSelectedRange([0, 0])\nelement.editor.insertString(\"Hello\")\n```\n\n### Inserting HTML\n\nTo 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.\n\n```js\n// Insert a bold “Hello” at the beginning of the document\nelement.editor.setSelectedRange([0, 0])\nelement.editor.insertHTML(\"\u003cstrong\u003eHello\u003c/strong\u003e\")\n```\n\n### Inserting a File\n\nTo insert a DOM [`File`](http://www.w3.org/TR/FileAPI/#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.\n\n```js\n// Insert the selected file from the first file input element\nvar file = document.querySelector(\"input[type=file]\").file\nelement.editor.insertFile(file)\n```\n\n### Inserting a Content Attachment\n\nContent 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.\n\nTo 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.\n\n```js\nvar attachment = new Trix.Attachment({ content: '\u003cspan class=\"mention\"\u003e@trix\u003c/span\u003e' })\nelement.editor.insertAttachment(attachment)\n```\n\n### Inserting a Line Break\n\nTo insert a line break, call the `editor.insertLineBreak` method, which is functionally equivalent to pressing the return key.\n\n```js\n// Insert “Hello\\n”\nelement.editor.insertString(\"Hello\")\nelement.editor.insertLineBreak()\n```\n\n### Deleting Text\n\nIf the current selection is collapsed, you can simulate deleting text before or after the cursor with the `editor.deleteInDirection` method.\n\n```js\n// “Backspace” the first character in the document\nelement.editor.setSelectedRange([1, 1])\nelement.editor.deleteInDirection(\"backward\")\n\n// Delete the second character in the document\nelement.editor.setSelectedRange([1, 1])\nelement.editor.deleteInDirection(\"forward\")\n```\n\nTo delete a range of text, first set the selected range, then call `editor.deleteInDirection` with either direction as the argument.\n\n```js\n// Delete the first five characters\nelement.editor.setSelectedRange([0, 4])\nelement.editor.deleteInDirection(\"forward\")\n```\n\n## Working With Attributes and Nesting\n\nTrix represents formatting as sets of _attributes_ applied across ranges of a document.\n\nBy default, Trix supports the inline attributes `bold`, `italic`, `href`, and `strike`, and the block-level attributes `heading1`, `quote`, `code`, `bullet`, and `number`.\n\n### Applying Formatting\n\nTo apply formatting to the current selection, use the `editor.activateAttribute` method.\n\n```js\nelement.editor.insertString(\"Hello\")\nelement.editor.setSelectedRange([0, 5])\nelement.editor.activateAttribute(\"bold\")\n```\n\nTo set the `href` attribute, pass a URL as the second argument to `editor.activateAttribute`.\n\n```js\nelement.editor.insertString(\"Trix\")\nelement.editor.setSelectedRange([0, 4])\nelement.editor.activateAttribute(\"href\", \"https://trix-editor.org/\")\n```\n\n### Removing Formatting\n\nUse the `editor.deactivateAttribute` method to remove formatting from a selection.\n\n```js\nelement.editor.setSelectedRange([2, 4])\nelement.editor.deactivateAttribute(\"bold\")\n```\n\n### Formatting With a Collapsed Selection\n\nIf 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`.\n\n```js\nelement.editor.activateAttribute(\"italic\")\nelement.editor.insertString(\"This is italic\")\n```\n\n### Adjusting the Nesting Level\n\nTo adjust the nesting level of quotes, bulleted lists, or numbered lists, call the `editor.increaseNestingLevel` and `editor.decreaseNestingLevel` methods.\n\n```js\nelement.editor.activateAttribute(\"quote\")\nelement.editor.increaseNestingLevel()\nelement.editor.decreaseNestingLevel()\n```\n\n## Using Undo and Redo\n\nTrix 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.\n\nCall the `editor.undo` and `editor.redo` methods to perform an undo or redo operation.\n\n```js\nelement.editor.undo()\nelement.editor.redo()\n```\n\nChanges 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.\n\n```js\nelement.editor.recordUndoEntry(\"Insert Text\")\nelement.editor.insertString(\"Hello\")\n```\n\n## Loading and Saving Editor State\n\nSerialize 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.\n\n```js\n// Save editor state to local storage\nlocalStorage[\"editorState\"] = JSON.stringify(element.editor)\n\n// Restore editor state from local storage\nelement.editor.loadJSON(JSON.parse(localStorage[\"editorState\"]))\n```\n\n## HTML Sanitization\n\nTrix uses [DOMPurify](https://github.com/cure53/DOMPurify/) to sanitize the editor content. You can set the DOMPurify config via `Trix.config.dompurify`.\n\nFor example if you want to keep a custom tag, you can access do that with:\n\n```js\nTrix.config.dompurify.ADD_TAGS = [ \"my-custom-tag\" ]\n```\n\n## Observing Editor Changes\n\nThe `\u003ctrix-editor\u003e` element emits several events which you can use to observe and respond to changes in editor state.\n\n* `trix-before-initialize` fires when the `\u003ctrix-editor\u003e` 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.\n\n* `trix-initialize` fires when the `\u003ctrix-editor\u003e` element is attached to the DOM and its `editor` object is ready for use.\n\n* `trix-change` fires whenever the editor’s contents have changed.\n\n* `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.\n\n* `trix-selection-change` fires any time the selected range changes in the editor.\n\n* `trix-focus` and `trix-blur` fire when the editor gains or loses focus, respectively.\n\n* `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.\n\n* `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](http://trix-editor.org/js/attachments.js) for detailed information.\n\n* `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.\n\n* `trix-action-invoke` fires when a Trix action is invoked. You can access the `\u003ctrix-editor\u003e` 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](#invoking-external-custom-actions) actions and not for [built-in](#invoking-internal-trix-actions).\n\n# Contributing to Trix\n\nTrix is open-source software, freely distributable under the terms of an [MIT-style license](LICENSE). The [source code is hosted on GitHub](https://github.com/basecamp/trix).\n\nWe welcome contributions in the form of bug reports, pull requests, or thoughtful discussions in the [GitHub issue tracker](https://github.com/basecamp/trix/issues). Please see the [Code of Conduct](CODE_OF_CONDUCT.md) for our pledge to contributors.\n\nTrix was created by [Javan Makhmali](https://twitter.com/javan) and [Sam Stephenson](https://twitter.com/sstephenson), with development sponsored by [37signals](https://37signals.com).\n\n### Building From Source\n\nTrix uses [Yarn](https://yarnpkg.com/) to manage dependencies and [Rollup](https://rollupjs.org/guide/en/) to bundle its source.\n\nInstall development dependencies with:\n\n```\n$ yarn install\n```\n\nTo generate distribution files run:\n\n```\n$ yarn build\n```\n\n### Developing In-Browser\n\nYou can run a watch process to automatically generate distribution files when your source file change:\n\n```\n$ yarn watch\n```\n\nWhen the watch process is running you can run a web server to serve the compiled assets:\n\n```\n$ yarn dev\n```\n\nWith 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.\n\nFor easier development, you can watch for changes to the JavaScript and style files, and serve the results in a browser, with a single command:\n\n```\n$ yarn start\n```\n\n### Running Tests\n\nYou can also run the test in a headless mode with:\n\n```\n$ yarn test\n```\n\n---\n\n© 37signals, LLC.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbasecamp%2Ftrix","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fbasecamp%2Ftrix","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbasecamp%2Ftrix/lists"}