From ff5210a891950c1a43e3b01740d9f19b008cbfa6 Mon Sep 17 00:00:00 2001 From: Andreas Nedbal Date: Sun, 2 Oct 2022 22:09:34 +0200 Subject: [PATCH] Implement character count as Stimulus controller --- .../controllers/character_count_controller.ts | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 app/javascript/retrospring/controllers/character_count_controller.ts diff --git a/app/javascript/retrospring/controllers/character_count_controller.ts b/app/javascript/retrospring/controllers/character_count_controller.ts new file mode 100644 index 00000000..885c8984 --- /dev/null +++ b/app/javascript/retrospring/controllers/character_count_controller.ts @@ -0,0 +1,36 @@ +import { Controller } from '@hotwired/stimulus'; + +export default class extends Controller { + static targets = ['input', 'counter', 'action']; + + declare readonly inputTarget: HTMLInputElement; + declare readonly counterTarget: HTMLElement; + declare readonly actionTarget: HTMLInputElement; + + static values = { + max: Number + }; + + declare readonly maxValue: number; + + connect(): void { + this.inputTarget.addEventListener('input', this.update.bind(this)); + } + + update(): void { + this.counterTarget.innerHTML = String(`${this.inputTarget.value.length} / ${this.maxValue}`); + + if (this.inputTarget.value.length > this.maxValue) { + if (!this.inputTarget.classList.contains('is-invalid') && !this.actionTarget.disabled) { + this.inputTarget.classList.add('is-invalid'); + this.actionTarget.disabled = true; + } + } + else { + if (this.inputTarget.classList.contains('is-invalid') && this.actionTarget.disabled) { + this.inputTarget.classList.remove('is-invalid'); + this.actionTarget.disabled = false; + } + } + } +}