diff --git a/README.md b/README.md index 0133f94a3..de851e70f 100644 --- a/README.md +++ b/README.md @@ -101,6 +101,22 @@ To store attachments, listen for the `trix-attachment-add` event. Upload the att 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. +## Limiting Accept Attachment File Types + +Trix accepts all file types as an attachment by default. You can configure it with the `trix-attachment-accept` attribute, which takes a comma-separated list of allowed file extensions or MIME types. + +```html + +``` + +```html + +``` + +```html + +``` + # Editing Text Programmatically You can manipulate a Trix editor programmatically through the `Trix.Editor` interface, available on each `` element through its `editor` property. diff --git a/src/trix/config/input.js b/src/trix/config/input.js index dadc163a1..fd5233667 100644 --- a/src/trix/config/input.js +++ b/src/trix/config/input.js @@ -3,6 +3,8 @@ import { makeElement, removeNode } from "trix/core/helpers/dom" const input = { level2Enabled: true, + fileInputId: `trix-file-input-${Date.now().toString(16)}`, + acceptedFileTypes: "*", getLevel() { if (this.level2Enabled && browser.supportsInputEvents) { @@ -11,16 +13,18 @@ const input = { return 0 } }, - pickFiles(callback) { - const input = makeElement("input", { type: "file", multiple: true, hidden: true, id: this.fileInputId }) + pickFiles(editorController) { + const editorElement = editorController.element + const acceptTypes = editorElement.getAttribute("trix-attachment-accept") || this.acceptedFileTypes + const input = makeElement("input", { type: "file", multiple: true, hidden: true, id: this.fileInputId, accept: acceptTypes }) input.addEventListener("change", () => { - callback(input.files) + editorController.insertFiles(input.files) removeNode(input) }) removeNode(document.getElementById(this.fileInputId)) - document.body.appendChild(input) + editorElement.parentNode.appendChild(input) input.click() } } diff --git a/src/trix/controllers/editor_controller.js b/src/trix/controllers/editor_controller.js index 6f469db5a..44eb1f740 100644 --- a/src/trix/controllers/editor_controller.js +++ b/src/trix/controllers/editor_controller.js @@ -64,7 +64,7 @@ export default class EditorController extends Controller { return true }, perform() { - return config.input.pickFiles(this.editor.insertFiles) + return config.input.pickFiles(this.editor) }, }, }