/*!
 * Custom elements for Nanopore-Digital Web applications
 */
import { proxyCustomElement, HTMLElement, createEvent, Host } from '@stencil/core/internal/client';
import { h } from './renderer.js';
import { a as clamp } from './math.js';
import { a as debounceEvent } from './throttle.js';

const rangeCss = ".sc-nano-range-h,*.sc-nano-range,*.sc-nano-range::before,*.sc-nano-range::after{box-sizing:border-box}[hidden].sc-nano-range{display:none !important}@media (prefers-reduced-motion: reduce){.sc-nano-range-h,*.sc-nano-range,*.sc-nano-range::before,*.sc-nano-range::after{animation-duration:0.01ms !important;animation-iteration-count:1 !important;transition-duration:0.01ms !important;scroll-behavior:auto !important}}.sc-nano-range-h,*.sc-nano-range,*.sc-nano-range::before,*.sc-nano-range::after{box-sizing:border-box}[hidden].sc-nano-range{display:none !important}@media (prefers-reduced-motion: reduce){.sc-nano-range-h,*.sc-nano-range,*.sc-nano-range::before,*.sc-nano-range::after{animation-duration:0.01ms !important;animation-iteration-count:1 !important;transition-duration:0.01ms !important;scroll-behavior:auto !important}}.sc-nano-range-h{--inactive-color:var(--nano-color-neutral-800);--knob-color:var(--nano-color-primary-1200);--knob-active-color:var(--nano-color-primary-1400);--knob-width:1.75rem;--knob-height:1.25rem;--bar-height:.5em;--bar-background:var(--nano-color-neutral-300);--bar-background-active:var(--nano-color-primary-1000);--tooltip-background:var(--nano-color-base-0);--tooltip-color:var(--nano-color-neutral-1400)}.range-wrap.sc-nano-range{display:flex;position:relative;flex:3;align-items:center;-webkit-user-select:none;user-select:none}.range-wrap.sc-nano-range-s>ion-icon[slot],.range-wrap .sc-nano-range-s>ion-icon[slot]{font-size:1.5em}.range-wrap.sc-nano-range-s>[slot=start],.range-wrap .sc-nano-range-s>[slot=start]{margin-inline:0 calc(var(--knob-width) * 0.66);margin-block:0;font-size:0.9em}.range-wrap.sc-nano-range-s>[slot=end],.range-wrap .sc-nano-range-s>[slot=end]{margin-inline:calc(var(--knob-width) * 0.66) 0;margin-block:0;font-size:0.9em}.range-slider.sc-nano-range{position:relative;flex:1;inline-size:100%;block-size:var(--knob-height);contain:size layout style;cursor:grab;touch-action:pan-y}.range-pressed.sc-nano-range-h .range-slider.sc-nano-range{cursor:grabbing}.range-label.sc-nano-range{inline-size:100%;overflow:clip;white-space:nowrap;text-overflow:ellipsis;color:var(--nano-color-base-1000);font-size:var(--nano-font-size-xs);padding-block-end:var(--nano-spacing-sm);line-height:1;display:flex;align-items:center}.visually-hidden.sc-nano-range{clip-path:inset(50%);block-size:1px;overflow:hidden;position:absolute;white-space:nowrap;inline-size:1px}.range-bar.sc-nano-range{inset-block-start:calc((var(--knob-height) - var(--bar-height)) / 2);inset-inline-start:0;position:absolute;inline-size:100%;block-size:var(--bar-height);background:var(--bar-background);pointer-events:none}.range-bar-active.sc-nano-range{inset-block-end:0;inline-size:auto;background:var(--bar-background-active)}.range-knob.sc-nano-range{border-radius:var(--nano-border-radius-pill);position:absolute;inline-size:var(--knob-width);block-size:var(--knob-height);background:var(--knob-color);z-index:2;pointer-events:none;inset-block-start:50%;inset-inline-start:50%;translate:-50% -50%}.sc-nano-range-h:not(.range-has-pin) .range-knob-pressed.sc-nano-range .range-knob.sc-nano-range{background:var(--knob-active-color)}.range-knob-handle.sc-nano-range{inset-block-start:50%;translate:0 -50%;inset-inline-start:0;margin-inline-start:calc(0px - var(--knob-width));position:absolute;inline-size:calc(var(--knob-width) * 2);block-size:calc(var(--knob-height) * 2);text-align:center}.range-knob-handle.sc-nano-range:focus{outline:none}.range-knob-handle.sc-nano-range:focus .range-knob.sc-nano-range{outline:var(--nano-focus-ring)}.range-tick.sc-nano-range{position:absolute;inset-block-start:calc((var(--knob-height) - var(--bar-height)) / 2);inline-size:var(--bar-height);block-size:var(--bar-height);background:var(--inactive-color);z-index:1;pointer-events:none}.range-tick-active.sc-nano-range{background:transparent}.range-pin.sc-nano-range{transform:translate3d(0, 0, 0) scale(0.01);transform-origin:center top;padding:0.66em 0;text-align:center;box-sizing:border-box;display:inline-block;position:relative;min-inline-size:2.33em;block-size:2.33em;transition:transform 120ms ease, background 120ms ease;background:var(--tooltip-background);color:var(--tooltip-color);font-size:0.75em;box-shadow:var(--nano-shadow-l1)}.range-knob-pressed.sc-nano-range .range-pin.sc-nano-range{transform:translate3d(0, -100%, 0) scale(1)}.range-disabled.sc-nano-range-h{pointer-events:none}.range-disabled.sc-nano-range-h .range-bar-active.sc-nano-range,.range-disabled.sc-nano-range-h .range-bar.sc-nano-range,.range-disabled.sc-nano-range-h .range-tick.sc-nano-range{background-color:var(--inactive-color)}.range-disabled.sc-nano-range-h .range-knob.sc-nano-range{transform:scale(0.55);outline:5px solid #fff;background-color:var(--inactive-color)}";

