import Vue from 'vue'

function getTarget (node) {
  if (node === void 0) {
      node = document.body
  }
  if (node === true) { return document.body }
  return node instanceof window.Node ? node : document.querySelector(node)
}
Vue.directive('transfer-dom', {
  inserted (el, { value }, vnode) {
    let parentNode = el.parentNode;
    if (!parentNode) return;
    let home = document.createComment('');
    let hasMovedOut = false;

    if (value !== false) {
      parentNode.replaceChild(home, el);
      getTarget(value).appendChild(el);
      hasMovedOut = true
    }
    if (!el.__transferDomData) {
      el.__transferDomData = {
        parentNode: parentNode,
        home: home,
        target: getTarget(value),
        hasMovedOut: hasMovedOut
      }
    }
  },
  componentUpdated (el, { value }) {
    let ref$1 = el.__transferDomData;
    if (!ref$1) return;
    let parentNode = ref$1.parentNode;
    let home = ref$1.home;
    let hasMovedOut = ref$1.hasMovedOut;

    if (!hasMovedOut && value) {
      parentNode.replaceChild(home, el);
      getTarget(value).appendChild(el);
      el.__transferDomData = Object.assign({}, el.__transferDomData, { hasMovedOut: true, target: getTarget(value) });
    } else if (hasMovedOut && value === false) {
      parentNode.replaceChild(el, home);
      el.__transferDomData = Object.assign({}, el.__transferDomData, { hasMovedOut: false, target: getTarget(value) });
    } else if (value) {
      getTarget(value).appendChild(el);
    }
  },
  unbind (el) {
    let ref$1 = el.__transferDomData;
    if (!ref$1) return;
    if (el.__transferDomData.hasMovedOut === true) {
      el.__transferDomData.parentNode && el.__transferDomData.parentNode.appendChild(el)
    }
    el.__transferDomData = null
  }
})