UNPKG

@postnord/web-components

Version:
970 lines (969 loc) 39.3 kB
/*! * Built with Stencil * By PostNord. */ import { h, Host, forceUpdate } from "@stencil/core"; import { uuidv4, en, awaitTopbar } from "../../../index"; import { alert_exclamation_circle, check, close, preview_on, preview_off } from "pn-design-assets/pn-assets/icons.js"; import { translations } from "./translations"; /** * The `pn-input` is a regular `input` but styled. This means you can use native events to listen to the changes. * Always use the `label` prop to make sure the input is accessible. * * @nativeInput Use the `input` event to listen to content being modified by the user. It is emitted everytime a user writes or removes content in the input. * @nativeChange The `change` event is emitted when the input loses focus, the user clicks `Enter` or makes a selection (such as auto complete or suggestions). * * @slot helpertext - You can use this slot instead of the prop `helpertext`. Recommended, only if you need to include additional HTML markup. * Such as a `pn-text-link`. Use a `span` element to wrap the text and link. {@since v7.2.0} * @slot error - You can use this slot instead of the prop `error`. Recommended, only if you need to include additional HTML markup. * Such as a `pn-text-link`. Use a `span` element to wrap the text and link. {@since v7.2.0} */ export class PnInput { id = `pn-input-${uuidv4()}`; idMessage = `${this.id}-message`; prefix; suffix; mo; hostElement; offsetLeft = 0; offsetRight = 0; showHelperSlot = false; showErrorSlot = false; showPassword = false; togglePassword() { this.showPassword = !this.showPassword; } /** Text label placed above the input field. */ label; /** Text message placed underneath the input field. */ helpertext; /** * Provide a unique HTML id to connect the input with the label. * A unique uuid ID will be generated if this field is left empty. **/ inputid = this.id; /** Set the value of the input. */ value = ''; /** * Set the language manually for the translations of show/hide/clear button text. * Not needed if you have the pntopbar on the page. **/ language = null; /** Use the compact label variant. The `placeholder` you provide will not be visible if used at the same time. @since v7.21.0 */ compact = false; /** * Select an icon to display before the input field value. * `icon` takes precedence over the `text-prefix` prop. * * @see {@link textPrefix} * @category Visual **/ icon; /** * Set a small text before the input field value. * Cannot be used together with an `icon` at the same time. * * @see {@link icon} * @see {@link textSuffix} * @category Visual **/ textPrefix; /** * Set a small text after the input field value. * Cannot be used with the `text-prefix` prop at the same time. * * @see {@link textPrefix} * @category Visual **/ textSuffix; /** pn-input supports: `text`, `password`, `url`, `tel`, `search`, `number` & `email`. @category HTML input */ type = 'text'; /** * HTML input name. Setting a name will help the browser understand what type of data the input have * and can better assist with autofill data based on previous entires much better. * * @category HTML input **/ name; /** * Provide a placeholder text. Remember that this is no replacement for a label. * The placeholder should be a nice addition to the label/helpertext, not important information. * * @category HTML input **/ placeholder; /** * Let the browser know what type of autocorrects the input should use. * Works much better if a `name` and `inputid` is supplied. * @see {@link name} * @see {@link inputid} * * @category HTML input */ autocomplete; /** The maximum number of characters the user should be able to add, also adds a visible counter. @category HTML input */ maxlength; /** * Hint the browser about what type of virtual keyboard should be used. * The browser will be able to decide this on its own most of the time, * especially if you use the `type`, `name` and `inputid` props. * * Leave empty or with a `''` value if you want the browsers default behaviour (`text`). * * @category HTML input **/ inputmode; /** Point to a datalist element for this input. @category HTML input */ list; /** Pattern prop. @category HTML input*/ pattern; /** Set the `min` value of the `number` input. @category HTML input */ min; /** Set the `max` value of the `number` input. @category HTML input */ max; /** Set a `step` for the number input. @category HTML input */ step; /** While you can use the `aria-label`, using a `label` is far more accessible. @category HTML input */ arialabel; /** Set the ID of what this input controls. @category HTML input */ ariacontrols; /** Set the input as `required`. @category State */ required = false; /** Set the input as `disabled`. @category State */ disabled = false; /** Set the input as `readonly`. @category State */ readonly = false; /** Set the input as `valid`. Provides a green color and a check icon. @category Validation */ valid = false; /** * Set the input as `invalid`. Provides a red color and red warning icon. * @see{@link error Provide an error message.} * @category Validation **/ invalid = false; /** * Set the input as `invalid` and display an error message (applies the same style as `invalid`). * * Error message; will take precedence over helpertext if both are provided. * @see{@link invalid Set invalid without an error message.} * @category Validation **/ error; handleOffset() { requestAnimationFrame(() => { const left = this.prefix?.clientWidth ? this.prefix.clientWidth + 8 : 0; const right = this.suffix?.clientWidth ? this.suffix.clientWidth + 8 : 0; this.offsetLeft = left; this.offsetRight = right; }); } handleMessage() { this.checkSlottedHelper(); this.checkSlottedError(); } connectedCallback() { this.mo = new MutationObserver(() => { forceUpdate(this.hostElement); this.handleOffset(); this.handleMessage(); }); this.mo.observe(this.hostElement, { childList: true, subtree: true }); } disconnectedCallback() { if (this.mo) this.mo.disconnect(); } async componentWillLoad() { this.handleMessage(); if (this.inputid !== this.id) this.idMessage = `${this.inputid}-message`; if (this.language === null) await awaitTopbar(this.hostElement); } componentDidLoad() { this.handleOffset(); } setVal(event) { const target = event.composedPath?.()[0]; this.value = target.value; } clearVal() { const inputClear = new InputEvent('input', { bubbles: true, data: '' }); const input = this.hostElement.querySelector('input'); this.value = ''; input.focus(); input.value = this.value; input.dispatchEvent(inputClear); } translate(prop) { return translations?.[prop]?.[this.language || en]; } hasHelperText() { return this.helpertext?.length > 0 || this.showHelperSlot; } hasErrorMessage() { return this.error?.length > 0 || this.showErrorSlot; } /** If any error is active, either via the prop `invalid` or `error` prop/slot. */ hasError() { return this.hasErrorMessage() || this.invalid || this.showErrorSlot; } /** If any helpertext or error message is active. Checks both props and slots. */ hasMessage() { return this.hasHelperText() || this.hasErrorMessage(); } checkSlottedHelper() { const slottedHelper = this.hostElement.querySelector('[slot=helpertext]')?.textContent; this.showHelperSlot = !!slottedHelper?.length; } checkSlottedError() { const slottedError = this.hostElement.querySelector('[slot=error]')?.textContent; this.showErrorSlot = !!slottedError?.length; } getInputType() { const types = ['text', 'password', 'url', 'tel', 'search', 'number', 'email']; return types.includes(this.type) && !this.showPassword ? this.type : 'text'; } isPassword() { if (this.disabled) return false; return this.type === 'password' || (this.type === 'text' && this.showPassword); } passwordText() { return this.translate(this.showPassword ? 'HIDE' : 'SHOW'); } /** Check if there is a valid or error state active. Returns false if neither is true. */ displayState() { return this.valid || this.hasError(); } /** * Returns the correct icon for the current state (valid or error). * Defaults to error icon. * @see {@link displayState} */ stateIcon() { if (this.valid) return check; return alert_exclamation_circle; } /** * Returns the correct color for the validation icon. Defaults to red. * @see {@link displayState} */ stateColor() { if (this.valid) return 'green700'; return 'warning'; } showPrefix() { return this.textPrefix && !this.icon; } showSuffix() { return !this.showPrefix() && !!this.textSuffix?.length && !this.isPassword() && this.type !== 'search'; } showClear() { if (this.disabled || this.readonly) return false; return this.type === 'search' && !!this.value?.length; } validLabel() { return this.label?.length > 0 || this.maxlength >= 1; } useLabel() { return this.validLabel() && !this.compact; } /** Compact label must be positioned after the input element in order to work. */ useCompactLabel() { return this.validLabel() && this.compact; } renderLabel() { return (h("label", { htmlFor: this.inputid, class: "pn-input-label", "data-compact": this.compact }, this.label && h("span", null, this.label), this.maxlength >= 0 && h("span", null, `${this.value.length}/${this.maxlength}`))); } render() { return (h(Host, { key: '3250630450288d09811b7c78bca5091ba93ec7ab' }, h("div", { key: 'db673ba19f300966eaf5c38136fe7d6143aa661d', class: "pn-input", "data-valid": this.valid, "data-error": this.hasError(), style: { '--pn-input-offset-left': `${this.offsetLeft}px`, '--pn-input-offset-right': `${this.offsetRight}px`, } }, this.useLabel() && this.renderLabel(), h("div", { key: 'b216b7f951be237aed6e46f1ccbcfd29b2a3cad1', class: "pn-input-group" }, h("input", { key: '4ee129c35c6a74a359df9d611b236132d7afac38', type: this.getInputType(), id: this.inputid, class: "pn-input-element", name: this.name, placeholder: this.compact ? this.placeholder || ' ' : this.placeholder, autocomplete: this.autocomplete, maxlength: this.maxlength, list: this.list, pattern: this.pattern, min: this.min, max: this.max, step: this.step, value: this.value, inputmode: this.inputmode, disabled: this.disabled, required: this.required, readonly: this.readonly, "aria-label": this.arialabel, "aria-describedby": this.hasMessage() ? this.idMessage : null, "aria-controls": this.ariacontrols, "aria-invalid": this.hasError()?.toString(), "data-compact": this.compact, "data-value": this.value?.length > 0, onInput: e => this.setVal(e) }), this.useCompactLabel() && this.renderLabel(), h("div", { key: '753a9abeaf5bfa5ffb3be10042a76aa7863bce9c', class: "pn-input-eyecandy", "data-prefix": true, ref: el => (this.prefix = el) }, !!this.icon && h("pn-icon", { key: 'acf1a6e42c9d37cab6f6a0453d8ea674df1cd0c3', icon: this.icon, "aria-hidden": "true" }), this.showPrefix() && h("span", { key: '70d2eb7e94e790d665a57557595c2bce4855b827', class: "pn-input-text" }, this.textPrefix)), h("div", { key: '1dcae3fb8489d2dc6aa7325baea693591acef31c', class: "pn-input-eyecandy", "data-suffix": true, ref: el => (this.suffix = el) }, this.showSuffix() && h("span", { key: '05044f3fbea582d507de30a0ff751abaf1da3206', class: "pn-input-text" }, this.textSuffix), this.displayState() && h("pn-icon", { key: '727650c9e6c9b9da2ef43e933fab95b6adc8a6bb', "aria-hidden": "true", icon: this.stateIcon(), color: this.stateColor() }), this.isPassword() && (h("pn-button", { key: '4e28eddff11c9aea670a6764aeb0316bccba1c1c', icon: this.showPassword ? preview_on : preview_off, iconOnly: true, arialabel: this.passwordText(), small: true, appearance: "light", variant: "borderless", onClick: () => this.togglePassword() })), this.showClear() && (h("pn-button", { key: '2181adb68c152d837ef03bf9b7e0eb66eb3ea6d2', icon: close, iconOnly: true, arialabel: this.translate('CLEAR'), small: true, appearance: "light", variant: "borderless", onClick: () => this.clearVal() })))), h("p", { key: 'b8b1039a61a23efd24ebd71285b15cce7bfc5ec0', class: "pn-input-message", id: this.idMessage, role: this.hasErrorMessage() ? 'alert' : null, hidden: !this.hasMessage() }, this.hasHelperText() && !this.hasError() && h("span", { key: '4433df6b700cc40ce2ae698d2474f57163b398a1', class: "pn-input-helper" }, this.helpertext), h("span", { key: '41c8fb1cbbc17b7c349922cac2ff42244a017e0c', class: "pn-input-helper-slot", hidden: !this.showHelperSlot || this.hasError() }, h("slot", { key: '5628bbc8db75161d18ad3e75c259bf3eb5fc9052', name: "helpertext" })), this.hasErrorMessage() && h("span", { key: 'e41145d7fab9f3ae35dd428971c79673d0531301', class: "pn-input-error" }, this.error), h("span", { key: 'ae85a9420fcb449cc874eadc7a066dd772f097a9', class: "pn-input-error-slot", hidden: !this.showErrorSlot }, h("slot", { key: 'bdd31ab2f706cac6e243562d035361a381ecfa43', name: "error" })))))); } static get is() { return "pn-input"; } static get originalStyleUrls() { return { "$": ["pn-input.scss"] }; } static get styleUrls() { return { "$": ["pn-input.css"] }; } static get properties() { return { "label": { "type": "string", "mutable": false, "complexType": { "original": "string", "resolved": "string", "references": {} }, "required": true, "optional": false, "docs": { "tags": [], "text": "Text label placed above the input field." }, "getter": false, "setter": false, "reflect": false, "attribute": "label" }, "helpertext": { "type": "string", "mutable": false, "complexType": { "original": "string", "resolved": "string", "references": {} }, "required": false, "optional": true, "docs": { "tags": [], "text": "Text message placed underneath the input field." }, "getter": false, "setter": false, "reflect": false, "attribute": "helpertext" }, "inputid": { "type": "string", "mutable": false, "complexType": { "original": "string", "resolved": "string", "references": {} }, "required": false, "optional": false, "docs": { "tags": [], "text": "Provide a unique HTML id to connect the input with the label.\nA unique uuid ID will be generated if this field is left empty." }, "getter": false, "setter": false, "reflect": false, "attribute": "inputid", "defaultValue": "this.id" }, "value": { "type": "string", "mutable": true, "complexType": { "original": "string", "resolved": "string", "references": {} }, "required": false, "optional": false, "docs": { "tags": [], "text": "Set the value of the input." }, "getter": false, "setter": false, "reflect": false, "attribute": "value", "defaultValue": "''" }, "language": { "type": "string", "mutable": false, "complexType": { "original": "PnLanguages", "resolved": "\"\" | \"da\" | \"en\" | \"fi\" | \"no\" | \"sv\"", "references": { "PnLanguages": { "location": "import", "path": "@/index", "id": "src/index.ts::PnLanguages", "referenceLocation": "PnLanguages" } } }, "required": false, "optional": true, "docs": { "tags": [], "text": "Set the language manually for the translations of show/hide/clear button text.\nNot needed if you have the pntopbar on the page." }, "getter": false, "setter": false, "reflect": false, "attribute": "language", "defaultValue": "null" }, "compact": { "type": "boolean", "mutable": false, "complexType": { "original": "boolean", "resolved": "boolean", "references": {} }, "required": false, "optional": true, "docs": { "tags": [{ "name": "since", "text": "v7.21.0" }], "text": "Use the compact label variant. The `placeholder` you provide will not be visible if used at the same time." }, "getter": false, "setter": false, "reflect": false, "attribute": "compact", "defaultValue": "false" }, "icon": { "type": "string", "mutable": false, "complexType": { "original": "string", "resolved": "string", "references": {} }, "required": false, "optional": false, "docs": { "tags": [{ "name": "see", "text": "{@link textPrefix }" }, { "name": "category", "text": "Visual" }], "text": "Select an icon to display before the input field value.\n`icon` takes precedence over the `text-prefix` prop." }, "getter": false, "setter": false, "reflect": false, "attribute": "icon" }, "textPrefix": { "type": "string", "mutable": false, "complexType": { "original": "string", "resolved": "string", "references": {} }, "required": false, "optional": false, "docs": { "tags": [{ "name": "see", "text": "{@link icon }" }, { "name": "see", "text": "{@link textSuffix }" }, { "name": "category", "text": "Visual" }], "text": "Set a small text before the input field value.\nCannot be used together with an `icon` at the same time." }, "getter": false, "setter": false, "reflect": false, "attribute": "text-prefix" }, "textSuffix": { "type": "string", "mutable": false, "complexType": { "original": "string", "resolved": "string", "references": {} }, "required": false, "optional": false, "docs": { "tags": [{ "name": "see", "text": "{@link textPrefix }" }, { "name": "category", "text": "Visual" }], "text": "Set a small text after the input field value.\nCannot be used with the `text-prefix` prop at the same time." }, "getter": false, "setter": false, "reflect": false, "attribute": "text-suffix" }, "type": { "type": "string", "mutable": true, "complexType": { "original": "'text' | 'password' | 'url' | 'tel' | 'search' | 'number' | 'email' | ''", "resolved": "\"\" | \"email\" | \"number\" | \"password\" | \"search\" | \"tel\" | \"text\" | \"url\"", "references": {} }, "required": false, "optional": true, "docs": { "tags": [{ "name": "category", "text": "HTML input" }], "text": "pn-input supports: `text`, `password`, `url`, `tel`, `search`, `number` & `email`." }, "getter": false, "setter": false, "reflect": false, "attribute": "type", "defaultValue": "'text'" }, "name": { "type": "string", "mutable": false, "complexType": { "original": "string", "resolved": "string", "references": {} }, "required": false, "optional": true, "docs": { "tags": [{ "name": "category", "text": "HTML input" }], "text": "HTML input name. Setting a name will help the browser understand what type of data the input have\nand can better assist with autofill data based on previous entires much better." }, "getter": false, "setter": false, "reflect": false, "attribute": "name" }, "placeholder": { "type": "string", "mutable": false, "complexType": { "original": "string", "resolved": "string", "references": {} }, "required": false, "optional": true, "docs": { "tags": [{ "name": "category", "text": "HTML input" }], "text": "Provide a placeholder text. Remember that this is no replacement for a label.\nThe placeholder should be a nice addition to the label/helpertext, not important information." }, "getter": false, "setter": false, "reflect": false, "attribute": "placeholder" }, "autocomplete": { "type": "string", "mutable": false, "complexType": { "original": "string", "resolved": "string", "references": {} }, "required": false, "optional": true, "docs": { "tags": [{ "name": "see", "text": "{@link name }" }, { "name": "see", "text": "{@link inputid }" }, { "name": "category", "text": "HTML input" }], "text": "Let the browser know what type of autocorrects the input should use.\nWorks much better if a `name` and `inputid` is supplied." }, "getter": false, "setter": false, "reflect": false, "attribute": "autocomplete" }, "maxlength": { "type": "number", "mutable": false, "complexType": { "original": "number", "resolved": "number", "references": {} }, "required": false, "optional": false, "docs": { "tags": [{ "name": "category", "text": "HTML input" }], "text": "The maximum number of characters the user should be able to add, also adds a visible counter." }, "getter": false, "setter": false, "reflect": false, "attribute": "maxlength" }, "inputmode": { "type": "string", "mutable": false, "complexType": { "original": "'text' | 'none' | 'decimal' | 'numeric' | 'tel' | 'search' | 'email' | 'url'", "resolved": "\"decimal\" | \"email\" | \"none\" | \"numeric\" | \"search\" | \"tel\" | \"text\" | \"url\"", "references": {} }, "required": false, "optional": true, "docs": { "tags": [{ "name": "category", "text": "HTML input" }], "text": "Hint the browser about what type of virtual keyboard should be used.\nThe browser will be able to decide this on its own most of the time,\nespecially if you use the `type`, `name` and `inputid` props.\n\nLeave empty or with a `''` value if you want the browsers default behaviour (`text`)." }, "getter": false, "setter": false, "reflect": false, "attribute": "inputmode" }, "list": { "type": "string", "mutable": false, "complexType": { "original": "string", "resolved": "string", "references": {} }, "required": false, "optional": true, "docs": { "tags": [{ "name": "category", "text": "HTML input" }], "text": "Point to a datalist element for this input." }, "getter": false, "setter": false, "reflect": false, "attribute": "list" }, "pattern": { "type": "string", "mutable": false, "complexType": { "original": "string", "resolved": "string", "references": {} }, "required": false, "optional": true, "docs": { "tags": [{ "name": "category", "text": "HTML input" }], "text": "Pattern prop." }, "getter": false, "setter": false, "reflect": false, "attribute": "pattern" }, "min": { "type": "any", "mutable": false, "complexType": { "original": "number | string", "resolved": "number | string", "references": {} }, "required": false, "optional": true, "docs": { "tags": [{ "name": "category", "text": "HTML input" }], "text": "Set the `min` value of the `number` input." }, "getter": false, "setter": false, "reflect": false, "attribute": "min" }, "max": { "type": "any", "mutable": false, "complexType": { "original": "number | string", "resolved": "number | string", "references": {} }, "required": false, "optional": true, "docs": { "tags": [{ "name": "category", "text": "HTML input" }], "text": "Set the `max` value of the `number` input." }, "getter": false, "setter": false, "reflect": false, "attribute": "max" }, "step": { "type": "any", "mutable": false, "complexType": { "original": "number | string", "resolved": "number | string", "references": {} }, "required": false, "optional": true, "docs": { "tags": [{ "name": "category", "text": "HTML input" }], "text": "Set a `step` for the number input." }, "getter": false, "setter": false, "reflect": false, "attribute": "step" }, "arialabel": { "type": "string", "mutable": false, "complexType": { "original": "string", "resolved": "string", "references": {} }, "required": false, "optional": true, "docs": { "tags": [{ "name": "category", "text": "HTML input" }], "text": "While you can use the `aria-label`, using a `label` is far more accessible." }, "getter": false, "setter": false, "reflect": false, "attribute": "arialabel" }, "ariacontrols": { "type": "string", "mutable": false, "complexType": { "original": "string", "resolved": "string", "references": {} }, "required": false, "optional": true, "docs": { "tags": [{ "name": "category", "text": "HTML input" }], "text": "Set the ID of what this input controls." }, "getter": false, "setter": false, "reflect": false, "attribute": "ariacontrols" }, "required": { "type": "boolean", "mutable": false, "complexType": { "original": "boolean", "resolved": "boolean", "references": {} }, "required": false, "optional": false, "docs": { "tags": [{ "name": "category", "text": "State" }], "text": "Set the input as `required`." }, "getter": false, "setter": false, "reflect": false, "attribute": "required", "defaultValue": "false" }, "disabled": { "type": "boolean", "mutable": false, "complexType": { "original": "boolean", "resolved": "boolean", "references": {} }, "required": false, "optional": false, "docs": { "tags": [{ "name": "category", "text": "State" }], "text": "Set the input as `disabled`." }, "getter": false, "setter": false, "reflect": false, "attribute": "disabled", "defaultValue": "false" }, "readonly": { "type": "boolean", "mutable": false, "complexType": { "original": "boolean", "resolved": "boolean", "references": {} }, "required": false, "optional": false, "docs": { "tags": [{ "name": "category", "text": "State" }], "text": "Set the input as `readonly`." }, "getter": false, "setter": false, "reflect": false, "attribute": "readonly", "defaultValue": "false" }, "valid": { "type": "boolean", "mutable": false, "complexType": { "original": "boolean", "resolved": "boolean", "references": {} }, "required": false, "optional": true, "docs": { "tags": [{ "name": "category", "text": "Validation" }], "text": "Set the input as `valid`. Provides a green color and a check icon." }, "getter": false, "setter": false, "reflect": false, "attribute": "valid", "defaultValue": "false" }, "invalid": { "type": "boolean", "mutable": false, "complexType": { "original": "boolean", "resolved": "boolean", "references": {} }, "required": false, "optional": false, "docs": { "tags": [{ "name": "see", "text": "{@link error Provide an error message.}" }, { "name": "category", "text": "Validation" }], "text": "Set the input as `invalid`. Provides a red color and red warning icon." }, "getter": false, "setter": false, "reflect": false, "attribute": "invalid", "defaultValue": "false" }, "error": { "type": "string", "mutable": false, "complexType": { "original": "string", "resolved": "string", "references": {} }, "required": false, "optional": true, "docs": { "tags": [{ "name": "see", "text": "{@link invalid Set invalid without an error message.}" }, { "name": "category", "text": "Validation" }], "text": "Set the input as `invalid` and display an error message (applies the same style as `invalid`).\n\nError message; will take precedence over helpertext if both are provided." }, "getter": false, "setter": false, "reflect": false, "attribute": "error" } }; } static get states() { return { "offsetLeft": {}, "offsetRight": {}, "showHelperSlot": {}, "showErrorSlot": {}, "showPassword": {} }; } static get elementRef() { return "hostElement"; } static get watchers() { return [{ "propName": "textPrefix", "methodName": "handleOffset" }, { "propName": "textSuffix", "methodName": "handleOffset" }, { "propName": "helpertext", "methodName": "handleMessage" }, { "propName": "error", "methodName": "handleMessage" }]; } }