const Range = /*@__PURE__*/ proxyCustomElement(class Range extends HTMLElement {
    constructor() {
        super();
        this.__registerHost();
        this.nanoChange = createEvent(this, "nanoChange", 7);
        this.nanoStyle = createEvent(this, "nanoStyle", 7);
        this.nanoFocus = createEvent(this, "nanoFocus", 7);
        this.nanoBlur = createEvent(this, "nanoBlur", 7);
    }
    noUpdate = false;
    rect;
    hasFocus = false;
    rangeSlider;
    gesture;
    get el() { return this; }
    ratioA = 0;
    ratioB = 0;
    pressedKnob;
    /**
     * How long, in milliseconds, to wait to trigger the
     * `nanoChange` event after each change in the range value.
     */
    debounce = 0;
    debounceChanged() {
        this.nanoChange = debounceEvent(this.nanoChange, this.debounce);
    }
    /**
     * The name of the control, which is submitted with the form data.
     */
    name = '';
    /**
     * If `true`, the user must fill in a value before submitting a form.
     * By default, setting this will also add an asterisk to the label.
     */
    required = false;
    /**
     * Visually hide the label - but make it accessible.
     */
    hideLabel = false;
    _label = '';
    /**
     * String to place within a label element. Alternatively you may use a label slot.
     */
    get label() {
        return this.required && !this._label.endsWith('*')
            ? this._label + ' *'
            : this._label;
    }
    set label(value) {
        this._label = value;
    }
    /**
     * Show two knobs.
     */
    dualKnobs = false;
    /**
     * Minimum integer value of the range.
     */
    min = 0;
    minChanged() {
        if (!this.noUpdate) {
            this.updateRatio();
        }
    }
    /**
     * Maximum integer value of the range.
     */
    max = 100;
    maxChanged() {
        if (!this.noUpdate) {
            this.updateRatio();
        }
    }
    /**
     * If `true`, a tooltip with integer value is shown when the knob
     * is pressed.
     */
    tooltip = true;
    /**
     * If `true`, the knob snaps to tick marks evenly spaced based
     * on the `step` property value.
     */
    snaps = false;
    /**
     * Specifies the value granularity.
     */
    step = 1;
    /**
     * If `true`, tick marks are displayed based on the step value.
     * Only applies when `snaps` is `true`.
     */
    ticks = false;
    /**
     * If `true`, the user cannot interact with the range.
     */
    disabled = false;
    disabledChanged() {
        if (this.gesture) {
            this.gesture.enable(!this.disabled);
        }
        this.emitStyle();
    }
    /**
     * the value of the range.
     */
    value = 0;
    valueChanged(value) {
        if (!this.noUpdate) {
            this.updateRatio();
        }
        value = this.ensureValueInBounds(value);
        this.nanoChange.emit({ value });
    }
    clampBounds = (value) => {
        return clamp(this.min, value, this.max);
    };
    ensureValueInBounds = (value) => {
        if (this.dualKnobs) {
            return {
                lower: this.clampBounds(value.lower),
                upper: this.clampBounds(value.upper),
            };
        }
        else {
            return this.clampBounds(value);
        }
    };
    /**
     * Emitted when the value property has changed.
     */
    nanoChange;
    /**
     * Emitted when the styles change.
     * @internal
     */
    nanoStyle;
    /**
     * Emitted when the range has focus.
     */
    nanoFocus;
    /**
     * Emitted when the range loses focus.
     */
    nanoBlur;
    connectedCallback() {
        this.updateRatio();
        this.debounceChanged();
        this.disabledChanged();
    }
    disconnectedCallback() {
        if (this.gesture) {
            this.gesture.destroy();
            this.gesture = undefined;
        }
    }
    async componentDidLoad() {
        const rangeSlider = this.rangeSlider;
        if (rangeSlider) {
            this.gesture = (await import('./index3.js')).createGesture({
                el: rangeSlider,
                gestureName: 'range',
                gesturePriority: 100,
                threshold: 0,
                onStart: (ev) => this.onStart(ev),
                onMove: (ev) => this.onMove(ev),
                onEnd: (ev) => this.onEnd(ev),
            });
            this.gesture.enable(!this.disabled);
        }
    }
    handleKeyboard = (knob, isIncrease) => {
        let step = this.step;
        step = step > 0 ? step : 1;
        step = step / (this.max - this.min);
        if (!isIncrease) {
            step *= -1;
        }
        if (knob === 'A') {
            this.ratioA = clamp(0, this.ratioA + step, 1);
        }
        else {
            this.ratioB = clamp(0, this.ratioB + step, 1);
        }
        this.updateValue();
    };
    getValue() {
        const value = this.value || 0;
        if (this.dualKnobs) {
            if (typeof value === 'object') {
                return value;
            }
            return {
                lower: 0,
                upper: value,
            };
        }
        else {
            if (typeof value === 'object') {
                return value.upper;
            }
            return value;
        }
    }
    emitStyle() {
        this.nanoStyle.emit({
            interactive: true,
            'interactive-disabled': this.disabled,
        });
    }
    onStart(detail) {
        const rect = (this.rect = this.rangeSlider.getBoundingClientRect());
        const currentX = detail.currentX;
        // figure out which knob they started closer to
        let ratio = clamp(0, (currentX - rect.left) / rect.width, 1);
        if (document.dir === 'rtl') {
            ratio = 1 - ratio;
        }
        this.pressedKnob =
            !this.dualKnobs ||
                Math.abs(this.ratioA - ratio) < Math.abs(this.ratioB - ratio)
                ? 'A'
                : 'B';
        this.setFocus(this.pressedKnob);
        // update the active knob's position
        this.update(currentX);
    }
    onMove(detail) {
        this.update(detail.currentX);
    }
    onEnd(detail) {
        this.update(detail.currentX);
        this.pressedKnob = undefined;
    }
    update(currentX) {
        // figure out where the pointer is currently at
        // update the knob being interacted with
        const rect = this.rect;
        let ratio = clamp(0, (currentX - rect.left) / rect.width, 1);
        if (document.dir === 'rtl') {
            ratio = 1 - ratio;
        }
        if (this.snaps) {
            // snaps the ratio to the current value
            ratio = valueToRatio(ratioToValue(ratio, this.min, this.max, this.step), this.min, this.max);
        }
        // update which knob is pressed
        if (this.pressedKnob === 'A') {
            this.ratioA = ratio;
        }
        else {
            this.ratioB = ratio;
        }
        // Update input value
        this.updateValue();
    }
    get valA() {
        return ratioToValue(this.ratioA, this.min, this.max, this.step);
    }
    get valB() {
        return ratioToValue(this.ratioB, this.min, this.max, this.step);
    }
    get ratioLower() {
        if (this.dualKnobs) {
            return Math.min(this.ratioA, this.ratioB);
        }
        return 0;
    }
    get ratioUpper() {
        if (this.dualKnobs) {
            return Math.max(this.ratioA, this.ratioB);
        }
        return this.ratioA;
    }
    updateRatio() {
        const value = this.getValue();
        const { min, max } = this;
        if (this.dualKnobs) {
            this.ratioA = valueToRatio(value.lower, min, max);
            this.ratioB = valueToRatio(value.upper, min, max);
        }
        else {
            this.ratioA = valueToRatio(value, min, max);
        }
    }
    updateValue() {
        this.noUpdate = true;
        const { valA, valB } = this;
        this.value = !this.dualKnobs
            ? valA
            : {
                lower: Math.min(valA, valB),
                upper: Math.max(valA, valB),
            };
        this.noUpdate = false;
    }
    setFocus(knob) {
        const knobEl = this.el.querySelector(knob === 'A' ? '.range-knob-a' : '.range-knob-b');
        if (knobEl) {
            knobEl.focus();
        }
    }
    onBlur = () => {
        if (this.hasFocus) {
            this.hasFocus = false;
            this.nanoBlur.emit();
            this.emitStyle();
        }
    };
    onFocus = () => {
        if (!this.hasFocus) {
            this.hasFocus = true;
            this.nanoFocus.emit();
            this.emitStyle();
        }
    };
    render() {
        const { min, max, step, handleKeyboard, pressedKnob, disabled, tooltip, ratioLower, ratioUpper, } = this;
        const barStart = `${ratioLower * 100}%`;
        const barEnd = `${100 - ratioUpper * 100}%`;
        const doc = document;
        const isRTL = doc.dir === 'rtl';
        const start = isRTL ? 'right' : 'left';
        const end = isRTL ? 'left' : 'right';
        const tickStyle = (tick) => {
            return {
                [start]: tick[start],
            };
        };
        const barStyle = {
            [start]: barStart,
            [end]: barEnd,
        };
        const ticks = [];
        if (this.snaps && this.ticks) {
            for (let value = min; value <= max; value += step) {
                const ratio = valueToRatio(value, min, max);
                const tick = {
                    ratio,
                    active: ratio >= ratioLower && ratio <= ratioUpper,
                };
                tick[start] = `${ratio * 100}%`;
                ticks.push(tick);
            }
        }
        return (h(Host, { onFocusin: this.onFocus, onFocusout: this.onBlur, class: {
                'range-disabled': disabled,
                'range-pressed': pressedKnob !== undefined,
                'range-has-pin': tooltip,
                'range-snaps': this.snaps,
                'nano-range': true,
            } }, h("label", { class: `range-label${this.hideLabel ? ' visually-hidden' : ''}`, part: "label", htmlFor: this.name }, h("slot", { name: "label" }, this.label)), h("input", { class: "range-input visually-hidden", name: this.name, id: this.name, disabled: this.disabled, required: this.required, value: JSON.stringify(this.getValue()), onFocus: () => {
                this.setFocus(this.pressedKnob || 'A');
            } }), h("div", { class: "range-wrap" }, h("slot", { name: "start" }), h("div", { class: "range-slider", ref: (rangeEl) => (this.rangeSlider = rangeEl) }, ticks.map((tick) => (h("span", { style: tickStyle(tick), role: "presentation", class: {
                'range-tick': true,
                'range-tick-active': tick.active,
            }, part: tick.active ? 'tick-active' : 'tick' }))), h("div", { class: "range-bar", role: "presentation", part: "bar" }), h("div", { class: "range-bar range-bar-active", role: "presentation", style: barStyle, part: "bar-active" }), renderKnob(isRTL, {
            knob: 'A',
            pressed: pressedKnob === 'A',
            value: this.valA,
            ratio: this.ratioA,
            tooltip,
            disabled,
            handleKeyboard,
            min,
            max,
        }), this.dualKnobs &&
            renderKnob(isRTL, {
                knob: 'B',
                pressed: pressedKnob === 'B',
                value: this.valB,
                ratio: this.ratioB,
                tooltip,
                disabled,
                handleKeyboard,
                min,
                max,
            })), h("slot", { name: "end" }))));
    }
    static get watchers() { return {
        "debounce": ["debounceChanged"],
        "min": ["minChanged"],
        "max": ["maxChanged"],
        "disabled": ["disabledChanged"],
        "value": ["valueChanged"]
    }; }
    static get style() { return rangeCss; }
}, [262, "nano-range", {
        "debounce": [2],
        "name": [1],
        "required": [4],
        "hideLabel": [4, "hide-label"],
        "label": [7169],
        "dualKnobs": [4, "dual-knobs"],
        "min": [2],
        "max": [2],
        "tooltip": [4],
        "snaps": [4],
        "step": [2],
        "ticks": [4],
        "disabled": [4],
        "value": [1026],
        "ratioA": [32],
        "ratioB": [32],
        "pressedKnob": [32]
    }, undefined, {
        "debounce": ["debounceChanged"],
        "min": ["minChanged"],
        "max": ["maxChanged"],
        "disabled": ["disabledChanged"],
        "value": ["valueChanged"]
    }]);
