dialog.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. 'use strict';
  2. var defaultData = require('./data');
  3. function getDialogCtx(_ref) {
  4. var selector = _ref.selector,
  5. pageCtx = _ref.pageCtx;
  6. var ctx = pageCtx;
  7. if (!ctx) {
  8. var pages = getCurrentPages();
  9. ctx = pages[pages.length - 1];
  10. }
  11. return ctx.selectComponent(selector);
  12. }
  13. function getParsedOptions() {
  14. var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  15. return Object.assign({
  16. // 自定义 btn 列表
  17. // { type: 按钮类型,回调时以此作为区分依据,text: 按钮文案, color: 按钮文字颜色 }
  18. buttons: []
  19. }, defaultData, options);
  20. }
  21. // options 使用参数
  22. // pageCtx 页面 page 上下文
  23. function Dialog(options, pageCtx) {
  24. var parsedOptions = getParsedOptions(options);
  25. var dialogCtx = getDialogCtx({
  26. selector: parsedOptions.selector,
  27. pageCtx: pageCtx
  28. });
  29. if (!dialogCtx) {
  30. console.error('无法找到对应的dialog组件,请于页面中注册并在 wxml 中声明 dialog 自定义组件');
  31. return Promise.reject({ type: 'component error' });
  32. }
  33. // 处理默认按钮的展示
  34. // 纵向排布确认按钮在上方
  35. var _parsedOptions$button = parsedOptions.buttons,
  36. buttons = _parsedOptions$button === undefined ? [] : _parsedOptions$button;
  37. var showCustomBtns = false;
  38. if (buttons.length === 0) {
  39. if (parsedOptions.showConfirmButton) {
  40. buttons.push({
  41. type: 'confirm',
  42. text: parsedOptions.confirmButtonText,
  43. color: parsedOptions.confirmButtonColor
  44. });
  45. }
  46. if (parsedOptions.showCancelButton) {
  47. var cancelButton = {
  48. type: 'cancel',
  49. text: parsedOptions.cancelButtonText,
  50. color: parsedOptions.cancelButtonColor
  51. };
  52. if (parsedOptions.buttonsShowVertical) {
  53. buttons.push(cancelButton);
  54. } else {
  55. buttons.unshift(cancelButton);
  56. }
  57. }
  58. } else {
  59. showCustomBtns = true;
  60. }
  61. return new Promise(function (resolve, reject) {
  62. dialogCtx.setData(Object.assign({}, parsedOptions, {
  63. buttons: buttons,
  64. showCustomBtns: showCustomBtns,
  65. key: '' + new Date().getTime(),
  66. show: true,
  67. promiseFunc: { resolve: resolve, reject: reject },
  68. openTypePromiseFunc: null
  69. }));
  70. });
  71. }
  72. Dialog.close = function (options, pageCtx) {
  73. var parsedOptions = getParsedOptions(options);
  74. var dialogCtx = getDialogCtx({
  75. selector: parsedOptions.selector,
  76. pageCtx: pageCtx
  77. });
  78. if (!dialogCtx) {
  79. return;
  80. }
  81. dialogCtx.setData({
  82. show: false,
  83. promiseFunc: null,
  84. openTypePromiseFunc: null
  85. });
  86. };
  87. module.exports = Dialog;