toast.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. "use strict";
  2. var __assign = (this && this.__assign) || function () {
  3. __assign = Object.assign || function(t) {
  4. for (var s, i = 1, n = arguments.length; i < n; i++) {
  5. s = arguments[i];
  6. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  7. t[p] = s[p];
  8. }
  9. return t;
  10. };
  11. return __assign.apply(this, arguments);
  12. };
  13. Object.defineProperty(exports, "__esModule", { value: true });
  14. var validator_1 = require("../common/validator");
  15. var defaultOptions = {
  16. type: 'text',
  17. mask: false,
  18. message: '',
  19. show: true,
  20. zIndex: 1000,
  21. duration: 2000,
  22. position: 'middle',
  23. forbidClick: false,
  24. loadingType: 'circular',
  25. selector: '#van-toast',
  26. };
  27. var queue = [];
  28. var currentOptions = __assign({}, defaultOptions);
  29. function parseOptions(message) {
  30. return (0, validator_1.isObj)(message) ? message : { message: message };
  31. }
  32. function getContext() {
  33. var pages = getCurrentPages();
  34. return pages[pages.length - 1];
  35. }
  36. function Toast(toastOptions) {
  37. var options = __assign(__assign({}, currentOptions), parseOptions(toastOptions));
  38. var context = options.context || getContext();
  39. var toast = context.selectComponent(options.selector);
  40. if (!toast) {
  41. console.warn('未找到 van-toast 节点,请确认 selector 及 context 是否正确');
  42. return;
  43. }
  44. delete options.context;
  45. delete options.selector;
  46. toast.clear = function () {
  47. toast.setData({ show: false });
  48. if (options.onClose) {
  49. options.onClose();
  50. }
  51. };
  52. queue.push(toast);
  53. toast.setData(options);
  54. clearTimeout(toast.timer);
  55. if (options.duration != null && options.duration > 0) {
  56. toast.timer = setTimeout(function () {
  57. toast.clear();
  58. queue = queue.filter(function (item) { return item !== toast; });
  59. }, options.duration);
  60. }
  61. return toast;
  62. }
  63. var createMethod = function (type) { return function (options) {
  64. return Toast(__assign({ type: type }, parseOptions(options)));
  65. }; };
  66. Toast.loading = createMethod('loading');
  67. Toast.success = createMethod('success');
  68. Toast.fail = createMethod('fail');
  69. Toast.clear = function () {
  70. queue.forEach(function (toast) {
  71. toast.clear();
  72. });
  73. queue = [];
  74. };
  75. Toast.setDefaultOptions = function (options) {
  76. Object.assign(currentOptions, options);
  77. };
  78. Toast.resetDefaultOptions = function () {
  79. currentOptions = __assign({}, defaultOptions);
  80. };
  81. exports.default = Toast;