const renderKnob = (isRTL, { knob, value, ratio, min, max, disabled, pressed, tooltip, handleKeyboard, }) => {
    const start = isRTL ? 'right' : 'left';
    const knobStyle = () => {
        const style = {};
        style[start] = `${ratio * 100}%`;
        return style;
    };
    return (h("div", { onKeyDown: (ev) => {
            const key = ev.key;
            if (key === 'ArrowLeft' || key === 'ArrowDown') {
                handleKeyboard(knob, false);
                ev.preventDefault();
                ev.stopPropagation();
            }
            else if (key === 'ArrowRight' || key === 'ArrowUp') {
                handleKeyboard(knob, true);
                ev.preventDefault();
                ev.stopPropagation();
            }
        }, class: {
            'range-knob-handle': true,
            'range-knob-a': knob === 'A',
            'range-knob-b': knob === 'B',
            'range-knob-pressed': pressed,
            'range-knob-min': value === min,
            'range-knob-max': value === max,
        }, style: knobStyle(), role: "slider", tabindex: disabled ? -1 : 0, "aria-valuemin": min, "aria-valuemax": max, "aria-disabled": disabled ? 'true' : null, "aria-valuenow": value }, tooltip && (h("div", { class: "range-pin", role: "presentation", part: "pin" }, Math.round(value))), h("div", { class: "range-knob", role: "presentation", part: "knob" })));
};
const ratioToValue = (ratio, min, max, step) => {
    let value = (max - min) * ratio;
    if (step > 0) {
        value = Math.round(value / step) * step + min;
    }
    return clamp(min, value, max);
};
const valueToRatio = (value, min, max) => {
    return clamp(0, (value - min) / (max - min), 1);
};
function defineCustomElement$1() {
    if (typeof customElements === "undefined") {
        return;
    }
    const components = ["nano-range"];
    components.forEach(tagName => { switch (tagName) {
        case "nano-range":
            if (!customElements.get(tagName)) {
                customElements.define(tagName, Range);
            }
            break;
    } });
}

const NanoRange = Range;
const defineCustomElement = defineCustomElement$1;

export { NanoRange, defineCustomElement };
