import { __decorate } from "tslib";
import { ChangeDetectionStrategy, Component, computed, ElementRef, inject, Input, signal, ViewChildren, } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { TuiControl } from '@taiga-ui/cdk/classes';
import { EMPTY_QUERY } from '@taiga-ui/cdk/constants';
import { tuiFallbackValueProvider } from '@taiga-ui/cdk/tokens';
import { tuiInjectElement } from '@taiga-ui/cdk/utils/dom';
import { tuiClamp, tuiQuantize } from '@taiga-ui/cdk/utils/math';
import { tuiPure } from '@taiga-ui/cdk/utils/miscellaneous';
import { TUI_SLIDER_OPTIONS, tuiKeyStepValueToPercentage, tuiPercentageToKeyStepValue, TuiSlider, TuiSliderComponent, } from '@taiga-ui/kit/components/slider';
import { TuiRangeChange } from './range-change.directive';
import * as i0 from "@angular/core";
import * as i1 from "./range-change.directive";
import * as i2 from "@angular/forms";
import * as i3 from "@taiga-ui/kit/components/slider";
class TuiRange extends TuiControl {
    constructor() {
        super(...arguments);
        // TODO: refactor to signal inputs after Angular update
        this.changes = signal(1);
        this.el = tuiInjectElement();
        this.options = inject(TUI_SLIDER_OPTIONS);
        this.lastActiveThumb = 'end';
        this.min = 0;
        this.max = 100;
        this.step = 1;
        this.size = this.options.size;
        this.segments = 1;
        this.keySteps = null;
        this.focusable = true;
        this.margin = 0;
        this.limit = Infinity;
        this.slidersRefs = EMPTY_QUERY;
        this.start = computed(() => this.toPercent(this.value()[0]));
        this.end = computed(() => 100 - this.toPercent(this.value()[1]));
        /**
         * TODO(v5): standardize logic between `TuiSlider` & `TuiInputSlider` & `Range` & `InputRange`
         * For non-linear slider (with `[keySteps]` property) `step` means percentage
         */
        this.legacyMode = true;
    }
    ngOnChanges() {
        this.changes.update((x) => x + 1);
    }
    processValue(value, end) {
        if (end) {
            this.updateEnd(value);
        }
        else {
            this.updateStart(value);
        }
        this.lastActiveThumb = end ? 'end' : 'start';
    }
    takeStep(coefficients) {
        return this.value().map((value, i) => {
            const fraction = this.toPercent(value) / 100;
            const newFractionValue = fraction + coefficients[i] * this.fractionStep;
            return this.toValue(newFractionValue);
        });
    }
    toValue(fraction) {
        return tuiPercentageToKeyStepValue(tuiClamp(tuiQuantize(fraction, this.fractionStep), 0, 1) * 100, this.computedKeySteps);
    }
    get fractionStep() {
        return this.legacyMode || !this.keySteps
            ? this.step / (this.max - this.min)
            : this.step / 100;
    }
    get computedKeySteps() {
        return this.computePureKeySteps(this.keySteps, this.min, this.max);
    }
    get segmentWidthRatio() {
        return 1 / this.segments;
    }
    get rtl() {
        return this.el.matches('[dir="rtl"] :scope');
    }
    changeByStep(coefficient, target) {
        const [startThumb, endThumb] = this.slidersRefs.map((x) => x?.nativeElement);
        const isEndThumb = target === this.el ? this.lastActiveThumb === 'end' : target === endThumb;
        const activeThumbElement = isEndThumb ? endThumb : startThumb;
        const newValue = this.takeStep(isEndThumb ? [0, coefficient] : [coefficient, 0]);
        this.processValue(newValue[isEndThumb ? 1 : 0], isEndThumb);
        activeThumbElement?.focus();
    }
    toPercent(value) {
        return (this.changes() && tuiKeyStepValueToPercentage(value, this.computedKeySteps));
    }
    computePureKeySteps(keySteps, min, max) {
        return (keySteps || [
            [0, min],
            [100, max],
        ]);
    }
    updateStart(value) {
        const newValue = Math.min(value, this.value()[1]);
        const distance = this.value()[1] - newValue;
        if (!this.checkDistance(distance)) {
            return;
        }
        this.onChange([newValue, this.value()[1]]);
    }
    updateEnd(value) {
        const newValue = Math.max(value, this.value()[0]);
        const distance = newValue - this.value()[0];
        if (!this.checkDistance(distance)) {
            return;
        }
        this.onChange([this.value()[0], newValue]);
    }
    checkDistance(distance) {
        return tuiClamp(distance, this.margin, this.limit) === distance;
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.2.12", ngImport: i0, type: TuiRange, deps: null, target: i0.ɵɵFactoryTarget.Component }); }
    static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "16.2.12", type: TuiRange, isStandalone: true, selector: "tui-range", inputs: { min: "min", max: "max", step: "step", size: "size", segments: "segments", keySteps: "keySteps", focusable: "focusable", margin: "margin", limit: "limit" }, host: { listeners: { "focusout": "onTouched()", "keydown.arrowUp.prevent": "changeByStep(1, $event.target)", "keydown.arrowDown.prevent": "changeByStep(-1, $event.target)", "keydown.arrowRight.prevent": "changeByStep(rtl ? -1 : 1, $event.target)", "keydown.arrowLeft.prevent": "changeByStep(rtl ? 1 : -1, $event.target)" }, properties: { "attr.data-size": "size", "attr.tabindex": "-1", "attr.aria-disabled": "disabled()", "style.--t-start.%": "start()", "style.--t-end.%": "end()", "style.background": "options.trackColor", "class._disabled": "disabled()" } }, providers: [tuiFallbackValueProvider([0, 0])], viewQueries: [{ propertyName: "slidersRefs", predicate: TuiSliderComponent, descendants: true, read: ElementRef }], usesInheritance: true, usesOnChanges: true, hostDirectives: [{ directive: i1.TuiRangeChange, outputs: ["activeThumbChange", "activeThumbChange"] }], ngImport: i0, template: "<div\n    class=\"t-track\"\n    [style.--t-bg-size-ratio]=\"1 - segmentWidthRatio\"\n    [style.--t-segment-width.%]=\"segmentWidthRatio * 100\"\n>\n    <input\n        automation-id=\"tui-range__left\"\n        readonly\n        step=\"any\"\n        tuiSlider\n        type=\"range\"\n        class=\"t-thumb\"\n        [disabled]=\"disabled()\"\n        [keySteps]=\"computedKeySteps\"\n        [max]=\"max\"\n        [min]=\"min\"\n        [ngModel]=\"value()[0]\"\n        [ngModelOptions]=\"{standalone: true}\"\n        [size]=\"size\"\n        [tabIndex]=\"focusable ? 0 : -1\"\n    />\n    <input\n        automation-id=\"tui-range__right\"\n        readonly\n        step=\"any\"\n        tuiSlider\n        type=\"range\"\n        class=\"t-thumb\"\n        [disabled]=\"disabled()\"\n        [keySteps]=\"computedKeySteps\"\n        [max]=\"max\"\n        [min]=\"min\"\n        [ngModel]=\"value()[1]\"\n        [ngModelOptions]=\"{standalone: true}\"\n        [size]=\"size\"\n        [tabIndex]=\"focusable ? 0 : -1\"\n    />\n</div>\n", styles: [":host{position:relative;display:block;block-size:var(--tui-thickness);border-radius:var(--tui-radius-m);cursor:pointer;outline:none;margin:calc((1rem - var(--tui-thickness)) / 2) 0;touch-action:pan-x;--tui-thickness: .125rem}:host:active{cursor:ew-resize}:host:after{content:\"\";position:absolute;top:50%;block-size:1rem;inline-size:100%;transform:translateY(-50%)}:host._disabled{opacity:var(--tui-disabled-opacity);pointer-events:none}:host[data-size=s] .t-track{position:relative;margin:0 .25rem;block-size:100%}:host[data-size=s] .t-track:before{content:\"\";position:absolute;top:0;left:max(calc(var(--t-start) - 1px),1px);right:max(var(--t-end),1px);inset-inline-start:max(calc(var(--t-start) - 1px),1px);inset-inline-end:max(var(--t-end),1px);block-size:100%;background:var(--tui-background-accent-1);margin:0 -.25rem}:host[data-size=s] .t-track:after{position:absolute;top:0;left:0;bottom:0;right:0;content:\"\";left:.125rem;right:.375rem;inset-inline-start:.125rem;inset-inline-end:.375rem;background-image:repeating-linear-gradient(to var(--tui-inline-end),var(--tui-text-tertiary) 0 .25rem,transparent 0 calc(var(--t-segment-width) / var(--t-bg-size-ratio)));background-position-x:var(--tui-inline-end);background-repeat:no-repeat;background-size:calc(100% * var(--t-bg-size-ratio))}:host[data-size=m] .t-track{position:relative;margin:0 .375rem;block-size:100%}:host[data-size=m] .t-track:before{content:\"\";position:absolute;top:0;left:max(calc(var(--t-start) - 1px),1px);right:max(var(--t-end),1px);inset-inline-start:max(calc(var(--t-start) - 1px),1px);inset-inline-end:max(var(--t-end),1px);block-size:100%;background:var(--tui-background-accent-1);margin:0 -.375rem}:host[data-size=m] .t-track:after{position:absolute;top:0;left:0;bottom:0;right:0;content:\"\";left:.25rem;right:.5rem;inset-inline-start:.25rem;inset-inline-end:.5rem;background-image:repeating-linear-gradient(to var(--tui-inline-end),var(--tui-text-tertiary) 0 .25rem,transparent 0 calc(var(--t-segment-width) / var(--t-bg-size-ratio)));background-position-x:var(--tui-inline-end);background-repeat:no-repeat;background-size:calc(100% * var(--t-bg-size-ratio))}.t-thumb{pointer-events:none;position:absolute;top:50%;left:0;right:0;z-index:1;transform:translateY(-50%)}.t-thumb::-webkit-slider-thumb{pointer-events:auto}.t-thumb::-moz-range-thumb{pointer-events:auto}:host._disabled .t-thumb::-webkit-slider-thumb{pointer-events:none}:host._disabled .t-thumb::-moz-range-thumb{pointer-events:none}input[type=range].t-thumb::-webkit-slider-runnable-track{background:transparent}input[type=range].t-thumb::-moz-range-track{background:transparent}input[type=range].t-thumb::-moz-range-progress{background:transparent}.t-thumb:first-of-type{--tui-slider-thumb-transform: translateX(calc(var(--tui-inline) * -50%)) translateX(calc(var(--tui-inline) * -1px))}.t-thumb:last-of-type{--tui-slider-thumb-transform: translateX(calc(var(--tui-inline) * 50%)) translateX(calc(var(--tui-inline) * 1px))}:host._disabled .t-thumb{opacity:1}\n"], dependencies: [{ kind: "ngmodule", type: FormsModule }, { kind: "directive", type: i2.DefaultValueAccessor, selector: "input:not([type=checkbox])[formControlName],textarea[formControlName],input:not([type=checkbox])[formControl],textarea[formControl],input:not([type=checkbox])[ngModel],textarea[ngModel],[ngDefaultControl]" }, { kind: "directive", type: i2.RangeValueAccessor, selector: "input[type=range][formControlName],input[type=range][formControl],input[type=range][ngModel]" }, { kind: "directive", type: i2.NgControlStatus, selector: "[formControlName],[ngModel],[formControl]" }, { kind: "directive", type: i2.NgModel, selector: "[ngModel]:not([formControlName]):not([formControl])", inputs: ["name", "disabled", "ngModel", "ngModelOptions"], outputs: ["ngModelChange"], exportAs: ["ngModel"] }, { kind: "component", type: i3.TuiSliderComponent, selector: "input[type=range][tuiSlider]", inputs: ["size", "segments"] }, { kind: "directive", type: i3.TuiSliderKeyStepsBase, selector: "input[tuiSlider][keySteps]", inputs: ["step", "keySteps"] }, { kind: "directive", type: i3.TuiSliderKeySteps, selector: "input[tuiSlider][keySteps][ngModel],input[tuiSlider][keySteps][formControl],input[tuiSlider][keySteps][formControlName]", inputs: ["keySteps"] }, { kind: "directive", type: i3.TuiSliderReadonly, selector: "input[tuiSlider][readonly]", inputs: ["readonly"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush }); }
}
__decorate([
    tuiPure
], TuiRange.prototype, "computePureKeySteps", null);
export { TuiRange };
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.2.12", ngImport: i0, type: TuiRange, decorators: [{
            type: Component,
            args: [{ standalone: true, selector: 'tui-range', imports: [FormsModule, TuiSlider], changeDetection: ChangeDetectionStrategy.OnPush, providers: [tuiFallbackValueProvider([0, 0])], hostDirectives: [
                        {
                            directive: TuiRangeChange,
                            outputs: ['activeThumbChange'],
                        },
                    ], host: {
                        '[attr.data-size]': 'size',
                        '[attr.tabindex]': '-1',
                        '[attr.aria-disabled]': 'disabled()',
                        '[style.--t-start.%]': 'start()',
                        '[style.--t-end.%]': 'end()',
                        '[style.background]': 'options.trackColor',
                        '[class._disabled]': 'disabled()',
                        '(focusout)': 'onTouched()',
                        '(keydown.arrowUp.prevent)': 'changeByStep(1, $event.target)',
                        '(keydown.arrowDown.prevent)': 'changeByStep(-1, $event.target)',
                        '(keydown.arrowRight.prevent)': 'changeByStep(rtl ? -1 : 1, $event.target)',
                        '(keydown.arrowLeft.prevent)': 'changeByStep(rtl ? 1 : -1, $event.target)',
                    }, template: "<div\n    class=\"t-track\"\n    [style.--t-bg-size-ratio]=\"1 - segmentWidthRatio\"\n    [style.--t-segment-width.%]=\"segmentWidthRatio * 100\"\n>\n    <input\n        automation-id=\"tui-range__left\"\n        readonly\n        step=\"any\"\n        tuiSlider\n        type=\"range\"\n        class=\"t-thumb\"\n        [disabled]=\"disabled()\"\n        [keySteps]=\"computedKeySteps\"\n        [max]=\"max\"\n        [min]=\"min\"\n        [ngModel]=\"value()[0]\"\n        [ngModelOptions]=\"{standalone: true}\"\n        [size]=\"size\"\n        [tabIndex]=\"focusable ? 0 : -1\"\n    />\n    <input\n        automation-id=\"tui-range__right\"\n        readonly\n        step=\"any\"\n        tuiSlider\n        type=\"range\"\n        class=\"t-thumb\"\n        [disabled]=\"disabled()\"\n        [keySteps]=\"computedKeySteps\"\n        [max]=\"max\"\n        [min]=\"min\"\n        [ngModel]=\"value()[1]\"\n        [ngModelOptions]=\"{standalone: true}\"\n        [size]=\"size\"\n        [tabIndex]=\"focusable ? 0 : -1\"\n    />\n</div>\n", styles: [":host{position:relative;display:block;block-size:var(--tui-thickness);border-radius:var(--tui-radius-m);cursor:pointer;outline:none;margin:calc((1rem - var(--tui-thickness)) / 2) 0;touch-action:pan-x;--tui-thickness: .125rem}:host:active{cursor:ew-resize}:host:after{content:\"\";position:absolute;top:50%;block-size:1rem;inline-size:100%;transform:translateY(-50%)}:host._disabled{opacity:var(--tui-disabled-opacity);pointer-events:none}:host[data-size=s] .t-track{position:relative;margin:0 .25rem;block-size:100%}:host[data-size=s] .t-track:before{content:\"\";position:absolute;top:0;left:max(calc(var(--t-start) - 1px),1px);right:max(var(--t-end),1px);inset-inline-start:max(calc(var(--t-start) - 1px),1px);inset-inline-end:max(var(--t-end),1px);block-size:100%;background:var(--tui-background-accent-1);margin:0 -.25rem}:host[data-size=s] .t-track:after{position:absolute;top:0;left:0;bottom:0;right:0;content:\"\";left:.125rem;right:.375rem;inset-inline-start:.125rem;inset-inline-end:.375rem;background-image:repeating-linear-gradient(to var(--tui-inline-end),var(--tui-text-tertiary) 0 .25rem,transparent 0 calc(var(--t-segment-width) / var(--t-bg-size-ratio)));background-position-x:var(--tui-inline-end);background-repeat:no-repeat;background-size:calc(100% * var(--t-bg-size-ratio))}:host[data-size=m] .t-track{position:relative;margin:0 .375rem;block-size:100%}:host[data-size=m] .t-track:before{content:\"\";position:absolute;top:0;left:max(calc(var(--t-start) - 1px),1px);right:max(var(--t-end),1px);inset-inline-start:max(calc(var(--t-start) - 1px),1px);inset-inline-end:max(var(--t-end),1px);block-size:100%;background:var(--tui-background-accent-1);margin:0 -.375rem}:host[data-size=m] .t-track:after{position:absolute;top:0;left:0;bottom:0;right:0;content:\"\";left:.25rem;right:.5rem;inset-inline-start:.25rem;inset-inline-end:.5rem;background-image:repeating-linear-gradient(to var(--tui-inline-end),var(--tui-text-tertiary) 0 .25rem,transparent 0 calc(var(--t-segment-width) / var(--t-bg-size-ratio)));background-position-x:var(--tui-inline-end);background-repeat:no-repeat;background-size:calc(100% * var(--t-bg-size-ratio))}.t-thumb{pointer-events:none;position:absolute;top:50%;left:0;right:0;z-index:1;transform:translateY(-50%)}.t-thumb::-webkit-slider-thumb{pointer-events:auto}.t-thumb::-moz-range-thumb{pointer-events:auto}:host._disabled .t-thumb::-webkit-slider-thumb{pointer-events:none}:host._disabled .t-thumb::-moz-range-thumb{pointer-events:none}input[type=range].t-thumb::-webkit-slider-runnable-track{background:transparent}input[type=range].t-thumb::-moz-range-track{background:transparent}input[type=range].t-thumb::-moz-range-progress{background:transparent}.t-thumb:first-of-type{--tui-slider-thumb-transform: translateX(calc(var(--tui-inline) * -50%)) translateX(calc(var(--tui-inline) * -1px))}.t-thumb:last-of-type{--tui-slider-thumb-transform: translateX(calc(var(--tui-inline) * 50%)) translateX(calc(var(--tui-inline) * 1px))}:host._disabled .t-thumb{opacity:1}\n"] }]
        }], propDecorators: { min: [{
                type: Input
            }], max: [{
                type: Input
            }], step: [{
                type: Input
            }], size: [{
                type: Input
            }], segments: [{
                type: Input
            }], keySteps: [{
                type: Input
            }], focusable: [{
                type: Input
            }], margin: [{
                type: Input
            }], limit: [{
                type: Input
            }], slidersRefs: [{
                type: ViewChildren,
                args: [TuiSliderComponent, { read: ElementRef }]
            }], computePureKeySteps: [] } });
//# sourceMappingURL=data:application/json;base64, 