UNPKG

nouislider

Version:

noUiSlider is a lightweight JavaScript range slider.

1,593 lines (1,306 loc) 110 kB
"use strict"; interface CssClasses { target: string; base: string; origin: string; handle: string; handleLower: string; handleUpper: string; touchArea: string; horizontal: string; vertical: string; background: string; connect: string; connects: string; ltr: string; rtl: string; textDirectionLtr: string; textDirectionRtl: string; draggable: string; drag: string; tap: string; active: string; tooltip: string; pips: string; pipsHorizontal: string; pipsVertical: string; marker: string; markerHorizontal: string; markerVertical: string; markerNormal: string; markerLarge: string; markerSub: string; value: string; valueHorizontal: string; valueVertical: string; valueNormal: string; valueLarge: string; valueSub: string; } export interface PartialFormatter { to: (value: number) => string | number; from?: (value: string) => number | false; } export interface Formatter extends PartialFormatter { from: (value: string) => number | false; } export enum PipsMode { Range = "range", Steps = "steps", Positions = "positions", Count = "count", Values = "values", } export enum PipsType { None = -1, NoValue = 0, LargeValue = 1, SmallValue = 2, } type WrappedSubRange = [number] | [number, number]; type SubRange = number | WrappedSubRange; interface Range { min: SubRange; max: SubRange; [key: `${number}%`]: SubRange; } //region Pips interface BasePips { mode: PipsMode; density?: number; filter?: PipsFilter; format?: PartialFormatter; } interface PositionsPips extends BasePips { mode: PipsMode.Positions; values: number[]; stepped?: boolean; } interface ValuesPips extends BasePips { mode: PipsMode.Values; values: number[]; stepped?: boolean; } interface CountPips extends BasePips { mode: PipsMode.Count; values: number; stepped?: boolean; } interface StepsPips extends BasePips { mode: PipsMode.Steps; } interface RangePips extends BasePips { mode: PipsMode.Range; } type Pips = PositionsPips | ValuesPips | CountPips | StepsPips | RangePips; //endregion type ValueArgument = number | string | null; type StartValues = ValueArgument | ValueArgument[]; type HandleAttributes = { [key: string]: string }; interface UpdatableOptions { range?: Range; start?: StartValues; margin?: number; limit?: number; padding?: number | number[]; snap?: boolean; step?: number; pips?: Pips; format?: Formatter; tooltips?: boolean | PartialFormatter | (boolean | PartialFormatter)[]; animate?: boolean; connect?: "lower" | "upper" | boolean | boolean[]; } export interface Options extends UpdatableOptions { range: Range; orientation?: "vertical" | "horizontal"; direction?: "ltr" | "rtl"; behaviour?: string; keyboardSupport?: boolean; keyboardPageMultiplier?: number; keyboardMultiplier?: number; keyboardDefaultStep?: number; documentElement?: HTMLElement; cssPrefix?: string; cssClasses?: CssClasses; ariaFormat?: PartialFormatter; animationDuration?: number; handleAttributes?: HandleAttributes[]; } interface Behaviour { tap: boolean; drag: boolean; dragAll: boolean; smoothSteps: boolean; fixed: boolean; snap: boolean; hover: boolean; unconstrained: boolean; invertConnects: boolean; } interface ParsedOptions { animate: boolean; connect: boolean[]; start: number[]; margin: number[] | null; limit: number[] | null; padding: number[][] | null; step?: number; orientation?: "vertical" | "horizontal"; direction?: "ltr" | "rtl"; tooltips?: (boolean | PartialFormatter)[]; keyboardSupport: boolean; keyboardPageMultiplier: number; keyboardMultiplier: number; keyboardDefaultStep: number; documentElement?: HTMLElement; cssPrefix?: string | false; cssClasses: CssClasses; ariaFormat: PartialFormatter; pips?: Pips; animationDuration: number; snap?: boolean; format: Formatter; handleAttributes?: HandleAttributes[]; range: Range; singleStep: number; transformRule: "transform" | "msTransform" | "webkitTransform"; style: "left" | "top" | "right" | "bottom"; ort: 0 | 1; handles: number; events: Behaviour; dir: 0 | 1; spectrum: Spectrum; } export interface API { destroy: () => void; steps: () => NextStepsForHandle[]; on: (eventName: string, callback: EventCallback) => void; off: (eventName: string) => void; get: (unencoded?: boolean) => GetResult; set: (input: ValueArgument | ValueArgument[], fireSetEvent?: boolean, exactInput?: boolean) => void; setHandle: (handleNumber: number, value: ValueArgument, fireSetEvent?: boolean, exactInput?: boolean) => void; reset: (fireSetEvent?: boolean) => void; disable: (handleNumber?: number) => void; enable: (handleNumber?: number) => void; options: Options; updateOptions: (optionsToUpdate: UpdatableOptions, fireSetEvent: boolean) => void; target: HTMLElement; removePips: () => void; removeTooltips: () => void; getPositions: () => number[]; getTooltips: () => (HTMLElement | false)[] | null; getOrigins: () => HTMLElement[]; pips: (grid: Pips) => HTMLElement; } interface TargetElement extends HTMLElement { noUiSlider?: API; } interface Origin extends HTMLElement { handle: HTMLElement; } interface CSSStyleDeclarationIE10 extends CSSStyleDeclaration { msTransform?: string; } interface EventData { target?: HTMLElement; handles?: HTMLElement[]; handle?: HTMLElement; connect?: HTMLElement; listeners?: [string, EventHandler][]; startCalcPoint?: number; baseSize?: number; pageOffset?: PageOffset; handleNumbers: number[]; buttonsProperty?: number; locations?: number[]; doNotReject?: boolean; hover?: boolean; } interface MoveEventData extends EventData { listeners: [string, EventHandler][]; startCalcPoint: number; baseSize: number; locations: number[]; } interface EndEventData extends EventData { listeners: [string, EventHandler][]; } interface NearByStep { startValue: number; step: number | false; highestStep: number; } interface NearBySteps { stepBefore: NearByStep; thisStep: NearByStep; stepAfter: NearByStep; } type EventHandler = (event: BrowserEvent) => false | undefined; type GetResult = number | string | (string | number)[]; type NextStepsForHandle = [number | false | null, number | false | null]; type OptionKey = keyof Options & keyof ParsedOptions & keyof UpdatableOptions; type PipsFilter = (value: number, type: PipsType) => PipsType; type PageOffset = { x: number; y: number }; type BrowserEvent = MouseEvent & TouchEvent & { pageOffset: PageOffset; points: [number, number]; cursor: boolean; calcPoint: number }; type EventCallback = ( this: API, values: (number | string)[], handleNumber: number, unencoded: number[], tap: boolean, locations: number[], slider: API ) => void; //region Helper Methods function isValidFormatter(entry: unknown): entry is Formatter { return isValidPartialFormatter(entry) && typeof (<Formatter>entry).from === "function"; } function isValidPartialFormatter(entry: unknown): entry is PartialFormatter { // partial formatters only need a to function and not a from function return typeof entry === "object" && typeof (<Formatter>entry).to === "function"; } function removeElement(el: HTMLElement): void { (el.parentElement as HTMLElement).removeChild(el); } function isSet<T>(value: T): value is Exclude<T, null | undefined> { return value !== null && value !== undefined; } // Bindable version function preventDefault(e: Event): void { e.preventDefault(); } // Removes duplicates from an array. function unique<Type>(array: Type[]): Type[] { return array.filter(function (a) { return !this[a] ? (this[a] = true) : false; }, {}); } // Round a value to the closest 'to'. function closest(value: number, to: number): number { return Math.round(value / to) * to; } // Current position of an element relative to the document. function offset(elem: HTMLElement, orientation: 0 | 1): number { const rect = elem.getBoundingClientRect(); const doc = elem.ownerDocument; const docElem = doc.documentElement; const pageOffset = getPageOffset(doc); // getBoundingClientRect contains left scroll in Chrome on Android. // I haven't found a feature detection that proves this. Worst case // scenario on mis-match: the 'tap' feature on horizontal sliders breaks. if (/webkit.*Chrome.*Mobile/i.test(navigator.userAgent)) { pageOffset.x = 0; } return orientation ? rect.top + pageOffset.y - docElem.clientTop : rect.left + pageOffset.x - docElem.clientLeft; } // Checks whether a value is numerical. function isNumeric(a: unknown): a is number { return typeof a === "number" && !isNaN(a) && isFinite(a); } // Sets a class and removes it after [duration] ms. function addClassFor(element: HTMLElement, className: string, duration: number): void { if (duration > 0) { addClass(element, className); setTimeout(function () { removeClass(element, className); }, duration); } } // Limits a value to 0 - 100 function limit(a: number): number { return Math.max(Math.min(a, 100), 0); } // Wraps a variable as an array, if it isn't one yet. // Note that an input array is returned by reference! function asArray<Type>(a: Type | Type[]): Type[] { return Array.isArray(a) ? a : [a]; } // Counts decimals function countDecimals(numStr: string | number | false): number { numStr = String(numStr); const pieces = numStr.split("."); return pieces.length > 1 ? pieces[1].length : 0; } // http://youmightnotneedjquery.com/#add_class function addClass(el: HTMLElement, className: string): void { if (el.classList && !/\s/.test(className)) { el.classList.add(className); } else { el.className += " " + className; } } // http://youmightnotneedjquery.com/#remove_class function removeClass(el: HTMLElement, className: string): void { if (el.classList && !/\s/.test(className)) { el.classList.remove(className); } else { el.className = el.className.replace( new RegExp("(^|\\b)" + className.split(" ").join("|") + "(\\b|$)", "gi"), " " ); } } // https://plainjs.com/javascript/attributes/adding-removing-and-testing-for-classes-9/ function hasClass(el: HTMLElement, className: string): boolean { return el.classList ? el.classList.contains(className) : new RegExp("\\b" + className + "\\b").test(el.className); } // https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollY#Notes function getPageOffset(doc: Document): PageOffset { const supportPageOffset = window.pageXOffset !== undefined; const isCSS1Compat = (doc.compatMode || "") === "CSS1Compat"; const x = supportPageOffset ? window.pageXOffset : isCSS1Compat ? doc.documentElement.scrollLeft : doc.body.scrollLeft; const y = supportPageOffset ? window.pageYOffset : isCSS1Compat ? doc.documentElement.scrollTop : doc.body.scrollTop; return { x: x, y: y, }; } // we provide a function to compute constants instead // of accessing window.* as soon as the module needs it // so that we do not compute anything if not needed function getActions(): { start: string; move: string; end: string } { // Determine the events to bind. IE11 implements pointerEvents without // a prefix, which breaks compatibility with the IE10 implementation. return (window.navigator as any).pointerEnabled ? { start: "pointerdown", move: "pointermove", end: "pointerup", } : (window.navigator as any).msPointerEnabled ? { start: "MSPointerDown", move: "MSPointerMove", end: "MSPointerUp", } : { start: "mousedown touchstart", move: "mousemove touchmove", end: "mouseup touchend", }; } // https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md // Issue #785 function getSupportsPassive(): boolean { let supportsPassive = false; /* eslint-disable */ try { const opts = Object.defineProperty({}, "passive", { get: function () { supportsPassive = true; }, }); // @ts-ignore window.addEventListener("test", null, opts); } catch (e) {} /* eslint-enable */ return supportsPassive; } function getSupportsTouchActionNone(): boolean { return window.CSS && CSS.supports && CSS.supports("touch-action", "none"); } //endregion //region Range Calculation // Determine the size of a sub-range in relation to a full range. function subRangeRatio(pa: number, pb: number): number { return 100 / (pb - pa); } // (percentage) How many percent is this value of this range? function fromPercentage(range: number[], value: number, startRange: number): number { return (value * 100) / (range[startRange + 1] - range[startRange]); } // (percentage) Where is this value on this range? function toPercentage(range: [number, number], value: number): number { return fromPercentage(range, range[0] < 0 ? value + Math.abs(range[0]) : value - range[0], 0); } // (value) How much is this percentage on this range? function isPercentage(range: [number, number], value: number): number { return (value * (range[1] - range[0])) / 100 + range[0]; } function getJ(value: number, arr: number[]): number { let j = 1; while (value >= arr[j]) { j += 1; } return j; } // (percentage) Input a value, find where, on a scale of 0-100, it applies. function toStepping(xVal: number[], xPct: number[], value: number): number { if (value >= xVal.slice(-1)[0]) { return 100; } const j = getJ(value, xVal); const va = xVal[j - 1]; const vb = xVal[j]; const pa = xPct[j - 1]; const pb = xPct[j]; return pa + toPercentage([va, vb], value) / subRangeRatio(pa, pb); } // (value) Input a percentage, find where it is on the specified range. function fromStepping(xVal: number[], xPct: number[], value: number): number { // There is no range group that fits 100 if (value >= 100) { return xVal.slice(-1)[0]; } const j = getJ(value, xPct); const va = xVal[j - 1]; const vb = xVal[j]; const pa = xPct[j - 1]; const pb = xPct[j]; return isPercentage([va, vb], (value - pa) * subRangeRatio(pa, pb)); } // (percentage) Get the step that applies at a certain value. function getStep(xPct: number[], xSteps: (number | false)[], snap: boolean, value: number): number { if (value === 100) { return value; } const j = getJ(value, xPct); const a = xPct[j - 1]; const b = xPct[j]; // If 'snap' is set, steps are used as fixed points on the slider. if (snap) { // Find the closest position, a or b. if (value - a > (b - a) / 2) { return b; } return a; } if (!xSteps[j - 1]) { return value; } return xPct[j - 1] + closest(value - xPct[j - 1], xSteps[j - 1] as number); } //endregion //region Spectrum class Spectrum { public xPct: number[] = []; public xVal: number[] = []; public xSteps: (number | false)[] = []; public xNumSteps: (number | false)[] = []; protected xHighestCompleteStep: number[] = []; protected snap: boolean; constructor(entry: Range, snap: boolean, singleStep: number) { this.xSteps = [singleStep || false]; this.xNumSteps = [false]; this.snap = snap; let index; const ordered: [WrappedSubRange, string][] = []; // Map the object keys to an array. Object.keys(entry).forEach((index: keyof Range) => { ordered.push([asArray(entry[index]) as WrappedSubRange, index]); }); // Sort all entries by value (numeric sort). ordered.sort(function (a, b) { return a[0][0] - b[0][0]; }); // Convert all entries to subranges. for (index = 0; index < ordered.length; index++) { this.handleEntryPoint(ordered[index][1], ordered[index][0]); } // Store the actual step values. // xSteps is sorted in the same order as xPct and xVal. this.xNumSteps = this.xSteps.slice(0); // Convert all numeric steps to the percentage of the subrange they represent. for (index = 0; index < this.xNumSteps.length; index++) { this.handleStepPoint(index, this.xNumSteps[index]); } } public getDistance(value: number): number[] { const distances = []; for (let index = 0; index < this.xNumSteps.length - 1; index++) { distances[index] = fromPercentage(this.xVal, value, index); } return distances; } // Calculate the percentual distance over the whole scale of ranges. // direction: 0 = backwards / 1 = forwards public getAbsoluteDistance(value: number, distances: number[] | null, direction: boolean): number { let xPct_index = 0; // Calculate range where to start calculation if (value < this.xPct[this.xPct.length - 1]) { while (value > this.xPct[xPct_index + 1]) { xPct_index++; } } else if (value === this.xPct[this.xPct.length - 1]) { xPct_index = this.xPct.length - 2; } // If looking backwards and the value is exactly at a range separator then look one range further if (!direction && value === this.xPct[xPct_index + 1]) { xPct_index++; } if (distances === null) { distances = []; } let start_factor; let rest_factor = 1; let rest_rel_distance = distances[xPct_index]; let range_pct = 0; let rel_range_distance = 0; let abs_distance_counter = 0; let range_counter = 0; // Calculate what part of the start range the value is if (direction) { start_factor = (value - this.xPct[xPct_index]) / (this.xPct[xPct_index + 1] - this.xPct[xPct_index]); } else { start_factor = (this.xPct[xPct_index + 1] - value) / (this.xPct[xPct_index + 1] - this.xPct[xPct_index]); } // Do until the complete distance across ranges is calculated while (rest_rel_distance > 0) { // Calculate the percentage of total range range_pct = this.xPct[xPct_index + 1 + range_counter] - this.xPct[xPct_index + range_counter]; // Detect if the margin, padding or limit is larger then the current range and calculate if (distances[xPct_index + range_counter] * rest_factor + 100 - start_factor * 100 > 100) { // If larger then take the percentual distance of the whole range rel_range_distance = range_pct * start_factor; // Rest factor of relative percentual distance still to be calculated rest_factor = (rest_rel_distance - 100 * start_factor) / distances[xPct_index + range_counter]; // Set start factor to 1 as for next range it does not apply. start_factor = 1; } else { // If smaller or equal then take the percentual distance of the calculate percentual part of that range rel_range_distance = ((distances[xPct_index + range_counter] * range_pct) / 100) * rest_factor; // No rest left as the rest fits in current range rest_factor = 0; } if (direction) { abs_distance_counter = abs_distance_counter - rel_range_distance; // Limit range to first range when distance becomes outside of minimum range if (this.xPct.length + range_counter >= 1) { range_counter--; } } else { abs_distance_counter = abs_distance_counter + rel_range_distance; // Limit range to last range when distance becomes outside of maximum range if (this.xPct.length - range_counter >= 1) { range_counter++; } } // Rest of relative percentual distance still to be calculated rest_rel_distance = distances[xPct_index + range_counter] * rest_factor; } return value + abs_distance_counter; } public toStepping(value: number): number { value = toStepping(this.xVal, this.xPct, value); return value; } public fromStepping(value: number): number { return fromStepping(this.xVal, this.xPct, value); } public getStep(value: number): number { value = getStep(this.xPct, this.xSteps, this.snap, value); return value; } public getDefaultStep(value: number, isDown: boolean, size: number): number { let j = getJ(value, this.xPct); // When at the top or stepping down, look at the previous sub-range if (value === 100 || (isDown && value === this.xPct[j - 1])) { j = Math.max(j - 1, 1); } return (this.xVal[j] - this.xVal[j - 1]) / size; } public getNearbySteps(value: number): NearBySteps { const j = getJ(value, this.xPct); return { stepBefore: { startValue: this.xVal[j - 2], step: this.xNumSteps[j - 2], highestStep: this.xHighestCompleteStep[j - 2], }, thisStep: { startValue: this.xVal[j - 1], step: this.xNumSteps[j - 1], highestStep: this.xHighestCompleteStep[j - 1], }, stepAfter: { startValue: this.xVal[j], step: this.xNumSteps[j], highestStep: this.xHighestCompleteStep[j], }, }; } public countStepDecimals(): number { const stepDecimals = this.xNumSteps.map(countDecimals); return Math.max.apply(null, stepDecimals); } public hasNoSize(): boolean { return this.xVal[0] === this.xVal[this.xVal.length - 1]; } // Outside testing public convert(value: number): number { return this.getStep(this.toStepping(value)); } private handleEntryPoint(index: string, value: WrappedSubRange): void { let percentage; // Covert min/max syntax to 0 and 100. if (index === "min") { percentage = 0; } else if (index === "max") { percentage = 100; } else { percentage = parseFloat(index); } // Check for correct input. if (!isNumeric(percentage) || !isNumeric(value[0])) { throw new Error("noUiSlider: 'range' value isn't numeric."); } // Store values. this.xPct.push(percentage); this.xVal.push(value[0]); const value1 = Number(value[1]); // NaN will evaluate to false too, but to keep // logging clear, set step explicitly. Make sure // not to override the 'step' setting with false. if (!percentage) { if (!isNaN(value1)) { this.xSteps[0] = value1; } } else { this.xSteps.push(isNaN(value1) ? false : value1); } this.xHighestCompleteStep.push(0); } private handleStepPoint(i: number, n: number | false): void { // Ignore 'false' stepping. if (!n) { return; } // Step over zero-length ranges (#948); if (this.xVal[i] === this.xVal[i + 1]) { this.xSteps[i] = this.xHighestCompleteStep[i] = this.xVal[i]; return; } // Factor to range ratio this.xSteps[i] = fromPercentage([this.xVal[i], this.xVal[i + 1]], n, 0) / subRangeRatio(this.xPct[i], this.xPct[i + 1]); const totalSteps = (this.xVal[i + 1] - this.xVal[i]) / (this.xNumSteps[i] as number); const highestStep = Math.ceil(Number(totalSteps.toFixed(3)) - 1); const step = this.xVal[i] + (this.xNumSteps[i] as number) * highestStep; this.xHighestCompleteStep[i] = step; } } //endregion //region Options /* Every input option is tested and parsed. This will prevent endless validation in internal methods. These tests are structured with an item for every option available. An option can be marked as required by setting the 'r' flag. The testing function is provided with three arguments: - The provided value for the option; - A reference to the options object; - The name for the option; The testing function returns false when an error is detected, or true when everything is OK. It can also modify the option object, to make sure all values can be correctly looped elsewhere. */ //region Defaults const defaultFormatter: Formatter = { to: function (value) { return value === undefined ? "" : value.toFixed(2); }, from: Number, }; const cssClasses: CssClasses = { target: "target", base: "base", origin: "origin", handle: "handle", handleLower: "handle-lower", handleUpper: "handle-upper", touchArea: "touch-area", horizontal: "horizontal", vertical: "vertical", background: "background", connect: "connect", connects: "connects", ltr: "ltr", rtl: "rtl", textDirectionLtr: "txt-dir-ltr", textDirectionRtl: "txt-dir-rtl", draggable: "draggable", drag: "state-drag", tap: "state-tap", active: "active", tooltip: "tooltip", pips: "pips", pipsHorizontal: "pips-horizontal", pipsVertical: "pips-vertical", marker: "marker", markerHorizontal: "marker-horizontal", markerVertical: "marker-vertical", markerNormal: "marker-normal", markerLarge: "marker-large", markerSub: "marker-sub", value: "value", valueHorizontal: "value-horizontal", valueVertical: "value-vertical", valueNormal: "value-normal", valueLarge: "value-large", valueSub: "value-sub", }; // Namespaces of internal event listeners const INTERNAL_EVENT_NS = { tooltips: ".__tooltips", aria: ".__aria", }; //endregion function testStep(parsed: ParsedOptions, entry: unknown): void { if (!isNumeric(entry)) { throw new Error("noUiSlider: 'step' is not numeric."); } // The step option can still be used to set stepping // for linear sliders. Overwritten if set in 'range'. parsed.singleStep = entry; } function testKeyboardPageMultiplier(parsed: ParsedOptions, entry: unknown): void { if (!isNumeric(entry)) { throw new Error("noUiSlider: 'keyboardPageMultiplier' is not numeric."); } parsed.keyboardPageMultiplier = entry; } function testKeyboardMultiplier(parsed: ParsedOptions, entry: unknown): void { if (!isNumeric(entry)) { throw new Error("noUiSlider: 'keyboardMultiplier' is not numeric."); } parsed.keyboardMultiplier = entry; } function testKeyboardDefaultStep(parsed: ParsedOptions, entry: unknown): void { if (!isNumeric(entry)) { throw new Error("noUiSlider: 'keyboardDefaultStep' is not numeric."); } parsed.keyboardDefaultStep = entry; } function testRange(parsed: ParsedOptions, entry: Range): void { // Filter incorrect input. if (typeof entry !== "object" || Array.isArray(entry)) { throw new Error("noUiSlider: 'range' is not an object."); } // Catch missing start or end. if (entry.min === undefined || entry.max === undefined) { throw new Error("noUiSlider: Missing 'min' or 'max' in 'range'."); } parsed.spectrum = new Spectrum(entry, parsed.snap || false, parsed.singleStep); } function testStart(parsed: ParsedOptions, entry: unknown): void { entry = asArray(entry); // Validate input. Values aren't tested, as the public .val method // will always provide a valid location. if (!Array.isArray(entry) || !entry.length) { throw new Error("noUiSlider: 'start' option is incorrect."); } // Store the number of handles. parsed.handles = entry.length; // When the slider is initialized, the .val method will // be called with the start options. parsed.start = entry; } function testSnap(parsed: ParsedOptions, entry: unknown): void { if (typeof entry !== "boolean") { throw new Error("noUiSlider: 'snap' option must be a boolean."); } // Enforce 100% stepping within subranges. parsed.snap = entry; } function testAnimate(parsed: ParsedOptions, entry: unknown): void { if (typeof entry !== "boolean") { throw new Error("noUiSlider: 'animate' option must be a boolean."); } // Enforce 100% stepping within subranges. parsed.animate = entry; } function testAnimationDuration(parsed: ParsedOptions, entry: unknown): void { if (typeof entry !== "number") { throw new Error("noUiSlider: 'animationDuration' option must be a number."); } parsed.animationDuration = entry; } function testConnect(parsed: ParsedOptions, entry: unknown): void { let connect = [false]; let i; // Map legacy options if (entry === "lower") { entry = [true, false]; } else if (entry === "upper") { entry = [false, true]; } // Handle boolean options if (entry === true || entry === false) { for (i = 1; i < parsed.handles; i++) { connect.push(entry); } connect.push(false); } // Reject invalid input else if (!Array.isArray(entry) || !entry.length || entry.length !== parsed.handles + 1) { throw new Error("noUiSlider: 'connect' option doesn't match handle count."); } else { connect = entry; } parsed.connect = connect; } function testOrientation(parsed: ParsedOptions, entry: unknown): void { // Set orientation to an a numerical value for easy // array selection. switch (entry) { case "horizontal": parsed.ort = 0; break; case "vertical": parsed.ort = 1; break; default: throw new Error("noUiSlider: 'orientation' option is invalid."); } } function testMargin(parsed: ParsedOptions, entry: unknown): void { if (!isNumeric(entry)) { throw new Error("noUiSlider: 'margin' option must be numeric."); } // Issue #582 if (entry === 0) { return; } parsed.margin = parsed.spectrum.getDistance(entry); } function testLimit(parsed: ParsedOptions, entry: unknown): void { if (!isNumeric(entry)) { throw new Error("noUiSlider: 'limit' option must be numeric."); } parsed.limit = parsed.spectrum.getDistance(entry); if (!parsed.limit || parsed.handles < 2) { throw new Error("noUiSlider: 'limit' option is only supported on linear sliders with 2 or more handles."); } } function testPadding(parsed: ParsedOptions, entry: number | [number, number]): void { let index; if (!isNumeric(entry) && !Array.isArray(entry)) { throw new Error("noUiSlider: 'padding' option must be numeric or array of exactly 2 numbers."); } if (Array.isArray(entry) && !(entry.length === 2 || isNumeric(entry[0]) || isNumeric(entry[1]))) { throw new Error("noUiSlider: 'padding' option must be numeric or array of exactly 2 numbers."); } if (entry === 0) { return; } if (!Array.isArray(entry)) { entry = [entry, entry]; } // 'getDistance' returns false for invalid values. parsed.padding = [parsed.spectrum.getDistance(entry[0]), parsed.spectrum.getDistance(entry[1])]; for (index = 0; index < parsed.spectrum.xNumSteps.length - 1; index++) { // last "range" can't contain step size as it is purely an endpoint. if (parsed.padding[0][index] < 0 || parsed.padding[1][index] < 0) { throw new Error("noUiSlider: 'padding' option must be a positive number(s)."); } } const totalPadding = entry[0] + entry[1]; const firstValue = parsed.spectrum.xVal[0]; const lastValue = parsed.spectrum.xVal[parsed.spectrum.xVal.length - 1]; if (totalPadding / (lastValue - firstValue) > 1) { throw new Error("noUiSlider: 'padding' option must not exceed 100% of the range."); } } function testDirection(parsed: ParsedOptions, entry: unknown): void { // Set direction as a numerical value for easy parsing. // Invert connection for RTL sliders, so that the proper // handles get the connect/background classes. switch (entry) { case "ltr": parsed.dir = 0; break; case "rtl": parsed.dir = 1; break; default: throw new Error("noUiSlider: 'direction' option was not recognized."); } } function testBehaviour(parsed: ParsedOptions, entry: unknown): void { // Make sure the input is a string. if (typeof entry !== "string") { throw new Error("noUiSlider: 'behaviour' must be a string containing options."); } // Check if the string contains any keywords. // None are required. const tap = entry.indexOf("tap") >= 0; const drag = entry.indexOf("drag") >= 0; const fixed = entry.indexOf("fixed") >= 0; const snap = entry.indexOf("snap") >= 0; const hover = entry.indexOf("hover") >= 0; const unconstrained = entry.indexOf("unconstrained") >= 0; const invertConnects = entry.indexOf("invert-connects") >= 0; const dragAll = entry.indexOf("drag-all") >= 0; const smoothSteps = entry.indexOf("smooth-steps") >= 0; if (fixed) { if (parsed.handles !== 2) { throw new Error("noUiSlider: 'fixed' behaviour must be used with 2 handles"); } // Use margin to enforce fixed state testMargin(parsed, parsed.start[1] - parsed.start[0]); } if (invertConnects && parsed.handles !== 2) { throw new Error("noUiSlider: 'invert-connects' behaviour must be used with 2 handles"); } if (unconstrained && (parsed.margin || parsed.limit)) { throw new Error("noUiSlider: 'unconstrained' behaviour cannot be used with margin or limit"); } parsed.events = { tap: tap || snap, drag: drag, dragAll: dragAll, smoothSteps: smoothSteps, fixed: fixed, snap: snap, hover: hover, unconstrained: unconstrained, invertConnects: invertConnects, }; } function testTooltips(parsed: ParsedOptions, entry: boolean | Formatter | (boolean | Formatter)[]): void { if (entry === false) { return; } if (entry === true || isValidPartialFormatter(entry)) { parsed.tooltips = []; for (let i = 0; i < parsed.handles; i++) { parsed.tooltips.push(entry); } } else { entry = asArray(entry); if (entry.length !== parsed.handles) { throw new Error("noUiSlider: must pass a formatter for all handles."); } entry.forEach(function (formatter) { if (typeof formatter !== "boolean" && !isValidPartialFormatter(formatter)) { throw new Error("noUiSlider: 'tooltips' must be passed a formatter or 'false'."); } }); parsed.tooltips = entry; } } function testHandleAttributes(parsed: ParsedOptions, entry: HandleAttributes[]): void { if (entry.length !== parsed.handles) { throw new Error("noUiSlider: must pass a attributes for all handles."); } parsed.handleAttributes = entry; } function testAriaFormat(parsed: ParsedOptions, entry: PartialFormatter): void { if (!isValidPartialFormatter(entry)) { throw new Error("noUiSlider: 'ariaFormat' requires 'to' method."); } parsed.ariaFormat = entry; } function testFormat(parsed: ParsedOptions, entry: Formatter): void { if (!isValidFormatter(entry)) { throw new Error("noUiSlider: 'format' requires 'to' and 'from' methods."); } parsed.format = entry; } function testKeyboardSupport(parsed: ParsedOptions, entry: unknown): void { if (typeof entry !== "boolean") { throw new Error("noUiSlider: 'keyboardSupport' option must be a boolean."); } parsed.keyboardSupport = entry; } function testDocumentElement(parsed: ParsedOptions, entry: HTMLElement): void { // This is an advanced option. Passed values are used without validation. parsed.documentElement = entry; } function testCssPrefix(parsed: ParsedOptions, entry: unknown): void { if (typeof entry !== "string" && entry !== false) { throw new Error("noUiSlider: 'cssPrefix' must be a string or `false`."); } parsed.cssPrefix = entry; } function testCssClasses(parsed: ParsedOptions, entry: CssClasses): void { if (typeof entry !== "object") { throw new Error("noUiSlider: 'cssClasses' must be an object."); } if (typeof parsed.cssPrefix === "string") { parsed.cssClasses = {} as CssClasses; Object.keys(entry).forEach((key: keyof CssClasses) => { parsed.cssClasses[key] = parsed.cssPrefix + entry[key]; }); } else { parsed.cssClasses = entry; } } // Test all developer settings and parse to assumption-safe values. function testOptions(options: Options): ParsedOptions { // To prove a fix for #537, freeze options here. // If the object is modified, an error will be thrown. // Object.freeze(options); const parsed = { margin: null, limit: null, padding: null, animate: true, animationDuration: 300, ariaFormat: defaultFormatter, format: defaultFormatter, } as ParsedOptions; // Tests are executed in the order they are presented here. const tests: { [key in keyof Options]: { r: boolean; t: (parsed: ParsedOptions, entry: unknown) => void } } = { step: { r: false, t: testStep }, keyboardPageMultiplier: { r: false, t: testKeyboardPageMultiplier }, keyboardMultiplier: { r: false, t: testKeyboardMultiplier }, keyboardDefaultStep: { r: false, t: testKeyboardDefaultStep }, start: { r: true, t: testStart }, connect: { r: true, t: testConnect }, direction: { r: true, t: testDirection }, snap: { r: false, t: testSnap }, animate: { r: false, t: testAnimate }, animationDuration: { r: false, t: testAnimationDuration }, range: { r: true, t: testRange }, orientation: { r: false, t: testOrientation }, margin: { r: false, t: testMargin }, limit: { r: false, t: testLimit }, padding: { r: false, t: testPadding }, behaviour: { r: true, t: testBehaviour }, ariaFormat: { r: false, t: testAriaFormat }, format: { r: false, t: testFormat }, tooltips: { r: false, t: testTooltips }, keyboardSupport: { r: true, t: testKeyboardSupport }, documentElement: { r: false, t: testDocumentElement }, cssPrefix: { r: true, t: testCssPrefix }, cssClasses: { r: true, t: testCssClasses }, handleAttributes: { r: false, t: testHandleAttributes }, }; const defaults = { connect: false, direction: "ltr", behaviour: "tap", orientation: "horizontal", keyboardSupport: true, cssPrefix: "noUi-", cssClasses: cssClasses, keyboardPageMultiplier: 5, keyboardMultiplier: 1, keyboardDefaultStep: 10, } as UpdatableOptions; // AriaFormat defaults to regular format, if any. if (options.format && !options.ariaFormat) { options.ariaFormat = options.format; } // Run all options through a testing mechanism to ensure correct // input. It should be noted that options might get modified to // be handled properly. E.g. wrapping integers in arrays. Object.keys(tests).forEach(function (name: OptionKey) { // If the option isn't set, but it is required, throw an error. if (!isSet(options[name]) && defaults[name] === undefined) { if ((tests[name] as any).r) { throw new Error("noUiSlider: '" + name + "' is required."); } return; } (tests[name] as any).t(parsed, !isSet(options[name]) ? defaults[name] : options[name]); }); // Forward pips options parsed.pips = options.pips; // All recent browsers accept unprefixed transform. // We need -ms- for IE9 and -webkit- for older Android; // Assume use of -webkit- if unprefixed and -ms- are not supported. // https://caniuse.com/#feat=transforms2d const d = document.createElement("div"); const msPrefix = (d.style as CSSStyleDeclarationIE10).msTransform !== undefined; const noPrefix = d.style.transform !== undefined; parsed.transformRule = noPrefix ? "transform" : msPrefix ? "msTransform" : "webkitTransform"; // Pips don't move, so we can place them using left/top. const styles = [ ["left", "top"], ["right", "bottom"], ]; parsed.style = styles[parsed.dir][parsed.ort] as "left" | "top" | "right" | "bottom"; return parsed; } //endregion function scope(target: TargetElement, options: ParsedOptions, originalOptions: Options): API { const actions = getActions(); const supportsTouchActionNone = getSupportsTouchActionNone(); const supportsPassive = supportsTouchActionNone && getSupportsPassive(); // All variables local to 'scope' are prefixed with 'scope_' // Slider DOM Nodes const scope_Target = target; let scope_Base: HTMLElement; let scope_ConnectBase: HTMLElement; let scope_Handles: Origin[]; let scope_Connects: (HTMLElement | false)[]; let scope_Pips: HTMLElement | null; let scope_Tooltips: (HTMLElement | false)[] | null; // Slider state values let scope_Spectrum = options.spectrum; const scope_Values: number[] = []; let scope_Locations: number[] = []; const scope_HandleNumbers: number[] = []; let scope_ActiveHandlesCount = 0; const scope_Events: { [key: string]: EventCallback[] } = {}; let scope_ConnectsInverted = false; // Document Nodes const scope_Document = target.ownerDocument; const scope_DocumentElement = options.documentElement || scope_Document.documentElement; const scope_Body = scope_Document.body; // For horizontal sliders in standard ltr documents, // make .noUi-origin overflow to the left so the document doesn't scroll. const scope_DirOffset = scope_Document.dir === "rtl" || options.ort === 1 ? 0 : 100; // Creates a node, adds it to target, returns the new node. function addNodeTo(addTarget: HTMLElement, className: string | false): HTMLElement { const div = scope_Document.createElement("div"); if (className) { addClass(div, className); } addTarget.appendChild(div); return div; } // Append a origin to the base function addOrigin(base: HTMLElement, handleNumber: number): Origin { const origin = addNodeTo(base, options.cssClasses.origin); const handle = addNodeTo(origin, options.cssClasses.handle); addNodeTo(handle, options.cssClasses.touchArea); handle.setAttribute("data-handle", String(handleNumber)); if (options.keyboardSupport) { // https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex // 0 = focusable and reachable handle.setAttribute("tabindex", "0"); handle.addEventListener("keydown", function (event) { return eventKeydown(event, handleNumber); }); } if (options.handleAttributes !== undefined) { const attributes: HandleAttributes = options.handleAttributes[handleNumber]; Object.keys(attributes).forEach(function (attribute: string) { handle.setAttribute(attribute, attributes[attribute]); }); } handle.setAttribute("role", "slider"); handle.setAttribute("aria-orientation", options.ort ? "vertical" : "horizontal"); if (handleNumber === 0) { addClass(handle, options.cssClasses.handleLower); } else if (handleNumber === options.handles - 1) { addClass(handle, options.cssClasses.handleUpper); } (origin as Origin).handle = handle; return origin as Origin; } // Insert nodes for connect elements function addConnect(base: HTMLElement, add: boolean): HTMLElement | false { if (!add) { return false; } return addNodeTo(base, options.cssClasses.connect); } // Add handles to the slider base. function addElements(connectOptions: boolean[], base: HTMLElement): void { scope_ConnectBase = addNodeTo(base, options.cssClasses.connects); scope_Handles = []; scope_Connects = []; scope_Connects.push(addConnect(scope_ConnectBase, connectOptions[0])); // [::::O====O====O====] // connectOptions = [0, 1, 1, 1] for (let i = 0; i < options.handles; i++) { // Keep a list of all added handles. scope_Handles.push(addOrigin(base, i)); scope_HandleNumbers[i] = i; scope_Connects.push(addConnect(scope_ConnectBase, connectOptions[i + 1])); } } // Initialize a single slider. function addSlider(addTarget: HTMLElement): HTMLElement { // Apply classes and data to the target. addClass(addTarget, options.cssClasses.target); if (options.dir === 0) { addClass(addTarget, options.cssClasses.ltr); } else { addClass(addTarget, options.cssClasses.rtl); } if (options.ort === 0) { addClass(addTarget, options.cssClasses.horizontal); } else { addClass(addTarget, options.cssClasses.vertical); } const textDirection = getComputedStyle(addTarget).direction; if (textDirection === "rtl") { addClass(addTarget, options.cssClasses.textDirectionRtl); } else { addClass(addTarget, options.cssClasses.textDirectionLtr); } return addNodeTo(addTarget, options.cssClasses.base); } function addTooltip(handle: HTMLElement, handleNumber: number): HTMLElement | false { if (!options.tooltips || !options.tooltips[handleNumber]) { return false; } return addNodeTo(handle.firstChild as HTMLElement, options.cssClasses.tooltip); } function isSliderDisabled(): boolean { return scope_Target.hasAttribute("disabled"); } // Disable the slider dragging if any handle is disabled function isHandleDisabled(handleNumber: number): boolean { const handleOrigin = scope_Handles[handleNumber]; return handleOrigin.hasAttribute("disabled"); } function disable(handleNumber?: number): void { if (handleNumber !== null && handleNumber !== undefined) { scope_Handles[handleNumber].setAttribute("disabled", ""); scope_Handles[handleNumber].handle.removeAttribute("tabindex"); } else { scope_Target.setAttribute("disabled", ""); scope_Handles.forEach(function (handle) { handle.handle.removeAttribute("tabindex"); }); } } function enable(handleNumber?: number): void { if (handleNumber !== null && handleNumber !== undefined) { scope_Handles[handleNumber].removeAttribute("disabled"); scope_Handles[handleNumber].handle.setAttribute("tabindex", "0"); } else { scope_Target.removeAttribute("disabled"); scope_Handles.forEach(function (handle) { handle.removeAttribute("disabled"); handle.handle.setAttribute("tabindex", "0"); }); } } function removeTooltips(): void { if (scope_Tooltips) { removeEvent("update" + INTERNAL_EVENT_NS.tooltips); scope_Tooltips.forEach(function (tooltip) { if (tooltip) { removeElement(tooltip); } }); scope_Tooltips = null; } } // The tooltips option is a shorthand for using the 'update' event. function tooltips(): void { removeTooltips(); // Tooltips are added with options.tooltips in original order. scope_Tooltips = scope_Handles.map(addTooltip); bindEvent("update" + INTERNAL_EVENT_NS.tooltips, function (values, handleNumber, unencoded) { if (!scope_Tooltips || !options.tooltips) { return; } if (scope_Tooltips[handleNumber] === false) { return; } let formattedValue = values[handleNumber]; if (options.tooltips[handleNumber] !== true) { formattedValue = (<Formatter>options.tooltips[handleNumber]).to(unencoded[handleNumber]); } (<HTMLElement>scope_Tooltips[handleNumber]).innerHTML = <string>formattedValue; }); } function aria(): void { removeEvent("update" + INTERNAL_EVENT_NS.aria); bindEvent("update" +