index.ts 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import Vue from 'vue';
  2. import VanNotify from './Notify';
  3. import { RED, WHITE } from '../utils/color';
  4. import { isObj, isServer } from '../utils';
  5. import { mount } from '../utils/functional';
  6. import { NotifyOptions } from 'types/notify';
  7. let timer: number | NodeJS.Timeout;
  8. let instance: any;
  9. function parseOptions(message: NotifyOptions): NotifyOptions {
  10. return isObj(message) ? message : ({ message } as NotifyOptions);
  11. }
  12. function Notify(options: NotifyOptions) {
  13. /* istanbul ignore if */
  14. if (isServer) {
  15. return;
  16. }
  17. if (!instance) {
  18. instance = mount(VanNotify);
  19. }
  20. options = {
  21. ...Notify.currentOptions,
  22. ...parseOptions(options)
  23. };
  24. Object.assign(instance, options);
  25. clearTimeout(timer as NodeJS.Timeout);
  26. if (options.duration && options.duration > 0) {
  27. timer = setTimeout(Notify.clear, options.duration);
  28. }
  29. return instance;
  30. }
  31. function defaultOptions(): NotifyOptions {
  32. return {
  33. value: true,
  34. message: '',
  35. color: WHITE,
  36. background: RED,
  37. duration: 3000,
  38. className: ''
  39. };
  40. }
  41. Notify.clear = () => {
  42. if (instance) {
  43. instance.value = false;
  44. }
  45. };
  46. Notify.currentOptions = defaultOptions();
  47. Notify.setDefaultOptions = (options: NotifyOptions) => {
  48. Object.assign(Notify.currentOptions, options);
  49. };
  50. Notify.resetDefaultOptions = () => {
  51. Notify.currentOptions = defaultOptions();
  52. };
  53. Notify.install = () => {
  54. Vue.use(VanNotify as any);
  55. };
  56. Vue.prototype.$notify = Notify;
  57. export default Notify;