UNPKG

@stimulus-library/controllers

Version:

A library of useful controllers for Stimulus

77 lines (76 loc) 2.83 kB
import { BaseController, debounce, isHTMLTextAreaElement, requestSubmit } from "@stimulus-library/utilities"; import { useEventListener } from "@stimulus-library/mixins"; export class AutoSubmitFormController extends BaseController { get _eventModes() { if (this.hasEventModeValue) { const modes = this.eventModeValue.split(" ").map(mode => mode.trim()); if (modes.length === 1 && modes[0] === "debounced") { return ["change", "input"]; } if (!modes.every(mode => ["change", "input"].includes(mode))) { throw new Error(`The modeValue provided '${this.eventModeValue}' is not one of the recognised configuration options`); } return modes; } else { return ["change"]; } } get _debounceTimeout() { return this.hasDebounceIntervalValue ? this.debounceIntervalValue : -1; } get _mode() { if (this.hasSubmitModeValue) { if (!["direct", "request"].includes(this.submitModeValue)) { throw new Error(`The modeValue provided '${this.submitModeValue}' is not one of the recognised configuration options`); } return this.submitModeValue; } else { return "request"; } } get inputElements() { const el = this.el; let subElements = Array.from(el.elements); subElements = subElements.filter(el => { return !this._ancestorIsTrix(el) && el.dataset.noAutosubmit == undefined; }); return subElements; } initialize() { if (this._debounceTimeout > 0) { this.submit = debounce.call(this, this.submit.bind(this), this._debounceTimeout, false, "autoSubmitTimeout"); } } connect() { this.inputElements.forEach(el => { useEventListener(this, el, "keypress", this.handleDeliberateKeyPress); useEventListener(this, el, this._eventModes, this.submit); }); } _ancestorIsTrix(element) { return element.closest("trix-toolbar") !== null && element.closest("trix-editor") !== null; } submit() { const el = this.el; if (this._mode == "request") { requestSubmit(el); } else { el.submit(); } } handleDeliberateKeyPress(event) { if (event.key === "Enter") { let target = event.target; if (isHTMLTextAreaElement(target) || this._ancestorIsTrix(target)) { return; } if (this.autoSubmitTimeout) { clearTimeout(this.autoSubmitTimeout); } } } } AutoSubmitFormController.values = { submitMode: String, eventMode: String, debounceInterval: Number };