riku
22 小时以前 cf4787bc8188cd0acc8a42793730b076742f29c1
miniprogram_npm/tdesign-miniprogram/slider/slider.js
@@ -1,308 +1 @@
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
import { SuperComponent, wxComponent } from '../common/src/index';
import config from '../common/config';
import { trimSingleValue, trimValue } from './tool';
import props from './props';
import { getRect } from '../common/utils';
import Bus from '../common/bus';
const { prefix } = config;
const name = `${prefix}-slider`;
let Slider = class Slider extends SuperComponent {
    constructor() {
        super(...arguments);
        this.externalClasses = [
            `${prefix}-class`,
            `${prefix}-class-bar`,
            `${prefix}-class-bar-active`,
            `${prefix}-class-bar-disabled`,
            `${prefix}-class-cursor`,
        ];
        this.properties = props;
        this.controlledProps = [
            {
                key: 'value',
                event: 'change',
            },
        ];
        this.data = {
            sliderStyles: '',
            classPrefix: name,
            initialLeft: null,
            initialRight: null,
            activeLeft: 0,
            activeRight: 0,
            maxRange: 0,
            lineLeft: 0,
            lineRight: 0,
            dotTopValue: [0, 0],
            _value: 0,
            blockSize: 20,
            isScale: false,
            scaleArray: [],
            scaleTextArray: [],
            prefix,
            isVisibleToScreenReader: false,
        };
        this.observers = {
            value(newValue) {
                this.handlePropsChange(newValue);
            },
            _value(newValue) {
                const { min, max, range } = this.properties;
                const { maxRange } = this.data;
                if (range) {
                    const left = (maxRange * (newValue[0] - Number(min))) / (Number(max) - Number(min));
                    const right = (maxRange * (Number(max) - newValue[1])) / (Number(max) - Number(min));
                    this.setLineStyle(left, right);
                }
                else {
                    this.setSingleBarWidth(newValue);
                }
                this.setData({
                    isVisibleToScreenReader: true,
                });
                setTimeout(() => {
                    this.setData({
                        isVisibleToScreenReader: false,
                    });
                }, 2e3);
            },
            marks(val) {
                if (this.data.initialLeft != null) {
                    this.handleMask(val);
                }
                else {
                    this.bus.on('initial', () => this.handleMask(val));
                }
            },
        };
        this.lifetimes = {
            created() {
                this.bus = new Bus();
            },
            attached() {
                const { value } = this.properties;
                if (!value)
                    this.handlePropsChange(0);
                this.getInitialStyle();
            },
        };
    }
    triggerValue(value) {
        if (this.preval === value)
            return;
        this.preval = value;
        this._trigger('change', {
            value: trimValue(value, this.properties),
        });
    }
    handlePropsChange(newValue) {
        const value = trimValue(newValue, this.properties);
        const setValueAndTrigger = () => {
            this.setData({
                _value: value,
            });
        };
        if (this.data.maxRange === 0) {
            this.getInitialStyle().then(setValueAndTrigger);
            return;
        }
        setValueAndTrigger();
    }
    handleMask(marks) {
        const calcPos = (arr) => {
            const { theme } = this.properties;
            const { blockSize, maxRange } = this.data;
            const margin = theme === 'capsule' ? blockSize / 2 : 0;
            return arr.map((item) => ({
                val: item,
                left: Math.round((item / 100) * maxRange) + margin,
            }));
        };
        if ((marks === null || marks === void 0 ? void 0 : marks.length) && Array.isArray(marks)) {
            this.setData({
                isScale: true,
                scaleArray: calcPos(marks),
                scaleTextArray: [],
            });
        }
        if (Object.prototype.toString.call(marks) === '[object Object]') {
            const scaleArray = Object.keys(marks).map((item) => Number(item));
            const scaleTextArray = scaleArray.map((item) => marks[item]);
            this.setData({
                isScale: scaleArray.length > 0,
                scaleArray: calcPos(scaleArray),
                scaleTextArray,
            });
        }
    }
    setSingleBarWidth(value) {
        const { max, min, theme } = this.properties;
        const { maxRange, blockSize } = this.data;
        const halfBlock = theme === 'capsule' ? Number(blockSize) / 2 : 0;
        const percentage = (Number(value) - Number(min)) / (Number(max) - Number(min));
        const width = percentage * maxRange + halfBlock;
        this.setData({
            lineBarWidth: `${width}px`,
        });
    }
    getInitialStyle() {
        return __awaiter(this, void 0, void 0, function* () {
            const line = yield getRect(this, '#sliderLine');
            const { blockSize } = this.data;
            const { theme } = this.properties;
            const halfBlock = Number(blockSize) / 2;
            let maxRange = line.right - line.left;
            let initialLeft = line.left;
            let initialRight = line.right;
            if (theme === 'capsule') {
                maxRange = maxRange - Number(blockSize) - 6;
                initialLeft -= halfBlock;
                initialRight -= halfBlock;
            }
            this.setData({
                maxRange,
                initialLeft,
                initialRight,
            });
            this.bus.emit('initial');
        });
    }
    stepValue(value) {
        const { step, min, max } = this.properties;
        const decimal = String(step).indexOf('.') > -1 ? String(step).length - String(step).indexOf('.') - 1 : 0;
        const closestStep = trimSingleValue(Number((Math.round(value / Number(step)) * Number(step)).toFixed(decimal)), Number(min), Number(max));
        return closestStep;
    }
    onSingleLineTap(e) {
        const { disabled } = this.properties;
        if (disabled)
            return;
        const value = this.getSingleChangeValue(e);
        this.triggerValue(value);
    }
    getSingleChangeValue(e) {
        const { min, max } = this.properties;
        const { initialLeft, maxRange } = this.data;
        const [touch] = e.changedTouches;
        const { pageX } = touch;
        const currentLeft = pageX - initialLeft;
        let value = 0;
        if (currentLeft <= 0) {
            value = Number(min);
        }
        else if (currentLeft >= maxRange) {
            value = Number(max);
        }
        else {
            value = (currentLeft / maxRange) * (Number(max) - Number(min)) + Number(min);
        }
        return this.stepValue(value);
    }
    convertPosToValue(posValue, dir) {
        const { maxRange } = this.data;
        const { max, min } = this.properties;
        return dir === 0
            ? (posValue / maxRange) * (Number(max) - Number(min)) + Number(min)
            : Number(max) - (posValue / maxRange) * (Number(max) - Number(min));
    }
    onLineTap(e) {
        const { disabled, theme } = this.properties;
        const { initialLeft, initialRight, maxRange, blockSize } = this.data;
        if (disabled)
            return;
        const [touch] = e.changedTouches;
        const { pageX } = touch;
        const halfBlock = theme === 'capsule' ? Number(blockSize) / 2 : 0;
        const currentLeft = pageX - initialLeft;
        if (currentLeft < 0 || currentLeft > maxRange + Number(blockSize))
            return;
        Promise.all([getRect(this, '#leftDot'), getRect(this, '#rightDot')]).then(([leftDot, rightDot]) => {
            const distanceLeft = Math.abs(pageX - leftDot.left - halfBlock);
            const distanceRight = Math.abs(rightDot.left - pageX + halfBlock);
            const isMoveLeft = distanceLeft < distanceRight;
            if (isMoveLeft) {
                const left = pageX - initialLeft;
                const leftValue = this.convertPosToValue(left, 0);
                this.triggerValue([this.stepValue(leftValue), this.data._value[1]]);
            }
            else {
                const right = -(pageX - initialRight);
                const rightValue = this.convertPosToValue(right, 1);
                this.triggerValue([this.data._value[0], this.stepValue(rightValue)]);
            }
        });
    }
    onTouchStart(e) {
        this.triggerEvent('dragstart', { e });
    }
    onTouchMoveLeft(e) {
        const { disabled } = this.properties;
        const { initialLeft, _value } = this.data;
        if (disabled)
            return;
        const [touch] = e.changedTouches;
        const { pageX } = touch;
        const currentLeft = pageX - initialLeft;
        const newData = [..._value];
        const leftValue = this.convertPosToValue(currentLeft, 0);
        newData[0] = this.stepValue(leftValue);
        this.triggerValue(newData);
    }
    onTouchMoveRight(e) {
        const { disabled } = this.properties;
        const { initialRight, _value } = this.data;
        if (disabled)
            return;
        const [touch] = e.changedTouches;
        const { pageX } = touch;
        const currentRight = -(pageX - initialRight);
        const newData = [..._value];
        const rightValue = this.convertPosToValue(currentRight, 1);
        newData[1] = this.stepValue(rightValue);
        this.triggerValue(newData);
    }
    setLineStyle(left, right) {
        const { theme } = this.properties;
        const { blockSize, maxRange } = this.data;
        const halfBlock = theme === 'capsule' ? Number(blockSize) / 2 : 0;
        const [a, b] = this.data._value;
        const cut = (v) => parseInt(v, 10);
        this.setData({
            dotTopValue: [a, b],
        });
        if (left + right <= maxRange) {
            this.setData({
                lineLeft: cut(left + halfBlock),
                lineRight: cut(right + halfBlock),
            });
        }
        else {
            this.setData({
                lineLeft: cut(maxRange + halfBlock - right),
                lineRight: cut(maxRange - left + halfBlock * 1.5),
            });
        }
    }
    onTouchEnd(e) {
        this.triggerEvent('dragend', { e });
    }
};
Slider = __decorate([
    wxComponent()
], Slider);
export default Slider;
import{__awaiter,__decorate}from"tslib";import{SuperComponent,wxComponent}from"../common/src/index";import config from"../common/config";import{trimSingleValue,trimValue}from"./tool";import props from"./props";import{getRect}from"../common/utils";import{isString,isFunction}from"../common/validator";import Bus from"../common/bus";const{prefix:prefix}=config,name=`${prefix}-slider`;let Slider=class extends SuperComponent{constructor(){super(...arguments),this.externalClasses=[`${prefix}-class`,`${prefix}-class-bar`,`${prefix}-class-bar-active`,`${prefix}-class-bar-disabled`,`${prefix}-class-cursor`],this.options={pureDataPattern:/^__/},this.properties=props,this.controlledProps=[{key:"value",event:"change"}],this.data={sliderStyles:"",classPrefix:name,initialLeft:null,initialRight:null,activeLeft:0,activeRight:0,maxRange:0,lineLeft:0,lineRight:0,dotTopValue:[0,0],_value:0,blockSize:20,isScale:!1,scaleArray:[],scaleTextArray:[],prefix:prefix,realLabel:"",extremeLabel:[],isVisibleToScreenReader:!1,identifier:[-1,-1],__inited:!1},this.observers={value(e){this.handlePropsChange(e)},_value(e){this.bus.on("initial",()=>this.renderLine(e)),this.toggleA11yTips()},marks(e){this.bus.on("initial",()=>this.handleMark(e))},label(e){this.setData({isShowLabel:Boolean(e)})},"showExtremeValue, min, max"(){this.getwExtremeLabel()}},this.lifetimes={created(){this.bus=new Bus},attached(){const{value:e}=this.properties;e||this.handlePropsChange(0),this.init(),this.injectPageScroll()}}}getwExtremeLabel(){const{showExtremeValue:e,min:t,max:i}=this.properties;e&&this.setData({extremeLabel:[this.getLabelByValue(Number(t),"min"),this.getLabelByValue(Number(i),"max")]})}injectPageScroll(){const{range:e,vertical:t}=this.properties;if(!e||!t)return;const i=getCurrentPages()||[];let a=null;if(i&&i.length-1>=0&&(a=i[i.length-1]),!a)return;const r=null==a?void 0:a.onPageScroll;a.onPageScroll=e=>{null==r||r.call(this,e),this.observerScrollTop(e)}}observerScrollTop(e){const{scrollTop:t}=e||{};this.pageScrollTop=t}toggleA11yTips(){this.setData({isVisibleToScreenReader:!0}),setTimeout(()=>{this.setData({isVisibleToScreenReader:!1})},2e3)}renderLine(e){const{min:t,max:i,range:a}=this.properties,{maxRange:r}=this.data;if(a){const a=r*(e[0]-Number(t))/(Number(i)-Number(t)),s=r*(Number(i)-e[1])/(Number(i)-Number(t));this.setLineStyle(a,s)}else this.setSingleBarWidth(e)}triggerValue(e){this.preval!==e&&(this.preval=e,this._trigger("change",{value:trimValue(e,this.properties)}))}getLabelByValue(e,t){const{label:i}=this.properties;if(isString(i)){let t=String(e);try{const a=/\${value}%/g;if(!a.test(i))throw t=i,new Error;t=i.replace(a,String(e))}catch(e){console.warn("fail to parse label prop, please pass string such as '${value}%'")}return t}return isFunction(i)?i(e,t):String(e)}handlePropsChange(e){const t=trimValue(e,this.properties),i=this.getLabelByValue(t);this.triggerValue(t);const a=()=>{this.setData({_value:t,realLabel:i})};0!==this.data.maxRange?a():this.init().then(a)}valueToPosition(e){const{min:t,max:i,theme:a}=this.properties,{blockSize:r,maxRange:s}=this.data,n="capsule"===a?Number(r)/2:0;return Math.round((Number(e)-Number(t))/(Number(i)-Number(t))*s)+n}handleMark(e){const t=e=>e.map(e=>({val:e,left:this.valueToPosition(e)}));if((null==e?void 0:e.length)&&Array.isArray(e)&&this.setData({isScale:!0,scaleArray:t(e),scaleTextArray:[]}),"[object Object]"===Object.prototype.toString.call(e)){const i=Object.keys(e).map(e=>Number(e)),a=i.map(t=>e[t]);this.setData({isScale:i.length>0,scaleArray:t(i),scaleTextArray:a})}}setSingleBarWidth(e){const t=this.valueToPosition(e);this.setData({lineBarWidth:`${t}px`})}init(){return __awaiter(this,void 0,void 0,function*(){if(this.data.__inited)return;const e=yield getRect(this,"#sliderLine"),{blockSize:t}=this.data,{theme:i,vertical:a}=this.properties,r=Number(t)/2,{top:s,bottom:n,right:l,left:o}=e;let h=a?n-s:l-o,u=a?s:o,c=a?n:l;0===u&&0===c||("capsule"===i&&(h=h-Number(t)-6,u-=r,c-=r),this.setData({maxRange:h,initialLeft:u,initialRight:c,__inited:!0}),this.bus.emit("initial"))})}stepValue(e){const{step:t,min:i,max:a}=this.properties,r=String(t).indexOf(".")>-1?String(t).length-String(t).indexOf(".")-1:0;return trimSingleValue(Number((Math.round(e/Number(t))*Number(t)).toFixed(r)),Number(i),Number(a))}onSingleLineTap(e){const{disabled:t}=this.properties;if(t)return;const i=-1===this.data.identifier[0];if(i){const[t]=e.changedTouches;this.data.identifier[0]=t.identifier}const a=this.getSingleChangeValue(e);i&&(this.data.identifier[0]=-1),this.triggerValue(a)}getSingleChangeValue(e){const{min:t,max:i,theme:a,vertical:r}=this.properties,{initialLeft:s,maxRange:n,blockSize:l}=this.data,o=e.changedTouches.find(e=>e.identifier===this.data.identifier[0]),h=this.getPagePosition(o);let u=0;"capsule"===a?(u=Number(l),r&&(u*=2),u+=6):r&&(u=Number(l));const c=h-s-u;let g=0;return g=c<=0?Number(t):c>=n?Number(i):c/n*(Number(i)-Number(t))+Number(t),this.stepValue(g)}convertPosToValue(e,t){const{maxRange:i}=this.data,{max:a,min:r}=this.properties;return 0===t?e/i*(Number(a)-Number(r))+Number(r):Number(a)-e/i*(Number(a)-Number(r))}onLineTap(e){const{disabled:t,theme:i,vertical:a}=this.properties,{initialLeft:r,initialRight:s,maxRange:n,blockSize:l}=this.data;if(t)return;const[o]=e.changedTouches,h=this.getPagePosition(o),u="capsule"===i?Number(l)/2:0;h-r<0||-(h-s)>n+Number(l)||Promise.all([getRect(this,"#leftDot"),getRect(this,"#rightDot")]).then(([e,t])=>{const n=this.pageScrollTop||0,o=a?e.top+n:e.left,c=Math.abs(h-o-u),g=a?t.top+n:t.left,m=c<Math.abs(g-h+u);let p=0;if("capsule"===i?(p=Number(l),a&&(p*=2),p+=6):a&&(p=Number(l)),m){const e=h-r-p,t=this.convertPosToValue(e,0);this.triggerValue([this.stepValue(t),this.data._value[1]])}else{let e=-(h-s);a&&(e+=p/2);const t=this.convertPosToValue(e,1);this.triggerValue([this.data._value[0],this.stepValue(t)])}})}onTouchStart(e){this.triggerEvent("dragstart",{e:e});const[t]=e.changedTouches;"rightDot"===e.currentTarget.id?this.data.identifier[1]=t.identifier:this.data.identifier[0]=t.identifier}onTouchMoveLeft(e){const{disabled:t,theme:i,vertical:a}=this.properties,{initialLeft:r,_value:s,blockSize:n}=this.data;if(t)return;const l=e.changedTouches.find(e=>e.identifier===this.data.identifier[0]),o=this.getPagePosition(l);let h=0;"capsule"===i&&(h+=Number(n)),a&&(h+=Number(n)+6);const u=o-r-h,c=[...s],g=this.convertPosToValue(u,0);c[0]=this.stepValue(g),this.triggerValue(c)}onTouchMoveRight(e){const{disabled:t,vertical:i}=this.properties,{initialRight:a,_value:r,blockSize:s}=this.data;if(t)return;const n=e.changedTouches.find(e=>e.identifier===this.data.identifier[1]),l=this.getPagePosition(n);let o=0;i&&(o+=Number(s)/2+6);const h=-(l-a-o),u=[...r],c=this.convertPosToValue(h,1);u[1]=this.stepValue(c),this.triggerValue(u)}setLineStyle(e,t){const{theme:i}=this.properties,{blockSize:a,maxRange:r}=this.data,s="capsule"===i?Number(a)/2:0,[n,l]=this.data._value,o=e=>parseInt(e,10);this.setData({dotTopValue:[n,l],realLabel:[this.getLabelByValue(n,"start"),this.getLabelByValue(l,"end")]}),e+t<=r?this.setData({lineLeft:o(e+s),lineRight:o(t+s)}):this.setData({lineLeft:o(r+s-t),lineRight:o(r-e+1.5*s)})}onTouchEnd(e){this.triggerEvent("dragend",{e:e,value:this.data._value}),"rightDot"===e.currentTarget.id?this.data.identifier[1]=-1:this.data.identifier[0]=-1}getPagePosition(e){const{pageX:t,pageY:i}=e,{vertical:a}=this.properties;return a?i:t}};Slider=__decorate([wxComponent()],Slider);export default Slider;