import { JSONObject, JSON } from "waft-json"; import { lodash } from "waft-ui-common"; import { Component, Props, setTimeout, clearTimeout, store } from "waft"; let iconMap: Map = new Map(); iconMap.set( "success", "https://gw.alicdn.com/imgextra/i1/O1CN01evbrT81s2JRO3tkra_!!6000000005708-2-tps-200-200.png" ); iconMap.set( "fail", "https://gw.alicdn.com/imgextra/i3/O1CN01cSL5BS1d7bmgm1pxt_!!6000000003689-2-tps-200-200.png" ); iconMap.set( "warning", "https://gw.alicdn.com/imgextra/i1/O1CN010fNfZk1dWnZ3vpV4R_!!6000000003744-2-tps-200-200.png" ); export class ToastOptions { message: string = "提示信息"; type: string = "info"; duration: i64 = 2000; position: string = "top"; iconURL: string = ""; } export class Toast extends Component { constructor(props: Props) { super(props); this.connect(["toastData"]); } static show(options: ToastOptions): void { // 将ToastOptions转换为JSONObject let toastData = this.getCurrentOptions(options); toastData.set("show", true); store.dispatch("toastData", toastData); // duration 后将show置为false this.closeToast(lodash.getInt(toastData, "duration", 2000 as i64)); } static success(message: string): void { this.toastMethod("success", message); } static warning(message: string): void { this.toastMethod("warning", message); } static fail(message: string): void { this.toastMethod("fail", message); } private static toastMethod(type: string, message: string): void { let toastOptions = new ToastOptions(); toastOptions.type = type; toastOptions.message = message; let toastData = this.getCurrentOptions(toastOptions); toastData.set("show", true); store.dispatch("toastData", toastData); this.closeToast(); } static timer: i32; private static closeToast(duration: i64 = 2000): void { console.log("****toast显示时间为" + duration.toString() + "****"); clearTimeout(Toast.timer); Toast.timer = setTimeout(() => { store.dispatch("toastData", JSON.parseObject(`{"show": false}`)); }, duration); } private static getCurrentOptions(options: ToastOptions): JSONObject { let resOptions: JSONObject = new JSONObject(); resOptions.set("message", options.message); resOptions.set("type", options.type); resOptions.set("duration", options.duration); resOptions.set("position", options.position); // 根据type和iconURL设置当前iconURL(参数iconURL优先级高于默认的) resOptions.set( "iconURL", options.iconURL != "" ? options.iconURL : iconMap.has(options.type) ? iconMap.get(options.type) : "" ); return resOptions; } }