riku
2026-04-02 3282e95db0207ee133d1e98d9771dec9d83b0fc4
miniprogram_npm/tdesign-miniprogram/upload/upload.js
@@ -1,221 +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 __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
import { isObject, SuperComponent, wxComponent } from '../common/src/index';
import props from './props';
import config from '../common/config';
import { isOverSize } from '../common/utils';
const { prefix } = config;
const name = `${prefix}-upload`;
let Upload = class Upload extends SuperComponent {
    constructor() {
        super(...arguments);
        this.externalClasses = [`${prefix}-class`];
        this.options = {
            multipleSlots: true,
        };
        this.data = {
            classPrefix: name,
            prefix,
            current: false,
            proofs: [],
            customFiles: [],
            customLimit: 0,
            column: 4,
        };
        this.properties = props;
        this.controlledProps = [
            {
                key: 'files',
                event: 'success',
            },
        ];
        this.observers = {
            'files, max'(files, max) {
                this.handleLimit(files, max);
            },
            gridConfig() {
                this.updateGrid();
            },
        };
        this.lifetimes = {
            ready() {
                this.handleLimit(this.data.customFiles, this.data.max);
                this.updateGrid();
            },
        };
        this.methods = {
            uploadFiles(files) {
                return new Promise((resolve) => {
                    const task = this.data.requestMethod(files);
                    if (task instanceof Promise) {
                        return task;
                    }
                    resolve({});
                });
            },
            startUpload(files) {
                if (typeof this.data.requestMethod === 'function') {
                    return this.uploadFiles(files)
                        .then(() => {
                        files.forEach((file) => {
                            file.percent = 100;
                        });
                        this.triggerSuccessEvent(files);
                    })
                        .catch((err) => {
                        this.triggerFailEvent(err);
                    });
                }
                this.triggerSuccessEvent(files);
                this.handleLimit(this.data.customFiles, this.data.max);
                return Promise.resolve();
            },
            onAddTap() {
                const { mediaType, source } = this.properties;
                if (source === 'media') {
                    this.chooseMedia(mediaType);
                }
                else {
                    this.chooseMessageFile(mediaType);
                }
            },
            chooseMedia(mediaType) {
                const { config, sizeLimit, customLimit } = this.data;
                wx.chooseMedia(Object.assign(Object.assign({ count: customLimit, mediaType }, config), { success: (res) => {
                        const files = [];
                        res.tempFiles.forEach((temp) => {
                            const { size, fileType, tempFilePath, width, height, duration, thumbTempFilePath } = temp, res = __rest(temp, ["size", "fileType", "tempFilePath", "width", "height", "duration", "thumbTempFilePath"]);
                            if (isOverSize(size, sizeLimit)) {
                                let title = `${fileType === 'image' ? '图片' : '视频'}大小超过限制`;
                                if (typeof sizeLimit !== 'number') {
                                    title = sizeLimit.message.replace('{sizeLimit}', sizeLimit === null || sizeLimit === void 0 ? void 0 : sizeLimit.size);
                                }
                                wx.showToast({ icon: 'none', title });
                                return;
                            }
                            const name = this.getRandFileName(tempFilePath);
                            files.push(Object.assign({ name, type: this.getFileType(mediaType, tempFilePath, fileType), url: tempFilePath, size: size, width: width, height: height, duration: duration, thumb: thumbTempFilePath, percent: 0 }, res));
                        });
                        this.afterSelect(files);
                    }, fail: (err) => {
                        this.triggerFailEvent(err);
                    }, complete: (res) => {
                        this.triggerEvent('complete', res);
                    } }));
            },
            chooseMessageFile(mediaType) {
                const { max, config, sizeLimit } = this.properties;
                wx.chooseMessageFile(Object.assign(Object.assign({ count: max, type: Array.isArray(mediaType) ? 'all' : mediaType }, config), { success: (res) => {
                        const files = [];
                        res.tempFiles.forEach((temp) => {
                            const { size, type: fileType, path: tempFilePath } = temp, res = __rest(temp, ["size", "type", "path"]);
                            if (isOverSize(size, sizeLimit)) {
                                let title = `${fileType === 'image' ? '图片' : '视频'}大小超过限制`;
                                if (typeof sizeLimit !== 'number') {
                                    title = sizeLimit.message.replace('{sizeLimit}', sizeLimit === null || sizeLimit === void 0 ? void 0 : sizeLimit.size);
                                }
                                wx.showToast({ icon: 'none', title });
                                return;
                            }
                            const name = this.getRandFileName(tempFilePath);
                            files.push(Object.assign({ name, type: this.getFileType(mediaType, tempFilePath, fileType), url: tempFilePath, size: size, percent: 0 }, res));
                        });
                        this.afterSelect(files);
                    }, fail: (err) => this.triggerFailEvent(err), complete: (res) => this.triggerEvent('complete', res) }));
            },
            afterSelect(files) {
                this._trigger('select-change', {
                    files: [...this.data.customFiles],
                    currentSelectedFiles: [files],
                });
                this._trigger('add', { files });
                this.startUpload(files);
            },
        };
    }
    onProofTap(e) {
        var _a;
        this.onFileClick(e);
        const { index } = e.currentTarget.dataset;
        wx.previewImage({
            urls: this.data.customFiles.filter((file) => file.percent !== -1).map((file) => file.url),
            current: (_a = this.data.customFiles[index]) === null || _a === void 0 ? void 0 : _a.url,
        });
    }
    handleLimit(customFiles, max) {
        if (max === 0) {
            max = 20;
        }
        this.setData({
            customFiles: customFiles.length > max ? customFiles.slice(0, max) : customFiles,
            customLimit: max - customFiles.length,
        });
    }
    triggerSuccessEvent(files) {
        this._trigger('success', { files: [...this.data.customFiles, ...files] });
    }
    triggerFailEvent(err) {
        this.triggerEvent('fail', err);
    }
    onFileClick(e) {
        const { file } = e.currentTarget.dataset;
        this.triggerEvent('click', { file });
    }
    getFileType(mediaType, tempFilePath, fileType) {
        if (fileType)
            return fileType;
        if (mediaType.length === 1) {
            return mediaType[0];
        }
        const videoType = ['avi', 'wmv', 'mkv', 'mp4', 'mov', 'rm', '3gp', 'flv', 'mpg', 'rmvb'];
        const temp = tempFilePath.split('.');
        const postfix = temp[temp.length - 1];
        if (videoType.includes(postfix.toLocaleLowerCase())) {
            return 'video';
        }
        return 'image';
    }
    getRandFileName(filePath) {
        const extIndex = filePath.lastIndexOf('.');
        const extName = extIndex === -1 ? '' : filePath.substr(extIndex);
        return parseInt(`${Date.now()}${Math.floor(Math.random() * 900 + 100)}`, 10).toString(36) + extName;
    }
    onDelete(e) {
        const { index } = e.currentTarget.dataset;
        this.deleteHandle(index);
    }
    deleteHandle(index) {
        const { customFiles } = this.data;
        const delFile = customFiles[index];
        this.triggerEvent('remove', { index, file: delFile });
    }
    updateGrid() {
        let { gridConfig = {} } = this.properties;
        if (!isObject(gridConfig))
            gridConfig = {};
        const { column = 4, width = 160, height = 160 } = gridConfig;
        this.setData({
            gridItemStyle: `width:${width}rpx;height:${height}rpx`,
            column: column,
        });
    }
};
Upload = __decorate([
    wxComponent()
], Upload);
export default Upload;
import{__decorate,__rest}from"tslib";import{SuperComponent,wxComponent}from"../common/src/index";import props from"./props";import config from"../common/config";import{isOverSize}from"../common/utils";import{isObject}from"../common/validator";const{prefix:prefix}=config,name=`${prefix}-upload`;let Upload=class extends SuperComponent{constructor(){super(...arguments),this.externalClasses=[`${prefix}-class`],this.options={multipleSlots:!0},this.data={classPrefix:name,prefix:prefix,current:!1,proofs:[],customFiles:[],customLimit:0,column:4,dragBaseData:{},rows:0,dragWrapStyle:"",dragList:[],dragging:!0,dragLayout:!1},this.properties=props,this.controlledProps=[{key:"files",event:"success"}],this.observers={"files, max, draggable"(t,e){this.handleLimit(t,e)},gridConfig(){this.updateGrid()}},this.lifetimes={ready(){this.handleLimit(this.data.customFiles,this.data.max),this.updateGrid()}},this.methods={getPreviewMediaSources(){const t=[];return this.data.customFiles.forEach(e=>{const i={url:e.url,type:e.type,poster:e.thumb||void 0};t.push(i)}),t},onPreview(t){this.onFileClick(t);const{preview:e}=this.properties;if(!e)return;this.data.customFiles.some(t=>"video"===t.type)?this.onPreviewMedia(t):this.onPreviewImage(t)},onPreviewImage(t){var e;const{index:i}=t.currentTarget.dataset,s=this.data.customFiles.filter(t=>-1!==t.percent).map(t=>t.url),r=null===(e=this.data.customFiles[i])||void 0===e?void 0:e.url;wx.previewImage({urls:s,current:r,fail(){wx.showToast({title:"预览图片失败",icon:"none"})}})},onPreviewMedia(t){const{index:e}=t.currentTarget.dataset,i=this.getPreviewMediaSources();wx.previewMedia({sources:i,current:e,fail(){wx.showToast({title:"预览视频失败",icon:"none"})}})},uploadFiles(t){return new Promise(e=>{const i=this.data.requestMethod(t);if(i instanceof Promise)return i;e({})})},startUpload(t){return"function"==typeof this.data.requestMethod?this.uploadFiles(t).then(()=>{t.forEach(t=>{t.percent=100}),this.triggerSuccessEvent(t)}).catch(t=>{this.triggerFailEvent(t)}):(this.triggerSuccessEvent(t),this.handleLimit(this.data.customFiles,this.data.max),Promise.resolve())},onAddTap(){const{disabled:t,mediaType:e,source:i}=this.properties;t||("media"===i?this.chooseMedia(e):this.chooseMessageFile(e))},chooseMedia(t){const{customLimit:e}=this.data,{config:i,sizeLimit:s}=this.properties;wx.chooseMedia(Object.assign(Object.assign({count:Math.min(20,e),mediaType:t},i),{success:e=>{const i=[];e.tempFiles.forEach(e=>{const{size:r,fileType:a,tempFilePath:o,width:n,height:l,duration:c,thumbTempFilePath:h}=e,d=__rest(e,["size","fileType","tempFilePath","width","height","duration","thumbTempFilePath"]);if(isOverSize(r,s)){let t=("image"===a?"图片":"视频")+"大小超过限制";return"number"!=typeof s&&(t=s.message.replace("{sizeLimit}",null==s?void 0:s.size)),void wx.showToast({icon:"none",title:t})}const g=this.getRandFileName(o);i.push(Object.assign({name:g,type:this.getFileType(t,o,a),url:o,size:r,width:n,height:l,duration:c,thumb:h,percent:0},d))}),this.afterSelect(i)},fail:t=>{this.triggerFailEvent(t)},complete:t=>{this.triggerEvent("complete",t)}}))},chooseMessageFile(t){const{customLimit:e}=this.data,{config:i,sizeLimit:s}=this.properties;wx.chooseMessageFile(Object.assign(Object.assign({count:Math.min(100,e),type:Array.isArray(t)?"all":t},i),{success:e=>{const i=[];e.tempFiles.forEach(e=>{const{size:r,type:a,path:o}=e,n=__rest(e,["size","type","path"]);if(isOverSize(r,s)){let t=("image"===a?"图片":"视频")+"大小超过限制";return"number"!=typeof s&&(t=s.message.replace("{sizeLimit}",null==s?void 0:s.size)),void wx.showToast({icon:"none",title:t})}const l=this.getRandFileName(o);i.push(Object.assign({name:l,type:this.getFileType(t,o,a),url:o,size:r,percent:0},n))}),this.afterSelect(i)},fail:t=>this.triggerFailEvent(t),complete:t=>this.triggerEvent("complete",t)}))},afterSelect(t){this._trigger("select-change",{files:[...this.data.customFiles],currentSelectedFiles:[t]}),this._trigger("add",{files:t}),this.startUpload(t)},dragVibrate(t){var e;const{vibrateType:i}=t,{draggable:s}=this.data,r=null===(e=null==s?void 0:s.vibrate)||void 0===e||e,a=null==s?void 0:s.collisionVibrate;(r&&"longPress"===i||a&&"touchMove"===i)&&wx.vibrateShort({type:"light"})},dragStatusChange(t){const{dragging:e}=t;this.setData({dragging:e})},dragEnd(t){const{dragCollisionList:e}=t;let i=[];i=0===e.length?this.data.customFiles:e.reduce((t,e)=>{const{realKey:i,data:s,fixed:r}=e;return r||(t[i]=Object.assign({},s)),t},[]),this.triggerDropEvent(i)},triggerDropEvent(t){const{transition:e}=this.properties;if(e.backTransition){const i=setTimeout(()=>{this.triggerEvent("drop",{files:t}),clearTimeout(i)},e.duration)}else this.triggerEvent("drop",{files:t})}}}handleLimit(t,e){0===e&&(e=Number.MAX_SAFE_INTEGER),this.setData({customFiles:t.length>e?t.slice(0,e):t,customLimit:e-t.length,dragging:!0}),this.initDragLayout()}triggerSuccessEvent(t){this._trigger("success",{files:[...this.data.customFiles,...t]})}triggerFailEvent(t){this.triggerEvent("fail",t)}onFileClick(t){const{file:e,index:i}=t.currentTarget.dataset;this.triggerEvent("click",{index:i,file:e})}getFileType(t,e,i){if(i)return i;if(1===t.length)return t[0];const s=e.split("."),r=s[s.length-1];return["avi","wmv","mkv","mp4","mov","rm","3gp","flv","mpg","rmvb"].includes(r.toLocaleLowerCase())?"video":"image"}getRandFileName(t){const e=t.lastIndexOf("."),i=-1===e?"":t.substr(e);return parseInt(`${Date.now()}${Math.floor(900*Math.random()+100)}`,10).toString(36)+i}onDelete(t){const{index:e}=t.currentTarget.dataset;this.deleteHandle(e)}deleteHandle(t){const{customFiles:e}=this.data,i=e[t];this.triggerEvent("remove",{index:t,file:i})}updateGrid(){let{gridConfig:t={}}=this.properties;isObject(t)||(t={});const{column:e=4,width:i=160,height:s=160}=t;this.setData({gridItemStyle:`width:${i}rpx;height:${s}rpx`,column:e})}resetDragLayout(){this.setData({dragBaseData:{},dragWrapStyle:"",dragLayout:!1})}initDragLayout(){const{draggable:t,disabled:e}=this.properties,{customFiles:i}=this.data;t&&!e&&0!==i.length?(this.initDragList(),this.initDragBaseData()):this.resetDragLayout()}initDragList(){let t=0;const{column:e,customFiles:i,customLimit:s}=this.data,r=[];if(i.forEach((i,s)=>{r.push({realKey:t,sortKey:s,tranX:s%e*100+"%",tranY:100*Math.floor(s/e)+"%",data:Object.assign({},i)}),t+=1}),s>0){const t=r.length;r.push({realKey:t,sortKey:t,tranX:t%e*100+"%",tranY:100*Math.floor(t/e)+"%",fixed:!0})}this.data.rows=Math.ceil(r.length/e),this.setData({dragList:r})}initDragBaseData(){const{classPrefix:t,rows:e,column:i}=this.data,s=this.createSelectorQuery(),r=`.${t} >>> .t-grid-item`,a=`.${t} >>> .t-grid`;s.select(r).boundingClientRect(),s.select(a).boundingClientRect(),s.selectViewport().scrollOffset(),s.exec(s=>{const[{width:r,height:a},{left:o,top:n},{scrollTop:l}]=s,c={rows:e,classPrefix:t,itemWidth:r,itemHeight:a,wrapLeft:o,wrapTop:n+l,columns:i},h=`height: ${e*a}px`;this.setData({dragBaseData:c,dragWrapStyle:h,dragLayout:!0},()=>{const t=setTimeout(()=>{this.setData({dragging:!1}),clearTimeout(t)},0)})})}};Upload=__decorate([wxComponent()],Upload);export default Upload;