import { defineWebComponent, JBBaseComponent, createInputEvent, createKeyboardEvent, listenAndSilentEvent, parseBooleanAttribute } from "jb-core"; import "jb-icons/close"; import CSS from "./jb-input.css"; import VariablesCSS from "./variables.css"; import { type ValidationItem, type ValidationResult, type WithValidation, ValidationHelper, type ShowValidationErrorParameters } from 'jb-validation'; import type { JBFormInputStandards } from 'jb-form'; import type { ValueSetterEventType, ElementsObject, JBInputValue, StandardValueCallbackFunc, ValidationValue, SupportedState, } from "./types"; import { renderClearButtonHTML, renderHTML } from "./render"; import { registerDefaultVariables } from 'jb-core/theme'; import { getRequiredMessage, i18n } from 'jb-core/i18n'; export class JBInputWebComponent extends JBBaseComponent implements WithValidation, JBFormInputStandards { static get formAssociated() { return true; } #value: JBInputValue = { displayValue: "", value: "" }; elements!: ElementsObject; #disabled = false; get disabled() { return this.#disabled; } get form(){ return this.#internals.form; } #clearable = false; get clearable() { return this.#clearable; } set clearable(value: boolean) { this.#clearable = value; this.#updateClearButton(); } set disabled(value: boolean) { this.#disabled = value; this.elements.input.disabled = value; this.#updateClearButton(); if (this.#internals) if (value) { this.#internals.states?.add("disabled"); this.#internals.ariaDisabled = "true"; } else { this.#internals.states?.delete("disabled"); this.#internals.ariaDisabled = "false"; } } #required = false; set required(value: boolean) { this.#required = value; this.elements.input.required = value; if (this.#internals) this.#internals.ariaRequired = value ? "true" : "false"; this.#checkValidity(false); } get required() { return this.#required; } #internals!: ElementInternals; hasState(state: SupportedState): boolean { return this.#internals.states.has(state); } /** * @description will determine if component trigger jb-validation mechanism automatically on user event or it just let user-developer handle validation mechanism by himself */ get isAutoValidationDisabled(): boolean { //currently we only support disable-validation in attribute and only in initiate time but later we can add support for change of this return parseBooleanAttribute(this.getAttribute('disable-auto-validation')); } #checkValidity(showError: boolean) { if (!this.isAutoValidationDisabled) { if(this.#internals.states.has("invalid")){ // if we currently showing error to user it make sure error get updated (when failed validation changed of function return different string as an error) showError=true; } return this.#validation.checkValidity({ showError }); } } #validation = new ValidationHelper({ clearValidationError: () => this.clearValidationError(), showValidationError: this.showValidationError.bind(this), getValue: () => this.#value, getValidations: this.#getInsideValidation.bind(this), getValueString: () => this.#value.displayValue, setValidationResult: this.#setValidationResult.bind(this) }); get validation() { return this.#validation; } get displayValue() { return this.#value.displayValue; } get value(): string { //do not write any logic or task here this function will be overrides by other inputs like mobile input or payment input return this.#value.value; } //do not call it from inside and use #setValue in inside set value(value: string) { //do not write any logic or task here this function will be overrides by other inputs like mobile input or payment input this.#isDirty = true; this.#setValue(value, "SET_VALUE"); } #setValue(value: string | null, eventType: ValueSetterEventType) { if (value === null || value === undefined) { this.#clearValue(eventType); return; } const standardValue = this.standardValue(value, eventType); this.#setValueByObject(standardValue); } /** * Re-applies a value after an internal configuration change without treating * that reformatting as a consumer-provided live value. */ protected setValueFromInternal(value: string | null, eventType: ValueSetterEventType = "SET_VALUE") { // Some formatters change the canonical domain as well as presentation // (CARD -> SHABA, for example). Transform the reset baseline with the same // configuration so reset and isDirty keep comparing equivalent values. this.#initialValue = this.standardValue(this.#initialValue, eventType).value; this.#setValue(value, eventType); } #setValueByObject(valueOnj: JBInputValue) { this.#value = valueOnj; this.#updateFormValue(); this.elements.input.value = valueOnj.displayValue; this.#updateClearButton(); } #clearValue(eventType: ValueSetterEventType = "SET_VALUE") { this.#setValueByObject(this.standardValue("", eventType)); } #updateFormValue() { if (this.#internals && typeof this.#internals.setFormValue == "function") { this.#internals.setFormValue(this.#value.value); } } #initialValue = ""; // Tracks whether the live value has been explicitly set. This is separate // from the public isDirty comparison against initialValue. #isDirty = false; get initialValue() { return this.#initialValue; } set initialValue(value: string) { // Keep the reset baseline in the same canonical form as the live value. // Derived inputs may remove separators or convert Persian digits here. const standardValue = this.standardValue(value ?? "", "SET_VALUE"); this.#initialValue = standardValue.value; if (!this.#isDirty) { this.#setValueByObject(standardValue); } } reset() { this.#isDirty = false; this.#setValue(this.initialValue, "SET_VALUE"); this.#validation.reset(); this.#internals?.setValidity({}, ''); } formResetCallback() { this.reset(); } formDisabledCallback(disabled: boolean) { this.disabled = disabled; } get isDirty(): boolean { return this.#value.value !== this.initialValue; } //selection input behavior get selectionStart(): number|null { return this.elements.input.selectionStart; } set selectionStart(value: number) { this.elements.input.selectionStart = value; } get selectionEnd(): number|null { return this.elements.input.selectionEnd; } set selectionEnd(value: number) { this.elements.input.selectionEnd = value; } get selectionDirection(): SelectionDirection | null { return this.elements.input.selectionDirection; } set selectionDirection(value: "forward" | "backward" | "none") { this.elements.input.selectionDirection = value; } get name():string{ return this.getAttribute('name') || ""; } set name(value: string | null) { if (value) { this.setAttribute('name', value) } else { this.removeAttribute('name') } } // end of selection input behavior constructor() { super(); if (typeof this.attachInternals == "function") { //some browser dont support attachInternals this.#internals = this.attachInternals(); this.#internals.role = "textbox" } this.#initWebComponent(); } connectedCallback(): void { // standard web component event that called when all of dom is banded this.#callOnLoadEvent(); this.initProp(); this.#callOnInitEvent(); } #callOnLoadEvent(): void { const event = new CustomEvent("load", { bubbles: true, composed: true }); this.dispatchEvent(event); } #callOnInitEvent(): void { const event = new CustomEvent("init", { bubbles: true, composed: false }); this.dispatchEvent(event); } #initWebComponent(): void { const shadowRoot = this.attachShadow({ mode: "open", delegatesFocus: true, serializable: true, }); registerDefaultVariables(); this.#render(); this.elements = { input: shadowRoot.querySelector(".control input")!, inputBox: shadowRoot.querySelector(".control")!, clearButton: null, label: shadowRoot.querySelector("label")!, messageBox: shadowRoot.querySelector(".message-box")!, slots: { inlineStart: shadowRoot.querySelector(".jb-input-inline-start-wrapper slot")!, inlineEnd: shadowRoot.querySelector(".jb-input-inline-end-wrapper slot")! } }; this.#registerEventListener(); } #render() { const html = `\n${renderHTML()}`; const element = document.createElement("template"); element.innerHTML = html; this.shadowRoot?.appendChild(element.content.cloneNode(true)); } #standardValueCallbacks: StandardValueCallbackFunc[] = [] addStandardValueCallback(func: StandardValueCallbackFunc) { this.#standardValueCallbacks.push(func); } /** * @description this function will get user inputted or pasted text and convert it to standard one base on developer config */ standardValue(valueString: string | number, eventType: ValueSetterEventType): JBInputValue { let standardValue: JBInputValue = { displayValue: valueString.toString(), value: valueString.toString(), }; standardValue = this.#standardValueCallbacks.reduce((acc, func) => { const res = func(valueString.toString(), this.#value, acc, eventType); return res; }, standardValue); return standardValue; } #registerEventListener(): void { this.elements.input.addEventListener("change", (e: Event) => this.#onInputChange(e), { capture: false }); this.elements.input.addEventListener("beforeinput", this.#onInputBeforeInput.bind(this), { capture: false }); this.elements.input.addEventListener("input", (e) => this.#onInputInput(e as InputEvent), { capture: false }); this.elements.input.addEventListener("blur", () => this.#onInputBlur(), { capture: false, passive: true }); //because keyboard event are composable and will scape from shadow dom we need to listen to them in document and stop their propagation listenAndSilentEvent(this.elements.input, "keyup", this.#onInputKeyUp.bind(this)); listenAndSilentEvent(this.elements.input, "keydown", this.#onInputKeyDown.bind(this)); listenAndSilentEvent(this.elements.input, "keypress", this.#onInputKeyPress.bind(this)); // by click on label input get focus this.elements.label.addEventListener("click", () => this.focus(), { capture: false, passive: true }); } initProp() { const valueAttribute = this.getAttribute("value"); if (valueAttribute !== null) { this.value = valueAttribute; } } static get observedAttributes(): string[] { return [ "label", "type", "message", "value", "name", "autocomplete", "placeholder", "clearable", "disabled", "inputmode", "readonly", 'disable-auto-validation', "virtualkeyboardpolicy", "required", "error", "size" ]; } //please do not add any other functionality in this func because it may override by enstatite d component attributeChangedCallback(name: string, _oldValue: string, newValue: string): void { // do something when an attribute has changed this.onAttributeChange(name, newValue); } protected onAttributeChange(name: string, value: string): void { switch (name) { case "name": case "autocomplete": case "inputmode": case "virtualkeyboardpolicy": this.elements.input.setAttribute(name, value); break; case "readonly": this.hasAttribute("readonly") ? this.elements.input.setAttribute("readonly", "") : this.elements.input.removeAttribute("readonly"); this.#updateClearButton(); break; case "label": this.elements.label.innerHTML = value; this.#internals.ariaLabel = value; break; case "type": this.elements.input.setAttribute("type", value); if (value == "number") { if (this.getAttribute("inputmode") == null) { this.setAttribute("inputmode", "numeric"); } } break; case "message": this.#internals.ariaDescription = value; if (!this.elements.messageBox.classList.contains("error")) { this.elements.messageBox.innerHTML = value; } break; case "value": this.value = value; break; case "placeholder": this.elements.input.placeholder = value; this.#internals.ariaPlaceholder = value; break; case "clearable": this.clearable = parseBooleanAttribute(value); break; case "disabled": this.disabled = parseBooleanAttribute(value); break; case "required": this.required = parseBooleanAttribute(value); break; case "error": //to check error and show or clear error message base on error attribute this.reportValidity(); } } #onInputBlur() { this.#checkValidity(true); } #updateClearButton() { if (!this.#clearable) { this.elements.clearButton?.remove(); this.elements.clearButton = null; return; } if (!this.elements.clearButton) { const template = document.createElement("template"); template.innerHTML = renderClearButtonHTML(); const clearButton = template.content.firstElementChild as HTMLButtonElement; clearButton.addEventListener("mousedown", (event) => event.preventDefault()); clearButton.addEventListener("click", this.#onClearButtonClick.bind(this)); this.elements.clearButton = clearButton; } this.elements.clearButton.hidden = this.#value.value.length === 0 || this.#disabled || this.hasAttribute("readonly"); if (!this.elements.clearButton.parentElement) { this.elements.slots.inlineEnd.before(this.elements.clearButton); } } #onClearButtonClick(e: MouseEvent) { e.preventDefault(); const eventInit: InputEventInit = { bubbles: true, composed: true, data: null, inputType: "deleteContentBackward" }; const beforeInputEvent = new InputEvent("beforeinput", { ...eventInit, cancelable: true }); if (this.#dispatchBeforeInputEvent(beforeInputEvent)) return; this.#isDirty = true; this.#clearValue("INPUT"); this.#checkValidity(true); this.#dispatchOnInputEvent(new InputEvent("input", { ...eventInit, cancelable: true })); this.#dispatchOnChangeEvent(new Event("change", { bubbles: true, composed: true })); } #onInputKeyDown(e: KeyboardEvent): void { this.#dispatchKeydownEvent(e); } #dispatchKeydownEvent(e: KeyboardEvent) { e.stopPropagation(); //trigger component event const event = createKeyboardEvent("keydown", e, { cancelable: true }); const isPrevented = !this.dispatchEvent(event); if (isPrevented) { e.preventDefault(); } } #onInputKeyPress(e: KeyboardEvent): void { e.stopPropagation(); const event = createKeyboardEvent("keypress", e, { cancelable: false }); this.dispatchEvent(event); } #onInputKeyUp(e: KeyboardEvent): void { this.#dispatchKeyupEvent(e); if (e.keyCode == 13) { this.#onInputEnter(e); } } #dispatchKeyupEvent(e: KeyboardEvent) { e.stopPropagation(); const event = createKeyboardEvent("keyup", e, { cancelable: false }); this.dispatchEvent(event); } #onInputEnter(e: KeyboardEvent): void { const event = createKeyboardEvent("enter", e, { cancelable: false }) this.dispatchEvent(event); } /** * * @param {InputEvent} e */ #onInputInput(e: InputEvent): void { const endCaretPos = (e.target as HTMLInputElement).selectionEnd || 0; const _startCaretPos = (e.target as HTMLInputElement).selectionStart || 0; const inputText = (e.target as HTMLInputElement).value; const target = (e.target as HTMLInputElement); //to standard value again this.#isDirty = true; this.#setValue(inputText, "INPUT"); //if user type in middle of text we will return the caret position to the middle of text because this.value = inputText will move caret to end if (endCaretPos !== inputText.length) { //because number input does not support setSelectionRange const typeAttr = this.getAttribute('type') if (!typeAttr || !['number'].includes(typeAttr)) { target.setSelectionRange(endCaretPos, endCaretPos); } } //e.target.setSelectionRange(startCaretPos + e.data, endCaretPos); this.#checkValidity(false); this.#dispatchOnInputEvent(e); } #dispatchOnInputEvent(e: InputEvent): void { e.stopPropagation(); const event = createInputEvent('input', e, { cancelable: false }); this.dispatchEvent(event); } #onInputBeforeInput(e: InputEvent): void { this.#dispatchBeforeInputEvent(e); } #dispatchBeforeInputEvent(e: InputEvent): boolean { e.stopPropagation(); const event = createInputEvent('beforeinput', e, { cancelable: true }); this.dispatchEvent(event); if (event.defaultPrevented) { e.preventDefault(); } return event.defaultPrevented; } #onInputChange(e: Event): void { const inputText = (e.target as HTMLInputElement).value; //here is the rare time we update value directly because we want trigger event that may read value directly from dom const oldValue = this.#value; const wasDirty = this.#isDirty; this.#isDirty = true; this.#setValue(inputText, "CHANGE"); this.#checkValidity(true); const isCanceled = this.#dispatchOnChangeEvent(e); if (isCanceled) { this.#value = oldValue; this.#updateFormValue(); this.#isDirty = wasDirty; e.preventDefault(); } } #dispatchOnChangeEvent(e: Event): boolean { e.stopPropagation(); const eventInit: EventInit = { bubbles: e.bubbles, cancelable: e.cancelable, composed: e.composed }; const event = new Event("change", eventInit); this.dispatchEvent(event); if (event.defaultPrevented) { return true; } return false; } /** * show validation message error under input box * @public */ showValidationError(error: ShowValidationErrorParameters) { this.elements.messageBox.innerHTML = error.message; this.elements.input.setAttribute("aria-invalid", "true"); this.elements.input.setAttribute("aria-errormessage", "message"); //invalid state is used for ui purpose this.#internals.states?.add("invalid"); this.#internals.ariaInvalid = "true" } /** * clear validation message error showing under input box * @public */ clearValidationError() { const text = this.getAttribute("message") || ""; this.elements.messageBox.innerHTML = text; this.elements.input.setAttribute("aria-invalid", "false"); this.elements.input.removeAttribute("aria-errormessage"); this.#internals.states?.delete("invalid"); this.#internals.ariaInvalid = "false" } /** * @public */ focus() { //public method this.elements.input.focus(); } setSelectionRange(start: number | null, end: number | null, direction?: "forward" | "backward" | "none") { this.elements.input.setSelectionRange(start, end, direction); } #getInsideValidation(): ValidationItem[] { const validationList: ValidationItem[] = []; if (this.required) { const message: string = this.getAttribute("required")??"".length > 0 ? this.getAttribute("required")! : getRequiredMessage(i18n, this.getAttribute("label")) validationList.push({ validator: /.{1}/g, message, stateType: "valueMissing" }); } const errorAttribute = this.getAttribute("error") if(errorAttribute && errorAttribute.trim().length > 0) { validationList.push({ validator: undefined, message: errorAttribute, stateType: "customError" }); } return validationList; } /** * @public * @description this method used to check for validity but doesn't show error to user and just return the result * this method used by #internal of component */ checkValidity(): boolean { const validationResult = this.#validation.checkValiditySync({ showError: false }); if (!validationResult.isAllValid) { const event = new CustomEvent('invalid'); this.dispatchEvent(event); } return validationResult.isAllValid; } /** * @public * @description this method used to check for validity and show error to user */ reportValidity(): boolean { const validationResult = this.#validation.checkValiditySync({ showError: true }); if (!validationResult.isAllValid) { const event = new CustomEvent('invalid'); this.dispatchEvent(event); } return validationResult.isAllValid; } /** * @description this method called on every checkValidity calls and update validation result of #internal */ #setValidationResult(result: ValidationResult) { if (result.isAllValid) { this.#internals.setValidity({}, ''); } else { const states: ValidityStateFlags = {}; let message = ""; result.validationList.forEach((res) => { if (!res.isValid) { if (res.validation.stateType) { states[res.validation.stateType] = true; } if (message == '') { message = res.message??""; } } }); this.#internals.setValidity(states, message); } } get validationMessage() { return this.#internals.validationMessage; } get validity() { return this.#internals.validity; } } defineWebComponent("jb-input", JBInputWebComponent); declare global { interface HTMLElementTagNameMap { "jb-input": JBInputWebComponent; } }