toast.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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 = (typeof options.context === 'function'
  39. ? options.context()
  40. : options.context) || getContext();
  41. var toast = context.selectComponent(options.selector);
  42. if (!toast) {
  43. console.warn('未找到 van-toast 节点,请确认 selector 及 context 是否正确');
  44. return;
  45. }
  46. delete options.context;
  47. delete options.selector;
  48. toast.clear = function () {
  49. toast.setData({ show: false });
  50. if (options.onClose) {
  51. options.onClose();
  52. }
  53. };
  54. queue.push(toast);
  55. toast.setData(options);
  56. clearTimeout(toast.timer);
  57. if (options.duration != null && options.duration > 0) {
  58. toast.timer = setTimeout(function () {
  59. toast.clear();
  60. queue = queue.filter(function (item) { return item !== toast; });
  61. }, options.duration);
  62. }
  63. return toast;
  64. }
  65. var createMethod = function (type) { return function (options) {
  66. return Toast(__assign({ type: type }, parseOptions(options)));
  67. }; };
  68. Toast.loading = createMethod('loading');
  69. Toast.success = createMethod('success');
  70. Toast.fail = createMethod('fail');
  71. Toast.clear = function () {
  72. queue.forEach(function (toast) {
  73. toast.clear();
  74. });
  75. queue = [];
  76. };
  77. Toast.setDefaultOptions = function (options) {
  78. Object.assign(currentOptions, options);
  79. };
  80. Toast.resetDefaultOptions = function () {
  81. currentOptions = __assign({}, defaultOptions);
  82. };
  83. exports.default = Toast;