UNPKG

@siberiaweb/components

Version:
141 lines (140 loc) 4.01 kB
import CSS from "./CSS"; import Icon from "../icon/Icon"; import Input from "../input/Input"; /** * Поле ввода пароля. */ export default class InputPassword extends Input { /** * Конструктор. */ constructor() { super(); this.revealIcon = this.createRevealIcon(); this.initInputPasswordControl(); } /** * Наблюдаемые атрибуты. */ static get observedAttributes() { return Input.observedAttributes.concat([ InputPassword.ATTR_REVEAL ]); } /** * Вывод пароля. */ showPassword() { this.getControl().type = "text"; } /** * Скрытие пароля. */ hidePassword() { this.getControl().type = "password"; } /** * Создание значка для просмотра пароля. */ createRevealIcon() { let icon = document.createElement(Icon.COMPONENT_NAME); icon.classList.add(CSS.REVEAL_ICON); icon.addEventListener("mousedown", (event) => { if (this.disabled) { return; } if ((event.button === 0) && !(event.altKey || event.ctrlKey || event.shiftKey)) { this.showPassword(); event.preventDefault(); } }); icon.addEventListener("mouseup", (event) => { this.hidePassword(); event.preventDefault(); }); icon.addEventListener("mouseleave", () => { this.hidePassword(); }); return icon; } /** * Вывод или скрытие значка для просмотра пароля. */ checkDisplayRevealIcon() { if (this.reveal) { if (this.isEmpty()) { this.revealIcon.remove(); } else { this.addTrailingIcon(this.revealIcon); } } else { this.revealIcon.remove(); } } /** * Инициализация элемента управления. */ initInputPasswordControl() { this.getControl().type = "password"; this.getControl().addEventListener("copy", (event) => { event.preventDefault(); }); this.getControl().addEventListener("input", () => { this.checkDisplayRevealIcon(); }); } /** * @override */ firstConnectedCallback() { super.firstConnectedCallback(); this.classList.add(CSS.INPUT_PASSWORD); } /** * Обработка изменения атрибута "reveal". */ attrRevealChange() { this.checkDisplayRevealIcon(); } /** * @override */ attrValueChange(newValue) { super.attrValueChange(newValue); this.checkDisplayRevealIcon(); } /** * @override */ attributeChangedCallback(name, oldValue, newValue) { super.attributeChangedCallback(name, oldValue, newValue); if (name === InputPassword.ATTR_REVEAL) { this.attrRevealChange(); } } /** * Получение признака разрешения просмотра пароля. */ get reveal() { return this.hasAttribute(InputPassword.ATTR_REVEAL); } /** * Установка признака разрешения просмотра пароля. * * @param value Значение. */ set reveal(value) { this.toggleAttribute(InputPassword.ATTR_REVEAL, value); } } /** * Наименование компонента. */ InputPassword.COMPONENT_NAME = "sw-input-password"; /** * Разрешение просмотра пароля. */ InputPassword.ATTR_REVEAL = "reveal"; InputPassword.define(Icon);