all files / packages/dialog/src/ dialog.js

42.59% Statements 23/54
15.38% Branches 4/26
10% Functions 1/10
32.61% Lines 15/46
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100                                                                                                                                                                            
import Vue from 'vue';
import Dialog from './dialog.vue';
import merge from 'src/utils/merge';
 
const DialogConstructor = Vue.extend(Dialog);
 
let currentDialog;
let instance;
let dialogQueue = [];
 
const defaultCallback = action => {
  if (currentDialog) {
    let callback = currentDialog.callback;
 
    if (typeof callback === 'function') {
      callback(action);
    }
 
    if (currentDialog.resolve && action === 'confirm') {
      currentDialog.resolve(action);
    } else if (currentDialog.reject && action === 'cancel') {
      currentDialog.reject(action);
    }
  }
};
 
const initInstance = () => {
  instance = new DialogConstructor({
    el: document.createElement('div')
  });
 
  instance.callback = defaultCallback;
};
 
const showNextDialog = () => {
  if (!instance) {
    initInstance();
  }
 
  if (!instance.value && dialogQueue.length > 0) {
    currentDialog = dialogQueue.shift();
 
    let options = currentDialog.options;
 
    for (let prop in options) {
      if (options.hasOwnProperty(prop)) {
        instance[prop] = options[prop];
      }
    }
 
    if (options.callback === undefined) {
      instance.callback = defaultCallback;
    }
 
    document.body.appendChild(instance.$el);
 
    Vue.nextTick(() => {
      instance.value = true;
    });
  }
};
 
var DialogBox = options => {
  return new Promise((resolve, reject) => { // eslint-disable-line
    dialogQueue.push({
      options: merge({}, options),
      callback: options.callback,
      resolve: resolve,
      reject: reject
    });
 
    showNextDialog();
  });
};
 
DialogBox.alert = function(options) {
  return DialogBox(merge({
    type: 'alert',
    closeOnClickOverlay: false,
    showCancelButton: false
  }, options));
};
 
DialogBox.confirm = function(options) {
  return DialogBox(merge({
    type: 'confirm',
    closeOnClickOverlay: true,
    showCancelButton: true
  }, options));
};
 
DialogBox.close = function() {
  instance.value = false;
  dialogQueue = [];
  currentDialog = null;
};
 
export default DialogBox;