/* * This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony). * * Copyright (C) 2019 - 2025 Jan Böhmer (https://github.com/jbtronics) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see . */ import { Controller } from '@hotwired/stimulus'; import '../css/components/toggle_password.css'; export default class extends Controller { static values = { visibleLabel: { type: String, default: 'Show' }, visibleIcon: { type: String, default: 'Default' }, hiddenLabel: { type: String, default: 'Hide' }, hiddenIcon: { type: String, default: 'Default' }, buttonClasses: Array, }; isDisplayed = false; visibleIcon = ` `; hiddenIcon = ` `; connect() { if (this.visibleIconValue !== 'Default') { this.visibleIcon = this.visibleIconValue; } if (this.hiddenIconValue !== 'Default') { this.hiddenIcon = this.hiddenIconValue; } const button = this.createButton(); this.element.insertAdjacentElement('afterend', button); this.dispatchEvent('connect', { element: this.element, button }); } /** * @returns {HTMLButtonElement} */ createButton() { const button = document.createElement('button'); button.type = 'button'; button.classList.add(...this.buttonClassesValue); button.setAttribute('tabindex', '-1'); button.addEventListener('click', this.toggle.bind(this)); button.innerHTML = `${this.visibleIcon} ${this.visibleLabelValue}`; return button; } /** * Toggle input type between "text" or "password" and update label accordingly */ toggle(event) { this.isDisplayed = !this.isDisplayed; const toggleButtonElement = event.currentTarget; toggleButtonElement.innerHTML = this.isDisplayed ? `${this.hiddenIcon} ${this.hiddenLabelValue}` : `${this.visibleIcon} ${this.visibleLabelValue}`; this.element.setAttribute('type', this.isDisplayed ? 'text' : 'password'); this.dispatchEvent(this.isDisplayed ? 'show' : 'hide', { element: this.element, button: toggleButtonElement }); } dispatchEvent(name, payload) { this.dispatch(name, { detail: payload, prefix: 'toggle-password' }); } }