53 lines
2.0 KiB
TypeScript
53 lines
2.0 KiB
TypeScript
import { MessagePlugin as TDesignMessage } from "tdesign-mobile-vue";
|
|
import type { MessagePluginOptions } from "tdesign-mobile-vue/es/message/message";
|
|
|
|
/** Message 支持的调用参数。 */
|
|
export type MessageOptions = MessagePluginOptions;
|
|
export type MessageInput = string | MessageOptions;
|
|
|
|
type MessageTheme = Exclude<NonNullable<MessageOptions["theme"]>, "loading">;
|
|
|
|
interface TDesignMessageApi {
|
|
info: (options: MessageOptions) => void;
|
|
success: (options: MessageOptions) => void;
|
|
warning: (options: MessageOptions) => void;
|
|
error: (options: MessageOptions) => void;
|
|
closeAll: () => void;
|
|
}
|
|
|
|
const tDesignMessage = TDesignMessage as unknown as TDesignMessageApi;
|
|
|
|
function normalizeOptions(input: MessageInput): MessageOptions {
|
|
return typeof input === "string" ? { content: input } : input;
|
|
}
|
|
|
|
function normalizeOptionsWithDuration(input: MessageInput, duration?: number): MessageOptions {
|
|
const options = normalizeOptions(input);
|
|
return duration === undefined ? options : { ...options, duration };
|
|
}
|
|
|
|
function showMessage(input: MessageInput, duration?: number): void {
|
|
const options = normalizeOptionsWithDuration(input, duration);
|
|
const theme = options.theme || "info";
|
|
tDesignMessage[theme](options);
|
|
}
|
|
|
|
function showMessageByTheme(theme: MessageTheme, input: MessageInput, duration?: number): void {
|
|
tDesignMessage[theme]({
|
|
offset: [10, 16],
|
|
...normalizeOptionsWithDuration(input, duration),
|
|
theme
|
|
});
|
|
}
|
|
|
|
/**
|
|
* 统一 Message 调用方式,使其支持类似 Toast 的字符串和配置对象调用。
|
|
*/
|
|
export const Message = Object.assign(showMessage, {
|
|
info: (input: MessageInput, duration?: number): void => showMessageByTheme("info", input, duration),
|
|
success: (input: MessageInput, duration?: number): void => showMessageByTheme("success", input, duration),
|
|
warning: (input: MessageInput, duration?: number): void => showMessageByTheme("warning", input, duration),
|
|
error: (input: MessageInput, duration?: number): void => showMessageByTheme("error", input, duration),
|
|
closeAll: (): void => tDesignMessage.closeAll()
|
|
});
|