UNPKG

@postnord/web-components

Version:
906 lines (905 loc) 36.5 kB
/*! * Built with Stencil * By PostNord. */ import { uuidv4 } from "../../../globals/helpers"; import { Fragment, Host, forceUpdate, h, } from "@stencil/core"; /** * Allow the user to use the slider to set a number value. Its built on the native `input[type=range]` element and * has support for most attributes. * * @slot helpertext - Set the helpertext via a slot instead of prop. Wrap the content like this: `<span slot="helpertext">`. * @slot error - Set the error message via a slot instead of prop. Wrap the content like this: `<span slot="error">`. * * @nativeInput Use the `input` event to listen to the range / input value being modified by the user. It is emitted everytime the user changes the value. * @nativeChange The `change` event is emitted when the user makes a final selection (letting go of the range/input). * * @since v7.20.0 */ export class PnRange { id = `pn-range-${uuidv4()}`; idEnd = `${this.id}-end`; idInput = `${this.id}-input`; idInputEnd = `${this.idEnd}-input`; idInputHidden = `${this.id}-hidden`; idHelpertext = `${this.id}-helpertext`; idError = `${this.id}-error`; idDatalist = `${this.id}-data`; mo; rangeTimeout; tooltipDefault = '{value}'; hostElement; showHelperSlot = false; showErrorSlot = false; /** If true, remove transition times. */ isPressing = false; /** When using `multiple`, decide which control is being pressed. */ pressControl = null; /** Label for the range input. */ label; /** Label for the range end input. */ labelEnd; /** Set a helpertext for the range input. */ helpertext = null; /** * Add markers. This will also render a `datalist` element with `options`. * Omitting the `label` for a marker will use the `value` as label instead. * Set `label` to `null` or `''` to hide it completely. */ markers = []; /** Set a prefix for the range/input field. */ textPrefix = null; /** Set a suffix for the range/input field. */ textSuffix = null; /** Set an icon for the range/input field. */ icon = null; /** Set an icon at the end of the range or for the second input field when using `multiple`. */ iconEnd = null; /** Set a custom HTML id. */ pnId = this.id; /** Set a custom HTML id. */ pnIdEnd = this.idEnd; /** The range input name. @category HTML Attributes */ name; /** The range input name. @category HTML Attributes */ nameEnd; /** The range input min value. @category HTML Attributes */ min = 0; /** The range input max value. @category HTML Attributes */ max = 100; /** The range input value. @category HTML Attributes */ value = 0; /** The range end input value. @category HTML Attributes */ valueEnd = 0; /** Set a step value for the range input. @category HTML Attributes */ step = ''; /** * Allow multiple values to be selected * @category Features */ multiple = false; /** * Display an input for the range value. * Allowing the user to type or use the slider to set the value. * @category Features */ input = false; /** Hide the tooltip. @category Features */ tooltipHide = false; /** * Range tooltip label template. Default is simply the value of the range input. * @example * // Show a suffixed '%' in the tooltip with '{value} %'. * <pn-range tooltip-template="{value} %" value="25" /> * @category Features */ tooltipTemplate = this.tooltipDefault; /** Disable the range input. @category State */ disabled = false; /** Set an error message for the range input. @category State */ error = null; /** Set the error visual for the range input, same as `error`, but without a message. @category State */ invalid = false; handleValue() { if (this.multiple && this.value > this.valueEnd) { this.valueEnd = this.value; } const percentage = this.calcPercentage(this.value); requestAnimationFrame(() => this.hostElement.style.setProperty('--pn-range-progress', `${percentage}%`)); } handleValueEnd() { if (!this.multiple) return; if (this.value > this.valueEnd) { this.value = this.valueEnd; } const percentage = this.calcPercentage(this.valueEnd); requestAnimationFrame(() => this.hostElement.style.setProperty('--pn-range-progress-end', `${percentage}%`)); } handleId() { this.idHelpertext = `${this.pnId}-helpertext`; this.idError = `${this.pnId}-error`; this.idDatalist = `${this.pnId}-data`; } handleMessage() { this.checkSlottedHelper(); this.checkSlottedError(); } handleMultiple() { this.isPressing = true; requestAnimationFrame(() => (this.isPressing = false)); } /** Emitted as the user makes any changes to the range/input value. */ rangeSelected; connectedCallback() { this.mo = new MutationObserver(() => forceUpdate(this.hostElement)); this.mo.observe(this.hostElement, { childList: true, subtree: true }); } disconnectedCallback() { if (this.mo) this.mo.disconnect(); } tooltipDirection(isEnd = false) { if (this.multiple) { const isSmall = this.hostElement.offsetWidth < 384; const percentageStart = this.calcPercentage(this.value); const percentageEnd = this.calcPercentage(this.valueEnd); const isClose = Math.abs(percentageEnd - percentageStart) < (isSmall ? 30 : 20); if (isClose) return isEnd ? 'left' : 'right'; if (!isEnd && this.value <= this.min + (this.max - this.min) * (isSmall ? 0.3 : 0.2)) return 'left'; if (isEnd && this.valueEnd > this.max * (isSmall ? 0.75 : 0.8)) return 'right'; } return 'center'; } isActiveMarker(value) { const isActive = this.value === value; if (this.multiple) return isActive || this.valueEnd === value; return isActive; } hasHelperText() { return this.helpertext?.length > 0 || this.showHelperSlot; } /** If any `error` text is present, either via prop/slot. */ 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; } 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; } calcPercentage(value) { return ((value - this.min) / (this.max - this.min)) * 100; } setValue(value, isEnd = false) { const isWithinMinMax = value >= this.min && value <= this.max; if (!isWithinMinMax) return; if (isEnd) this.valueEnd = value; else this.value = value; const range = Number((this.valueEnd - this.value).toPrecision(4)); const percentageStart = this.calcPercentage(this.value); const percentageEnd = this.calcPercentage(this.valueEnd); const percentage = Number((this.multiple ? percentageEnd - percentageStart : percentageStart).toPrecision(4)); const rangeDetail = this.multiple ? { valueEnd: this.valueEnd, difference: range, } : {}; this.rangeSelected.emit({ value: this.value, percentage, ...rangeDetail, }); } getTooltipLabel(isEnd = false) { return this.tooltipTemplate?.replace(this.tooltipDefault, (isEnd ? this.valueEnd : this.value)?.toString()); } getMarkerLabel({ value, label }) { if (label === null || label === '') return ''; return (label || value).toString(); } ariaDescribedby() { const list = []; if (this.hasErrorMessage()) list.push(this.idError); else if (this.hasHelperText()) list.push(this.idHelpertext); return list.length ? list.join(' ') : null; } handleChange(event) { const target = event.target; const { id, valueAsNumber, type } = target; const numberValue = isNaN(valueAsNumber) ? 0 : valueAsNumber; const isEnd = type === 'range' ? id === this.pnIdEnd : id === this.idInputEnd; this.setValue(numberValue, isEnd); } setListeners(isOverlay = false) { const inputEvent = (event) => (isOverlay ? this.handleOverlayInput(event) : this.handleChange(event)); return { onInput: inputEvent, onTouchStart: (e) => this.handlePress(e), onTouchEnd: () => this.handleRelease(), onMouseDown: (e) => this.handlePress(e), onMouseUp: () => this.handleRelease(), }; } handlePress(event) { this.rangeTimeout = setTimeout(() => { this.isPressing = true; }, event.type === 'touchstart' ? 200 : 100); } handleRelease() { clearTimeout(this.rangeTimeout); this.isPressing = false; this.pressControl = null; } commonAttrs() { return { step: this.step, min: this.min, max: this.max, list: this.markers?.length ? this.idDatalist : null, disabled: this.disabled, }; } renderPrefix() { if (this.input) return this.renderNumberInput(); if (this.icon) return h("pn-icon", { class: "pn-range-icon", icon: this.icon }); if (this.textPrefix && !this.input) return h("span", { class: "pn-range-text" }, this.textPrefix); return null; } renderSuffix() { if (this.input && this.multiple) return this.renderNumberInput(true); if (this.iconEnd) return h("pn-icon", { class: "pn-range-icon", icon: this.iconEnd }); if (this.textSuffix && !this.input) return h("span", { class: "pn-range-text" }, this.textSuffix); return null; } renderNumberInput(isEnd = false) { const label = isEnd ? this.labelEnd : this.label; const value = isEnd ? this.valueEnd : this.value; const idInput = isEnd ? this.idInputEnd : this.idInput; return (h("pn-input", { class: "pn-range-field", label: label, type: "number", name: `${isEnd ? this.nameEnd : this.name}-input`, ...this.commonAttrs(), icon: isEnd ? this.iconEnd : this.icon, textPrefix: this.textPrefix, textSuffix: this.textSuffix, value: value?.toString(), inputid: idInput, invalid: this.hasError(), "data-single": !this.multiple, ...this.setListeners() })); } renderRangeInput(isEnd = false) { const id = isEnd ? this.pnIdEnd : this.pnId; const value = isEnd ? this.valueEnd : this.value; const customTooltip = this.tooltipDefault !== this.tooltipTemplate; return (h("input", { id: id, class: "pn-range-input", type: "range", name: isEnd ? this.nameEnd : this.name, ...this.commonAttrs(), value: value, "aria-valuetext": customTooltip ? this.getTooltipLabel(isEnd) : null, "aria-describedby": this.ariaDescribedby(), "aria-invalid": this.hasError().toString(), "data-start": isEnd ? null : true, "data-end": isEnd ? true : null, ...this.setListeners() })); } renderTooltip(isEnd = false) { return (h("div", { class: "pn-range-thumb", "data-start": isEnd ? null : true, "data-end": isEnd ? true : null, "data-align": this.tooltipDirection(isEnd), "aria-hidden": "true" }, !this.tooltipHide && (h("div", { class: "pn-range-tooltip" }, h("span", { class: "pn-range-tooltip-label" }, this.getTooltipLabel(isEnd)))))); } handleOverlayInput(event) { const target = event.target; const { valueAsNumber } = target; const numberValue = isNaN(valueAsNumber) ? 0 : valueAsNumber; if (!this.pressControl) { this.pressControl = Math.abs(numberValue - this.value) <= Math.abs(numberValue - this.valueEnd) ? 'start' : 'end'; } this.setValue(numberValue, this.pressControl === 'end'); } render() { return (h(Host, { key: '0a79e6606d509d701b83da4a2c3d3636c7d73979' }, h("div", { key: 'f56834025691e3c67544e4ddb2b54630bfa46095', class: "pn-range", "data-markers": !!this.markers?.length, "data-input": this.input }, h("div", { key: 'e39b5994468fc6f50ad479c5b3875732a29a4761', class: "pn-range-header", "data-input": this.input }, h("label", { key: '724a16a534343838e392480163517afc7bd15b6f', htmlFor: this.pnId, class: "pn-range-label" }, h("span", { key: 'ebd27275aeb63e79df5f2f0f5f4d1f5d118cd137' }, this.label)), this.multiple && (h("label", { key: 'aebe4d8b124cc5a905b61624566dc4db52f1f4a0', htmlFor: this.pnIdEnd, class: "pn-range-label" }, h("span", { key: '7a90745fadc39d81bac3083d562c9d7fe47c1d00' }, this.labelEnd)))), this.renderPrefix(), h("div", { key: '28fcae728841f246bfac7ae488710459d468e4f2', class: "pn-range-group", "data-pressing": this.isPressing }, this.renderRangeInput(), this.multiple && (h(Fragment, { key: '87dae83eea2f5e4eb5318759767dfabc74a0f128' }, this.renderRangeInput(true), h("input", { key: 'aa461034dfe94c78310409f87c1efaa0a4fb0a4d', id: this.idInputHidden, type: "range", class: "pn-range-overlay-input", ...this.commonAttrs(), "aria-invalid": this.hasError().toString(), hidden: true, tabIndex: -1, ...this.setListeners(true) }))), h("div", { key: '3282ce9652ff135db9e5bfa533af1c7fd1d29adb', class: "pn-range-track", "data-multiple": this.multiple, "aria-hidden": "true" }), this.renderTooltip(), this.multiple && this.renderTooltip(true), !!this.markers?.length && (h("ul", { key: '1692843e137439b5bdedb5728104a3312d26ffc2', "aria-hidden": "true", class: "pn-range-markers" }, this.markers.map(({ label, value }) => (h("li", { class: "pn-range-markers-item", "data-min": this.calcPercentage(value) === this.min, "data-max": this.calcPercentage(value) === this.max, style: { '--pn-range-marker-position': `${this.calcPercentage(value)}%` } }, h("span", { class: "pn-range-markers-label", "data-active": this.isActiveMarker(value) }, this.getMarkerLabel({ value, label })))))))), this.renderSuffix(), !!this.markers?.length && (h("datalist", { key: 'ed0ea3e4e284366f3e4eaf94245a1a71ccf20a17', id: this.idDatalist }, this.markers.map(({ label, value }) => (h("option", { value: value, label: label === null ? null : label }))))), h("p", { key: '3dd6afe5a2f142b1df60fdd87c0c23f942d83a71', id: this.idHelpertext, class: "pn-range-message", hidden: !this.hasHelperText() || this.hasError() }, h("span", { key: '048797709bcb778a9c1f2d71ae1ee1b1eef665f0' }, this.helpertext), h("slot", { key: '2fabbbc425b643917415653f831126e9d7319efd', name: "helpertext" })), h("p", { key: '65061b23a86338d7490bbfc2759308c1326f5d4e', id: this.idError, class: "pn-range-message pn-range-error", role: "alert", hidden: !this.hasErrorMessage() }, h("span", { key: 'a0be85a1e70ac6b07bb1447b6c8e9a04c72aade0' }, this.error), h("slot", { key: 'c13f70e99ec137373be96fa9d5a06b0266808fcf', name: "error" }))))); } static get is() { return "pn-range"; } static get originalStyleUrls() { return { "$": ["pn-range.scss"] }; } static get styleUrls() { return { "$": ["pn-range.css"] }; } static get properties() { return { "label": { "type": "string", "mutable": false, "complexType": { "original": "string", "resolved": "string", "references": {} }, "required": true, "optional": false, "docs": { "tags": [], "text": "Label for the range input." }, "getter": false, "setter": false, "reflect": false, "attribute": "label" }, "labelEnd": { "type": "string", "mutable": false, "complexType": { "original": "string", "resolved": "string", "references": {} }, "required": false, "optional": false, "docs": { "tags": [], "text": "Label for the range end input." }, "getter": false, "setter": false, "reflect": false, "attribute": "label-end" }, "helpertext": { "type": "string", "mutable": false, "complexType": { "original": "string", "resolved": "string", "references": {} }, "required": false, "optional": true, "docs": { "tags": [], "text": "Set a helpertext for the range input." }, "getter": false, "setter": false, "reflect": false, "attribute": "helpertext", "defaultValue": "null" }, "markers": { "type": "unknown", "mutable": false, "complexType": { "original": "{ value: number; label?: string }[]", "resolved": "{ value: number; label?: string; }[]", "references": {} }, "required": false, "optional": true, "docs": { "tags": [], "text": "Add markers. This will also render a `datalist` element with `options`.\nOmitting the `label` for a marker will use the `value` as label instead.\nSet `label` to `null` or `''` to hide it completely." }, "getter": false, "setter": false, "defaultValue": "[]" }, "textPrefix": { "type": "string", "mutable": false, "complexType": { "original": "string", "resolved": "string", "references": {} }, "required": false, "optional": true, "docs": { "tags": [], "text": "Set a prefix for the range/input field." }, "getter": false, "setter": false, "reflect": false, "attribute": "text-prefix", "defaultValue": "null" }, "textSuffix": { "type": "string", "mutable": false, "complexType": { "original": "string", "resolved": "string", "references": {} }, "required": false, "optional": true, "docs": { "tags": [], "text": "Set a suffix for the range/input field." }, "getter": false, "setter": false, "reflect": false, "attribute": "text-suffix", "defaultValue": "null" }, "icon": { "type": "string", "mutable": false, "complexType": { "original": "string", "resolved": "string", "references": {} }, "required": false, "optional": true, "docs": { "tags": [], "text": "Set an icon for the range/input field." }, "getter": false, "setter": false, "reflect": false, "attribute": "icon", "defaultValue": "null" }, "iconEnd": { "type": "string", "mutable": false, "complexType": { "original": "string", "resolved": "string", "references": {} }, "required": false, "optional": true, "docs": { "tags": [], "text": "Set an icon at the end of the range or for the second input field when using `multiple`." }, "getter": false, "setter": false, "reflect": false, "attribute": "icon-end", "defaultValue": "null" }, "pnId": { "type": "string", "mutable": false, "complexType": { "original": "string", "resolved": "string", "references": {} }, "required": false, "optional": true, "docs": { "tags": [], "text": "Set a custom HTML id." }, "getter": false, "setter": false, "reflect": false, "attribute": "pn-id", "defaultValue": "this.id" }, "pnIdEnd": { "type": "string", "mutable": false, "complexType": { "original": "string", "resolved": "string", "references": {} }, "required": false, "optional": true, "docs": { "tags": [], "text": "Set a custom HTML id." }, "getter": false, "setter": false, "reflect": false, "attribute": "pn-id-end", "defaultValue": "this.idEnd" }, "name": { "type": "string", "mutable": false, "complexType": { "original": "string", "resolved": "string", "references": {} }, "required": false, "optional": true, "docs": { "tags": [{ "name": "category", "text": "HTML Attributes" }], "text": "The range input name." }, "getter": false, "setter": false, "reflect": false, "attribute": "name" }, "nameEnd": { "type": "string", "mutable": false, "complexType": { "original": "string", "resolved": "string", "references": {} }, "required": false, "optional": true, "docs": { "tags": [{ "name": "category", "text": "HTML Attributes" }], "text": "The range input name." }, "getter": false, "setter": false, "reflect": false, "attribute": "name-end" }, "min": { "type": "number", "mutable": false, "complexType": { "original": "number", "resolved": "number", "references": {} }, "required": false, "optional": true, "docs": { "tags": [{ "name": "category", "text": "HTML Attributes" }], "text": "The range input min value." }, "getter": false, "setter": false, "reflect": false, "attribute": "min", "defaultValue": "0" }, "max": { "type": "number", "mutable": false, "complexType": { "original": "number", "resolved": "number", "references": {} }, "required": false, "optional": true, "docs": { "tags": [{ "name": "category", "text": "HTML Attributes" }], "text": "The range input max value." }, "getter": false, "setter": false, "reflect": false, "attribute": "max", "defaultValue": "100" }, "value": { "type": "number", "mutable": true, "complexType": { "original": "number", "resolved": "number", "references": {} }, "required": false, "optional": true, "docs": { "tags": [{ "name": "category", "text": "HTML Attributes" }], "text": "The range input value." }, "getter": false, "setter": false, "reflect": true, "attribute": "value", "defaultValue": "0" }, "valueEnd": { "type": "number", "mutable": true, "complexType": { "original": "number", "resolved": "number", "references": {} }, "required": false, "optional": true, "docs": { "tags": [{ "name": "category", "text": "HTML Attributes" }], "text": "The range end input value." }, "getter": false, "setter": false, "reflect": true, "attribute": "value-end", "defaultValue": "0" }, "step": { "type": "string", "mutable": false, "complexType": { "original": "HTMLInputElement['step']", "resolved": "string", "references": { "HTMLInputElement": { "location": "global", "id": "global::HTMLInputElement" } } }, "required": false, "optional": true, "docs": { "tags": [{ "name": "category", "text": "HTML Attributes" }], "text": "Set a step value for the range input." }, "getter": false, "setter": false, "reflect": false, "attribute": "step", "defaultValue": "''" }, "multiple": { "type": "boolean", "mutable": false, "complexType": { "original": "boolean", "resolved": "boolean", "references": {} }, "required": false, "optional": true, "docs": { "tags": [{ "name": "category", "text": "Features" }], "text": "Allow multiple values to be selected" }, "getter": false, "setter": false, "reflect": false, "attribute": "multiple", "defaultValue": "false" }, "input": { "type": "boolean", "mutable": false, "complexType": { "original": "boolean", "resolved": "boolean", "references": {} }, "required": false, "optional": true, "docs": { "tags": [{ "name": "category", "text": "Features" }], "text": "Display an input for the range value.\nAllowing the user to type or use the slider to set the value." }, "getter": false, "setter": false, "reflect": false, "attribute": "input", "defaultValue": "false" }, "tooltipHide": { "type": "boolean", "mutable": false, "complexType": { "original": "boolean", "resolved": "boolean", "references": {} }, "required": false, "optional": true, "docs": { "tags": [{ "name": "category", "text": "Features" }], "text": "Hide the tooltip." }, "getter": false, "setter": false, "reflect": false, "attribute": "tooltip-hide", "defaultValue": "false" }, "tooltipTemplate": { "type": "string", "mutable": false, "complexType": { "original": "string", "resolved": "string", "references": {} }, "required": false, "optional": true, "docs": { "tags": [{ "name": "example", "text": "// Show a suffixed '%' in the tooltip with '{value} %'.\n<pn-range tooltip-template=\"{value} %\" value=\"25\" />" }, { "name": "category", "text": "Features" }], "text": "Range tooltip label template. Default is simply the value of the range input." }, "getter": false, "setter": false, "reflect": false, "attribute": "tooltip-template", "defaultValue": "this.tooltipDefault" }, "disabled": { "type": "boolean", "mutable": false, "complexType": { "original": "boolean", "resolved": "boolean", "references": {} }, "required": false, "optional": true, "docs": { "tags": [{ "name": "category", "text": "State" }], "text": "Disable the range input." }, "getter": false, "setter": false, "reflect": false, "attribute": "disabled", "defaultValue": "false" }, "error": { "type": "string", "mutable": false, "complexType": { "original": "string", "resolved": "string", "references": {} }, "required": false, "optional": true, "docs": { "tags": [{ "name": "category", "text": "State" }], "text": "Set an error message for the range input." }, "getter": false, "setter": false, "reflect": false, "attribute": "error", "defaultValue": "null" }, "invalid": { "type": "boolean", "mutable": false, "complexType": { "original": "boolean", "resolved": "boolean", "references": {} }, "required": false, "optional": true, "docs": { "tags": [{ "name": "category", "text": "State" }], "text": "Set the error visual for the range input, same as `error`, but without a message." }, "getter": false, "setter": false, "reflect": false, "attribute": "invalid", "defaultValue": "false" } }; } static get states() { return { "showHelperSlot": {}, "showErrorSlot": {}, "isPressing": {}, "pressControl": {} }; } static get events() { return [{ "method": "rangeSelected", "name": "rangeSelected", "bubbles": true, "cancelable": true, "composed": true, "docs": { "tags": [], "text": "Emitted as the user makes any changes to the range/input value." }, "complexType": { "original": "{\n value: number;\n /* The end value when using `multiple`. */\n valueEnd?: number;\n /* The selected percentage of the range input. */\n percentage: number;\n /* The difference between `value` and `valueEnd`. */\n difference?: number;\n }", "resolved": "{ value: number; valueEnd?: number; percentage: number; difference?: number; }", "references": {} } }]; } static get elementRef() { return "hostElement"; } static get watchers() { return [{ "propName": "value", "methodName": "handleValue", "handlerOptions": { "immediate": true } }, { "propName": "valueEnd", "methodName": "handleValueEnd", "handlerOptions": { "immediate": true } }, { "propName": "pnId", "methodName": "handleId", "handlerOptions": { "immediate": true } }, { "propName": "helpertext", "methodName": "handleMessage", "handlerOptions": { "immediate": true } }, { "propName": "error", "methodName": "handleMessage" }, { "propName": "multiple", "methodName": "handleMultiple" }]; } }