/*
* XmlDigitalTeaching v0.0.1
* Copyright ©Wed Jun 12 2024 12:02:25 GMT+0800 (中国标准时间) smile
* Released under the ISC License.
*/
import Vue from 'vue';
import crypto from 'crypto';

//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//

var script$3 = {
  name: 'XmlTextDialogRender',
  props: {
    content: {
      type: String,
      default: ''
    },
    textstyle: {
      type: String,
      default: 'A'
    },
    pageType: {
      type: String,
      default: 'h5'
    },
    resourceBasisPath: {
      type: String,
      default: ''
    },
    projectId: {
      type: String,
      default: ''
    }
  },
  watch: {
    content() {
      this.show = false;
      this.$nextTick(() => {
        this.show = true;
      });
    }
  },
  data() {
    return {
      show: true,
      source: ''
    };
  },
  created() {
    this.source = this.$route.query.pageType;
  },
  methods: {
    formatImg(str) {
      if (str) {
        let data = str.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/gi, (match, p1) => {
          if (match.indexOf('style') !== -1) {
            let src = this.resourceBasisPath + p1.split('./')[1];
            let image = match.indexOf('http') !== -1 ? match : match.replace(p1, src);
            return image.split('style="')[0] + 'style="max-width:100% !important;' + image.split('style="')[1];
          } else {
            return `<img src='${p1.indexOf('http') > -1 ? p1 : this.resourceBasisPath + p1.split('./')[1]}' style="max-width:100%;" />`;
          }
        });
        return data;
      }
    }
  }
};

var __$_require_static_images_leaflet_icons_scroll_png__ = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAAAPCAYAAAChtYCSAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyJpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMy1jMDExIDY2LjE0NTY2MSwgMjAxMi8wMi8wNi0xNDo1NjoyNyAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNiAoV2luZG93cykiIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6QjkxMUYzODUxMkZFMTFFRThGNzY5QzE0NjRGQzZERjciIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6QjkxMUYzODYxMkZFMTFFRThGNzY5QzE0NjRGQzZERjciPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDpCOTExRjM4MzEyRkUxMUVFOEY3NjlDMTQ2NEZDNkRGNyIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDpCOTExRjM4NDEyRkUxMUVFOEY3NjlDMTQ2NEZDNkRGNyIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/Pgx/R5cAAAJ7SURBVHja7JpPaNNQHMe/L03TbuqUiehlKv456EE8KV5Ehn/Ag3/w4k1PXibuIljcwIKCiiAoO+lFRRARke2qKCh69KLzNIYbKG6Msbaza9o0z99LGywleYngpenvA1/ya36/95L8ml9e8hJz7Gw/dBzJvfTNa6QcKQuG6VwqpNuk/OtbZyKDTdIQaZh0ivStPSCVtnxzhJTm/DIdjrrAX1UFoonZT3pGuiNoBCmSsYZUJ82EtThx4+02zi2TFCZGB6dDXCnSlqZdNJvF4TtCiyCTXcVZZZJEnAt+nxm3N6tnNaeU6TpiF0gmywXCdGGBbNp5AFIKzE19AoQBq3cdhBAkdcclyecCroRl/Z28ki0diIBOZYtPhsRE9SVDfreujxsDTRtothlnvS4PUQT1234MQccYN7e6PsNyjojcIaCt1OxPnP//f+Quat/b2/b0bWzYdReuW/XOd8NMo2aX4dgl9A/sgZASojA/KyulRbwYGcSx4cfYvu84yoV5SNelxg7qTpVUw/rNu/hywiSGpZ9TSJkWYKS8AUEVR+/aDViYmcTz3EEcHXqIgb2HYH4eH4PZnMqdfPMEP75+gF0pwa051JaqykjTKCJx+OI9ziqTGD4+vU7ntuEViEGieyVvuVJY8PyzX95jefEX1DRvYzQStJDhg92FR985q0xieHB+6z8+pEv9naBdLnBWme57SI8baFeKnC2mKwtkmeTP4c6RfgcFOnaZ36QzSWJa41Nv0tU07pJ6BrlExmXSOdK79siT+Ve+WQV/i8UkgxrJGs+fDvPvJk2Q7qoR5H5TgTi1Fd+8SbpCynB+mQ7GRuNrXh3qo90dyvgjwAA2ZLfYDdkYOgAAAABJRU5ErkJggg==";

function normalizeComponent(template, style, script, scopeId, isFunctionalTemplate, moduleIdentifier /* server only */, shadowMode, createInjector, createInjectorSSR, createInjectorShadow) {
  if (typeof shadowMode !== 'boolean') {
    createInjectorSSR = createInjector;
    createInjector = shadowMode;
    shadowMode = false;
  }
  // Vue.extend constructor export interop.
  const options = typeof script === 'function' ? script.options : script;
  // render functions
  if (template && template.render) {
    options.render = template.render;
    options.staticRenderFns = template.staticRenderFns;
    options._compiled = true;
    // functional template
    if (isFunctionalTemplate) {
      options.functional = true;
    }
  }
  // scopedId
  if (scopeId) {
    options._scopeId = scopeId;
  }
  let hook;
  if (moduleIdentifier) {
    // server build
    hook = function (context) {
      // 2.3 injection
      context = context ||
      // cached call
      this.$vnode && this.$vnode.ssrContext ||
      // stateful
      this.parent && this.parent.$vnode && this.parent.$vnode.ssrContext; // functional
      // 2.2 with runInNewContext: true
      if (!context && typeof __VUE_SSR_CONTEXT__ !== 'undefined') {
        context = __VUE_SSR_CONTEXT__;
      }
      // inject component styles
      if (style) {
        style.call(this, createInjectorSSR(context));
      }
      // register component module identifier for async chunk inference
      if (context && context._registeredComponents) {
        context._registeredComponents.add(moduleIdentifier);
      }
    };
    // used by ssr in case component is cached and beforeCreate
    // never gets called
    options._ssrRegister = hook;
  } else if (style) {
    hook = shadowMode ? function (context) {
      style.call(this, createInjectorShadow(context, this.$root.$options.shadowRoot));
    } : function (context) {
      style.call(this, createInjector(context));
    };
  }
  if (hook) {
    if (options.functional) {
      // register for functional component in vue file
      const originalRender = options.render;
      options.render = function renderWithStyleInjection(h, context) {
        hook.call(context);
        return originalRender(h, context);
      };
    } else {
      // inject component registration as beforeCreate hook
      const existing = options.beforeCreate;
      options.beforeCreate = existing ? [].concat(existing, hook) : [hook];
    }
  }
  return script;
}

/* script */
const __vue_script__$3 = script$3;
var __vue_render__$4 = function () {
  var _vm = this;
  var _h = _vm.$createElement;
  var _c = _vm._self._c || _h;
  return _c("div", [
    _vm.textstyle == "D"
      ? _c("div", [
          _c("div", { staticClass: "style-body-boxA" }, [
            _c("div", { staticClass: "style-wrapper" }, [
              _c("div", { staticClass: "top-line" }),
              _vm._v(" "),
              _c("div", {
                staticClass: "native-html-wrapper",
                domProps: { innerHTML: _vm._s(_vm.formatImg(_vm.content)) },
              }),
              _vm._v(" "),
              _c("div", { staticClass: "bottom-margin" }),
              _vm._v(" "),
              _c("div", { staticClass: "bottom-triangle" }),
            ]),
          ]),
        ])
      : _vm._e(),
    _vm._v(" "),
    _vm.textstyle == "A"
      ? _c("div", [
          _c("div", { staticClass: "style-body-boxA" }, [
            _c("div", { staticClass: "top-bg" }),
            _vm._v(" "),
            _c("div", {
              staticClass: "style-content-box",
              domProps: { innerHTML: _vm._s(_vm.formatImg(_vm.content)) },
            }),
            _vm._v(" "),
            _c("div", { staticClass: "paper-clip-icon" }),
            _vm._v(" "),
            _c("div", { staticClass: "style-content-bg" }),
          ]),
        ])
      : _vm._e(),
    _vm._v(" "),
    _vm.textstyle == "B"
      ? _c("div", [
          _c("div", { staticClass: "style-body-boxB" }, [
            _c("div", { staticClass: "top-bg" }),
            _vm._v(" "),
            _c("div", {
              staticClass: "style-content-box",
              domProps: { innerHTML: _vm._s(_vm.formatImg(_vm.content)) },
            }),
            _vm._v(" "),
            _c("div", { staticClass: "style-content-bg" }),
            _vm._v(" "),
            _vm._m(0),
          ]),
        ])
      : _vm._e(),
    _vm._v(" "),
    _vm.textstyle == "C"
      ? _c("div", [
          _c("div", { staticClass: "style-body-boxC" }, [
            _c("div", { staticClass: "top-bg" }),
            _vm._v(" "),
            _c("div", {
              staticClass: "style-content-box",
              domProps: { innerHTML: _vm._s(_vm.formatImg(_vm.content)) },
            }),
            _vm._v(" "),
            _c("div", { staticClass: "style-content-bg" }),
            _vm._v(" "),
            _vm._m(1),
          ]),
        ])
      : _vm._e(),
    _vm._v(" "),
    _vm.textstyle == "E"
      ? _c("div", [
          _c("div", { staticClass: "style-body-boxE" }, [
            _c("div", { staticClass: "scroll-top" }, [
              _c("img", {
                style: _vm.pageType == "pc" ? "height:20px" : "",
                attrs: {
                  src: __$_require_static_images_leaflet_icons_scroll_png__,
                  alt: "",
                },
              }),
            ]),
            _vm._v(" "),
            _c("div", {
              staticClass: "style-content-box",
              domProps: { innerHTML: _vm._s(_vm.formatImg(_vm.content)) },
            }),
            _vm._v(" "),
            _c("div", { staticClass: "scroll-bottom" }, [
              _c("img", {
                style: _vm.pageType == "pc" ? "height:20px" : "",
                attrs: {
                  src: __$_require_static_images_leaflet_icons_scroll_png__,
                  alt: "",
                },
              }),
            ]),
          ]),
        ])
      : _vm._e(),
  ])
};
var __vue_staticRenderFns__$3 = [
  function () {
    var _vm = this;
    var _h = _vm.$createElement;
    var _c = _vm._self._c || _h;
    return _c("div", { staticClass: "top-style-box" }, [
      _c("div"),
      _vm._v(" "),
      _c("div"),
      _vm._v(" "),
      _c("div"),
      _vm._v(" "),
      _c("div"),
      _vm._v(" "),
      _c("div"),
      _vm._v(" "),
      _c("div"),
      _vm._v(" "),
      _c("div"),
      _vm._v(" "),
      _c("div"),
    ])
  },
  function () {
    var _vm = this;
    var _h = _vm.$createElement;
    var _c = _vm._self._c || _h;
    return _c("div", { staticClass: "top-style-box" }, [
      _c("div"),
      _vm._v(" "),
      _c("div"),
      _vm._v(" "),
      _c("div"),
      _vm._v(" "),
      _c("div"),
      _vm._v(" "),
      _c("div"),
      _vm._v(" "),
      _c("div"),
      _vm._v(" "),
      _c("div"),
      _vm._v(" "),
      _c("div"),
    ])
  },
];
__vue_render__$4._withStripped = true;

  /* style */
  const __vue_inject_styles__$3 = undefined;
  /* scoped */
  const __vue_scope_id__$3 = "data-v-0994a01b";
  /* module identifier */
  const __vue_module_identifier__$3 = undefined;
  /* functional template */
  const __vue_is_functional_template__$3 = false;
  /* style inject */
  
  /* style inject SSR */
  
  /* style inject shadow dom */
  

  
  const __vue_component__$3 = /*#__PURE__*/normalizeComponent(
    { render: __vue_render__$4, staticRenderFns: __vue_staticRenderFns__$3 },
    __vue_inject_styles__$3,
    __vue_script__$3,
    __vue_scope_id__$3,
    __vue_is_functional_template__$3,
    __vue_module_identifier__$3,
    false,
    undefined,
    undefined,
    undefined
  );

const reHtml = str => {
  return str ? str.replace(/&((g|l|quo|ldquo|rdquo)t|amp|#39|nbsp);/g, function (m) {
    return {
      '&lt;': '<',
      '&amp;': '&',
      '&quot;': '"',
      '&ldquo;': '“',
      '&rdquo;': '”',
      '&gt;': '>',
      '&#39;': "'",
      '&nbsp;': ' '
    }[m];
  }) : '';
};
class MagicLink extends HTMLElement {
  static get observedAttributes() {
    return ['data-plaintext', 'data-type', 'data-title', 'data-content', 'data-isplaying'];
  }
  constructor() {
    super();
    this.createShadow();
    setTimeout(() => {
      this.insertContent();
    });
  }
  createShadow() {
    this.shadow = this.attachShadow({
      mode: 'closed'
    });
  }
  insertContent() {
    const type = this.getAttribute('data-type');
    const title = this.getAttribute('data-title');
    const wrapper = document.createElement('span');
    wrapper.setAttribute('class', `magic-link magic-link--${type}`);
    wrapper.setAttribute('contenteditable', 'false');
    wrapper.innerHTML = reHtml(title);
    const style = document.createElement('style');
    // console.log("%c%s","font-size:2em;background: #00965E;color: #FFF",'WCE内部样式连接',style.isConnected)

    style.textContent = `
      p {
        margin: 0;
      }
      .magic-link {
        display: inline;
        text-indent: initial;
        // color: #6883FA;
        color: #00F;
        transition: all 240ms ease-in-out;
      }
      .magic-link:hover {
        text-decoration: underline;
      }
      .wifi-symbol {
        display: inline-block;
        width: 21px;
        height: 21px;
        box-sizing: border-box;
        overflow: hidden;
        vertical-align: text-bottom;
      }
      .wifi-symbol svg {
        display:block;
      }
      .wifi-symbol.playing .play-path {
        animation: fade-in 900ms cubic-bezier(0.43, 0.2, 0.56, 0.94) infinite;
      }
      @keyframes fadeInOut {
        0% {
          opacity: 0;
        }
        100% {
          opacity: 1;
        }
      }
    `;
    this.shadow.appendChild(style);
    this.shadow.appendChild(wrapper);
    if (type === 'audio') {
      let audioExtra = document.createElement('div');
      audioExtra.setAttribute('class', 'wifi-symbol');
      audioExtra.innerHTML = `
      <svg width="21" height="21" viewBox="-3 -5 50 64">
        <defs>
          <style>
            .play-path {fill:#3fa9f5;}
            @keyframes fade-in{
              to {opacity: 0;}
            }
            .play-path:nth-of-type(2){
              animation-delay: 0.25s !important;
            }
            .play-path:nth-of-type(3){
              animation-delay: 0.5s !important;
            }
          </style>
        </defs>
        <path class="play-path" d="M12.69,39.57a12,12,0,0,0-1.3-21.73L1.18,28.06Z" />
        <path class="play-path" d="M24,29a17,17,0,0,1-7.67,14.2l3.59,3.6A22,22,0,0,0,18.8,10.44l-3.65,3.64A17,17,0,0,1,24,29Z" />
        <path class="play-path" d="M26.4,2.56,22.83,6.13a27,27,0,0,1,.2,43.6l3.56,3.56A32,32,0,0,0,26.4,2.56Z" />
      </svg>
      `;
      this.shadow.appendChild(audioExtra);
    }
  }
  updateContent({
    key,
    oldValue,
    newValue
  }) {
    let _this = this;
    // console.log("%c%s","font-size:2em;background: #00965E;color: #FFF",'wce更新逻辑',[this],this.shadow)
    const type = this.getAttribute('data-type');
    this.getAttribute('data-title');
    const content = this.getAttribute('data-content');
    if (oldValue === null && newValue) {
      // 首次加载
      if (type === 'leaflet' && key === 'data-title') {
        setTimeout(() => {
          const links = this.shadow.querySelectorAll('.magic-link a');
          this.shadow.querySelector('.magic-link.magic-link--leaflet');
          // console.log("%c%s","font-size:2em;background: #00965E;color: #FFF",'wcce leflet', links, this.shadow)
          links.forEach((elem, index) => {
            elem.addEventListener('click', e => {
              // console.log("%c%s","font-size:2em;background: #00965E;color: #FFF",'link内点击',e,elem)
              _this.shadow.dispatchEvent(new CustomEvent('openTarget', {
                detail: {
                  aid: elem.id,
                  aindex: index,
                  elem,
                  targets: content
                }
              }));
            });
          });
        }, 50);
      }
    }
    if (oldValue !== null && newValue) {
      // 后续更新
      if (type === 'audio') {
        if (key === 'data-isplaying') {
          let target = this.shadow.querySelector('.wifi-symbol');
          let classNames = newValue === 'true' ? 'wifi-symbol playing' : 'wifi-symbol';
          target.setAttribute('class', classNames);
          // console.log("%c%s","font-size:2em;background: #00965E;color: #FFF", 'target', [target])
        }
      }
    }
  }

  //生命周期 - 首次被插入文档 DOM 时
  connectedCallback() {
    // console.log("%c%s","font-size:2em;background: #00965E;color: #FFF",'WCE嵌入',)
    // updateContent(this);
  }

  //生命周期 - 从文档 DOM 中删除时
  disconnectedCallback() {
    // console.log("%c%s","font-size:2em;background: #00965E;color: #FFF",'WCE销毁',)
  }

  //生命周期 - 被移动到新的文档时
  adoptedCallback() {
    // console.log("%c%s","font-size:2em;background: #00965E;color: #FFF",'WCE迁移',)
  }

  //生命周期 - 增加、删除、修改自身属性时
  attributeChangedCallback(key, oldValue, newValue) {
    // console.log("%c%s","font-size:2em;background: #00965E;color: #FFF",'WCE更新',{key, oldValue, newValue})
    this.updateContent({
      key,
      oldValue,
      newValue
    });
  }
}

/* istanbul ignore next */
Vue.prototype.$isServer;

/* istanbul ignore next */
const trim$1 = function (string) {
  return (string || '').replace(/^[\s\uFEFF]+|[\s\uFEFF]+$/g, '');
};

/* istanbul ignore next */
function hasClass(el, cls) {
  if (!el || !cls) return false;
  if (cls.indexOf(' ') !== -1) throw new Error('className should not contain space.');
  if (el.classList) {
    return el.classList.contains(cls);
  } else {
    return (' ' + el.className + ' ').indexOf(' ' + cls + ' ') > -1;
  }
}

/* istanbul ignore next */
function addClass(el, cls) {
  if (!el) return;
  var curClass = el.className;
  var classes = (cls || '').split(' ');
  for (var i = 0, j = classes.length; i < j; i++) {
    var clsName = classes[i];
    if (!clsName) continue;
    if (el.classList) {
      el.classList.add(clsName);
    } else if (!hasClass(el, clsName)) {
      curClass += ' ' + clsName;
    }
  }
  if (!el.classList) {
    el.setAttribute('class', curClass);
  }
}

/* istanbul ignore next */
function removeClass(el, cls) {
  if (!el || !cls) return;
  var classes = cls.split(' ');
  var curClass = ' ' + el.className + ' ';
  for (var i = 0, j = classes.length; i < j; i++) {
    var clsName = classes[i];
    if (!clsName) continue;
    if (el.classList) {
      el.classList.remove(clsName);
    } else if (hasClass(el, clsName)) {
      curClass = curClass.replace(' ' + clsName + ' ', ' ');
    }
  }
  if (!el.classList) {
    el.setAttribute('class', trim$1(curClass));
  }
}

if (typeof /./ !== 'function' && typeof Int8Array !== 'object' && (Vue.prototype.$isServer || typeof document.childNodes !== 'function')) ;

const isFirefox = function () {
  return !Vue.prototype.$isServer && !!window.navigator.userAgent.match(/firefox/i);
};

let hasModal = false;
let hasInitZIndex = false;
let zIndex;
const getModal = function () {
  if (Vue.prototype.$isServer) return;
  let modalDom = PopupManager.modalDom;
  if (modalDom) {
    hasModal = true;
  } else {
    hasModal = false;
    modalDom = document.createElement('div');
    PopupManager.modalDom = modalDom;
    modalDom.addEventListener('touchmove', function (event) {
      event.preventDefault();
      event.stopPropagation();
    });
    modalDom.addEventListener('click', function () {
      PopupManager.doOnModalClick && PopupManager.doOnModalClick();
    });
  }
  return modalDom;
};
const instances = {};
const PopupManager = {
  modalFade: true,
  getInstance: function (id) {
    return instances[id];
  },
  register: function (id, instance) {
    if (id && instance) {
      instances[id] = instance;
    }
  },
  deregister: function (id) {
    if (id) {
      instances[id] = null;
      delete instances[id];
    }
  },
  nextZIndex: function () {
    return PopupManager.zIndex++;
  },
  modalStack: [],
  doOnModalClick: function () {
    const topItem = PopupManager.modalStack[PopupManager.modalStack.length - 1];
    if (!topItem) return;
    const instance = PopupManager.getInstance(topItem.id);
    if (instance && instance.closeOnClickModal) {
      instance.close();
    }
  },
  openModal: function (id, zIndex, dom, modalClass, modalFade) {
    if (Vue.prototype.$isServer) return;
    if (!id || zIndex === undefined) return;
    this.modalFade = modalFade;
    const modalStack = this.modalStack;
    for (let i = 0, j = modalStack.length; i < j; i++) {
      const item = modalStack[i];
      if (item.id === id) {
        return;
      }
    }
    const modalDom = getModal();
    addClass(modalDom, 'v-modal');
    if (this.modalFade && !hasModal) {
      addClass(modalDom, 'v-modal-enter');
    }
    if (modalClass) {
      let classArr = modalClass.trim().split(/\s+/);
      classArr.forEach(item => addClass(modalDom, item));
    }
    setTimeout(() => {
      removeClass(modalDom, 'v-modal-enter');
    }, 200);
    if (dom && dom.parentNode && dom.parentNode.nodeType !== 11) {
      dom.parentNode.appendChild(modalDom);
    } else {
      document.body.appendChild(modalDom);
    }
    if (zIndex) {
      modalDom.style.zIndex = zIndex;
    }
    modalDom.tabIndex = 0;
    modalDom.style.display = '';
    this.modalStack.push({
      id: id,
      zIndex: zIndex,
      modalClass: modalClass
    });
  },
  closeModal: function (id) {
    const modalStack = this.modalStack;
    const modalDom = getModal();
    if (modalStack.length > 0) {
      const topItem = modalStack[modalStack.length - 1];
      if (topItem.id === id) {
        if (topItem.modalClass) {
          let classArr = topItem.modalClass.trim().split(/\s+/);
          classArr.forEach(item => removeClass(modalDom, item));
        }
        modalStack.pop();
        if (modalStack.length > 0) {
          modalDom.style.zIndex = modalStack[modalStack.length - 1].zIndex;
        }
      } else {
        for (let i = modalStack.length - 1; i >= 0; i--) {
          if (modalStack[i].id === id) {
            modalStack.splice(i, 1);
            break;
          }
        }
      }
    }
    if (modalStack.length === 0) {
      if (this.modalFade) {
        addClass(modalDom, 'v-modal-leave');
      }
      setTimeout(() => {
        if (modalStack.length === 0) {
          if (modalDom.parentNode) modalDom.parentNode.removeChild(modalDom);
          modalDom.style.display = 'none';
          PopupManager.modalDom = undefined;
        }
        removeClass(modalDom, 'v-modal-leave');
      }, 200);
    }
  }
};
Object.defineProperty(PopupManager, 'zIndex', {
  configurable: true,
  get() {
    if (!hasInitZIndex) {
      zIndex = zIndex || (Vue.prototype.$ELEMENT || {}).zIndex || 2000;
      hasInitZIndex = true;
    }
    return zIndex;
  },
  set(value) {
    zIndex = value;
  }
});
const getTopPopup = function () {
  if (Vue.prototype.$isServer) return;
  if (PopupManager.modalStack.length > 0) {
    const topPopup = PopupManager.modalStack[PopupManager.modalStack.length - 1];
    if (!topPopup) return;
    const instance = PopupManager.getInstance(topPopup.id);
    return instance;
  }
};
if (!Vue.prototype.$isServer) {
  // handle `esc` key when the popup is shown
  window.addEventListener('keydown', function (event) {
    if (event.keyCode === 27) {
      const topPopup = getTopPopup();
      if (topPopup && topPopup.closeOnPressEscape) {
        topPopup.handleClose ? topPopup.handleClose() : topPopup.handleAction ? topPopup.handleAction('cancel') : topPopup.close();
      }
    }
  });
}

//
isFirefox() ? 'DOMMouseScroll' : 'mousewheel';

/* script */

/* template */
var __vue_render__$3 = function () {
  var _vm = this;
  var _h = _vm.$createElement;
  var _c = _vm._self._c || _h;
  return _c("transition", { attrs: { name: "viewer-fade" } }, [
    _c(
      "div",
      {
        ref: "el-image-viewer__wrapper",
        staticClass: "el-image-viewer__wrapper",
        style: { "z-index": _vm.viewerZIndex },
        attrs: { tabindex: "-1" },
      },
      [
        _c("div", {
          staticClass: "el-image-viewer__mask",
          on: {
            click: function ($event) {
              if ($event.target !== $event.currentTarget) {
                return null
              }
              return _vm.handleMaskClick.apply(null, arguments)
            },
          },
        }),
        _vm._v(" "),
        _c(
          "span",
          {
            staticClass: "el-image-viewer__btn el-image-viewer__close",
            on: { click: _vm.hide },
          },
          [_c("i", { staticClass: "el-icon-close" })]
        ),
        _vm._v(" "),
        _c(
          "div",
          { staticClass: "el-image-viewer__btn el-image-viewer__actions" },
          [
            _c("div", { staticClass: "el-image-viewer__actions__inner" }, [
              !_vm.isSingle
                ? _c("i", {
                    class: [
                      "el-icon-arrow-left",
                      !_vm.infinite && _vm.isFirst ? "is-disabled" : "",
                    ],
                    on: { click: _vm.prev },
                  })
                : _vm._e(),
              _vm._v(" "),
              _c("i", {
                staticClass: "el-icon-zoom-out",
                on: {
                  click: function ($event) {
                    return _vm.handleActions("zoomOut")
                  },
                },
              }),
              _vm._v(" "),
              _c("i", {
                staticClass: "el-icon-zoom-in",
                on: {
                  click: function ($event) {
                    return _vm.handleActions("zoomIn")
                  },
                },
              }),
              _vm._v(" "),
              _c("i", { staticClass: "el-image-viewer__actions__divider" }),
              _vm._v(" "),
              _c("i", { class: _vm.mode.icon, on: { click: _vm.toggleMode } }),
              _vm._v(" "),
              _c("i", { staticClass: "el-image-viewer__actions__divider" }),
              _vm._v(" "),
              _c("i", {
                staticClass: "el-icon-refresh-left",
                on: {
                  click: function ($event) {
                    return _vm.handleActions("anticlocelise")
                  },
                },
              }),
              _vm._v(" "),
              _c("i", {
                staticClass: "el-icon-refresh-right",
                on: {
                  click: function ($event) {
                    return _vm.handleActions("clocelise")
                  },
                },
              }),
              _vm._v(" "),
              !_vm.isSingle
                ? _c("i", {
                    class: [
                      "el-icon-arrow-right",
                      !_vm.infinite && _vm.isLast ? "is-disabled" : "",
                    ],
                    on: { click: _vm.next },
                  })
                : _vm._e(),
            ]),
          ]
        ),
        _vm._v(" "),
        _vm.title.length && _vm.title[_vm.index]
          ? _c(
              "div",
              { staticClass: "el-image-viewer__btn el-image-viewer__title" },
              [
                _vm._v(
                  "\n      " +
                    _vm._s(_vm.title.length ? _vm.title[_vm.index] : "") +
                    "\n    "
                ),
              ]
            )
          : _vm._e(),
        _vm._v(" "),
        _vm.contents.length && _vm.contents[_vm.index]
          ? _c(
              "div",
              { staticClass: "el-image-viewer__btn el-image-viewer__content" },
              [
                _c(
                  "el-collapse-transition",
                  { attrs: { name: "el-fade-in" } },
                  [
                    _c(
                      "div",
                      {
                        directives: [
                          {
                            name: "show",
                            rawName: "v-show",
                            value: _vm.ellipsisReady,
                            expression: "ellipsisReady",
                          },
                        ],
                        class: [
                          "ellipsis-box",
                          _vm.contentExpand ? "" : "text-ellipsis-3",
                        ],
                      },
                      [
                        _vm._v(
                          "\n          " +
                            _vm._s(
                              _vm.contents.length ? _vm.contents[_vm.index] : ""
                            ) +
                            "\n        "
                        ),
                      ]
                    ),
                  ]
                ),
                _vm._v(" "),
                _c(
                  "el-button",
                  {
                    directives: [
                      {
                        name: "show",
                        rawName: "v-show",
                        value: _vm.showEllipsisButton,
                        expression: "showEllipsisButton",
                      },
                    ],
                    attrs: { type: "text", size: "mini" },
                    on: { click: _vm.toggleEllipsis },
                  },
                  [
                    _vm._v(_vm._s(_vm.contentExpand ? "收起" : "展开")),
                    _c("i", {
                      class: _vm.contentExpand
                        ? "el-icon-arrow-up"
                        : "el-icon-arrow-down",
                    }),
                  ]
                ),
              ],
              1
            )
          : _vm._e(),
        _vm._v(" "),
        _c(
          "div",
          { staticClass: "el-image-viewer__canvas" },
          _vm._l(_vm.urlList, function (url, i) {
            return i === _vm.index
              ? _c("img", {
                  key: url,
                  ref: "img",
                  refInFor: true,
                  staticClass: "el-image-viewer__img",
                  style: _vm.imgStyle,
                  attrs: { src: _vm.currentImg },
                  on: {
                    load: _vm.handleImgLoad,
                    error: _vm.handleImgError,
                    mousedown: _vm.handleMouseDown,
                    touchstart: _vm.touchstart,
                    touchmove: _vm.touchmove,
                  },
                })
              : _vm._e()
          }),
          0
        ),
      ]
    ),
  ])
};
__vue_render__$3._withStripped = true;

const rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate

let poolPtr = rnds8Pool.length;
function rng() {
  if (poolPtr > rnds8Pool.length - 16) {
    crypto.randomFillSync(rnds8Pool);
    poolPtr = 0;
  }
  return rnds8Pool.slice(poolPtr, poolPtr += 16);
}

var REGEX = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;

function validate(uuid) {
  return typeof uuid === 'string' && REGEX.test(uuid);
}

/**
 * Convert array of 16 byte values to UUID string format of the form:
 * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
 */

const byteToHex = [];
for (let i = 0; i < 256; ++i) {
  byteToHex.push((i + 0x100).toString(16).substr(1));
}
function stringify(arr, offset = 0) {
  // Note: Be careful editing this code!  It's been tuned for performance
  // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
  const uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID.  If this throws, it's likely due to one
  // of the following:
  // - One or more input array values don't map to a hex octet (leading to
  // "undefined" in the uuid)
  // - Invalid input values for the RFC `version` or `variant` fields

  if (!validate(uuid)) {
    throw TypeError('Stringified UUID is invalid');
  }
  return uuid;
}

function v4(options, buf, offset) {
  options = options || {};
  const rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`

  rnds[6] = rnds[6] & 0x0f | 0x40;
  rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided

  if (buf) {
    offset = offset || 0;
    for (let i = 0; i < 16; ++i) {
      buf[offset + i] = rnds[i];
    }
    return buf;
  }
  return stringify(rnds);
}

var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};

function createCommonjsModule(fn, module) {
	return module = { exports: {} }, fn(module, module.exports), module.exports;
}

var jquery = createCommonjsModule(function (module) {
/*!
 * jQuery JavaScript Library v3.7.1
 * https://jquery.com/
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license
 * https://jquery.org/license
 *
 * Date: 2023-08-28T13:37Z
 */
(function (global, factory) {

  {
    // For CommonJS and CommonJS-like environments where a proper `window`
    // is present, execute the factory and get jQuery.
    // For environments that do not have a `window` with a `document`
    // (such as Node.js), expose a factory as module.exports.
    // This accentuates the need for the creation of a real `window`.
    // e.g. var jQuery = require("jquery")(window);
    // See ticket trac-14549 for more info.
    module.exports = global.document ? factory(global, true) : function (w) {
      if (!w.document) {
        throw new Error("jQuery requires a window with a document");
      }
      return factory(w);
    };
  }

  // Pass this if window is not defined yet
})(typeof window !== "undefined" ? window : commonjsGlobal, function (window, noGlobal) {

  var arr = [];
  var getProto = Object.getPrototypeOf;
  var slice = arr.slice;
  var flat = arr.flat ? function (array) {
    return arr.flat.call(array);
  } : function (array) {
    return arr.concat.apply([], array);
  };
  var push = arr.push;
  var indexOf = arr.indexOf;
  var class2type = {};
  var toString = class2type.toString;
  var hasOwn = class2type.hasOwnProperty;
  var fnToString = hasOwn.toString;
  var ObjectFunctionString = fnToString.call(Object);
  var support = {};
  var isFunction = function isFunction(obj) {
    // Support: Chrome <=57, Firefox <=52
    // In some browsers, typeof returns "function" for HTML <object> elements
    // (i.e., `typeof document.createElement( "object" ) === "function"`).
    // We don't want to classify *any* DOM node as a function.
    // Support: QtWeb <=3.8.5, WebKit <=534.34, wkhtmltopdf tool <=0.12.5
    // Plus for old WebKit, typeof returns "function" for HTML collections
    // (e.g., `typeof document.getElementsByTagName("div") === "function"`). (gh-4756)
    return typeof obj === "function" && typeof obj.nodeType !== "number" && typeof obj.item !== "function";
  };
  var isWindow = function isWindow(obj) {
    return obj != null && obj === obj.window;
  };
  var document = window.document;
  var preservedScriptAttributes = {
    type: true,
    src: true,
    nonce: true,
    noModule: true
  };
  function DOMEval(code, node, doc) {
    doc = doc || document;
    var i,
      val,
      script = doc.createElement("script");
    script.text = code;
    if (node) {
      for (i in preservedScriptAttributes) {
        // Support: Firefox 64+, Edge 18+
        // Some browsers don't support the "nonce" property on scripts.
        // On the other hand, just using `getAttribute` is not enough as
        // the `nonce` attribute is reset to an empty string whenever it
        // becomes browsing-context connected.
        // See https://github.com/whatwg/html/issues/2369
        // See https://html.spec.whatwg.org/#nonce-attributes
        // The `node.getAttribute` check was added for the sake of
        // `jQuery.globalEval` so that it can fake a nonce-containing node
        // via an object.
        val = node[i] || node.getAttribute && node.getAttribute(i);
        if (val) {
          script.setAttribute(i, val);
        }
      }
    }
    doc.head.appendChild(script).parentNode.removeChild(script);
  }
  function toType(obj) {
    if (obj == null) {
      return obj + "";
    }

    // Support: Android <=2.3 only (functionish RegExp)
    return typeof obj === "object" || typeof obj === "function" ? class2type[toString.call(obj)] || "object" : typeof obj;
  }
  /* global Symbol */
  // Defining this global in .eslintrc.json would create a danger of using the global
  // unguarded in another place, it seems safer to define global only for this module

  var version = "3.7.1",
    rhtmlSuffix = /HTML$/i,
    // Define a local copy of jQuery
    jQuery = function (selector, context) {
      // The jQuery object is actually just the init constructor 'enhanced'
      // Need init if jQuery is called (just allow error to be thrown if not included)
      return new jQuery.fn.init(selector, context);
    };
  jQuery.fn = jQuery.prototype = {
    // The current version of jQuery being used
    jquery: version,
    constructor: jQuery,
    // The default length of a jQuery object is 0
    length: 0,
    toArray: function () {
      return slice.call(this);
    },
    // Get the Nth element in the matched element set OR
    // Get the whole matched element set as a clean array
    get: function (num) {
      // Return all the elements in a clean array
      if (num == null) {
        return slice.call(this);
      }

      // Return just the one element from the set
      return num < 0 ? this[num + this.length] : this[num];
    },
    // Take an array of elements and push it onto the stack
    // (returning the new matched element set)
    pushStack: function (elems) {
      // Build a new jQuery matched element set
      var ret = jQuery.merge(this.constructor(), elems);

      // Add the old object onto the stack (as a reference)
      ret.prevObject = this;

      // Return the newly-formed element set
      return ret;
    },
    // Execute a callback for every element in the matched set.
    each: function (callback) {
      return jQuery.each(this, callback);
    },
    map: function (callback) {
      return this.pushStack(jQuery.map(this, function (elem, i) {
        return callback.call(elem, i, elem);
      }));
    },
    slice: function () {
      return this.pushStack(slice.apply(this, arguments));
    },
    first: function () {
      return this.eq(0);
    },
    last: function () {
      return this.eq(-1);
    },
    even: function () {
      return this.pushStack(jQuery.grep(this, function (_elem, i) {
        return (i + 1) % 2;
      }));
    },
    odd: function () {
      return this.pushStack(jQuery.grep(this, function (_elem, i) {
        return i % 2;
      }));
    },
    eq: function (i) {
      var len = this.length,
        j = +i + (i < 0 ? len : 0);
      return this.pushStack(j >= 0 && j < len ? [this[j]] : []);
    },
    end: function () {
      return this.prevObject || this.constructor();
    },
    // For internal use only.
    // Behaves like an Array's method, not like a jQuery method.
    push: push,
    sort: arr.sort,
    splice: arr.splice
  };
  jQuery.extend = jQuery.fn.extend = function () {
    var options,
      name,
      src,
      copy,
      copyIsArray,
      clone,
      target = arguments[0] || {},
      i = 1,
      length = arguments.length,
      deep = false;

    // Handle a deep copy situation
    if (typeof target === "boolean") {
      deep = target;

      // Skip the boolean and the target
      target = arguments[i] || {};
      i++;
    }

    // Handle case when target is a string or something (possible in deep copy)
    if (typeof target !== "object" && !isFunction(target)) {
      target = {};
    }

    // Extend jQuery itself if only one argument is passed
    if (i === length) {
      target = this;
      i--;
    }
    for (; i < length; i++) {
      // Only deal with non-null/undefined values
      if ((options = arguments[i]) != null) {
        // Extend the base object
        for (name in options) {
          copy = options[name];

          // Prevent Object.prototype pollution
          // Prevent never-ending loop
          if (name === "__proto__" || target === copy) {
            continue;
          }

          // Recurse if we're merging plain objects or arrays
          if (deep && copy && (jQuery.isPlainObject(copy) || (copyIsArray = Array.isArray(copy)))) {
            src = target[name];

            // Ensure proper type for the source value
            if (copyIsArray && !Array.isArray(src)) {
              clone = [];
            } else if (!copyIsArray && !jQuery.isPlainObject(src)) {
              clone = {};
            } else {
              clone = src;
            }
            copyIsArray = false;

            // Never move original objects, clone them
            target[name] = jQuery.extend(deep, clone, copy);

            // Don't bring in undefined values
          } else if (copy !== undefined) {
            target[name] = copy;
          }
        }
      }
    }

    // Return the modified object
    return target;
  };
  jQuery.extend({
    // Unique for each copy of jQuery on the page
    expando: "jQuery" + (version + Math.random()).replace(/\D/g, ""),
    // Assume jQuery is ready without the ready module
    isReady: true,
    error: function (msg) {
      throw new Error(msg);
    },
    noop: function () {},
    isPlainObject: function (obj) {
      var proto, Ctor;

      // Detect obvious negatives
      // Use toString instead of jQuery.type to catch host objects
      if (!obj || toString.call(obj) !== "[object Object]") {
        return false;
      }
      proto = getProto(obj);

      // Objects with no prototype (e.g., `Object.create( null )`) are plain
      if (!proto) {
        return true;
      }

      // Objects with prototype are plain iff they were constructed by a global Object function
      Ctor = hasOwn.call(proto, "constructor") && proto.constructor;
      return typeof Ctor === "function" && fnToString.call(Ctor) === ObjectFunctionString;
    },
    isEmptyObject: function (obj) {
      var name;
      for (name in obj) {
        return false;
      }
      return true;
    },
    // Evaluates a script in a provided context; falls back to the global one
    // if not specified.
    globalEval: function (code, options, doc) {
      DOMEval(code, {
        nonce: options && options.nonce
      }, doc);
    },
    each: function (obj, callback) {
      var length,
        i = 0;
      if (isArrayLike(obj)) {
        length = obj.length;
        for (; i < length; i++) {
          if (callback.call(obj[i], i, obj[i]) === false) {
            break;
          }
        }
      } else {
        for (i in obj) {
          if (callback.call(obj[i], i, obj[i]) === false) {
            break;
          }
        }
      }
      return obj;
    },
    // Retrieve the text value of an array of DOM nodes
    text: function (elem) {
      var node,
        ret = "",
        i = 0,
        nodeType = elem.nodeType;
      if (!nodeType) {
        // If no nodeType, this is expected to be an array
        while (node = elem[i++]) {
          // Do not traverse comment nodes
          ret += jQuery.text(node);
        }
      }
      if (nodeType === 1 || nodeType === 11) {
        return elem.textContent;
      }
      if (nodeType === 9) {
        return elem.documentElement.textContent;
      }
      if (nodeType === 3 || nodeType === 4) {
        return elem.nodeValue;
      }

      // Do not include comment or processing instruction nodes

      return ret;
    },
    // results is for internal usage only
    makeArray: function (arr, results) {
      var ret = results || [];
      if (arr != null) {
        if (isArrayLike(Object(arr))) {
          jQuery.merge(ret, typeof arr === "string" ? [arr] : arr);
        } else {
          push.call(ret, arr);
        }
      }
      return ret;
    },
    inArray: function (elem, arr, i) {
      return arr == null ? -1 : indexOf.call(arr, elem, i);
    },
    isXMLDoc: function (elem) {
      var namespace = elem && elem.namespaceURI,
        docElem = elem && (elem.ownerDocument || elem).documentElement;

      // Assume HTML when documentElement doesn't yet exist, such as inside
      // document fragments.
      return !rhtmlSuffix.test(namespace || docElem && docElem.nodeName || "HTML");
    },
    // Support: Android <=4.0 only, PhantomJS 1 only
    // push.apply(_, arraylike) throws on ancient WebKit
    merge: function (first, second) {
      var len = +second.length,
        j = 0,
        i = first.length;
      for (; j < len; j++) {
        first[i++] = second[j];
      }
      first.length = i;
      return first;
    },
    grep: function (elems, callback, invert) {
      var callbackInverse,
        matches = [],
        i = 0,
        length = elems.length,
        callbackExpect = !invert;

      // Go through the array, only saving the items
      // that pass the validator function
      for (; i < length; i++) {
        callbackInverse = !callback(elems[i], i);
        if (callbackInverse !== callbackExpect) {
          matches.push(elems[i]);
        }
      }
      return matches;
    },
    // arg is for internal usage only
    map: function (elems, callback, arg) {
      var length,
        value,
        i = 0,
        ret = [];

      // Go through the array, translating each of the items to their new values
      if (isArrayLike(elems)) {
        length = elems.length;
        for (; i < length; i++) {
          value = callback(elems[i], i, arg);
          if (value != null) {
            ret.push(value);
          }
        }

        // Go through every key on the object,
      } else {
        for (i in elems) {
          value = callback(elems[i], i, arg);
          if (value != null) {
            ret.push(value);
          }
        }
      }

      // Flatten any nested arrays
      return flat(ret);
    },
    // A global GUID counter for objects
    guid: 1,
    // jQuery.support is not used in Core but other projects attach their
    // properties to it so it needs to exist.
    support: support
  });
  if (typeof Symbol === "function") {
    jQuery.fn[Symbol.iterator] = arr[Symbol.iterator];
  }

  // Populate the class2type map
  jQuery.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "), function (_i, name) {
    class2type["[object " + name + "]"] = name.toLowerCase();
  });
  function isArrayLike(obj) {
    // Support: real iOS 8.2 only (not reproducible in simulator)
    // `in` check used to prevent JIT error (gh-2145)
    // hasOwn isn't used here due to false negatives
    // regarding Nodelist length in IE
    var length = !!obj && "length" in obj && obj.length,
      type = toType(obj);
    if (isFunction(obj) || isWindow(obj)) {
      return false;
    }
    return type === "array" || length === 0 || typeof length === "number" && length > 0 && length - 1 in obj;
  }
  function nodeName(elem, name) {
    return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
  }
  var pop = arr.pop;
  var sort = arr.sort;
  var splice = arr.splice;
  var whitespace = "[\\x20\\t\\r\\n\\f]";
  var rtrimCSS = new RegExp("^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g");

  // Note: an element does not contain itself
  jQuery.contains = function (a, b) {
    var bup = b && b.parentNode;
    return a === bup || !!(bup && bup.nodeType === 1 && (
    // Support: IE 9 - 11+
    // IE doesn't have `contains` on SVG.
    a.contains ? a.contains(bup) : a.compareDocumentPosition && a.compareDocumentPosition(bup) & 16));
  };

  // CSS string/identifier serialization
  // https://drafts.csswg.org/cssom/#common-serializing-idioms
  var rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\x80-\uFFFF\w-]/g;
  function fcssescape(ch, asCodePoint) {
    if (asCodePoint) {
      // U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER
      if (ch === "\0") {
        return "\uFFFD";
      }

      // Control characters and (dependent upon position) numbers get escaped as code points
      return ch.slice(0, -1) + "\\" + ch.charCodeAt(ch.length - 1).toString(16) + " ";
    }

    // Other potentially-special ASCII characters get backslash-escaped
    return "\\" + ch;
  }
  jQuery.escapeSelector = function (sel) {
    return (sel + "").replace(rcssescape, fcssescape);
  };
  var preferredDoc = document,
    pushNative = push;
  (function () {
    var i,
      Expr,
      outermostContext,
      sortInput,
      hasDuplicate,
      push = pushNative,
      // Local document vars
      document,
      documentElement,
      documentIsHTML,
      rbuggyQSA,
      matches,
      // Instance-specific data
      expando = jQuery.expando,
      dirruns = 0,
      done = 0,
      classCache = createCache(),
      tokenCache = createCache(),
      compilerCache = createCache(),
      nonnativeSelectorCache = createCache(),
      sortOrder = function (a, b) {
        if (a === b) {
          hasDuplicate = true;
        }
        return 0;
      },
      booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|" + "loop|multiple|open|readonly|required|scoped",
      // Regular expressions

      // https://www.w3.org/TR/css-syntax-3/#ident-token-diagram
      identifier = "(?:\\\\[\\da-fA-F]{1,6}" + whitespace + "?|\\\\[^\\r\\n\\f]|[\\w-]|[^\0-\\x7f])+",
      // Attribute selectors: https://www.w3.org/TR/selectors/#attribute-selectors
      attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace +
      // Operator (capture 2)
      "*([*^$|!~]?=)" + whitespace +
      // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]"
      "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + "*\\]",
      pseudos = ":(" + identifier + ")(?:\\((" +
      // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments:
      // 1. quoted (capture 3; capture 4 or capture 5)
      "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" +
      // 2. simple (capture 6)
      "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" +
      // 3. anything else (capture 2)
      ".*" + ")\\)|)",
      // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
      rwhitespace = new RegExp(whitespace + "+", "g"),
      rcomma = new RegExp("^" + whitespace + "*," + whitespace + "*"),
      rleadingCombinator = new RegExp("^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*"),
      rdescend = new RegExp(whitespace + "|>"),
      rpseudo = new RegExp(pseudos),
      ridentifier = new RegExp("^" + identifier + "$"),
      matchExpr = {
        ID: new RegExp("^#(" + identifier + ")"),
        CLASS: new RegExp("^\\.(" + identifier + ")"),
        TAG: new RegExp("^(" + identifier + "|[*])"),
        ATTR: new RegExp("^" + attributes),
        PSEUDO: new RegExp("^" + pseudos),
        CHILD: new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i"),
        bool: new RegExp("^(?:" + booleans + ")$", "i"),
        // For use in libraries implementing .is()
        // We use this for POS matching in `select`
        needsContext: new RegExp("^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i")
      },
      rinputs = /^(?:input|select|textarea|button)$/i,
      rheader = /^h\d$/i,
      // Easily-parseable/retrievable ID or TAG or CLASS selectors
      rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
      rsibling = /[+~]/,
      // CSS escapes
      // https://www.w3.org/TR/CSS21/syndata.html#escaped-characters
      runescape = new RegExp("\\\\[\\da-fA-F]{1,6}" + whitespace + "?|\\\\([^\\r\\n\\f])", "g"),
      funescape = function (escape, nonHex) {
        var high = "0x" + escape.slice(1) - 0x10000;
        if (nonHex) {
          // Strip the backslash prefix from a non-hex escape sequence
          return nonHex;
        }

        // Replace a hexadecimal escape sequence with the encoded Unicode code point
        // Support: IE <=11+
        // For values outside the Basic Multilingual Plane (BMP), manually construct a
        // surrogate pair
        return high < 0 ? String.fromCharCode(high + 0x10000) : String.fromCharCode(high >> 10 | 0xD800, high & 0x3FF | 0xDC00);
      },
      // Used for iframes; see `setDocument`.
      // Support: IE 9 - 11+, Edge 12 - 18+
      // Removing the function wrapper causes a "Permission Denied"
      // error in IE/Edge.
      unloadHandler = function () {
        setDocument();
      },
      inDisabledFieldset = addCombinator(function (elem) {
        return elem.disabled === true && nodeName(elem, "fieldset");
      }, {
        dir: "parentNode",
        next: "legend"
      });

    // Support: IE <=9 only
    // Accessing document.activeElement can throw unexpectedly
    // https://bugs.jquery.com/ticket/13393
    function safeActiveElement() {
      try {
        return document.activeElement;
      } catch (err) {}
    }

    // Optimize for push.apply( _, NodeList )
    try {
      push.apply(arr = slice.call(preferredDoc.childNodes), preferredDoc.childNodes);

      // Support: Android <=4.0
      // Detect silently failing push.apply
      // eslint-disable-next-line no-unused-expressions
      arr[preferredDoc.childNodes.length].nodeType;
    } catch (e) {
      push = {
        apply: function (target, els) {
          pushNative.apply(target, slice.call(els));
        },
        call: function (target) {
          pushNative.apply(target, slice.call(arguments, 1));
        }
      };
    }
    function find(selector, context, results, seed) {
      var m,
        i,
        elem,
        nid,
        match,
        groups,
        newSelector,
        newContext = context && context.ownerDocument,
        // nodeType defaults to 9, since context defaults to document
        nodeType = context ? context.nodeType : 9;
      results = results || [];

      // Return early from calls with invalid selector or context
      if (typeof selector !== "string" || !selector || nodeType !== 1 && nodeType !== 9 && nodeType !== 11) {
        return results;
      }

      // Try to shortcut find operations (as opposed to filters) in HTML documents
      if (!seed) {
        setDocument(context);
        context = context || document;
        if (documentIsHTML) {
          // If the selector is sufficiently simple, try using a "get*By*" DOM method
          // (excepting DocumentFragment context, where the methods don't exist)
          if (nodeType !== 11 && (match = rquickExpr.exec(selector))) {
            // ID selector
            if (m = match[1]) {
              // Document context
              if (nodeType === 9) {
                if (elem = context.getElementById(m)) {
                  // Support: IE 9 only
                  // getElementById can match elements by name instead of ID
                  if (elem.id === m) {
                    push.call(results, elem);
                    return results;
                  }
                } else {
                  return results;
                }

                // Element context
              } else {
                // Support: IE 9 only
                // getElementById can match elements by name instead of ID
                if (newContext && (elem = newContext.getElementById(m)) && find.contains(context, elem) && elem.id === m) {
                  push.call(results, elem);
                  return results;
                }
              }

              // Type selector
            } else if (match[2]) {
              push.apply(results, context.getElementsByTagName(selector));
              return results;

              // Class selector
            } else if ((m = match[3]) && context.getElementsByClassName) {
              push.apply(results, context.getElementsByClassName(m));
              return results;
            }
          }

          // Take advantage of querySelectorAll
          if (!nonnativeSelectorCache[selector + " "] && (!rbuggyQSA || !rbuggyQSA.test(selector))) {
            newSelector = selector;
            newContext = context;

            // qSA considers elements outside a scoping root when evaluating child or
            // descendant combinators, which is not what we want.
            // In such cases, we work around the behavior by prefixing every selector in the
            // list with an ID selector referencing the scope context.
            // The technique has to be used as well when a leading combinator is used
            // as such selectors are not recognized by querySelectorAll.
            // Thanks to Andrew Dupont for this technique.
            if (nodeType === 1 && (rdescend.test(selector) || rleadingCombinator.test(selector))) {
              // Expand context for sibling selectors
              newContext = rsibling.test(selector) && testContext(context.parentNode) || context;

              // We can use :scope instead of the ID hack if the browser
              // supports it & if we're not changing the context.
              // Support: IE 11+, Edge 17 - 18+
              // IE/Edge sometimes throw a "Permission denied" error when
              // strict-comparing two documents; shallow comparisons work.
              // eslint-disable-next-line eqeqeq
              if (newContext != context || !support.scope) {
                // Capture the context ID, setting it first if necessary
                if (nid = context.getAttribute("id")) {
                  nid = jQuery.escapeSelector(nid);
                } else {
                  context.setAttribute("id", nid = expando);
                }
              }

              // Prefix every selector in the list
              groups = tokenize(selector);
              i = groups.length;
              while (i--) {
                groups[i] = (nid ? "#" + nid : ":scope") + " " + toSelector(groups[i]);
              }
              newSelector = groups.join(",");
            }
            try {
              push.apply(results, newContext.querySelectorAll(newSelector));
              return results;
            } catch (qsaError) {
              nonnativeSelectorCache(selector, true);
            } finally {
              if (nid === expando) {
                context.removeAttribute("id");
              }
            }
          }
        }
      }

      // All others
      return select(selector.replace(rtrimCSS, "$1"), context, results, seed);
    }

    /**
     * Create key-value caches of limited size
     * @returns {function(string, object)} Returns the Object data after storing it on itself with
     *	property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
     *	deleting the oldest entry
     */
    function createCache() {
      var keys = [];
      function cache(key, value) {
        // Use (key + " ") to avoid collision with native prototype properties
        // (see https://github.com/jquery/sizzle/issues/157)
        if (keys.push(key + " ") > Expr.cacheLength) {
          // Only keep the most recent entries
          delete cache[keys.shift()];
        }
        return cache[key + " "] = value;
      }
      return cache;
    }

    /**
     * Mark a function for special use by jQuery selector module
     * @param {Function} fn The function to mark
     */
    function markFunction(fn) {
      fn[expando] = true;
      return fn;
    }

    /**
     * Support testing using an element
     * @param {Function} fn Passed the created element and returns a boolean result
     */
    function assert(fn) {
      var el = document.createElement("fieldset");
      try {
        return !!fn(el);
      } catch (e) {
        return false;
      } finally {
        // Remove from its parent by default
        if (el.parentNode) {
          el.parentNode.removeChild(el);
        }

        // release memory in IE
        el = null;
      }
    }

    /**
     * Returns a function to use in pseudos for input types
     * @param {String} type
     */
    function createInputPseudo(type) {
      return function (elem) {
        return nodeName(elem, "input") && elem.type === type;
      };
    }

    /**
     * Returns a function to use in pseudos for buttons
     * @param {String} type
     */
    function createButtonPseudo(type) {
      return function (elem) {
        return (nodeName(elem, "input") || nodeName(elem, "button")) && elem.type === type;
      };
    }

    /**
     * Returns a function to use in pseudos for :enabled/:disabled
     * @param {Boolean} disabled true for :disabled; false for :enabled
     */
    function createDisabledPseudo(disabled) {
      // Known :disabled false positives: fieldset[disabled] > legend:nth-of-type(n+2) :can-disable
      return function (elem) {
        // Only certain elements can match :enabled or :disabled
        // https://html.spec.whatwg.org/multipage/scripting.html#selector-enabled
        // https://html.spec.whatwg.org/multipage/scripting.html#selector-disabled
        if ("form" in elem) {
          // Check for inherited disabledness on relevant non-disabled elements:
          // * listed form-associated elements in a disabled fieldset
          //   https://html.spec.whatwg.org/multipage/forms.html#category-listed
          //   https://html.spec.whatwg.org/multipage/forms.html#concept-fe-disabled
          // * option elements in a disabled optgroup
          //   https://html.spec.whatwg.org/multipage/forms.html#concept-option-disabled
          // All such elements have a "form" property.
          if (elem.parentNode && elem.disabled === false) {
            // Option elements defer to a parent optgroup if present
            if ("label" in elem) {
              if ("label" in elem.parentNode) {
                return elem.parentNode.disabled === disabled;
              } else {
                return elem.disabled === disabled;
              }
            }

            // Support: IE 6 - 11+
            // Use the isDisabled shortcut property to check for disabled fieldset ancestors
            return elem.isDisabled === disabled ||
            // Where there is no isDisabled, check manually
            elem.isDisabled !== !disabled && inDisabledFieldset(elem) === disabled;
          }
          return elem.disabled === disabled;

          // Try to winnow out elements that can't be disabled before trusting the disabled property.
          // Some victims get caught in our net (label, legend, menu, track), but it shouldn't
          // even exist on them, let alone have a boolean value.
        } else if ("label" in elem) {
          return elem.disabled === disabled;
        }

        // Remaining elements are neither :enabled nor :disabled
        return false;
      };
    }

    /**
     * Returns a function to use in pseudos for positionals
     * @param {Function} fn
     */
    function createPositionalPseudo(fn) {
      return markFunction(function (argument) {
        argument = +argument;
        return markFunction(function (seed, matches) {
          var j,
            matchIndexes = fn([], seed.length, argument),
            i = matchIndexes.length;

          // Match elements found at the specified indexes
          while (i--) {
            if (seed[j = matchIndexes[i]]) {
              seed[j] = !(matches[j] = seed[j]);
            }
          }
        });
      });
    }

    /**
     * Checks a node for validity as a jQuery selector context
     * @param {Element|Object=} context
     * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value
     */
    function testContext(context) {
      return context && typeof context.getElementsByTagName !== "undefined" && context;
    }

    /**
     * Sets document-related variables once based on the current document
     * @param {Element|Object} [node] An element or document object to use to set the document
     * @returns {Object} Returns the current document
     */
    function setDocument(node) {
      var subWindow,
        doc = node ? node.ownerDocument || node : preferredDoc;

      // Return early if doc is invalid or already selected
      // Support: IE 11+, Edge 17 - 18+
      // IE/Edge sometimes throw a "Permission denied" error when strict-comparing
      // two documents; shallow comparisons work.
      // eslint-disable-next-line eqeqeq
      if (doc == document || doc.nodeType !== 9 || !doc.documentElement) {
        return document;
      }

      // Update global variables
      document = doc;
      documentElement = document.documentElement;
      documentIsHTML = !jQuery.isXMLDoc(document);

      // Support: iOS 7 only, IE 9 - 11+
      // Older browsers didn't support unprefixed `matches`.
      matches = documentElement.matches || documentElement.webkitMatchesSelector || documentElement.msMatchesSelector;

      // Support: IE 9 - 11+, Edge 12 - 18+
      // Accessing iframe documents after unload throws "permission denied" errors
      // (see trac-13936).
      // Limit the fix to IE & Edge Legacy; despite Edge 15+ implementing `matches`,
      // all IE 9+ and Edge Legacy versions implement `msMatchesSelector` as well.
      if (documentElement.msMatchesSelector &&
      // Support: IE 11+, Edge 17 - 18+
      // IE/Edge sometimes throw a "Permission denied" error when strict-comparing
      // two documents; shallow comparisons work.
      // eslint-disable-next-line eqeqeq
      preferredDoc != document && (subWindow = document.defaultView) && subWindow.top !== subWindow) {
        // Support: IE 9 - 11+, Edge 12 - 18+
        subWindow.addEventListener("unload", unloadHandler);
      }

      // Support: IE <10
      // Check if getElementById returns elements by name
      // The broken getElementById methods don't pick up programmatically-set names,
      // so use a roundabout getElementsByName test
      support.getById = assert(function (el) {
        documentElement.appendChild(el).id = jQuery.expando;
        return !document.getElementsByName || !document.getElementsByName(jQuery.expando).length;
      });

      // Support: IE 9 only
      // Check to see if it's possible to do matchesSelector
      // on a disconnected node.
      support.disconnectedMatch = assert(function (el) {
        return matches.call(el, "*");
      });

      // Support: IE 9 - 11+, Edge 12 - 18+
      // IE/Edge don't support the :scope pseudo-class.
      support.scope = assert(function () {
        return document.querySelectorAll(":scope");
      });

      // Support: Chrome 105 - 111 only, Safari 15.4 - 16.3 only
      // Make sure the `:has()` argument is parsed unforgivingly.
      // We include `*` in the test to detect buggy implementations that are
      // _selectively_ forgiving (specifically when the list includes at least
      // one valid selector).
      // Note that we treat complete lack of support for `:has()` as if it were
      // spec-compliant support, which is fine because use of `:has()` in such
      // environments will fail in the qSA path and fall back to jQuery traversal
      // anyway.
      support.cssHas = assert(function () {
        try {
          document.querySelector(":has(*,:jqfake)");
          return false;
        } catch (e) {
          return true;
        }
      });

      // ID filter and find
      if (support.getById) {
        Expr.filter.ID = function (id) {
          var attrId = id.replace(runescape, funescape);
          return function (elem) {
            return elem.getAttribute("id") === attrId;
          };
        };
        Expr.find.ID = function (id, context) {
          if (typeof context.getElementById !== "undefined" && documentIsHTML) {
            var elem = context.getElementById(id);
            return elem ? [elem] : [];
          }
        };
      } else {
        Expr.filter.ID = function (id) {
          var attrId = id.replace(runescape, funescape);
          return function (elem) {
            var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id");
            return node && node.value === attrId;
          };
        };

        // Support: IE 6 - 7 only
        // getElementById is not reliable as a find shortcut
        Expr.find.ID = function (id, context) {
          if (typeof context.getElementById !== "undefined" && documentIsHTML) {
            var node,
              i,
              elems,
              elem = context.getElementById(id);
            if (elem) {
              // Verify the id attribute
              node = elem.getAttributeNode("id");
              if (node && node.value === id) {
                return [elem];
              }

              // Fall back on getElementsByName
              elems = context.getElementsByName(id);
              i = 0;
              while (elem = elems[i++]) {
                node = elem.getAttributeNode("id");
                if (node && node.value === id) {
                  return [elem];
                }
              }
            }
            return [];
          }
        };
      }

      // Tag
      Expr.find.TAG = function (tag, context) {
        if (typeof context.getElementsByTagName !== "undefined") {
          return context.getElementsByTagName(tag);

          // DocumentFragment nodes don't have gEBTN
        } else {
          return context.querySelectorAll(tag);
        }
      };

      // Class
      Expr.find.CLASS = function (className, context) {
        if (typeof context.getElementsByClassName !== "undefined" && documentIsHTML) {
          return context.getElementsByClassName(className);
        }
      };

      /* QSA/matchesSelector
      ---------------------------------------------------------------------- */

      // QSA and matchesSelector support

      rbuggyQSA = [];

      // Build QSA regex
      // Regex strategy adopted from Diego Perini
      assert(function (el) {
        var input;
        documentElement.appendChild(el).innerHTML = "<a id='" + expando + "' href='' disabled='disabled'></a>" + "<select id='" + expando + "-\r\\' disabled='disabled'>" + "<option selected=''></option></select>";

        // Support: iOS <=7 - 8 only
        // Boolean attributes and "value" are not treated correctly in some XML documents
        if (!el.querySelectorAll("[selected]").length) {
          rbuggyQSA.push("\\[" + whitespace + "*(?:value|" + booleans + ")");
        }

        // Support: iOS <=7 - 8 only
        if (!el.querySelectorAll("[id~=" + expando + "-]").length) {
          rbuggyQSA.push("~=");
        }

        // Support: iOS 8 only
        // https://bugs.webkit.org/show_bug.cgi?id=136851
        // In-page `selector#id sibling-combinator selector` fails
        if (!el.querySelectorAll("a#" + expando + "+*").length) {
          rbuggyQSA.push(".#.+[+~]");
        }

        // Support: Chrome <=105+, Firefox <=104+, Safari <=15.4+
        // In some of the document kinds, these selectors wouldn't work natively.
        // This is probably OK but for backwards compatibility we want to maintain
        // handling them through jQuery traversal in jQuery 3.x.
        if (!el.querySelectorAll(":checked").length) {
          rbuggyQSA.push(":checked");
        }

        // Support: Windows 8 Native Apps
        // The type and name attributes are restricted during .innerHTML assignment
        input = document.createElement("input");
        input.setAttribute("type", "hidden");
        el.appendChild(input).setAttribute("name", "D");

        // Support: IE 9 - 11+
        // IE's :disabled selector does not pick up the children of disabled fieldsets
        // Support: Chrome <=105+, Firefox <=104+, Safari <=15.4+
        // In some of the document kinds, these selectors wouldn't work natively.
        // This is probably OK but for backwards compatibility we want to maintain
        // handling them through jQuery traversal in jQuery 3.x.
        documentElement.appendChild(el).disabled = true;
        if (el.querySelectorAll(":disabled").length !== 2) {
          rbuggyQSA.push(":enabled", ":disabled");
        }

        // Support: IE 11+, Edge 15 - 18+
        // IE 11/Edge don't find elements on a `[name='']` query in some cases.
        // Adding a temporary attribute to the document before the selection works
        // around the issue.
        // Interestingly, IE 10 & older don't seem to have the issue.
        input = document.createElement("input");
        input.setAttribute("name", "");
        el.appendChild(input);
        if (!el.querySelectorAll("[name='']").length) {
          rbuggyQSA.push("\\[" + whitespace + "*name" + whitespace + "*=" + whitespace + "*(?:''|\"\")");
        }
      });
      if (!support.cssHas) {
        // Support: Chrome 105 - 110+, Safari 15.4 - 16.3+
        // Our regular `try-catch` mechanism fails to detect natively-unsupported
        // pseudo-classes inside `:has()` (such as `:has(:contains("Foo"))`)
        // in browsers that parse the `:has()` argument as a forgiving selector list.
        // https://drafts.csswg.org/selectors/#relational now requires the argument
        // to be parsed unforgivingly, but browsers have not yet fully adjusted.
        rbuggyQSA.push(":has");
      }
      rbuggyQSA = rbuggyQSA.length && new RegExp(rbuggyQSA.join("|"));

      /* Sorting
      ---------------------------------------------------------------------- */

      // Document order sorting
      sortOrder = function (a, b) {
        // Flag for duplicate removal
        if (a === b) {
          hasDuplicate = true;
          return 0;
        }

        // Sort on method existence if only one input has compareDocumentPosition
        var compare = !a.compareDocumentPosition - !b.compareDocumentPosition;
        if (compare) {
          return compare;
        }

        // Calculate position if both inputs belong to the same document
        // Support: IE 11+, Edge 17 - 18+
        // IE/Edge sometimes throw a "Permission denied" error when strict-comparing
        // two documents; shallow comparisons work.
        // eslint-disable-next-line eqeqeq
        compare = (a.ownerDocument || a) == (b.ownerDocument || b) ? a.compareDocumentPosition(b) :
        // Otherwise we know they are disconnected
        1;

        // Disconnected nodes
        if (compare & 1 || !support.sortDetached && b.compareDocumentPosition(a) === compare) {
          // Choose the first element that is related to our preferred document
          // Support: IE 11+, Edge 17 - 18+
          // IE/Edge sometimes throw a "Permission denied" error when strict-comparing
          // two documents; shallow comparisons work.
          // eslint-disable-next-line eqeqeq
          if (a === document || a.ownerDocument == preferredDoc && find.contains(preferredDoc, a)) {
            return -1;
          }

          // Support: IE 11+, Edge 17 - 18+
          // IE/Edge sometimes throw a "Permission denied" error when strict-comparing
          // two documents; shallow comparisons work.
          // eslint-disable-next-line eqeqeq
          if (b === document || b.ownerDocument == preferredDoc && find.contains(preferredDoc, b)) {
            return 1;
          }

          // Maintain original order
          return sortInput ? indexOf.call(sortInput, a) - indexOf.call(sortInput, b) : 0;
        }
        return compare & 4 ? -1 : 1;
      };
      return document;
    }
    find.matches = function (expr, elements) {
      return find(expr, null, null, elements);
    };
    find.matchesSelector = function (elem, expr) {
      setDocument(elem);
      if (documentIsHTML && !nonnativeSelectorCache[expr + " "] && (!rbuggyQSA || !rbuggyQSA.test(expr))) {
        try {
          var ret = matches.call(elem, expr);

          // IE 9's matchesSelector returns false on disconnected nodes
          if (ret || support.disconnectedMatch ||
          // As well, disconnected nodes are said to be in a document
          // fragment in IE 9
          elem.document && elem.document.nodeType !== 11) {
            return ret;
          }
        } catch (e) {
          nonnativeSelectorCache(expr, true);
        }
      }
      return find(expr, document, null, [elem]).length > 0;
    };
    find.contains = function (context, elem) {
      // Set document vars if needed
      // Support: IE 11+, Edge 17 - 18+
      // IE/Edge sometimes throw a "Permission denied" error when strict-comparing
      // two documents; shallow comparisons work.
      // eslint-disable-next-line eqeqeq
      if ((context.ownerDocument || context) != document) {
        setDocument(context);
      }
      return jQuery.contains(context, elem);
    };
    find.attr = function (elem, name) {
      // Set document vars if needed
      // Support: IE 11+, Edge 17 - 18+
      // IE/Edge sometimes throw a "Permission denied" error when strict-comparing
      // two documents; shallow comparisons work.
      // eslint-disable-next-line eqeqeq
      if ((elem.ownerDocument || elem) != document) {
        setDocument(elem);
      }
      var fn = Expr.attrHandle[name.toLowerCase()],
        // Don't get fooled by Object.prototype properties (see trac-13807)
        val = fn && hasOwn.call(Expr.attrHandle, name.toLowerCase()) ? fn(elem, name, !documentIsHTML) : undefined;
      if (val !== undefined) {
        return val;
      }
      return elem.getAttribute(name);
    };
    find.error = function (msg) {
      throw new Error("Syntax error, unrecognized expression: " + msg);
    };

    /**
     * Document sorting and removing duplicates
     * @param {ArrayLike} results
     */
    jQuery.uniqueSort = function (results) {
      var elem,
        duplicates = [],
        j = 0,
        i = 0;

      // Unless we *know* we can detect duplicates, assume their presence
      //
      // Support: Android <=4.0+
      // Testing for detecting duplicates is unpredictable so instead assume we can't
      // depend on duplicate detection in all browsers without a stable sort.
      hasDuplicate = !support.sortStable;
      sortInput = !support.sortStable && slice.call(results, 0);
      sort.call(results, sortOrder);
      if (hasDuplicate) {
        while (elem = results[i++]) {
          if (elem === results[i]) {
            j = duplicates.push(i);
          }
        }
        while (j--) {
          splice.call(results, duplicates[j], 1);
        }
      }

      // Clear input after sorting to release objects
      // See https://github.com/jquery/sizzle/pull/225
      sortInput = null;
      return results;
    };
    jQuery.fn.uniqueSort = function () {
      return this.pushStack(jQuery.uniqueSort(slice.apply(this)));
    };
    Expr = jQuery.expr = {
      // Can be adjusted by the user
      cacheLength: 50,
      createPseudo: markFunction,
      match: matchExpr,
      attrHandle: {},
      find: {},
      relative: {
        ">": {
          dir: "parentNode",
          first: true
        },
        " ": {
          dir: "parentNode"
        },
        "+": {
          dir: "previousSibling",
          first: true
        },
        "~": {
          dir: "previousSibling"
        }
      },
      preFilter: {
        ATTR: function (match) {
          match[1] = match[1].replace(runescape, funescape);

          // Move the given value to match[3] whether quoted or unquoted
          match[3] = (match[3] || match[4] || match[5] || "").replace(runescape, funescape);
          if (match[2] === "~=") {
            match[3] = " " + match[3] + " ";
          }
          return match.slice(0, 4);
        },
        CHILD: function (match) {
          /* matches from matchExpr["CHILD"]
          	1 type (only|nth|...)
          	2 what (child|of-type)
          	3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
          	4 xn-component of xn+y argument ([+-]?\d*n|)
          	5 sign of xn-component
          	6 x of xn-component
          	7 sign of y-component
          	8 y of y-component
          */
          match[1] = match[1].toLowerCase();
          if (match[1].slice(0, 3) === "nth") {
            // nth-* requires argument
            if (!match[3]) {
              find.error(match[0]);
            }

            // numeric x and y parameters for Expr.filter.CHILD
            // remember that false/true cast respectively to 0/1
            match[4] = +(match[4] ? match[5] + (match[6] || 1) : 2 * (match[3] === "even" || match[3] === "odd"));
            match[5] = +(match[7] + match[8] || match[3] === "odd");

            // other types prohibit arguments
          } else if (match[3]) {
            find.error(match[0]);
          }
          return match;
        },
        PSEUDO: function (match) {
          var excess,
            unquoted = !match[6] && match[2];
          if (matchExpr.CHILD.test(match[0])) {
            return null;
          }

          // Accept quoted arguments as-is
          if (match[3]) {
            match[2] = match[4] || match[5] || "";

            // Strip excess characters from unquoted arguments
          } else if (unquoted && rpseudo.test(unquoted) && (
          // Get excess from tokenize (recursively)
          excess = tokenize(unquoted, true)) && (
          // advance to the next closing parenthesis
          excess = unquoted.indexOf(")", unquoted.length - excess) - unquoted.length)) {
            // excess is a negative index
            match[0] = match[0].slice(0, excess);
            match[2] = unquoted.slice(0, excess);
          }

          // Return only captures needed by the pseudo filter method (type and argument)
          return match.slice(0, 3);
        }
      },
      filter: {
        TAG: function (nodeNameSelector) {
          var expectedNodeName = nodeNameSelector.replace(runescape, funescape).toLowerCase();
          return nodeNameSelector === "*" ? function () {
            return true;
          } : function (elem) {
            return nodeName(elem, expectedNodeName);
          };
        },
        CLASS: function (className) {
          var pattern = classCache[className + " "];
          return pattern || (pattern = new RegExp("(^|" + whitespace + ")" + className + "(" + whitespace + "|$)")) && classCache(className, function (elem) {
            return pattern.test(typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute("class") || "");
          });
        },
        ATTR: function (name, operator, check) {
          return function (elem) {
            var result = find.attr(elem, name);
            if (result == null) {
              return operator === "!=";
            }
            if (!operator) {
              return true;
            }
            result += "";
            if (operator === "=") {
              return result === check;
            }
            if (operator === "!=") {
              return result !== check;
            }
            if (operator === "^=") {
              return check && result.indexOf(check) === 0;
            }
            if (operator === "*=") {
              return check && result.indexOf(check) > -1;
            }
            if (operator === "$=") {
              return check && result.slice(-check.length) === check;
            }
            if (operator === "~=") {
              return (" " + result.replace(rwhitespace, " ") + " ").indexOf(check) > -1;
            }
            if (operator === "|=") {
              return result === check || result.slice(0, check.length + 1) === check + "-";
            }
            return false;
          };
        },
        CHILD: function (type, what, _argument, first, last) {
          var simple = type.slice(0, 3) !== "nth",
            forward = type.slice(-4) !== "last",
            ofType = what === "of-type";
          return first === 1 && last === 0 ?
          // Shortcut for :nth-*(n)
          function (elem) {
            return !!elem.parentNode;
          } : function (elem, _context, xml) {
            var cache,
              outerCache,
              node,
              nodeIndex,
              start,
              dir = simple !== forward ? "nextSibling" : "previousSibling",
              parent = elem.parentNode,
              name = ofType && elem.nodeName.toLowerCase(),
              useCache = !xml && !ofType,
              diff = false;
            if (parent) {
              // :(first|last|only)-(child|of-type)
              if (simple) {
                while (dir) {
                  node = elem;
                  while (node = node[dir]) {
                    if (ofType ? nodeName(node, name) : node.nodeType === 1) {
                      return false;
                    }
                  }

                  // Reverse direction for :only-* (if we haven't yet done so)
                  start = dir = type === "only" && !start && "nextSibling";
                }
                return true;
              }
              start = [forward ? parent.firstChild : parent.lastChild];

              // non-xml :nth-child(...) stores cache data on `parent`
              if (forward && useCache) {
                // Seek `elem` from a previously-cached index
                outerCache = parent[expando] || (parent[expando] = {});
                cache = outerCache[type] || [];
                nodeIndex = cache[0] === dirruns && cache[1];
                diff = nodeIndex && cache[2];
                node = nodeIndex && parent.childNodes[nodeIndex];
                while (node = ++nodeIndex && node && node[dir] || (
                // Fallback to seeking `elem` from the start
                diff = nodeIndex = 0) || start.pop()) {
                  // When found, cache indexes on `parent` and break
                  if (node.nodeType === 1 && ++diff && node === elem) {
                    outerCache[type] = [dirruns, nodeIndex, diff];
                    break;
                  }
                }
              } else {
                // Use previously-cached element index if available
                if (useCache) {
                  outerCache = elem[expando] || (elem[expando] = {});
                  cache = outerCache[type] || [];
                  nodeIndex = cache[0] === dirruns && cache[1];
                  diff = nodeIndex;
                }

                // xml :nth-child(...)
                // or :nth-last-child(...) or :nth(-last)?-of-type(...)
                if (diff === false) {
                  // Use the same loop as above to seek `elem` from the start
                  while (node = ++nodeIndex && node && node[dir] || (diff = nodeIndex = 0) || start.pop()) {
                    if ((ofType ? nodeName(node, name) : node.nodeType === 1) && ++diff) {
                      // Cache the index of each encountered element
                      if (useCache) {
                        outerCache = node[expando] || (node[expando] = {});
                        outerCache[type] = [dirruns, diff];
                      }
                      if (node === elem) {
                        break;
                      }
                    }
                  }
                }
              }

              // Incorporate the offset, then check against cycle size
              diff -= last;
              return diff === first || diff % first === 0 && diff / first >= 0;
            }
          };
        },
        PSEUDO: function (pseudo, argument) {
          // pseudo-class names are case-insensitive
          // https://www.w3.org/TR/selectors/#pseudo-classes
          // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
          // Remember that setFilters inherits from pseudos
          var args,
            fn = Expr.pseudos[pseudo] || Expr.setFilters[pseudo.toLowerCase()] || find.error("unsupported pseudo: " + pseudo);

          // The user may use createPseudo to indicate that
          // arguments are needed to create the filter function
          // just as jQuery does
          if (fn[expando]) {
            return fn(argument);
          }

          // But maintain support for old signatures
          if (fn.length > 1) {
            args = [pseudo, pseudo, "", argument];
            return Expr.setFilters.hasOwnProperty(pseudo.toLowerCase()) ? markFunction(function (seed, matches) {
              var idx,
                matched = fn(seed, argument),
                i = matched.length;
              while (i--) {
                idx = indexOf.call(seed, matched[i]);
                seed[idx] = !(matches[idx] = matched[i]);
              }
            }) : function (elem) {
              return fn(elem, 0, args);
            };
          }
          return fn;
        }
      },
      pseudos: {
        // Potentially complex pseudos
        not: markFunction(function (selector) {
          // Trim the selector passed to compile
          // to avoid treating leading and trailing
          // spaces as combinators
          var input = [],
            results = [],
            matcher = compile(selector.replace(rtrimCSS, "$1"));
          return matcher[expando] ? markFunction(function (seed, matches, _context, xml) {
            var elem,
              unmatched = matcher(seed, null, xml, []),
              i = seed.length;

            // Match elements unmatched by `matcher`
            while (i--) {
              if (elem = unmatched[i]) {
                seed[i] = !(matches[i] = elem);
              }
            }
          }) : function (elem, _context, xml) {
            input[0] = elem;
            matcher(input, null, xml, results);

            // Don't keep the element
            // (see https://github.com/jquery/sizzle/issues/299)
            input[0] = null;
            return !results.pop();
          };
        }),
        has: markFunction(function (selector) {
          return function (elem) {
            return find(selector, elem).length > 0;
          };
        }),
        contains: markFunction(function (text) {
          text = text.replace(runescape, funescape);
          return function (elem) {
            return (elem.textContent || jQuery.text(elem)).indexOf(text) > -1;
          };
        }),
        // "Whether an element is represented by a :lang() selector
        // is based solely on the element's language value
        // being equal to the identifier C,
        // or beginning with the identifier C immediately followed by "-".
        // The matching of C against the element's language value is performed case-insensitively.
        // The identifier C does not have to be a valid language name."
        // https://www.w3.org/TR/selectors/#lang-pseudo
        lang: markFunction(function (lang) {
          // lang value must be a valid identifier
          if (!ridentifier.test(lang || "")) {
            find.error("unsupported lang: " + lang);
          }
          lang = lang.replace(runescape, funescape).toLowerCase();
          return function (elem) {
            var elemLang;
            do {
              if (elemLang = documentIsHTML ? elem.lang : elem.getAttribute("xml:lang") || elem.getAttribute("lang")) {
                elemLang = elemLang.toLowerCase();
                return elemLang === lang || elemLang.indexOf(lang + "-") === 0;
              }
            } while ((elem = elem.parentNode) && elem.nodeType === 1);
            return false;
          };
        }),
        // Miscellaneous
        target: function (elem) {
          var hash = window.location && window.location.hash;
          return hash && hash.slice(1) === elem.id;
        },
        root: function (elem) {
          return elem === documentElement;
        },
        focus: function (elem) {
          return elem === safeActiveElement() && document.hasFocus() && !!(elem.type || elem.href || ~elem.tabIndex);
        },
        // Boolean properties
        enabled: createDisabledPseudo(false),
        disabled: createDisabledPseudo(true),
        checked: function (elem) {
          // In CSS3, :checked should return both checked and selected elements
          // https://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
          return nodeName(elem, "input") && !!elem.checked || nodeName(elem, "option") && !!elem.selected;
        },
        selected: function (elem) {
          // Support: IE <=11+
          // Accessing the selectedIndex property
          // forces the browser to treat the default option as
          // selected when in an optgroup.
          if (elem.parentNode) {
            // eslint-disable-next-line no-unused-expressions
            elem.parentNode.selectedIndex;
          }
          return elem.selected === true;
        },
        // Contents
        empty: function (elem) {
          // https://www.w3.org/TR/selectors/#empty-pseudo
          // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5),
          //   but not by others (comment: 8; processing instruction: 7; etc.)
          // nodeType < 6 works because attributes (2) do not appear as children
          for (elem = elem.firstChild; elem; elem = elem.nextSibling) {
            if (elem.nodeType < 6) {
              return false;
            }
          }
          return true;
        },
        parent: function (elem) {
          return !Expr.pseudos.empty(elem);
        },
        // Element/input types
        header: function (elem) {
          return rheader.test(elem.nodeName);
        },
        input: function (elem) {
          return rinputs.test(elem.nodeName);
        },
        button: function (elem) {
          return nodeName(elem, "input") && elem.type === "button" || nodeName(elem, "button");
        },
        text: function (elem) {
          var attr;
          return nodeName(elem, "input") && elem.type === "text" && (
          // Support: IE <10 only
          // New HTML5 attribute values (e.g., "search") appear
          // with elem.type === "text"
          (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text");
        },
        // Position-in-collection
        first: createPositionalPseudo(function () {
          return [0];
        }),
        last: createPositionalPseudo(function (_matchIndexes, length) {
          return [length - 1];
        }),
        eq: createPositionalPseudo(function (_matchIndexes, length, argument) {
          return [argument < 0 ? argument + length : argument];
        }),
        even: createPositionalPseudo(function (matchIndexes, length) {
          var i = 0;
          for (; i < length; i += 2) {
            matchIndexes.push(i);
          }
          return matchIndexes;
        }),
        odd: createPositionalPseudo(function (matchIndexes, length) {
          var i = 1;
          for (; i < length; i += 2) {
            matchIndexes.push(i);
          }
          return matchIndexes;
        }),
        lt: createPositionalPseudo(function (matchIndexes, length, argument) {
          var i;
          if (argument < 0) {
            i = argument + length;
          } else if (argument > length) {
            i = length;
          } else {
            i = argument;
          }
          for (; --i >= 0;) {
            matchIndexes.push(i);
          }
          return matchIndexes;
        }),
        gt: createPositionalPseudo(function (matchIndexes, length, argument) {
          var i = argument < 0 ? argument + length : argument;
          for (; ++i < length;) {
            matchIndexes.push(i);
          }
          return matchIndexes;
        })
      }
    };
    Expr.pseudos.nth = Expr.pseudos.eq;

    // Add button/input type pseudos
    for (i in {
      radio: true,
      checkbox: true,
      file: true,
      password: true,
      image: true
    }) {
      Expr.pseudos[i] = createInputPseudo(i);
    }
    for (i in {
      submit: true,
      reset: true
    }) {
      Expr.pseudos[i] = createButtonPseudo(i);
    }

    // Easy API for creating new setFilters
    function setFilters() {}
    setFilters.prototype = Expr.filters = Expr.pseudos;
    Expr.setFilters = new setFilters();
    function tokenize(selector, parseOnly) {
      var matched,
        match,
        tokens,
        type,
        soFar,
        groups,
        preFilters,
        cached = tokenCache[selector + " "];
      if (cached) {
        return parseOnly ? 0 : cached.slice(0);
      }
      soFar = selector;
      groups = [];
      preFilters = Expr.preFilter;
      while (soFar) {
        // Comma and first run
        if (!matched || (match = rcomma.exec(soFar))) {
          if (match) {
            // Don't consume trailing commas as valid
            soFar = soFar.slice(match[0].length) || soFar;
          }
          groups.push(tokens = []);
        }
        matched = false;

        // Combinators
        if (match = rleadingCombinator.exec(soFar)) {
          matched = match.shift();
          tokens.push({
            value: matched,
            // Cast descendant combinators to space
            type: match[0].replace(rtrimCSS, " ")
          });
          soFar = soFar.slice(matched.length);
        }

        // Filters
        for (type in Expr.filter) {
          if ((match = matchExpr[type].exec(soFar)) && (!preFilters[type] || (match = preFilters[type](match)))) {
            matched = match.shift();
            tokens.push({
              value: matched,
              type: type,
              matches: match
            });
            soFar = soFar.slice(matched.length);
          }
        }
        if (!matched) {
          break;
        }
      }

      // Return the length of the invalid excess
      // if we're just parsing
      // Otherwise, throw an error or return tokens
      if (parseOnly) {
        return soFar.length;
      }
      return soFar ? find.error(selector) :
      // Cache the tokens
      tokenCache(selector, groups).slice(0);
    }
    function toSelector(tokens) {
      var i = 0,
        len = tokens.length,
        selector = "";
      for (; i < len; i++) {
        selector += tokens[i].value;
      }
      return selector;
    }
    function addCombinator(matcher, combinator, base) {
      var dir = combinator.dir,
        skip = combinator.next,
        key = skip || dir,
        checkNonElements = base && key === "parentNode",
        doneName = done++;
      return combinator.first ?
      // Check against closest ancestor/preceding element
      function (elem, context, xml) {
        while (elem = elem[dir]) {
          if (elem.nodeType === 1 || checkNonElements) {
            return matcher(elem, context, xml);
          }
        }
        return false;
      } :
      // Check against all ancestor/preceding elements
      function (elem, context, xml) {
        var oldCache,
          outerCache,
          newCache = [dirruns, doneName];

        // We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching
        if (xml) {
          while (elem = elem[dir]) {
            if (elem.nodeType === 1 || checkNonElements) {
              if (matcher(elem, context, xml)) {
                return true;
              }
            }
          }
        } else {
          while (elem = elem[dir]) {
            if (elem.nodeType === 1 || checkNonElements) {
              outerCache = elem[expando] || (elem[expando] = {});
              if (skip && nodeName(elem, skip)) {
                elem = elem[dir] || elem;
              } else if ((oldCache = outerCache[key]) && oldCache[0] === dirruns && oldCache[1] === doneName) {
                // Assign to newCache so results back-propagate to previous elements
                return newCache[2] = oldCache[2];
              } else {
                // Reuse newcache so results back-propagate to previous elements
                outerCache[key] = newCache;

                // A match means we're done; a fail means we have to keep checking
                if (newCache[2] = matcher(elem, context, xml)) {
                  return true;
                }
              }
            }
          }
        }
        return false;
      };
    }
    function elementMatcher(matchers) {
      return matchers.length > 1 ? function (elem, context, xml) {
        var i = matchers.length;
        while (i--) {
          if (!matchers[i](elem, context, xml)) {
            return false;
          }
        }
        return true;
      } : matchers[0];
    }
    function multipleContexts(selector, contexts, results) {
      var i = 0,
        len = contexts.length;
      for (; i < len; i++) {
        find(selector, contexts[i], results);
      }
      return results;
    }
    function condense(unmatched, map, filter, context, xml) {
      var elem,
        newUnmatched = [],
        i = 0,
        len = unmatched.length,
        mapped = map != null;
      for (; i < len; i++) {
        if (elem = unmatched[i]) {
          if (!filter || filter(elem, context, xml)) {
            newUnmatched.push(elem);
            if (mapped) {
              map.push(i);
            }
          }
        }
      }
      return newUnmatched;
    }
    function setMatcher(preFilter, selector, matcher, postFilter, postFinder, postSelector) {
      if (postFilter && !postFilter[expando]) {
        postFilter = setMatcher(postFilter);
      }
      if (postFinder && !postFinder[expando]) {
        postFinder = setMatcher(postFinder, postSelector);
      }
      return markFunction(function (seed, results, context, xml) {
        var temp,
          i,
          elem,
          matcherOut,
          preMap = [],
          postMap = [],
          preexisting = results.length,
          // Get initial elements from seed or context
          elems = seed || multipleContexts(selector || "*", context.nodeType ? [context] : context, []),
          // Prefilter to get matcher input, preserving a map for seed-results synchronization
          matcherIn = preFilter && (seed || !selector) ? condense(elems, preMap, preFilter, context, xml) : elems;
        if (matcher) {
          // If we have a postFinder, or filtered seed, or non-seed postFilter
          // or preexisting results,
          matcherOut = postFinder || (seed ? preFilter : preexisting || postFilter) ?
          // ...intermediate processing is necessary
          [] :
          // ...otherwise use results directly
          results;

          // Find primary matches
          matcher(matcherIn, matcherOut, context, xml);
        } else {
          matcherOut = matcherIn;
        }

        // Apply postFilter
        if (postFilter) {
          temp = condense(matcherOut, postMap);
          postFilter(temp, [], context, xml);

          // Un-match failing elements by moving them back to matcherIn
          i = temp.length;
          while (i--) {
            if (elem = temp[i]) {
              matcherOut[postMap[i]] = !(matcherIn[postMap[i]] = elem);
            }
          }
        }
        if (seed) {
          if (postFinder || preFilter) {
            if (postFinder) {
              // Get the final matcherOut by condensing this intermediate into postFinder contexts
              temp = [];
              i = matcherOut.length;
              while (i--) {
                if (elem = matcherOut[i]) {
                  // Restore matcherIn since elem is not yet a final match
                  temp.push(matcherIn[i] = elem);
                }
              }
              postFinder(null, matcherOut = [], temp, xml);
            }

            // Move matched elements from seed to results to keep them synchronized
            i = matcherOut.length;
            while (i--) {
              if ((elem = matcherOut[i]) && (temp = postFinder ? indexOf.call(seed, elem) : preMap[i]) > -1) {
                seed[temp] = !(results[temp] = elem);
              }
            }
          }

          // Add elements to results, through postFinder if defined
        } else {
          matcherOut = condense(matcherOut === results ? matcherOut.splice(preexisting, matcherOut.length) : matcherOut);
          if (postFinder) {
            postFinder(null, results, matcherOut, xml);
          } else {
            push.apply(results, matcherOut);
          }
        }
      });
    }
    function matcherFromTokens(tokens) {
      var checkContext,
        matcher,
        j,
        len = tokens.length,
        leadingRelative = Expr.relative[tokens[0].type],
        implicitRelative = leadingRelative || Expr.relative[" "],
        i = leadingRelative ? 1 : 0,
        // The foundational matcher ensures that elements are reachable from top-level context(s)
        matchContext = addCombinator(function (elem) {
          return elem === checkContext;
        }, implicitRelative, true),
        matchAnyContext = addCombinator(function (elem) {
          return indexOf.call(checkContext, elem) > -1;
        }, implicitRelative, true),
        matchers = [function (elem, context, xml) {
          // Support: IE 11+, Edge 17 - 18+
          // IE/Edge sometimes throw a "Permission denied" error when strict-comparing
          // two documents; shallow comparisons work.
          // eslint-disable-next-line eqeqeq
          var ret = !leadingRelative && (xml || context != outermostContext) || ((checkContext = context).nodeType ? matchContext(elem, context, xml) : matchAnyContext(elem, context, xml));

          // Avoid hanging onto element
          // (see https://github.com/jquery/sizzle/issues/299)
          checkContext = null;
          return ret;
        }];
      for (; i < len; i++) {
        if (matcher = Expr.relative[tokens[i].type]) {
          matchers = [addCombinator(elementMatcher(matchers), matcher)];
        } else {
          matcher = Expr.filter[tokens[i].type].apply(null, tokens[i].matches);

          // Return special upon seeing a positional matcher
          if (matcher[expando]) {
            // Find the next relative operator (if any) for proper handling
            j = ++i;
            for (; j < len; j++) {
              if (Expr.relative[tokens[j].type]) {
                break;
              }
            }
            return setMatcher(i > 1 && elementMatcher(matchers), i > 1 && toSelector(
            // If the preceding token was a descendant combinator, insert an implicit any-element `*`
            tokens.slice(0, i - 1).concat({
              value: tokens[i - 2].type === " " ? "*" : ""
            })).replace(rtrimCSS, "$1"), matcher, i < j && matcherFromTokens(tokens.slice(i, j)), j < len && matcherFromTokens(tokens = tokens.slice(j)), j < len && toSelector(tokens));
          }
          matchers.push(matcher);
        }
      }
      return elementMatcher(matchers);
    }
    function matcherFromGroupMatchers(elementMatchers, setMatchers) {
      var bySet = setMatchers.length > 0,
        byElement = elementMatchers.length > 0,
        superMatcher = function (seed, context, xml, results, outermost) {
          var elem,
            j,
            matcher,
            matchedCount = 0,
            i = "0",
            unmatched = seed && [],
            setMatched = [],
            contextBackup = outermostContext,
            // We must always have either seed elements or outermost context
            elems = seed || byElement && Expr.find.TAG("*", outermost),
            // Use integer dirruns iff this is the outermost matcher
            dirrunsUnique = dirruns += contextBackup == null ? 1 : Math.random() || 0.1,
            len = elems.length;
          if (outermost) {
            // Support: IE 11+, Edge 17 - 18+
            // IE/Edge sometimes throw a "Permission denied" error when strict-comparing
            // two documents; shallow comparisons work.
            // eslint-disable-next-line eqeqeq
            outermostContext = context == document || context || outermost;
          }

          // Add elements passing elementMatchers directly to results
          // Support: iOS <=7 - 9 only
          // Tolerate NodeList properties (IE: "length"; Safari: <number>) matching
          // elements by id. (see trac-14142)
          for (; i !== len && (elem = elems[i]) != null; i++) {
            if (byElement && elem) {
              j = 0;

              // Support: IE 11+, Edge 17 - 18+
              // IE/Edge sometimes throw a "Permission denied" error when strict-comparing
              // two documents; shallow comparisons work.
              // eslint-disable-next-line eqeqeq
              if (!context && elem.ownerDocument != document) {
                setDocument(elem);
                xml = !documentIsHTML;
              }
              while (matcher = elementMatchers[j++]) {
                if (matcher(elem, context || document, xml)) {
                  push.call(results, elem);
                  break;
                }
              }
              if (outermost) {
                dirruns = dirrunsUnique;
              }
            }

            // Track unmatched elements for set filters
            if (bySet) {
              // They will have gone through all possible matchers
              if (elem = !matcher && elem) {
                matchedCount--;
              }

              // Lengthen the array for every element, matched or not
              if (seed) {
                unmatched.push(elem);
              }
            }
          }

          // `i` is now the count of elements visited above, and adding it to `matchedCount`
          // makes the latter nonnegative.
          matchedCount += i;

          // Apply set filters to unmatched elements
          // NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount`
          // equals `i`), unless we didn't visit _any_ elements in the above loop because we have
          // no element matchers and no seed.
          // Incrementing an initially-string "0" `i` allows `i` to remain a string only in that
          // case, which will result in a "00" `matchedCount` that differs from `i` but is also
          // numerically zero.
          if (bySet && i !== matchedCount) {
            j = 0;
            while (matcher = setMatchers[j++]) {
              matcher(unmatched, setMatched, context, xml);
            }
            if (seed) {
              // Reintegrate element matches to eliminate the need for sorting
              if (matchedCount > 0) {
                while (i--) {
                  if (!(unmatched[i] || setMatched[i])) {
                    setMatched[i] = pop.call(results);
                  }
                }
              }

              // Discard index placeholder values to get only actual matches
              setMatched = condense(setMatched);
            }

            // Add matches to results
            push.apply(results, setMatched);

            // Seedless set matches succeeding multiple successful matchers stipulate sorting
            if (outermost && !seed && setMatched.length > 0 && matchedCount + setMatchers.length > 1) {
              jQuery.uniqueSort(results);
            }
          }

          // Override manipulation of globals by nested matchers
          if (outermost) {
            dirruns = dirrunsUnique;
            outermostContext = contextBackup;
          }
          return unmatched;
        };
      return bySet ? markFunction(superMatcher) : superMatcher;
    }
    function compile(selector, match /* Internal Use Only */) {
      var i,
        setMatchers = [],
        elementMatchers = [],
        cached = compilerCache[selector + " "];
      if (!cached) {
        // Generate a function of recursive functions that can be used to check each element
        if (!match) {
          match = tokenize(selector);
        }
        i = match.length;
        while (i--) {
          cached = matcherFromTokens(match[i]);
          if (cached[expando]) {
            setMatchers.push(cached);
          } else {
            elementMatchers.push(cached);
          }
        }

        // Cache the compiled function
        cached = compilerCache(selector, matcherFromGroupMatchers(elementMatchers, setMatchers));

        // Save selector and tokenization
        cached.selector = selector;
      }
      return cached;
    }

    /**
     * A low-level selection function that works with jQuery's compiled
     *  selector functions
     * @param {String|Function} selector A selector or a pre-compiled
     *  selector function built with jQuery selector compile
     * @param {Element} context
     * @param {Array} [results]
     * @param {Array} [seed] A set of elements to match against
     */
    function select(selector, context, results, seed) {
      var i,
        tokens,
        token,
        type,
        find,
        compiled = typeof selector === "function" && selector,
        match = !seed && tokenize(selector = compiled.selector || selector);
      results = results || [];

      // Try to minimize operations if there is only one selector in the list and no seed
      // (the latter of which guarantees us context)
      if (match.length === 1) {
        // Reduce context if the leading compound selector is an ID
        tokens = match[0] = match[0].slice(0);
        if (tokens.length > 2 && (token = tokens[0]).type === "ID" && context.nodeType === 9 && documentIsHTML && Expr.relative[tokens[1].type]) {
          context = (Expr.find.ID(token.matches[0].replace(runescape, funescape), context) || [])[0];
          if (!context) {
            return results;

            // Precompiled matchers will still verify ancestry, so step up a level
          } else if (compiled) {
            context = context.parentNode;
          }
          selector = selector.slice(tokens.shift().value.length);
        }

        // Fetch a seed set for right-to-left matching
        i = matchExpr.needsContext.test(selector) ? 0 : tokens.length;
        while (i--) {
          token = tokens[i];

          // Abort if we hit a combinator
          if (Expr.relative[type = token.type]) {
            break;
          }
          if (find = Expr.find[type]) {
            // Search, expanding context for leading sibling combinators
            if (seed = find(token.matches[0].replace(runescape, funescape), rsibling.test(tokens[0].type) && testContext(context.parentNode) || context)) {
              // If seed is empty or no tokens remain, we can return early
              tokens.splice(i, 1);
              selector = seed.length && toSelector(tokens);
              if (!selector) {
                push.apply(results, seed);
                return results;
              }
              break;
            }
          }
        }
      }

      // Compile and execute a filtering function if one is not provided
      // Provide `match` to avoid retokenization if we modified the selector above
      (compiled || compile(selector, match))(seed, context, !documentIsHTML, results, !context || rsibling.test(selector) && testContext(context.parentNode) || context);
      return results;
    }

    // One-time assignments

    // Support: Android <=4.0 - 4.1+
    // Sort stability
    support.sortStable = expando.split("").sort(sortOrder).join("") === expando;

    // Initialize against the default document
    setDocument();

    // Support: Android <=4.0 - 4.1+
    // Detached nodes confoundingly follow *each other*
    support.sortDetached = assert(function (el) {
      // Should return 1, but returns 4 (following)
      return el.compareDocumentPosition(document.createElement("fieldset")) & 1;
    });
    jQuery.find = find;

    // Deprecated
    jQuery.expr[":"] = jQuery.expr.pseudos;
    jQuery.unique = jQuery.uniqueSort;

    // These have always been private, but they used to be documented as part of
    // Sizzle so let's maintain them for now for backwards compatibility purposes.
    find.compile = compile;
    find.select = select;
    find.setDocument = setDocument;
    find.tokenize = tokenize;
    find.escape = jQuery.escapeSelector;
    find.getText = jQuery.text;
    find.isXML = jQuery.isXMLDoc;
    find.selectors = jQuery.expr;
    find.support = jQuery.support;
    find.uniqueSort = jQuery.uniqueSort;

    /* eslint-enable */
  })();
  var dir = function (elem, dir, until) {
    var matched = [],
      truncate = until !== undefined;
    while ((elem = elem[dir]) && elem.nodeType !== 9) {
      if (elem.nodeType === 1) {
        if (truncate && jQuery(elem).is(until)) {
          break;
        }
        matched.push(elem);
      }
    }
    return matched;
  };
  var siblings = function (n, elem) {
    var matched = [];
    for (; n; n = n.nextSibling) {
      if (n.nodeType === 1 && n !== elem) {
        matched.push(n);
      }
    }
    return matched;
  };
  var rneedsContext = jQuery.expr.match.needsContext;
  var rsingleTag = /^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;

  // Implement the identical functionality for filter and not
  function winnow(elements, qualifier, not) {
    if (isFunction(qualifier)) {
      return jQuery.grep(elements, function (elem, i) {
        return !!qualifier.call(elem, i, elem) !== not;
      });
    }

    // Single element
    if (qualifier.nodeType) {
      return jQuery.grep(elements, function (elem) {
        return elem === qualifier !== not;
      });
    }

    // Arraylike of elements (jQuery, arguments, Array)
    if (typeof qualifier !== "string") {
      return jQuery.grep(elements, function (elem) {
        return indexOf.call(qualifier, elem) > -1 !== not;
      });
    }

    // Filtered directly for both simple and complex selectors
    return jQuery.filter(qualifier, elements, not);
  }
  jQuery.filter = function (expr, elems, not) {
    var elem = elems[0];
    if (not) {
      expr = ":not(" + expr + ")";
    }
    if (elems.length === 1 && elem.nodeType === 1) {
      return jQuery.find.matchesSelector(elem, expr) ? [elem] : [];
    }
    return jQuery.find.matches(expr, jQuery.grep(elems, function (elem) {
      return elem.nodeType === 1;
    }));
  };
  jQuery.fn.extend({
    find: function (selector) {
      var i,
        ret,
        len = this.length,
        self = this;
      if (typeof selector !== "string") {
        return this.pushStack(jQuery(selector).filter(function () {
          for (i = 0; i < len; i++) {
            if (jQuery.contains(self[i], this)) {
              return true;
            }
          }
        }));
      }
      ret = this.pushStack([]);
      for (i = 0; i < len; i++) {
        jQuery.find(selector, self[i], ret);
      }
      return len > 1 ? jQuery.uniqueSort(ret) : ret;
    },
    filter: function (selector) {
      return this.pushStack(winnow(this, selector || [], false));
    },
    not: function (selector) {
      return this.pushStack(winnow(this, selector || [], true));
    },
    is: function (selector) {
      return !!winnow(this,
      // If this is a positional/relative selector, check membership in the returned set
      // so $("p:first").is("p:last") won't return true for a doc with two "p".
      typeof selector === "string" && rneedsContext.test(selector) ? jQuery(selector) : selector || [], false).length;
    }
  });

  // Initialize a jQuery object

  // A central reference to the root jQuery(document)
  var rootjQuery,
    // A simple way to check for HTML strings
    // Prioritize #id over <tag> to avoid XSS via location.hash (trac-9521)
    // Strict HTML recognition (trac-11290: must start with <)
    // Shortcut simple #id case for speed
    rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/,
    init = jQuery.fn.init = function (selector, context, root) {
      var match, elem;

      // HANDLE: $(""), $(null), $(undefined), $(false)
      if (!selector) {
        return this;
      }

      // Method init() accepts an alternate rootjQuery
      // so migrate can support jQuery.sub (gh-2101)
      root = root || rootjQuery;

      // Handle HTML strings
      if (typeof selector === "string") {
        if (selector[0] === "<" && selector[selector.length - 1] === ">" && selector.length >= 3) {
          // Assume that strings that start and end with <> are HTML and skip the regex check
          match = [null, selector, null];
        } else {
          match = rquickExpr.exec(selector);
        }

        // Match html or make sure no context is specified for #id
        if (match && (match[1] || !context)) {
          // HANDLE: $(html) -> $(array)
          if (match[1]) {
            context = context instanceof jQuery ? context[0] : context;

            // Option to run scripts is true for back-compat
            // Intentionally let the error be thrown if parseHTML is not present
            jQuery.merge(this, jQuery.parseHTML(match[1], context && context.nodeType ? context.ownerDocument || context : document, true));

            // HANDLE: $(html, props)
            if (rsingleTag.test(match[1]) && jQuery.isPlainObject(context)) {
              for (match in context) {
                // Properties of context are called as methods if possible
                if (isFunction(this[match])) {
                  this[match](context[match]);

                  // ...and otherwise set as attributes
                } else {
                  this.attr(match, context[match]);
                }
              }
            }
            return this;

            // HANDLE: $(#id)
          } else {
            elem = document.getElementById(match[2]);
            if (elem) {
              // Inject the element directly into the jQuery object
              this[0] = elem;
              this.length = 1;
            }
            return this;
          }

          // HANDLE: $(expr, $(...))
        } else if (!context || context.jquery) {
          return (context || root).find(selector);

          // HANDLE: $(expr, context)
          // (which is just equivalent to: $(context).find(expr)
        } else {
          return this.constructor(context).find(selector);
        }

        // HANDLE: $(DOMElement)
      } else if (selector.nodeType) {
        this[0] = selector;
        this.length = 1;
        return this;

        // HANDLE: $(function)
        // Shortcut for document ready
      } else if (isFunction(selector)) {
        return root.ready !== undefined ? root.ready(selector) :
        // Execute immediately if ready is not present
        selector(jQuery);
      }
      return jQuery.makeArray(selector, this);
    };

  // Give the init function the jQuery prototype for later instantiation
  init.prototype = jQuery.fn;

  // Initialize central reference
  rootjQuery = jQuery(document);
  var rparentsprev = /^(?:parents|prev(?:Until|All))/,
    // Methods guaranteed to produce a unique set when starting from a unique set
    guaranteedUnique = {
      children: true,
      contents: true,
      next: true,
      prev: true
    };
  jQuery.fn.extend({
    has: function (target) {
      var targets = jQuery(target, this),
        l = targets.length;
      return this.filter(function () {
        var i = 0;
        for (; i < l; i++) {
          if (jQuery.contains(this, targets[i])) {
            return true;
          }
        }
      });
    },
    closest: function (selectors, context) {
      var cur,
        i = 0,
        l = this.length,
        matched = [],
        targets = typeof selectors !== "string" && jQuery(selectors);

      // Positional selectors never match, since there's no _selection_ context
      if (!rneedsContext.test(selectors)) {
        for (; i < l; i++) {
          for (cur = this[i]; cur && cur !== context; cur = cur.parentNode) {
            // Always skip document fragments
            if (cur.nodeType < 11 && (targets ? targets.index(cur) > -1 :
            // Don't pass non-elements to jQuery#find
            cur.nodeType === 1 && jQuery.find.matchesSelector(cur, selectors))) {
              matched.push(cur);
              break;
            }
          }
        }
      }
      return this.pushStack(matched.length > 1 ? jQuery.uniqueSort(matched) : matched);
    },
    // Determine the position of an element within the set
    index: function (elem) {
      // No argument, return index in parent
      if (!elem) {
        return this[0] && this[0].parentNode ? this.first().prevAll().length : -1;
      }

      // Index in selector
      if (typeof elem === "string") {
        return indexOf.call(jQuery(elem), this[0]);
      }

      // Locate the position of the desired element
      return indexOf.call(this,
      // If it receives a jQuery object, the first element is used
      elem.jquery ? elem[0] : elem);
    },
    add: function (selector, context) {
      return this.pushStack(jQuery.uniqueSort(jQuery.merge(this.get(), jQuery(selector, context))));
    },
    addBack: function (selector) {
      return this.add(selector == null ? this.prevObject : this.prevObject.filter(selector));
    }
  });
  function sibling(cur, dir) {
    while ((cur = cur[dir]) && cur.nodeType !== 1) {}
    return cur;
  }
  jQuery.each({
    parent: function (elem) {
      var parent = elem.parentNode;
      return parent && parent.nodeType !== 11 ? parent : null;
    },
    parents: function (elem) {
      return dir(elem, "parentNode");
    },
    parentsUntil: function (elem, _i, until) {
      return dir(elem, "parentNode", until);
    },
    next: function (elem) {
      return sibling(elem, "nextSibling");
    },
    prev: function (elem) {
      return sibling(elem, "previousSibling");
    },
    nextAll: function (elem) {
      return dir(elem, "nextSibling");
    },
    prevAll: function (elem) {
      return dir(elem, "previousSibling");
    },
    nextUntil: function (elem, _i, until) {
      return dir(elem, "nextSibling", until);
    },
    prevUntil: function (elem, _i, until) {
      return dir(elem, "previousSibling", until);
    },
    siblings: function (elem) {
      return siblings((elem.parentNode || {}).firstChild, elem);
    },
    children: function (elem) {
      return siblings(elem.firstChild);
    },
    contents: function (elem) {
      if (elem.contentDocument != null &&
      // Support: IE 11+
      // <object> elements with no `data` attribute has an object
      // `contentDocument` with a `null` prototype.
      getProto(elem.contentDocument)) {
        return elem.contentDocument;
      }

      // Support: IE 9 - 11 only, iOS 7 only, Android Browser <=4.3 only
      // Treat the template element as a regular one in browsers that
      // don't support it.
      if (nodeName(elem, "template")) {
        elem = elem.content || elem;
      }
      return jQuery.merge([], elem.childNodes);
    }
  }, function (name, fn) {
    jQuery.fn[name] = function (until, selector) {
      var matched = jQuery.map(this, fn, until);
      if (name.slice(-5) !== "Until") {
        selector = until;
      }
      if (selector && typeof selector === "string") {
        matched = jQuery.filter(selector, matched);
      }
      if (this.length > 1) {
        // Remove duplicates
        if (!guaranteedUnique[name]) {
          jQuery.uniqueSort(matched);
        }

        // Reverse order for parents* and prev-derivatives
        if (rparentsprev.test(name)) {
          matched.reverse();
        }
      }
      return this.pushStack(matched);
    };
  });
  var rnothtmlwhite = /[^\x20\t\r\n\f]+/g;

  // Convert String-formatted options into Object-formatted ones
  function createOptions(options) {
    var object = {};
    jQuery.each(options.match(rnothtmlwhite) || [], function (_, flag) {
      object[flag] = true;
    });
    return object;
  }

  /*
   * Create a callback list using the following parameters:
   *
   *	options: an optional list of space-separated options that will change how
   *			the callback list behaves or a more traditional option object
   *
   * By default a callback list will act like an event callback list and can be
   * "fired" multiple times.
   *
   * Possible options:
   *
   *	once:			will ensure the callback list can only be fired once (like a Deferred)
   *
   *	memory:			will keep track of previous values and will call any callback added
   *					after the list has been fired right away with the latest "memorized"
   *					values (like a Deferred)
   *
   *	unique:			will ensure a callback can only be added once (no duplicate in the list)
   *
   *	stopOnFalse:	interrupt callings when a callback returns false
   *
   */
  jQuery.Callbacks = function (options) {
    // Convert options from String-formatted to Object-formatted if needed
    // (we check in cache first)
    options = typeof options === "string" ? createOptions(options) : jQuery.extend({}, options);
    var
      // Flag to know if list is currently firing
      firing,
      // Last fire value for non-forgettable lists
      memory,
      // Flag to know if list was already fired
      fired,
      // Flag to prevent firing
      locked,
      // Actual callback list
      list = [],
      // Queue of execution data for repeatable lists
      queue = [],
      // Index of currently firing callback (modified by add/remove as needed)
      firingIndex = -1,
      // Fire callbacks
      fire = function () {
        // Enforce single-firing
        locked = locked || options.once;

        // Execute callbacks for all pending executions,
        // respecting firingIndex overrides and runtime changes
        fired = firing = true;
        for (; queue.length; firingIndex = -1) {
          memory = queue.shift();
          while (++firingIndex < list.length) {
            // Run callback and check for early termination
            if (list[firingIndex].apply(memory[0], memory[1]) === false && options.stopOnFalse) {
              // Jump to end and forget the data so .add doesn't re-fire
              firingIndex = list.length;
              memory = false;
            }
          }
        }

        // Forget the data if we're done with it
        if (!options.memory) {
          memory = false;
        }
        firing = false;

        // Clean up if we're done firing for good
        if (locked) {
          // Keep an empty list if we have data for future add calls
          if (memory) {
            list = [];

            // Otherwise, this object is spent
          } else {
            list = "";
          }
        }
      },
      // Actual Callbacks object
      self = {
        // Add a callback or a collection of callbacks to the list
        add: function () {
          if (list) {
            // If we have memory from a past run, we should fire after adding
            if (memory && !firing) {
              firingIndex = list.length - 1;
              queue.push(memory);
            }
            (function add(args) {
              jQuery.each(args, function (_, arg) {
                if (isFunction(arg)) {
                  if (!options.unique || !self.has(arg)) {
                    list.push(arg);
                  }
                } else if (arg && arg.length && toType(arg) !== "string") {
                  // Inspect recursively
                  add(arg);
                }
              });
            })(arguments);
            if (memory && !firing) {
              fire();
            }
          }
          return this;
        },
        // Remove a callback from the list
        remove: function () {
          jQuery.each(arguments, function (_, arg) {
            var index;
            while ((index = jQuery.inArray(arg, list, index)) > -1) {
              list.splice(index, 1);

              // Handle firing indexes
              if (index <= firingIndex) {
                firingIndex--;
              }
            }
          });
          return this;
        },
        // Check if a given callback is in the list.
        // If no argument is given, return whether or not list has callbacks attached.
        has: function (fn) {
          return fn ? jQuery.inArray(fn, list) > -1 : list.length > 0;
        },
        // Remove all callbacks from the list
        empty: function () {
          if (list) {
            list = [];
          }
          return this;
        },
        // Disable .fire and .add
        // Abort any current/pending executions
        // Clear all callbacks and values
        disable: function () {
          locked = queue = [];
          list = memory = "";
          return this;
        },
        disabled: function () {
          return !list;
        },
        // Disable .fire
        // Also disable .add unless we have memory (since it would have no effect)
        // Abort any pending executions
        lock: function () {
          locked = queue = [];
          if (!memory && !firing) {
            list = memory = "";
          }
          return this;
        },
        locked: function () {
          return !!locked;
        },
        // Call all callbacks with the given context and arguments
        fireWith: function (context, args) {
          if (!locked) {
            args = args || [];
            args = [context, args.slice ? args.slice() : args];
            queue.push(args);
            if (!firing) {
              fire();
            }
          }
          return this;
        },
        // Call all the callbacks with the given arguments
        fire: function () {
          self.fireWith(this, arguments);
          return this;
        },
        // To know if the callbacks have already been called at least once
        fired: function () {
          return !!fired;
        }
      };
    return self;
  };
  function Identity(v) {
    return v;
  }
  function Thrower(ex) {
    throw ex;
  }
  function adoptValue(value, resolve, reject, noValue) {
    var method;
    try {
      // Check for promise aspect first to privilege synchronous behavior
      if (value && isFunction(method = value.promise)) {
        method.call(value).done(resolve).fail(reject);

        // Other thenables
      } else if (value && isFunction(method = value.then)) {
        method.call(value, resolve, reject);

        // Other non-thenables
      } else {
        // Control `resolve` arguments by letting Array#slice cast boolean `noValue` to integer:
        // * false: [ value ].slice( 0 ) => resolve( value )
        // * true: [ value ].slice( 1 ) => resolve()
        resolve.apply(undefined, [value].slice(noValue));
      }

      // For Promises/A+, convert exceptions into rejections
      // Since jQuery.when doesn't unwrap thenables, we can skip the extra checks appearing in
      // Deferred#then to conditionally suppress rejection.
    } catch (value) {
      // Support: Android 4.0 only
      // Strict mode functions invoked without .call/.apply get global-object context
      reject.apply(undefined, [value]);
    }
  }
  jQuery.extend({
    Deferred: function (func) {
      var tuples = [
        // action, add listener, callbacks,
        // ... .then handlers, argument index, [final state]
        ["notify", "progress", jQuery.Callbacks("memory"), jQuery.Callbacks("memory"), 2], ["resolve", "done", jQuery.Callbacks("once memory"), jQuery.Callbacks("once memory"), 0, "resolved"], ["reject", "fail", jQuery.Callbacks("once memory"), jQuery.Callbacks("once memory"), 1, "rejected"]],
        state = "pending",
        promise = {
          state: function () {
            return state;
          },
          always: function () {
            deferred.done(arguments).fail(arguments);
            return this;
          },
          "catch": function (fn) {
            return promise.then(null, fn);
          },
          // Keep pipe for back-compat
          pipe: function /* fnDone, fnFail, fnProgress */
          () {
            var fns = arguments;
            return jQuery.Deferred(function (newDefer) {
              jQuery.each(tuples, function (_i, tuple) {
                // Map tuples (progress, done, fail) to arguments (done, fail, progress)
                var fn = isFunction(fns[tuple[4]]) && fns[tuple[4]];

                // deferred.progress(function() { bind to newDefer or newDefer.notify })
                // deferred.done(function() { bind to newDefer or newDefer.resolve })
                // deferred.fail(function() { bind to newDefer or newDefer.reject })
                deferred[tuple[1]](function () {
                  var returned = fn && fn.apply(this, arguments);
                  if (returned && isFunction(returned.promise)) {
                    returned.promise().progress(newDefer.notify).done(newDefer.resolve).fail(newDefer.reject);
                  } else {
                    newDefer[tuple[0] + "With"](this, fn ? [returned] : arguments);
                  }
                });
              });
              fns = null;
            }).promise();
          },
          then: function (onFulfilled, onRejected, onProgress) {
            var maxDepth = 0;
            function resolve(depth, deferred, handler, special) {
              return function () {
                var that = this,
                  args = arguments,
                  mightThrow = function () {
                    var returned, then;

                    // Support: Promises/A+ section 2.3.3.3.3
                    // https://promisesaplus.com/#point-59
                    // Ignore double-resolution attempts
                    if (depth < maxDepth) {
                      return;
                    }
                    returned = handler.apply(that, args);

                    // Support: Promises/A+ section 2.3.1
                    // https://promisesaplus.com/#point-48
                    if (returned === deferred.promise()) {
                      throw new TypeError("Thenable self-resolution");
                    }

                    // Support: Promises/A+ sections 2.3.3.1, 3.5
                    // https://promisesaplus.com/#point-54
                    // https://promisesaplus.com/#point-75
                    // Retrieve `then` only once
                    then = returned && (
                    // Support: Promises/A+ section 2.3.4
                    // https://promisesaplus.com/#point-64
                    // Only check objects and functions for thenability
                    typeof returned === "object" || typeof returned === "function") && returned.then;

                    // Handle a returned thenable
                    if (isFunction(then)) {
                      // Special processors (notify) just wait for resolution
                      if (special) {
                        then.call(returned, resolve(maxDepth, deferred, Identity, special), resolve(maxDepth, deferred, Thrower, special));

                        // Normal processors (resolve) also hook into progress
                      } else {
                        // ...and disregard older resolution values
                        maxDepth++;
                        then.call(returned, resolve(maxDepth, deferred, Identity, special), resolve(maxDepth, deferred, Thrower, special), resolve(maxDepth, deferred, Identity, deferred.notifyWith));
                      }

                      // Handle all other returned values
                    } else {
                      // Only substitute handlers pass on context
                      // and multiple values (non-spec behavior)
                      if (handler !== Identity) {
                        that = undefined;
                        args = [returned];
                      }

                      // Process the value(s)
                      // Default process is resolve
                      (special || deferred.resolveWith)(that, args);
                    }
                  },
                  // Only normal processors (resolve) catch and reject exceptions
                  process = special ? mightThrow : function () {
                    try {
                      mightThrow();
                    } catch (e) {
                      if (jQuery.Deferred.exceptionHook) {
                        jQuery.Deferred.exceptionHook(e, process.error);
                      }

                      // Support: Promises/A+ section 2.3.3.3.4.1
                      // https://promisesaplus.com/#point-61
                      // Ignore post-resolution exceptions
                      if (depth + 1 >= maxDepth) {
                        // Only substitute handlers pass on context
                        // and multiple values (non-spec behavior)
                        if (handler !== Thrower) {
                          that = undefined;
                          args = [e];
                        }
                        deferred.rejectWith(that, args);
                      }
                    }
                  };

                // Support: Promises/A+ section 2.3.3.3.1
                // https://promisesaplus.com/#point-57
                // Re-resolve promises immediately to dodge false rejection from
                // subsequent errors
                if (depth) {
                  process();
                } else {
                  // Call an optional hook to record the error, in case of exception
                  // since it's otherwise lost when execution goes async
                  if (jQuery.Deferred.getErrorHook) {
                    process.error = jQuery.Deferred.getErrorHook();

                    // The deprecated alias of the above. While the name suggests
                    // returning the stack, not an error instance, jQuery just passes
                    // it directly to `console.warn` so both will work; an instance
                    // just better cooperates with source maps.
                  } else if (jQuery.Deferred.getStackHook) {
                    process.error = jQuery.Deferred.getStackHook();
                  }
                  window.setTimeout(process);
                }
              };
            }
            return jQuery.Deferred(function (newDefer) {
              // progress_handlers.add( ... )
              tuples[0][3].add(resolve(0, newDefer, isFunction(onProgress) ? onProgress : Identity, newDefer.notifyWith));

              // fulfilled_handlers.add( ... )
              tuples[1][3].add(resolve(0, newDefer, isFunction(onFulfilled) ? onFulfilled : Identity));

              // rejected_handlers.add( ... )
              tuples[2][3].add(resolve(0, newDefer, isFunction(onRejected) ? onRejected : Thrower));
            }).promise();
          },
          // Get a promise for this deferred
          // If obj is provided, the promise aspect is added to the object
          promise: function (obj) {
            return obj != null ? jQuery.extend(obj, promise) : promise;
          }
        },
        deferred = {};

      // Add list-specific methods
      jQuery.each(tuples, function (i, tuple) {
        var list = tuple[2],
          stateString = tuple[5];

        // promise.progress = list.add
        // promise.done = list.add
        // promise.fail = list.add
        promise[tuple[1]] = list.add;

        // Handle state
        if (stateString) {
          list.add(function () {
            // state = "resolved" (i.e., fulfilled)
            // state = "rejected"
            state = stateString;
          },
          // rejected_callbacks.disable
          // fulfilled_callbacks.disable
          tuples[3 - i][2].disable,
          // rejected_handlers.disable
          // fulfilled_handlers.disable
          tuples[3 - i][3].disable,
          // progress_callbacks.lock
          tuples[0][2].lock,
          // progress_handlers.lock
          tuples[0][3].lock);
        }

        // progress_handlers.fire
        // fulfilled_handlers.fire
        // rejected_handlers.fire
        list.add(tuple[3].fire);

        // deferred.notify = function() { deferred.notifyWith(...) }
        // deferred.resolve = function() { deferred.resolveWith(...) }
        // deferred.reject = function() { deferred.rejectWith(...) }
        deferred[tuple[0]] = function () {
          deferred[tuple[0] + "With"](this === deferred ? undefined : this, arguments);
          return this;
        };

        // deferred.notifyWith = list.fireWith
        // deferred.resolveWith = list.fireWith
        // deferred.rejectWith = list.fireWith
        deferred[tuple[0] + "With"] = list.fireWith;
      });

      // Make the deferred a promise
      promise.promise(deferred);

      // Call given func if any
      if (func) {
        func.call(deferred, deferred);
      }

      // All done!
      return deferred;
    },
    // Deferred helper
    when: function (singleValue) {
      var
        // count of uncompleted subordinates
        remaining = arguments.length,
        // count of unprocessed arguments
        i = remaining,
        // subordinate fulfillment data
        resolveContexts = Array(i),
        resolveValues = slice.call(arguments),
        // the primary Deferred
        primary = jQuery.Deferred(),
        // subordinate callback factory
        updateFunc = function (i) {
          return function (value) {
            resolveContexts[i] = this;
            resolveValues[i] = arguments.length > 1 ? slice.call(arguments) : value;
            if (! --remaining) {
              primary.resolveWith(resolveContexts, resolveValues);
            }
          };
        };

      // Single- and empty arguments are adopted like Promise.resolve
      if (remaining <= 1) {
        adoptValue(singleValue, primary.done(updateFunc(i)).resolve, primary.reject, !remaining);

        // Use .then() to unwrap secondary thenables (cf. gh-3000)
        if (primary.state() === "pending" || isFunction(resolveValues[i] && resolveValues[i].then)) {
          return primary.then();
        }
      }

      // Multiple arguments are aggregated like Promise.all array elements
      while (i--) {
        adoptValue(resolveValues[i], updateFunc(i), primary.reject);
      }
      return primary.promise();
    }
  });

  // These usually indicate a programmer mistake during development,
  // warn about them ASAP rather than swallowing them by default.
  var rerrorNames = /^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/;

  // If `jQuery.Deferred.getErrorHook` is defined, `asyncError` is an error
  // captured before the async barrier to get the original error cause
  // which may otherwise be hidden.
  jQuery.Deferred.exceptionHook = function (error, asyncError) {
    // Support: IE 8 - 9 only
    // Console exists when dev tools are open, which can happen at any time
    if (window.console && window.console.warn && error && rerrorNames.test(error.name)) {
      window.console.warn("jQuery.Deferred exception: " + error.message, error.stack, asyncError);
    }
  };
  jQuery.readyException = function (error) {
    window.setTimeout(function () {
      throw error;
    });
  };

  // The deferred used on DOM ready
  var readyList = jQuery.Deferred();
  jQuery.fn.ready = function (fn) {
    readyList.then(fn)

    // Wrap jQuery.readyException in a function so that the lookup
    // happens at the time of error handling instead of callback
    // registration.
    .catch(function (error) {
      jQuery.readyException(error);
    });
    return this;
  };
  jQuery.extend({
    // Is the DOM ready to be used? Set to true once it occurs.
    isReady: false,
    // A counter to track how many items to wait for before
    // the ready event fires. See trac-6781
    readyWait: 1,
    // Handle when the DOM is ready
    ready: function (wait) {
      // Abort if there are pending holds or we're already ready
      if (wait === true ? --jQuery.readyWait : jQuery.isReady) {
        return;
      }

      // Remember that the DOM is ready
      jQuery.isReady = true;

      // If a normal DOM Ready event fired, decrement, and wait if need be
      if (wait !== true && --jQuery.readyWait > 0) {
        return;
      }

      // If there are functions bound, to execute
      readyList.resolveWith(document, [jQuery]);
    }
  });
  jQuery.ready.then = readyList.then;

  // The ready event handler and self cleanup method
  function completed() {
    document.removeEventListener("DOMContentLoaded", completed);
    window.removeEventListener("load", completed);
    jQuery.ready();
  }

  // Catch cases where $(document).ready() is called
  // after the browser event has already occurred.
  // Support: IE <=9 - 10 only
  // Older IE sometimes signals "interactive" too soon
  if (document.readyState === "complete" || document.readyState !== "loading" && !document.documentElement.doScroll) {
    // Handle it asynchronously to allow scripts the opportunity to delay ready
    window.setTimeout(jQuery.ready);
  } else {
    // Use the handy event callback
    document.addEventListener("DOMContentLoaded", completed);

    // A fallback to window.onload, that will always work
    window.addEventListener("load", completed);
  }

  // Multifunctional method to get and set values of a collection
  // The value/s can optionally be executed if it's a function
  var access = function (elems, fn, key, value, chainable, emptyGet, raw) {
    var i = 0,
      len = elems.length,
      bulk = key == null;

    // Sets many values
    if (toType(key) === "object") {
      chainable = true;
      for (i in key) {
        access(elems, fn, i, key[i], true, emptyGet, raw);
      }

      // Sets one value
    } else if (value !== undefined) {
      chainable = true;
      if (!isFunction(value)) {
        raw = true;
      }
      if (bulk) {
        // Bulk operations run against the entire set
        if (raw) {
          fn.call(elems, value);
          fn = null;

          // ...except when executing function values
        } else {
          bulk = fn;
          fn = function (elem, _key, value) {
            return bulk.call(jQuery(elem), value);
          };
        }
      }
      if (fn) {
        for (; i < len; i++) {
          fn(elems[i], key, raw ? value : value.call(elems[i], i, fn(elems[i], key)));
        }
      }
    }
    if (chainable) {
      return elems;
    }

    // Gets
    if (bulk) {
      return fn.call(elems);
    }
    return len ? fn(elems[0], key) : emptyGet;
  };

  // Matches dashed string for camelizing
  var rmsPrefix = /^-ms-/,
    rdashAlpha = /-([a-z])/g;

  // Used by camelCase as callback to replace()
  function fcamelCase(_all, letter) {
    return letter.toUpperCase();
  }

  // Convert dashed to camelCase; used by the css and data modules
  // Support: IE <=9 - 11, Edge 12 - 15
  // Microsoft forgot to hump their vendor prefix (trac-9572)
  function camelCase(string) {
    return string.replace(rmsPrefix, "ms-").replace(rdashAlpha, fcamelCase);
  }
  var acceptData = function (owner) {
    // Accepts only:
    //  - Node
    //    - Node.ELEMENT_NODE
    //    - Node.DOCUMENT_NODE
    //  - Object
    //    - Any
    return owner.nodeType === 1 || owner.nodeType === 9 || !+owner.nodeType;
  };
  function Data() {
    this.expando = jQuery.expando + Data.uid++;
  }
  Data.uid = 1;
  Data.prototype = {
    cache: function (owner) {
      // Check if the owner object already has a cache
      var value = owner[this.expando];

      // If not, create one
      if (!value) {
        value = {};

        // We can accept data for non-element nodes in modern browsers,
        // but we should not, see trac-8335.
        // Always return an empty object.
        if (acceptData(owner)) {
          // If it is a node unlikely to be stringify-ed or looped over
          // use plain assignment
          if (owner.nodeType) {
            owner[this.expando] = value;

            // Otherwise secure it in a non-enumerable property
            // configurable must be true to allow the property to be
            // deleted when data is removed
          } else {
            Object.defineProperty(owner, this.expando, {
              value: value,
              configurable: true
            });
          }
        }
      }
      return value;
    },
    set: function (owner, data, value) {
      var prop,
        cache = this.cache(owner);

      // Handle: [ owner, key, value ] args
      // Always use camelCase key (gh-2257)
      if (typeof data === "string") {
        cache[camelCase(data)] = value;

        // Handle: [ owner, { properties } ] args
      } else {
        // Copy the properties one-by-one to the cache object
        for (prop in data) {
          cache[camelCase(prop)] = data[prop];
        }
      }
      return cache;
    },
    get: function (owner, key) {
      return key === undefined ? this.cache(owner) :
      // Always use camelCase key (gh-2257)
      owner[this.expando] && owner[this.expando][camelCase(key)];
    },
    access: function (owner, key, value) {
      // In cases where either:
      //
      //   1. No key was specified
      //   2. A string key was specified, but no value provided
      //
      // Take the "read" path and allow the get method to determine
      // which value to return, respectively either:
      //
      //   1. The entire cache object
      //   2. The data stored at the key
      //
      if (key === undefined || key && typeof key === "string" && value === undefined) {
        return this.get(owner, key);
      }

      // When the key is not a string, or both a key and value
      // are specified, set or extend (existing objects) with either:
      //
      //   1. An object of properties
      //   2. A key and value
      //
      this.set(owner, key, value);

      // Since the "set" path can have two possible entry points
      // return the expected data based on which path was taken[*]
      return value !== undefined ? value : key;
    },
    remove: function (owner, key) {
      var i,
        cache = owner[this.expando];
      if (cache === undefined) {
        return;
      }
      if (key !== undefined) {
        // Support array or space separated string of keys
        if (Array.isArray(key)) {
          // If key is an array of keys...
          // We always set camelCase keys, so remove that.
          key = key.map(camelCase);
        } else {
          key = camelCase(key);

          // If a key with the spaces exists, use it.
          // Otherwise, create an array by matching non-whitespace
          key = key in cache ? [key] : key.match(rnothtmlwhite) || [];
        }
        i = key.length;
        while (i--) {
          delete cache[key[i]];
        }
      }

      // Remove the expando if there's no more data
      if (key === undefined || jQuery.isEmptyObject(cache)) {
        // Support: Chrome <=35 - 45
        // Webkit & Blink performance suffers when deleting properties
        // from DOM nodes, so set to undefined instead
        // https://bugs.chromium.org/p/chromium/issues/detail?id=378607 (bug restricted)
        if (owner.nodeType) {
          owner[this.expando] = undefined;
        } else {
          delete owner[this.expando];
        }
      }
    },
    hasData: function (owner) {
      var cache = owner[this.expando];
      return cache !== undefined && !jQuery.isEmptyObject(cache);
    }
  };
  var dataPriv = new Data();
  var dataUser = new Data();

  //	Implementation Summary
  //
  //	1. Enforce API surface and semantic compatibility with 1.9.x branch
  //	2. Improve the module's maintainability by reducing the storage
  //		paths to a single mechanism.
  //	3. Use the same single mechanism to support "private" and "user" data.
  //	4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData)
  //	5. Avoid exposing implementation details on user objects (eg. expando properties)
  //	6. Provide a clear path for implementation upgrade to WeakMap in 2014

  var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,
    rmultiDash = /[A-Z]/g;
  function getData(data) {
    if (data === "true") {
      return true;
    }
    if (data === "false") {
      return false;
    }
    if (data === "null") {
      return null;
    }

    // Only convert to a number if it doesn't change the string
    if (data === +data + "") {
      return +data;
    }
    if (rbrace.test(data)) {
      return JSON.parse(data);
    }
    return data;
  }
  function dataAttr(elem, key, data) {
    var name;

    // If nothing was found internally, try to fetch any
    // data from the HTML5 data-* attribute
    if (data === undefined && elem.nodeType === 1) {
      name = "data-" + key.replace(rmultiDash, "-$&").toLowerCase();
      data = elem.getAttribute(name);
      if (typeof data === "string") {
        try {
          data = getData(data);
        } catch (e) {}

        // Make sure we set the data so it isn't changed later
        dataUser.set(elem, key, data);
      } else {
        data = undefined;
      }
    }
    return data;
  }
  jQuery.extend({
    hasData: function (elem) {
      return dataUser.hasData(elem) || dataPriv.hasData(elem);
    },
    data: function (elem, name, data) {
      return dataUser.access(elem, name, data);
    },
    removeData: function (elem, name) {
      dataUser.remove(elem, name);
    },
    // TODO: Now that all calls to _data and _removeData have been replaced
    // with direct calls to dataPriv methods, these can be deprecated.
    _data: function (elem, name, data) {
      return dataPriv.access(elem, name, data);
    },
    _removeData: function (elem, name) {
      dataPriv.remove(elem, name);
    }
  });
  jQuery.fn.extend({
    data: function (key, value) {
      var i,
        name,
        data,
        elem = this[0],
        attrs = elem && elem.attributes;

      // Gets all values
      if (key === undefined) {
        if (this.length) {
          data = dataUser.get(elem);
          if (elem.nodeType === 1 && !dataPriv.get(elem, "hasDataAttrs")) {
            i = attrs.length;
            while (i--) {
              // Support: IE 11 only
              // The attrs elements can be null (trac-14894)
              if (attrs[i]) {
                name = attrs[i].name;
                if (name.indexOf("data-") === 0) {
                  name = camelCase(name.slice(5));
                  dataAttr(elem, name, data[name]);
                }
              }
            }
            dataPriv.set(elem, "hasDataAttrs", true);
          }
        }
        return data;
      }

      // Sets multiple values
      if (typeof key === "object") {
        return this.each(function () {
          dataUser.set(this, key);
        });
      }
      return access(this, function (value) {
        var data;

        // The calling jQuery object (element matches) is not empty
        // (and therefore has an element appears at this[ 0 ]) and the
        // `value` parameter was not undefined. An empty jQuery object
        // will result in `undefined` for elem = this[ 0 ] which will
        // throw an exception if an attempt to read a data cache is made.
        if (elem && value === undefined) {
          // Attempt to get data from the cache
          // The key will always be camelCased in Data
          data = dataUser.get(elem, key);
          if (data !== undefined) {
            return data;
          }

          // Attempt to "discover" the data in
          // HTML5 custom data-* attrs
          data = dataAttr(elem, key);
          if (data !== undefined) {
            return data;
          }

          // We tried really hard, but the data doesn't exist.
          return;
        }

        // Set the data...
        this.each(function () {
          // We always store the camelCased key
          dataUser.set(this, key, value);
        });
      }, null, value, arguments.length > 1, null, true);
    },
    removeData: function (key) {
      return this.each(function () {
        dataUser.remove(this, key);
      });
    }
  });
  jQuery.extend({
    queue: function (elem, type, data) {
      var queue;
      if (elem) {
        type = (type || "fx") + "queue";
        queue = dataPriv.get(elem, type);

        // Speed up dequeue by getting out quickly if this is just a lookup
        if (data) {
          if (!queue || Array.isArray(data)) {
            queue = dataPriv.access(elem, type, jQuery.makeArray(data));
          } else {
            queue.push(data);
          }
        }
        return queue || [];
      }
    },
    dequeue: function (elem, type) {
      type = type || "fx";
      var queue = jQuery.queue(elem, type),
        startLength = queue.length,
        fn = queue.shift(),
        hooks = jQuery._queueHooks(elem, type),
        next = function () {
          jQuery.dequeue(elem, type);
        };

      // If the fx queue is dequeued, always remove the progress sentinel
      if (fn === "inprogress") {
        fn = queue.shift();
        startLength--;
      }
      if (fn) {
        // Add a progress sentinel to prevent the fx queue from being
        // automatically dequeued
        if (type === "fx") {
          queue.unshift("inprogress");
        }

        // Clear up the last queue stop function
        delete hooks.stop;
        fn.call(elem, next, hooks);
      }
      if (!startLength && hooks) {
        hooks.empty.fire();
      }
    },
    // Not public - generate a queueHooks object, or return the current one
    _queueHooks: function (elem, type) {
      var key = type + "queueHooks";
      return dataPriv.get(elem, key) || dataPriv.access(elem, key, {
        empty: jQuery.Callbacks("once memory").add(function () {
          dataPriv.remove(elem, [type + "queue", key]);
        })
      });
    }
  });
  jQuery.fn.extend({
    queue: function (type, data) {
      var setter = 2;
      if (typeof type !== "string") {
        data = type;
        type = "fx";
        setter--;
      }
      if (arguments.length < setter) {
        return jQuery.queue(this[0], type);
      }
      return data === undefined ? this : this.each(function () {
        var queue = jQuery.queue(this, type, data);

        // Ensure a hooks for this queue
        jQuery._queueHooks(this, type);
        if (type === "fx" && queue[0] !== "inprogress") {
          jQuery.dequeue(this, type);
        }
      });
    },
    dequeue: function (type) {
      return this.each(function () {
        jQuery.dequeue(this, type);
      });
    },
    clearQueue: function (type) {
      return this.queue(type || "fx", []);
    },
    // Get a promise resolved when queues of a certain type
    // are emptied (fx is the type by default)
    promise: function (type, obj) {
      var tmp,
        count = 1,
        defer = jQuery.Deferred(),
        elements = this,
        i = this.length,
        resolve = function () {
          if (! --count) {
            defer.resolveWith(elements, [elements]);
          }
        };
      if (typeof type !== "string") {
        obj = type;
        type = undefined;
      }
      type = type || "fx";
      while (i--) {
        tmp = dataPriv.get(elements[i], type + "queueHooks");
        if (tmp && tmp.empty) {
          count++;
          tmp.empty.add(resolve);
        }
      }
      resolve();
      return defer.promise(obj);
    }
  });
  var pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source;
  var rcssNum = new RegExp("^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i");
  var cssExpand = ["Top", "Right", "Bottom", "Left"];
  var documentElement = document.documentElement;
  var isAttached = function (elem) {
      return jQuery.contains(elem.ownerDocument, elem);
    },
    composed = {
      composed: true
    };

  // Support: IE 9 - 11+, Edge 12 - 18+, iOS 10.0 - 10.2 only
  // Check attachment across shadow DOM boundaries when possible (gh-3504)
  // Support: iOS 10.0-10.2 only
  // Early iOS 10 versions support `attachShadow` but not `getRootNode`,
  // leading to errors. We need to check for `getRootNode`.
  if (documentElement.getRootNode) {
    isAttached = function (elem) {
      return jQuery.contains(elem.ownerDocument, elem) || elem.getRootNode(composed) === elem.ownerDocument;
    };
  }
  var isHiddenWithinTree = function (elem, el) {
    // isHiddenWithinTree might be called from jQuery#filter function;
    // in that case, element will be second argument
    elem = el || elem;

    // Inline style trumps all
    return elem.style.display === "none" || elem.style.display === "" &&
    // Otherwise, check computed style
    // Support: Firefox <=43 - 45
    // Disconnected elements can have computed display: none, so first confirm that elem is
    // in the document.
    isAttached(elem) && jQuery.css(elem, "display") === "none";
  };
  function adjustCSS(elem, prop, valueParts, tween) {
    var adjusted,
      scale,
      maxIterations = 20,
      currentValue = tween ? function () {
        return tween.cur();
      } : function () {
        return jQuery.css(elem, prop, "");
      },
      initial = currentValue(),
      unit = valueParts && valueParts[3] || (jQuery.cssNumber[prop] ? "" : "px"),
      // Starting value computation is required for potential unit mismatches
      initialInUnit = elem.nodeType && (jQuery.cssNumber[prop] || unit !== "px" && +initial) && rcssNum.exec(jQuery.css(elem, prop));
    if (initialInUnit && initialInUnit[3] !== unit) {
      // Support: Firefox <=54
      // Halve the iteration target value to prevent interference from CSS upper bounds (gh-2144)
      initial = initial / 2;

      // Trust units reported by jQuery.css
      unit = unit || initialInUnit[3];

      // Iteratively approximate from a nonzero starting point
      initialInUnit = +initial || 1;
      while (maxIterations--) {
        // Evaluate and update our best guess (doubling guesses that zero out).
        // Finish if the scale equals or crosses 1 (making the old*new product non-positive).
        jQuery.style(elem, prop, initialInUnit + unit);
        if ((1 - scale) * (1 - (scale = currentValue() / initial || 0.5)) <= 0) {
          maxIterations = 0;
        }
        initialInUnit = initialInUnit / scale;
      }
      initialInUnit = initialInUnit * 2;
      jQuery.style(elem, prop, initialInUnit + unit);

      // Make sure we update the tween properties later on
      valueParts = valueParts || [];
    }
    if (valueParts) {
      initialInUnit = +initialInUnit || +initial || 0;

      // Apply relative offset (+=/-=) if specified
      adjusted = valueParts[1] ? initialInUnit + (valueParts[1] + 1) * valueParts[2] : +valueParts[2];
      if (tween) {
        tween.unit = unit;
        tween.start = initialInUnit;
        tween.end = adjusted;
      }
    }
    return adjusted;
  }
  var defaultDisplayMap = {};
  function getDefaultDisplay(elem) {
    var temp,
      doc = elem.ownerDocument,
      nodeName = elem.nodeName,
      display = defaultDisplayMap[nodeName];
    if (display) {
      return display;
    }
    temp = doc.body.appendChild(doc.createElement(nodeName));
    display = jQuery.css(temp, "display");
    temp.parentNode.removeChild(temp);
    if (display === "none") {
      display = "block";
    }
    defaultDisplayMap[nodeName] = display;
    return display;
  }
  function showHide(elements, show) {
    var display,
      elem,
      values = [],
      index = 0,
      length = elements.length;

    // Determine new display value for elements that need to change
    for (; index < length; index++) {
      elem = elements[index];
      if (!elem.style) {
        continue;
      }
      display = elem.style.display;
      if (show) {
        // Since we force visibility upon cascade-hidden elements, an immediate (and slow)
        // check is required in this first loop unless we have a nonempty display value (either
        // inline or about-to-be-restored)
        if (display === "none") {
          values[index] = dataPriv.get(elem, "display") || null;
          if (!values[index]) {
            elem.style.display = "";
          }
        }
        if (elem.style.display === "" && isHiddenWithinTree(elem)) {
          values[index] = getDefaultDisplay(elem);
        }
      } else {
        if (display !== "none") {
          values[index] = "none";

          // Remember what we're overwriting
          dataPriv.set(elem, "display", display);
        }
      }
    }

    // Set the display of the elements in a second loop to avoid constant reflow
    for (index = 0; index < length; index++) {
      if (values[index] != null) {
        elements[index].style.display = values[index];
      }
    }
    return elements;
  }
  jQuery.fn.extend({
    show: function () {
      return showHide(this, true);
    },
    hide: function () {
      return showHide(this);
    },
    toggle: function (state) {
      if (typeof state === "boolean") {
        return state ? this.show() : this.hide();
      }
      return this.each(function () {
        if (isHiddenWithinTree(this)) {
          jQuery(this).show();
        } else {
          jQuery(this).hide();
        }
      });
    }
  });
  var rcheckableType = /^(?:checkbox|radio)$/i;
  var rtagName = /<([a-z][^\/\0>\x20\t\r\n\f]*)/i;
  var rscriptType = /^$|^module$|\/(?:java|ecma)script/i;
  (function () {
    var fragment = document.createDocumentFragment(),
      div = fragment.appendChild(document.createElement("div")),
      input = document.createElement("input");

    // Support: Android 4.0 - 4.3 only
    // Check state lost if the name is set (trac-11217)
    // Support: Windows Web Apps (WWA)
    // `name` and `type` must use .setAttribute for WWA (trac-14901)
    input.setAttribute("type", "radio");
    input.setAttribute("checked", "checked");
    input.setAttribute("name", "t");
    div.appendChild(input);

    // Support: Android <=4.1 only
    // Older WebKit doesn't clone checked state correctly in fragments
    support.checkClone = div.cloneNode(true).cloneNode(true).lastChild.checked;

    // Support: IE <=11 only
    // Make sure textarea (and checkbox) defaultValue is properly cloned
    div.innerHTML = "<textarea>x</textarea>";
    support.noCloneChecked = !!div.cloneNode(true).lastChild.defaultValue;

    // Support: IE <=9 only
    // IE <=9 replaces <option> tags with their contents when inserted outside of
    // the select element.
    div.innerHTML = "<option></option>";
    support.option = !!div.lastChild;
  })();

  // We have to close these tags to support XHTML (trac-13200)
  var wrapMap = {
    // XHTML parsers do not magically insert elements in the
    // same way that tag soup parsers do. So we cannot shorten
    // this by omitting <tbody> or other required elements.
    thead: [1, "<table>", "</table>"],
    col: [2, "<table><colgroup>", "</colgroup></table>"],
    tr: [2, "<table><tbody>", "</tbody></table>"],
    td: [3, "<table><tbody><tr>", "</tr></tbody></table>"],
    _default: [0, "", ""]
  };
  wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
  wrapMap.th = wrapMap.td;

  // Support: IE <=9 only
  if (!support.option) {
    wrapMap.optgroup = wrapMap.option = [1, "<select multiple='multiple'>", "</select>"];
  }
  function getAll(context, tag) {
    // Support: IE <=9 - 11 only
    // Use typeof to avoid zero-argument method invocation on host objects (trac-15151)
    var ret;
    if (typeof context.getElementsByTagName !== "undefined") {
      ret = context.getElementsByTagName(tag || "*");
    } else if (typeof context.querySelectorAll !== "undefined") {
      ret = context.querySelectorAll(tag || "*");
    } else {
      ret = [];
    }
    if (tag === undefined || tag && nodeName(context, tag)) {
      return jQuery.merge([context], ret);
    }
    return ret;
  }

  // Mark scripts as having already been evaluated
  function setGlobalEval(elems, refElements) {
    var i = 0,
      l = elems.length;
    for (; i < l; i++) {
      dataPriv.set(elems[i], "globalEval", !refElements || dataPriv.get(refElements[i], "globalEval"));
    }
  }
  var rhtml = /<|&#?\w+;/;
  function buildFragment(elems, context, scripts, selection, ignored) {
    var elem,
      tmp,
      tag,
      wrap,
      attached,
      j,
      fragment = context.createDocumentFragment(),
      nodes = [],
      i = 0,
      l = elems.length;
    for (; i < l; i++) {
      elem = elems[i];
      if (elem || elem === 0) {
        // Add nodes directly
        if (toType(elem) === "object") {
          // Support: Android <=4.0 only, PhantomJS 1 only
          // push.apply(_, arraylike) throws on ancient WebKit
          jQuery.merge(nodes, elem.nodeType ? [elem] : elem);

          // Convert non-html into a text node
        } else if (!rhtml.test(elem)) {
          nodes.push(context.createTextNode(elem));

          // Convert html into DOM nodes
        } else {
          tmp = tmp || fragment.appendChild(context.createElement("div"));

          // Deserialize a standard representation
          tag = (rtagName.exec(elem) || ["", ""])[1].toLowerCase();
          wrap = wrapMap[tag] || wrapMap._default;
          tmp.innerHTML = wrap[1] + jQuery.htmlPrefilter(elem) + wrap[2];

          // Descend through wrappers to the right content
          j = wrap[0];
          while (j--) {
            tmp = tmp.lastChild;
          }

          // Support: Android <=4.0 only, PhantomJS 1 only
          // push.apply(_, arraylike) throws on ancient WebKit
          jQuery.merge(nodes, tmp.childNodes);

          // Remember the top-level container
          tmp = fragment.firstChild;

          // Ensure the created nodes are orphaned (trac-12392)
          tmp.textContent = "";
        }
      }
    }

    // Remove wrapper from fragment
    fragment.textContent = "";
    i = 0;
    while (elem = nodes[i++]) {
      // Skip elements already in the context collection (trac-4087)
      if (selection && jQuery.inArray(elem, selection) > -1) {
        if (ignored) {
          ignored.push(elem);
        }
        continue;
      }
      attached = isAttached(elem);

      // Append to fragment
      tmp = getAll(fragment.appendChild(elem), "script");

      // Preserve script evaluation history
      if (attached) {
        setGlobalEval(tmp);
      }

      // Capture executables
      if (scripts) {
        j = 0;
        while (elem = tmp[j++]) {
          if (rscriptType.test(elem.type || "")) {
            scripts.push(elem);
          }
        }
      }
    }
    return fragment;
  }
  var rtypenamespace = /^([^.]*)(?:\.(.+)|)/;
  function returnTrue() {
    return true;
  }
  function returnFalse() {
    return false;
  }
  function on(elem, types, selector, data, fn, one) {
    var origFn, type;

    // Types can be a map of types/handlers
    if (typeof types === "object") {
      // ( types-Object, selector, data )
      if (typeof selector !== "string") {
        // ( types-Object, data )
        data = data || selector;
        selector = undefined;
      }
      for (type in types) {
        on(elem, type, selector, data, types[type], one);
      }
      return elem;
    }
    if (data == null && fn == null) {
      // ( types, fn )
      fn = selector;
      data = selector = undefined;
    } else if (fn == null) {
      if (typeof selector === "string") {
        // ( types, selector, fn )
        fn = data;
        data = undefined;
      } else {
        // ( types, data, fn )
        fn = data;
        data = selector;
        selector = undefined;
      }
    }
    if (fn === false) {
      fn = returnFalse;
    } else if (!fn) {
      return elem;
    }
    if (one === 1) {
      origFn = fn;
      fn = function (event) {
        // Can use an empty set, since event contains the info
        jQuery().off(event);
        return origFn.apply(this, arguments);
      };

      // Use same guid so caller can remove using origFn
      fn.guid = origFn.guid || (origFn.guid = jQuery.guid++);
    }
    return elem.each(function () {
      jQuery.event.add(this, types, fn, data, selector);
    });
  }

  /*
   * Helper functions for managing events -- not part of the public interface.
   * Props to Dean Edwards' addEvent library for many of the ideas.
   */
  jQuery.event = {
    global: {},
    add: function (elem, types, handler, data, selector) {
      var handleObjIn,
        eventHandle,
        tmp,
        events,
        t,
        handleObj,
        special,
        handlers,
        type,
        namespaces,
        origType,
        elemData = dataPriv.get(elem);

      // Only attach events to objects that accept data
      if (!acceptData(elem)) {
        return;
      }

      // Caller can pass in an object of custom data in lieu of the handler
      if (handler.handler) {
        handleObjIn = handler;
        handler = handleObjIn.handler;
        selector = handleObjIn.selector;
      }

      // Ensure that invalid selectors throw exceptions at attach time
      // Evaluate against documentElement in case elem is a non-element node (e.g., document)
      if (selector) {
        jQuery.find.matchesSelector(documentElement, selector);
      }

      // Make sure that the handler has a unique ID, used to find/remove it later
      if (!handler.guid) {
        handler.guid = jQuery.guid++;
      }

      // Init the element's event structure and main handler, if this is the first
      if (!(events = elemData.events)) {
        events = elemData.events = Object.create(null);
      }
      if (!(eventHandle = elemData.handle)) {
        eventHandle = elemData.handle = function (e) {
          // Discard the second event of a jQuery.event.trigger() and
          // when an event is called after a page has unloaded
          return typeof jQuery !== "undefined" && jQuery.event.triggered !== e.type ? jQuery.event.dispatch.apply(elem, arguments) : undefined;
        };
      }

      // Handle multiple events separated by a space
      types = (types || "").match(rnothtmlwhite) || [""];
      t = types.length;
      while (t--) {
        tmp = rtypenamespace.exec(types[t]) || [];
        type = origType = tmp[1];
        namespaces = (tmp[2] || "").split(".").sort();

        // There *must* be a type, no attaching namespace-only handlers
        if (!type) {
          continue;
        }

        // If event changes its type, use the special event handlers for the changed type
        special = jQuery.event.special[type] || {};

        // If selector defined, determine special event api type, otherwise given type
        type = (selector ? special.delegateType : special.bindType) || type;

        // Update special based on newly reset type
        special = jQuery.event.special[type] || {};

        // handleObj is passed to all event handlers
        handleObj = jQuery.extend({
          type: type,
          origType: origType,
          data: data,
          handler: handler,
          guid: handler.guid,
          selector: selector,
          needsContext: selector && jQuery.expr.match.needsContext.test(selector),
          namespace: namespaces.join(".")
        }, handleObjIn);

        // Init the event handler queue if we're the first
        if (!(handlers = events[type])) {
          handlers = events[type] = [];
          handlers.delegateCount = 0;

          // Only use addEventListener if the special events handler returns false
          if (!special.setup || special.setup.call(elem, data, namespaces, eventHandle) === false) {
            if (elem.addEventListener) {
              elem.addEventListener(type, eventHandle);
            }
          }
        }
        if (special.add) {
          special.add.call(elem, handleObj);
          if (!handleObj.handler.guid) {
            handleObj.handler.guid = handler.guid;
          }
        }

        // Add to the element's handler list, delegates in front
        if (selector) {
          handlers.splice(handlers.delegateCount++, 0, handleObj);
        } else {
          handlers.push(handleObj);
        }

        // Keep track of which events have ever been used, for event optimization
        jQuery.event.global[type] = true;
      }
    },
    // Detach an event or set of events from an element
    remove: function (elem, types, handler, selector, mappedTypes) {
      var j,
        origCount,
        tmp,
        events,
        t,
        handleObj,
        special,
        handlers,
        type,
        namespaces,
        origType,
        elemData = dataPriv.hasData(elem) && dataPriv.get(elem);
      if (!elemData || !(events = elemData.events)) {
        return;
      }

      // Once for each type.namespace in types; type may be omitted
      types = (types || "").match(rnothtmlwhite) || [""];
      t = types.length;
      while (t--) {
        tmp = rtypenamespace.exec(types[t]) || [];
        type = origType = tmp[1];
        namespaces = (tmp[2] || "").split(".").sort();

        // Unbind all events (on this namespace, if provided) for the element
        if (!type) {
          for (type in events) {
            jQuery.event.remove(elem, type + types[t], handler, selector, true);
          }
          continue;
        }
        special = jQuery.event.special[type] || {};
        type = (selector ? special.delegateType : special.bindType) || type;
        handlers = events[type] || [];
        tmp = tmp[2] && new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)");

        // Remove matching events
        origCount = j = handlers.length;
        while (j--) {
          handleObj = handlers[j];
          if ((mappedTypes || origType === handleObj.origType) && (!handler || handler.guid === handleObj.guid) && (!tmp || tmp.test(handleObj.namespace)) && (!selector || selector === handleObj.selector || selector === "**" && handleObj.selector)) {
            handlers.splice(j, 1);
            if (handleObj.selector) {
              handlers.delegateCount--;
            }
            if (special.remove) {
              special.remove.call(elem, handleObj);
            }
          }
        }

        // Remove generic event handler if we removed something and no more handlers exist
        // (avoids potential for endless recursion during removal of special event handlers)
        if (origCount && !handlers.length) {
          if (!special.teardown || special.teardown.call(elem, namespaces, elemData.handle) === false) {
            jQuery.removeEvent(elem, type, elemData.handle);
          }
          delete events[type];
        }
      }

      // Remove data and the expando if it's no longer used
      if (jQuery.isEmptyObject(events)) {
        dataPriv.remove(elem, "handle events");
      }
    },
    dispatch: function (nativeEvent) {
      var i,
        j,
        ret,
        matched,
        handleObj,
        handlerQueue,
        args = new Array(arguments.length),
        // Make a writable jQuery.Event from the native event object
        event = jQuery.event.fix(nativeEvent),
        handlers = (dataPriv.get(this, "events") || Object.create(null))[event.type] || [],
        special = jQuery.event.special[event.type] || {};

      // Use the fix-ed jQuery.Event rather than the (read-only) native event
      args[0] = event;
      for (i = 1; i < arguments.length; i++) {
        args[i] = arguments[i];
      }
      event.delegateTarget = this;

      // Call the preDispatch hook for the mapped type, and let it bail if desired
      if (special.preDispatch && special.preDispatch.call(this, event) === false) {
        return;
      }

      // Determine handlers
      handlerQueue = jQuery.event.handlers.call(this, event, handlers);

      // Run delegates first; they may want to stop propagation beneath us
      i = 0;
      while ((matched = handlerQueue[i++]) && !event.isPropagationStopped()) {
        event.currentTarget = matched.elem;
        j = 0;
        while ((handleObj = matched.handlers[j++]) && !event.isImmediatePropagationStopped()) {
          // If the event is namespaced, then each handler is only invoked if it is
          // specially universal or its namespaces are a superset of the event's.
          if (!event.rnamespace || handleObj.namespace === false || event.rnamespace.test(handleObj.namespace)) {
            event.handleObj = handleObj;
            event.data = handleObj.data;
            ret = ((jQuery.event.special[handleObj.origType] || {}).handle || handleObj.handler).apply(matched.elem, args);
            if (ret !== undefined) {
              if ((event.result = ret) === false) {
                event.preventDefault();
                event.stopPropagation();
              }
            }
          }
        }
      }

      // Call the postDispatch hook for the mapped type
      if (special.postDispatch) {
        special.postDispatch.call(this, event);
      }
      return event.result;
    },
    handlers: function (event, handlers) {
      var i,
        handleObj,
        sel,
        matchedHandlers,
        matchedSelectors,
        handlerQueue = [],
        delegateCount = handlers.delegateCount,
        cur = event.target;

      // Find delegate handlers
      if (delegateCount &&
      // Support: IE <=9
      // Black-hole SVG <use> instance trees (trac-13180)
      cur.nodeType &&
      // Support: Firefox <=42
      // Suppress spec-violating clicks indicating a non-primary pointer button (trac-3861)
      // https://www.w3.org/TR/DOM-Level-3-Events/#event-type-click
      // Support: IE 11 only
      // ...but not arrow key "clicks" of radio inputs, which can have `button` -1 (gh-2343)
      !(event.type === "click" && event.button >= 1)) {
        for (; cur !== this; cur = cur.parentNode || this) {
          // Don't check non-elements (trac-13208)
          // Don't process clicks on disabled elements (trac-6911, trac-8165, trac-11382, trac-11764)
          if (cur.nodeType === 1 && !(event.type === "click" && cur.disabled === true)) {
            matchedHandlers = [];
            matchedSelectors = {};
            for (i = 0; i < delegateCount; i++) {
              handleObj = handlers[i];

              // Don't conflict with Object.prototype properties (trac-13203)
              sel = handleObj.selector + " ";
              if (matchedSelectors[sel] === undefined) {
                matchedSelectors[sel] = handleObj.needsContext ? jQuery(sel, this).index(cur) > -1 : jQuery.find(sel, this, null, [cur]).length;
              }
              if (matchedSelectors[sel]) {
                matchedHandlers.push(handleObj);
              }
            }
            if (matchedHandlers.length) {
              handlerQueue.push({
                elem: cur,
                handlers: matchedHandlers
              });
            }
          }
        }
      }

      // Add the remaining (directly-bound) handlers
      cur = this;
      if (delegateCount < handlers.length) {
        handlerQueue.push({
          elem: cur,
          handlers: handlers.slice(delegateCount)
        });
      }
      return handlerQueue;
    },
    addProp: function (name, hook) {
      Object.defineProperty(jQuery.Event.prototype, name, {
        enumerable: true,
        configurable: true,
        get: isFunction(hook) ? function () {
          if (this.originalEvent) {
            return hook(this.originalEvent);
          }
        } : function () {
          if (this.originalEvent) {
            return this.originalEvent[name];
          }
        },
        set: function (value) {
          Object.defineProperty(this, name, {
            enumerable: true,
            configurable: true,
            writable: true,
            value: value
          });
        }
      });
    },
    fix: function (originalEvent) {
      return originalEvent[jQuery.expando] ? originalEvent : new jQuery.Event(originalEvent);
    },
    special: {
      load: {
        // Prevent triggered image.load events from bubbling to window.load
        noBubble: true
      },
      click: {
        // Utilize native event to ensure correct state for checkable inputs
        setup: function (data) {
          // For mutual compressibility with _default, replace `this` access with a local var.
          // `|| data` is dead code meant only to preserve the variable through minification.
          var el = this || data;

          // Claim the first handler
          if (rcheckableType.test(el.type) && el.click && nodeName(el, "input")) {
            // dataPriv.set( el, "click", ... )
            leverageNative(el, "click", true);
          }

          // Return false to allow normal processing in the caller
          return false;
        },
        trigger: function (data) {
          // For mutual compressibility with _default, replace `this` access with a local var.
          // `|| data` is dead code meant only to preserve the variable through minification.
          var el = this || data;

          // Force setup before triggering a click
          if (rcheckableType.test(el.type) && el.click && nodeName(el, "input")) {
            leverageNative(el, "click");
          }

          // Return non-false to allow normal event-path propagation
          return true;
        },
        // For cross-browser consistency, suppress native .click() on links
        // Also prevent it if we're currently inside a leveraged native-event stack
        _default: function (event) {
          var target = event.target;
          return rcheckableType.test(target.type) && target.click && nodeName(target, "input") && dataPriv.get(target, "click") || nodeName(target, "a");
        }
      },
      beforeunload: {
        postDispatch: function (event) {
          // Support: Firefox 20+
          // Firefox doesn't alert if the returnValue field is not set.
          if (event.result !== undefined && event.originalEvent) {
            event.originalEvent.returnValue = event.result;
          }
        }
      }
    }
  };

  // Ensure the presence of an event listener that handles manually-triggered
  // synthetic events by interrupting progress until reinvoked in response to
  // *native* events that it fires directly, ensuring that state changes have
  // already occurred before other listeners are invoked.
  function leverageNative(el, type, isSetup) {
    // Missing `isSetup` indicates a trigger call, which must force setup through jQuery.event.add
    if (!isSetup) {
      if (dataPriv.get(el, type) === undefined) {
        jQuery.event.add(el, type, returnTrue);
      }
      return;
    }

    // Register the controller as a special universal handler for all event namespaces
    dataPriv.set(el, type, false);
    jQuery.event.add(el, type, {
      namespace: false,
      handler: function (event) {
        var result,
          saved = dataPriv.get(this, type);
        if (event.isTrigger & 1 && this[type]) {
          // Interrupt processing of the outer synthetic .trigger()ed event
          if (!saved) {
            // Store arguments for use when handling the inner native event
            // There will always be at least one argument (an event object), so this array
            // will not be confused with a leftover capture object.
            saved = slice.call(arguments);
            dataPriv.set(this, type, saved);

            // Trigger the native event and capture its result
            this[type]();
            result = dataPriv.get(this, type);
            dataPriv.set(this, type, false);
            if (saved !== result) {
              // Cancel the outer synthetic event
              event.stopImmediatePropagation();
              event.preventDefault();
              return result;
            }

            // If this is an inner synthetic event for an event with a bubbling surrogate
            // (focus or blur), assume that the surrogate already propagated from triggering
            // the native event and prevent that from happening again here.
            // This technically gets the ordering wrong w.r.t. to `.trigger()` (in which the
            // bubbling surrogate propagates *after* the non-bubbling base), but that seems
            // less bad than duplication.
          } else if ((jQuery.event.special[type] || {}).delegateType) {
            event.stopPropagation();
          }

          // If this is a native event triggered above, everything is now in order
          // Fire an inner synthetic event with the original arguments
        } else if (saved) {
          // ...and capture the result
          dataPriv.set(this, type, jQuery.event.trigger(saved[0], saved.slice(1), this));

          // Abort handling of the native event by all jQuery handlers while allowing
          // native handlers on the same element to run. On target, this is achieved
          // by stopping immediate propagation just on the jQuery event. However,
          // the native event is re-wrapped by a jQuery one on each level of the
          // propagation so the only way to stop it for jQuery is to stop it for
          // everyone via native `stopPropagation()`. This is not a problem for
          // focus/blur which don't bubble, but it does also stop click on checkboxes
          // and radios. We accept this limitation.
          event.stopPropagation();
          event.isImmediatePropagationStopped = returnTrue;
        }
      }
    });
  }
  jQuery.removeEvent = function (elem, type, handle) {
    // This "if" is needed for plain objects
    if (elem.removeEventListener) {
      elem.removeEventListener(type, handle);
    }
  };
  jQuery.Event = function (src, props) {
    // Allow instantiation without the 'new' keyword
    if (!(this instanceof jQuery.Event)) {
      return new jQuery.Event(src, props);
    }

    // Event object
    if (src && src.type) {
      this.originalEvent = src;
      this.type = src.type;

      // Events bubbling up the document may have been marked as prevented
      // by a handler lower down the tree; reflect the correct value.
      this.isDefaultPrevented = src.defaultPrevented || src.defaultPrevented === undefined &&
      // Support: Android <=2.3 only
      src.returnValue === false ? returnTrue : returnFalse;

      // Create target properties
      // Support: Safari <=6 - 7 only
      // Target should not be a text node (trac-504, trac-13143)
      this.target = src.target && src.target.nodeType === 3 ? src.target.parentNode : src.target;
      this.currentTarget = src.currentTarget;
      this.relatedTarget = src.relatedTarget;

      // Event type
    } else {
      this.type = src;
    }

    // Put explicitly provided properties onto the event object
    if (props) {
      jQuery.extend(this, props);
    }

    // Create a timestamp if incoming event doesn't have one
    this.timeStamp = src && src.timeStamp || Date.now();

    // Mark it as fixed
    this[jQuery.expando] = true;
  };

  // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
  // https://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
  jQuery.Event.prototype = {
    constructor: jQuery.Event,
    isDefaultPrevented: returnFalse,
    isPropagationStopped: returnFalse,
    isImmediatePropagationStopped: returnFalse,
    isSimulated: false,
    preventDefault: function () {
      var e = this.originalEvent;
      this.isDefaultPrevented = returnTrue;
      if (e && !this.isSimulated) {
        e.preventDefault();
      }
    },
    stopPropagation: function () {
      var e = this.originalEvent;
      this.isPropagationStopped = returnTrue;
      if (e && !this.isSimulated) {
        e.stopPropagation();
      }
    },
    stopImmediatePropagation: function () {
      var e = this.originalEvent;
      this.isImmediatePropagationStopped = returnTrue;
      if (e && !this.isSimulated) {
        e.stopImmediatePropagation();
      }
      this.stopPropagation();
    }
  };

  // Includes all common event props including KeyEvent and MouseEvent specific props
  jQuery.each({
    altKey: true,
    bubbles: true,
    cancelable: true,
    changedTouches: true,
    ctrlKey: true,
    detail: true,
    eventPhase: true,
    metaKey: true,
    pageX: true,
    pageY: true,
    shiftKey: true,
    view: true,
    "char": true,
    code: true,
    charCode: true,
    key: true,
    keyCode: true,
    button: true,
    buttons: true,
    clientX: true,
    clientY: true,
    offsetX: true,
    offsetY: true,
    pointerId: true,
    pointerType: true,
    screenX: true,
    screenY: true,
    targetTouches: true,
    toElement: true,
    touches: true,
    which: true
  }, jQuery.event.addProp);
  jQuery.each({
    focus: "focusin",
    blur: "focusout"
  }, function (type, delegateType) {
    function focusMappedHandler(nativeEvent) {
      if (document.documentMode) {
        // Support: IE 11+
        // Attach a single focusin/focusout handler on the document while someone wants
        // focus/blur. This is because the former are synchronous in IE while the latter
        // are async. In other browsers, all those handlers are invoked synchronously.

        // `handle` from private data would already wrap the event, but we need
        // to change the `type` here.
        var handle = dataPriv.get(this, "handle"),
          event = jQuery.event.fix(nativeEvent);
        event.type = nativeEvent.type === "focusin" ? "focus" : "blur";
        event.isSimulated = true;

        // First, handle focusin/focusout
        handle(nativeEvent);

        // ...then, handle focus/blur
        //
        // focus/blur don't bubble while focusin/focusout do; simulate the former by only
        // invoking the handler at the lower level.
        if (event.target === event.currentTarget) {
          // The setup part calls `leverageNative`, which, in turn, calls
          // `jQuery.event.add`, so event handle will already have been set
          // by this point.
          handle(event);
        }
      } else {
        // For non-IE browsers, attach a single capturing handler on the document
        // while someone wants focusin/focusout.
        jQuery.event.simulate(delegateType, nativeEvent.target, jQuery.event.fix(nativeEvent));
      }
    }
    jQuery.event.special[type] = {
      // Utilize native event if possible so blur/focus sequence is correct
      setup: function () {
        var attaches;

        // Claim the first handler
        // dataPriv.set( this, "focus", ... )
        // dataPriv.set( this, "blur", ... )
        leverageNative(this, type, true);
        if (document.documentMode) {
          // Support: IE 9 - 11+
          // We use the same native handler for focusin & focus (and focusout & blur)
          // so we need to coordinate setup & teardown parts between those events.
          // Use `delegateType` as the key as `type` is already used by `leverageNative`.
          attaches = dataPriv.get(this, delegateType);
          if (!attaches) {
            this.addEventListener(delegateType, focusMappedHandler);
          }
          dataPriv.set(this, delegateType, (attaches || 0) + 1);
        } else {
          // Return false to allow normal processing in the caller
          return false;
        }
      },
      trigger: function () {
        // Force setup before trigger
        leverageNative(this, type);

        // Return non-false to allow normal event-path propagation
        return true;
      },
      teardown: function () {
        var attaches;
        if (document.documentMode) {
          attaches = dataPriv.get(this, delegateType) - 1;
          if (!attaches) {
            this.removeEventListener(delegateType, focusMappedHandler);
            dataPriv.remove(this, delegateType);
          } else {
            dataPriv.set(this, delegateType, attaches);
          }
        } else {
          // Return false to indicate standard teardown should be applied
          return false;
        }
      },
      // Suppress native focus or blur if we're currently inside
      // a leveraged native-event stack
      _default: function (event) {
        return dataPriv.get(event.target, type);
      },
      delegateType: delegateType
    };

    // Support: Firefox <=44
    // Firefox doesn't have focus(in | out) events
    // Related ticket - https://bugzilla.mozilla.org/show_bug.cgi?id=687787
    //
    // Support: Chrome <=48 - 49, Safari <=9.0 - 9.1
    // focus(in | out) events fire after focus & blur events,
    // which is spec violation - http://www.w3.org/TR/DOM-Level-3-Events/#events-focusevent-event-order
    // Related ticket - https://bugs.chromium.org/p/chromium/issues/detail?id=449857
    //
    // Support: IE 9 - 11+
    // To preserve relative focusin/focus & focusout/blur event order guaranteed on the 3.x branch,
    // attach a single handler for both events in IE.
    jQuery.event.special[delegateType] = {
      setup: function () {
        // Handle: regular nodes (via `this.ownerDocument`), window
        // (via `this.document`) & document (via `this`).
        var doc = this.ownerDocument || this.document || this,
          dataHolder = document.documentMode ? this : doc,
          attaches = dataPriv.get(dataHolder, delegateType);

        // Support: IE 9 - 11+
        // We use the same native handler for focusin & focus (and focusout & blur)
        // so we need to coordinate setup & teardown parts between those events.
        // Use `delegateType` as the key as `type` is already used by `leverageNative`.
        if (!attaches) {
          if (document.documentMode) {
            this.addEventListener(delegateType, focusMappedHandler);
          } else {
            doc.addEventListener(type, focusMappedHandler, true);
          }
        }
        dataPriv.set(dataHolder, delegateType, (attaches || 0) + 1);
      },
      teardown: function () {
        var doc = this.ownerDocument || this.document || this,
          dataHolder = document.documentMode ? this : doc,
          attaches = dataPriv.get(dataHolder, delegateType) - 1;
        if (!attaches) {
          if (document.documentMode) {
            this.removeEventListener(delegateType, focusMappedHandler);
          } else {
            doc.removeEventListener(type, focusMappedHandler, true);
          }
          dataPriv.remove(dataHolder, delegateType);
        } else {
          dataPriv.set(dataHolder, delegateType, attaches);
        }
      }
    };
  });

  // Create mouseenter/leave events using mouseover/out and event-time checks
  // so that event delegation works in jQuery.
  // Do the same for pointerenter/pointerleave and pointerover/pointerout
  //
  // Support: Safari 7 only
  // Safari sends mouseenter too often; see:
  // https://bugs.chromium.org/p/chromium/issues/detail?id=470258
  // for the description of the bug (it existed in older Chrome versions as well).
  jQuery.each({
    mouseenter: "mouseover",
    mouseleave: "mouseout",
    pointerenter: "pointerover",
    pointerleave: "pointerout"
  }, function (orig, fix) {
    jQuery.event.special[orig] = {
      delegateType: fix,
      bindType: fix,
      handle: function (event) {
        var ret,
          target = this,
          related = event.relatedTarget,
          handleObj = event.handleObj;

        // For mouseenter/leave call the handler if related is outside the target.
        // NB: No relatedTarget if the mouse left/entered the browser window
        if (!related || related !== target && !jQuery.contains(target, related)) {
          event.type = handleObj.origType;
          ret = handleObj.handler.apply(this, arguments);
          event.type = fix;
        }
        return ret;
      }
    };
  });
  jQuery.fn.extend({
    on: function (types, selector, data, fn) {
      return on(this, types, selector, data, fn);
    },
    one: function (types, selector, data, fn) {
      return on(this, types, selector, data, fn, 1);
    },
    off: function (types, selector, fn) {
      var handleObj, type;
      if (types && types.preventDefault && types.handleObj) {
        // ( event )  dispatched jQuery.Event
        handleObj = types.handleObj;
        jQuery(types.delegateTarget).off(handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler);
        return this;
      }
      if (typeof types === "object") {
        // ( types-object [, selector] )
        for (type in types) {
          this.off(type, selector, types[type]);
        }
        return this;
      }
      if (selector === false || typeof selector === "function") {
        // ( types [, fn] )
        fn = selector;
        selector = undefined;
      }
      if (fn === false) {
        fn = returnFalse;
      }
      return this.each(function () {
        jQuery.event.remove(this, types, fn, selector);
      });
    }
  });
  var
    // Support: IE <=10 - 11, Edge 12 - 13 only
    // In IE/Edge using regex groups here causes severe slowdowns.
    // See https://connect.microsoft.com/IE/feedback/details/1736512/
    rnoInnerhtml = /<script|<style|<link/i,
    // checked="checked" or checked
    rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
    rcleanScript = /^\s*<!\[CDATA\[|\]\]>\s*$/g;

  // Prefer a tbody over its parent table for containing new rows
  function manipulationTarget(elem, content) {
    if (nodeName(elem, "table") && nodeName(content.nodeType !== 11 ? content : content.firstChild, "tr")) {
      return jQuery(elem).children("tbody")[0] || elem;
    }
    return elem;
  }

  // Replace/restore the type attribute of script elements for safe DOM manipulation
  function disableScript(elem) {
    elem.type = (elem.getAttribute("type") !== null) + "/" + elem.type;
    return elem;
  }
  function restoreScript(elem) {
    if ((elem.type || "").slice(0, 5) === "true/") {
      elem.type = elem.type.slice(5);
    } else {
      elem.removeAttribute("type");
    }
    return elem;
  }
  function cloneCopyEvent(src, dest) {
    var i, l, type, pdataOld, udataOld, udataCur, events;
    if (dest.nodeType !== 1) {
      return;
    }

    // 1. Copy private data: events, handlers, etc.
    if (dataPriv.hasData(src)) {
      pdataOld = dataPriv.get(src);
      events = pdataOld.events;
      if (events) {
        dataPriv.remove(dest, "handle events");
        for (type in events) {
          for (i = 0, l = events[type].length; i < l; i++) {
            jQuery.event.add(dest, type, events[type][i]);
          }
        }
      }
    }

    // 2. Copy user data
    if (dataUser.hasData(src)) {
      udataOld = dataUser.access(src);
      udataCur = jQuery.extend({}, udataOld);
      dataUser.set(dest, udataCur);
    }
  }

  // Fix IE bugs, see support tests
  function fixInput(src, dest) {
    var nodeName = dest.nodeName.toLowerCase();

    // Fails to persist the checked state of a cloned checkbox or radio button.
    if (nodeName === "input" && rcheckableType.test(src.type)) {
      dest.checked = src.checked;

      // Fails to return the selected option to the default selected state when cloning options
    } else if (nodeName === "input" || nodeName === "textarea") {
      dest.defaultValue = src.defaultValue;
    }
  }
  function domManip(collection, args, callback, ignored) {
    // Flatten any nested arrays
    args = flat(args);
    var fragment,
      first,
      scripts,
      hasScripts,
      node,
      doc,
      i = 0,
      l = collection.length,
      iNoClone = l - 1,
      value = args[0],
      valueIsFunction = isFunction(value);

    // We can't cloneNode fragments that contain checked, in WebKit
    if (valueIsFunction || l > 1 && typeof value === "string" && !support.checkClone && rchecked.test(value)) {
      return collection.each(function (index) {
        var self = collection.eq(index);
        if (valueIsFunction) {
          args[0] = value.call(this, index, self.html());
        }
        domManip(self, args, callback, ignored);
      });
    }
    if (l) {
      fragment = buildFragment(args, collection[0].ownerDocument, false, collection, ignored);
      first = fragment.firstChild;
      if (fragment.childNodes.length === 1) {
        fragment = first;
      }

      // Require either new content or an interest in ignored elements to invoke the callback
      if (first || ignored) {
        scripts = jQuery.map(getAll(fragment, "script"), disableScript);
        hasScripts = scripts.length;

        // Use the original fragment for the last item
        // instead of the first because it can end up
        // being emptied incorrectly in certain situations (trac-8070).
        for (; i < l; i++) {
          node = fragment;
          if (i !== iNoClone) {
            node = jQuery.clone(node, true, true);

            // Keep references to cloned scripts for later restoration
            if (hasScripts) {
              // Support: Android <=4.0 only, PhantomJS 1 only
              // push.apply(_, arraylike) throws on ancient WebKit
              jQuery.merge(scripts, getAll(node, "script"));
            }
          }
          callback.call(collection[i], node, i);
        }
        if (hasScripts) {
          doc = scripts[scripts.length - 1].ownerDocument;

          // Re-enable scripts
          jQuery.map(scripts, restoreScript);

          // Evaluate executable scripts on first document insertion
          for (i = 0; i < hasScripts; i++) {
            node = scripts[i];
            if (rscriptType.test(node.type || "") && !dataPriv.access(node, "globalEval") && jQuery.contains(doc, node)) {
              if (node.src && (node.type || "").toLowerCase() !== "module") {
                // Optional AJAX dependency, but won't run scripts if not present
                if (jQuery._evalUrl && !node.noModule) {
                  jQuery._evalUrl(node.src, {
                    nonce: node.nonce || node.getAttribute("nonce")
                  }, doc);
                }
              } else {
                // Unwrap a CDATA section containing script contents. This shouldn't be
                // needed as in XML documents they're already not visible when
                // inspecting element contents and in HTML documents they have no
                // meaning but we're preserving that logic for backwards compatibility.
                // This will be removed completely in 4.0. See gh-4904.
                DOMEval(node.textContent.replace(rcleanScript, ""), node, doc);
              }
            }
          }
        }
      }
    }
    return collection;
  }
  function remove(elem, selector, keepData) {
    var node,
      nodes = selector ? jQuery.filter(selector, elem) : elem,
      i = 0;
    for (; (node = nodes[i]) != null; i++) {
      if (!keepData && node.nodeType === 1) {
        jQuery.cleanData(getAll(node));
      }
      if (node.parentNode) {
        if (keepData && isAttached(node)) {
          setGlobalEval(getAll(node, "script"));
        }
        node.parentNode.removeChild(node);
      }
    }
    return elem;
  }
  jQuery.extend({
    htmlPrefilter: function (html) {
      return html;
    },
    clone: function (elem, dataAndEvents, deepDataAndEvents) {
      var i,
        l,
        srcElements,
        destElements,
        clone = elem.cloneNode(true),
        inPage = isAttached(elem);

      // Fix IE cloning issues
      if (!support.noCloneChecked && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem)) {
        // We eschew jQuery#find here for performance reasons:
        // https://jsperf.com/getall-vs-sizzle/2
        destElements = getAll(clone);
        srcElements = getAll(elem);
        for (i = 0, l = srcElements.length; i < l; i++) {
          fixInput(srcElements[i], destElements[i]);
        }
      }

      // Copy the events from the original to the clone
      if (dataAndEvents) {
        if (deepDataAndEvents) {
          srcElements = srcElements || getAll(elem);
          destElements = destElements || getAll(clone);
          for (i = 0, l = srcElements.length; i < l; i++) {
            cloneCopyEvent(srcElements[i], destElements[i]);
          }
        } else {
          cloneCopyEvent(elem, clone);
        }
      }

      // Preserve script evaluation history
      destElements = getAll(clone, "script");
      if (destElements.length > 0) {
        setGlobalEval(destElements, !inPage && getAll(elem, "script"));
      }

      // Return the cloned set
      return clone;
    },
    cleanData: function (elems) {
      var data,
        elem,
        type,
        special = jQuery.event.special,
        i = 0;
      for (; (elem = elems[i]) !== undefined; i++) {
        if (acceptData(elem)) {
          if (data = elem[dataPriv.expando]) {
            if (data.events) {
              for (type in data.events) {
                if (special[type]) {
                  jQuery.event.remove(elem, type);

                  // This is a shortcut to avoid jQuery.event.remove's overhead
                } else {
                  jQuery.removeEvent(elem, type, data.handle);
                }
              }
            }

            // Support: Chrome <=35 - 45+
            // Assign undefined instead of using delete, see Data#remove
            elem[dataPriv.expando] = undefined;
          }
          if (elem[dataUser.expando]) {
            // Support: Chrome <=35 - 45+
            // Assign undefined instead of using delete, see Data#remove
            elem[dataUser.expando] = undefined;
          }
        }
      }
    }
  });
  jQuery.fn.extend({
    detach: function (selector) {
      return remove(this, selector, true);
    },
    remove: function (selector) {
      return remove(this, selector);
    },
    text: function (value) {
      return access(this, function (value) {
        return value === undefined ? jQuery.text(this) : this.empty().each(function () {
          if (this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9) {
            this.textContent = value;
          }
        });
      }, null, value, arguments.length);
    },
    append: function () {
      return domManip(this, arguments, function (elem) {
        if (this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9) {
          var target = manipulationTarget(this, elem);
          target.appendChild(elem);
        }
      });
    },
    prepend: function () {
      return domManip(this, arguments, function (elem) {
        if (this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9) {
          var target = manipulationTarget(this, elem);
          target.insertBefore(elem, target.firstChild);
        }
      });
    },
    before: function () {
      return domManip(this, arguments, function (elem) {
        if (this.parentNode) {
          this.parentNode.insertBefore(elem, this);
        }
      });
    },
    after: function () {
      return domManip(this, arguments, function (elem) {
        if (this.parentNode) {
          this.parentNode.insertBefore(elem, this.nextSibling);
        }
      });
    },
    empty: function () {
      var elem,
        i = 0;
      for (; (elem = this[i]) != null; i++) {
        if (elem.nodeType === 1) {
          // Prevent memory leaks
          jQuery.cleanData(getAll(elem, false));

          // Remove any remaining nodes
          elem.textContent = "";
        }
      }
      return this;
    },
    clone: function (dataAndEvents, deepDataAndEvents) {
      dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
      deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
      return this.map(function () {
        return jQuery.clone(this, dataAndEvents, deepDataAndEvents);
      });
    },
    html: function (value) {
      return access(this, function (value) {
        var elem = this[0] || {},
          i = 0,
          l = this.length;
        if (value === undefined && elem.nodeType === 1) {
          return elem.innerHTML;
        }

        // See if we can take a shortcut and just use innerHTML
        if (typeof value === "string" && !rnoInnerhtml.test(value) && !wrapMap[(rtagName.exec(value) || ["", ""])[1].toLowerCase()]) {
          value = jQuery.htmlPrefilter(value);
          try {
            for (; i < l; i++) {
              elem = this[i] || {};

              // Remove element nodes and prevent memory leaks
              if (elem.nodeType === 1) {
                jQuery.cleanData(getAll(elem, false));
                elem.innerHTML = value;
              }
            }
            elem = 0;

            // If using innerHTML throws an exception, use the fallback method
          } catch (e) {}
        }
        if (elem) {
          this.empty().append(value);
        }
      }, null, value, arguments.length);
    },
    replaceWith: function () {
      var ignored = [];

      // Make the changes, replacing each non-ignored context element with the new content
      return domManip(this, arguments, function (elem) {
        var parent = this.parentNode;
        if (jQuery.inArray(this, ignored) < 0) {
          jQuery.cleanData(getAll(this));
          if (parent) {
            parent.replaceChild(elem, this);
          }
        }

        // Force callback invocation
      }, ignored);
    }
  });
  jQuery.each({
    appendTo: "append",
    prependTo: "prepend",
    insertBefore: "before",
    insertAfter: "after",
    replaceAll: "replaceWith"
  }, function (name, original) {
    jQuery.fn[name] = function (selector) {
      var elems,
        ret = [],
        insert = jQuery(selector),
        last = insert.length - 1,
        i = 0;
      for (; i <= last; i++) {
        elems = i === last ? this : this.clone(true);
        jQuery(insert[i])[original](elems);

        // Support: Android <=4.0 only, PhantomJS 1 only
        // .get() because push.apply(_, arraylike) throws on ancient WebKit
        push.apply(ret, elems.get());
      }
      return this.pushStack(ret);
    };
  });
  var rnumnonpx = new RegExp("^(" + pnum + ")(?!px)[a-z%]+$", "i");
  var rcustomProp = /^--/;
  var getStyles = function (elem) {
    // Support: IE <=11 only, Firefox <=30 (trac-15098, trac-14150)
    // IE throws on elements created in popups
    // FF meanwhile throws on frame elements through "defaultView.getComputedStyle"
    var view = elem.ownerDocument.defaultView;
    if (!view || !view.opener) {
      view = window;
    }
    return view.getComputedStyle(elem);
  };
  var swap = function (elem, options, callback) {
    var ret,
      name,
      old = {};

    // Remember the old values, and insert the new ones
    for (name in options) {
      old[name] = elem.style[name];
      elem.style[name] = options[name];
    }
    ret = callback.call(elem);

    // Revert the old values
    for (name in options) {
      elem.style[name] = old[name];
    }
    return ret;
  };
  var rboxStyle = new RegExp(cssExpand.join("|"), "i");
  (function () {
    // Executing both pixelPosition & boxSizingReliable tests require only one layout
    // so they're executed at the same time to save the second computation.
    function computeStyleTests() {
      // This is a singleton, we need to execute it only once
      if (!div) {
        return;
      }
      container.style.cssText = "position:absolute;left:-11111px;width:60px;" + "margin-top:1px;padding:0;border:0";
      div.style.cssText = "position:relative;display:block;box-sizing:border-box;overflow:scroll;" + "margin:auto;border:1px;padding:1px;" + "width:60%;top:1%";
      documentElement.appendChild(container).appendChild(div);
      var divStyle = window.getComputedStyle(div);
      pixelPositionVal = divStyle.top !== "1%";

      // Support: Android 4.0 - 4.3 only, Firefox <=3 - 44
      reliableMarginLeftVal = roundPixelMeasures(divStyle.marginLeft) === 12;

      // Support: Android 4.0 - 4.3 only, Safari <=9.1 - 10.1, iOS <=7.0 - 9.3
      // Some styles come back with percentage values, even though they shouldn't
      div.style.right = "60%";
      pixelBoxStylesVal = roundPixelMeasures(divStyle.right) === 36;

      // Support: IE 9 - 11 only
      // Detect misreporting of content dimensions for box-sizing:border-box elements
      boxSizingReliableVal = roundPixelMeasures(divStyle.width) === 36;

      // Support: IE 9 only
      // Detect overflow:scroll screwiness (gh-3699)
      // Support: Chrome <=64
      // Don't get tricked when zoom affects offsetWidth (gh-4029)
      div.style.position = "absolute";
      scrollboxSizeVal = roundPixelMeasures(div.offsetWidth / 3) === 12;
      documentElement.removeChild(container);

      // Nullify the div so it wouldn't be stored in the memory and
      // it will also be a sign that checks already performed
      div = null;
    }
    function roundPixelMeasures(measure) {
      return Math.round(parseFloat(measure));
    }
    var pixelPositionVal,
      boxSizingReliableVal,
      scrollboxSizeVal,
      pixelBoxStylesVal,
      reliableTrDimensionsVal,
      reliableMarginLeftVal,
      container = document.createElement("div"),
      div = document.createElement("div");

    // Finish early in limited (non-browser) environments
    if (!div.style) {
      return;
    }

    // Support: IE <=9 - 11 only
    // Style of cloned element affects source element cloned (trac-8908)
    div.style.backgroundClip = "content-box";
    div.cloneNode(true).style.backgroundClip = "";
    support.clearCloneStyle = div.style.backgroundClip === "content-box";
    jQuery.extend(support, {
      boxSizingReliable: function () {
        computeStyleTests();
        return boxSizingReliableVal;
      },
      pixelBoxStyles: function () {
        computeStyleTests();
        return pixelBoxStylesVal;
      },
      pixelPosition: function () {
        computeStyleTests();
        return pixelPositionVal;
      },
      reliableMarginLeft: function () {
        computeStyleTests();
        return reliableMarginLeftVal;
      },
      scrollboxSize: function () {
        computeStyleTests();
        return scrollboxSizeVal;
      },
      // Support: IE 9 - 11+, Edge 15 - 18+
      // IE/Edge misreport `getComputedStyle` of table rows with width/height
      // set in CSS while `offset*` properties report correct values.
      // Behavior in IE 9 is more subtle than in newer versions & it passes
      // some versions of this test; make sure not to make it pass there!
      //
      // Support: Firefox 70+
      // Only Firefox includes border widths
      // in computed dimensions. (gh-4529)
      reliableTrDimensions: function () {
        var table, tr, trChild, trStyle;
        if (reliableTrDimensionsVal == null) {
          table = document.createElement("table");
          tr = document.createElement("tr");
          trChild = document.createElement("div");
          table.style.cssText = "position:absolute;left:-11111px;border-collapse:separate";
          tr.style.cssText = "box-sizing:content-box;border:1px solid";

          // Support: Chrome 86+
          // Height set through cssText does not get applied.
          // Computed height then comes back as 0.
          tr.style.height = "1px";
          trChild.style.height = "9px";

          // Support: Android 8 Chrome 86+
          // In our bodyBackground.html iframe,
          // display for all div elements is set to "inline",
          // which causes a problem only in Android 8 Chrome 86.
          // Ensuring the div is `display: block`
          // gets around this issue.
          trChild.style.display = "block";
          documentElement.appendChild(table).appendChild(tr).appendChild(trChild);
          trStyle = window.getComputedStyle(tr);
          reliableTrDimensionsVal = parseInt(trStyle.height, 10) + parseInt(trStyle.borderTopWidth, 10) + parseInt(trStyle.borderBottomWidth, 10) === tr.offsetHeight;
          documentElement.removeChild(table);
        }
        return reliableTrDimensionsVal;
      }
    });
  })();
  function curCSS(elem, name, computed) {
    var width,
      minWidth,
      maxWidth,
      ret,
      isCustomProp = rcustomProp.test(name),
      // Support: Firefox 51+
      // Retrieving style before computed somehow
      // fixes an issue with getting wrong values
      // on detached elements
      style = elem.style;
    computed = computed || getStyles(elem);

    // getPropertyValue is needed for:
    //   .css('filter') (IE 9 only, trac-12537)
    //   .css('--customProperty) (gh-3144)
    if (computed) {
      // Support: IE <=9 - 11+
      // IE only supports `"float"` in `getPropertyValue`; in computed styles
      // it's only available as `"cssFloat"`. We no longer modify properties
      // sent to `.css()` apart from camelCasing, so we need to check both.
      // Normally, this would create difference in behavior: if
      // `getPropertyValue` returns an empty string, the value returned
      // by `.css()` would be `undefined`. This is usually the case for
      // disconnected elements. However, in IE even disconnected elements
      // with no styles return `"none"` for `getPropertyValue( "float" )`
      ret = computed.getPropertyValue(name) || computed[name];
      if (isCustomProp && ret) {
        // Support: Firefox 105+, Chrome <=105+
        // Spec requires trimming whitespace for custom properties (gh-4926).
        // Firefox only trims leading whitespace. Chrome just collapses
        // both leading & trailing whitespace to a single space.
        //
        // Fall back to `undefined` if empty string returned.
        // This collapses a missing definition with property defined
        // and set to an empty string but there's no standard API
        // allowing us to differentiate them without a performance penalty
        // and returning `undefined` aligns with older jQuery.
        //
        // rtrimCSS treats U+000D CARRIAGE RETURN and U+000C FORM FEED
        // as whitespace while CSS does not, but this is not a problem
        // because CSS preprocessing replaces them with U+000A LINE FEED
        // (which *is* CSS whitespace)
        // https://www.w3.org/TR/css-syntax-3/#input-preprocessing
        ret = ret.replace(rtrimCSS, "$1") || undefined;
      }
      if (ret === "" && !isAttached(elem)) {
        ret = jQuery.style(elem, name);
      }

      // A tribute to the "awesome hack by Dean Edwards"
      // Android Browser returns percentage for some values,
      // but width seems to be reliably pixels.
      // This is against the CSSOM draft spec:
      // https://drafts.csswg.org/cssom/#resolved-values
      if (!support.pixelBoxStyles() && rnumnonpx.test(ret) && rboxStyle.test(name)) {
        // Remember the original values
        width = style.width;
        minWidth = style.minWidth;
        maxWidth = style.maxWidth;

        // Put in the new values to get a computed value out
        style.minWidth = style.maxWidth = style.width = ret;
        ret = computed.width;

        // Revert the changed values
        style.width = width;
        style.minWidth = minWidth;
        style.maxWidth = maxWidth;
      }
    }
    return ret !== undefined ?
    // Support: IE <=9 - 11 only
    // IE returns zIndex value as an integer.
    ret + "" : ret;
  }
  function addGetHookIf(conditionFn, hookFn) {
    // Define the hook, we'll check on the first run if it's really needed.
    return {
      get: function () {
        if (conditionFn()) {
          // Hook not needed (or it's not possible to use it due
          // to missing dependency), remove it.
          delete this.get;
          return;
        }

        // Hook needed; redefine it so that the support test is not executed again.
        return (this.get = hookFn).apply(this, arguments);
      }
    };
  }
  var cssPrefixes = ["Webkit", "Moz", "ms"],
    emptyStyle = document.createElement("div").style,
    vendorProps = {};

  // Return a vendor-prefixed property or undefined
  function vendorPropName(name) {
    // Check for vendor prefixed names
    var capName = name[0].toUpperCase() + name.slice(1),
      i = cssPrefixes.length;
    while (i--) {
      name = cssPrefixes[i] + capName;
      if (name in emptyStyle) {
        return name;
      }
    }
  }

  // Return a potentially-mapped jQuery.cssProps or vendor prefixed property
  function finalPropName(name) {
    var final = jQuery.cssProps[name] || vendorProps[name];
    if (final) {
      return final;
    }
    if (name in emptyStyle) {
      return name;
    }
    return vendorProps[name] = vendorPropName(name) || name;
  }
  var
    // Swappable if display is none or starts with table
    // except "table", "table-cell", or "table-caption"
    // See here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
    rdisplayswap = /^(none|table(?!-c[ea]).+)/,
    cssShow = {
      position: "absolute",
      visibility: "hidden",
      display: "block"
    },
    cssNormalTransform = {
      letterSpacing: "0",
      fontWeight: "400"
    };
  function setPositiveNumber(_elem, value, subtract) {
    // Any relative (+/-) values have already been
    // normalized at this point
    var matches = rcssNum.exec(value);
    return matches ?
    // Guard against undefined "subtract", e.g., when used as in cssHooks
    Math.max(0, matches[2] - (subtract || 0)) + (matches[3] || "px") : value;
  }
  function boxModelAdjustment(elem, dimension, box, isBorderBox, styles, computedVal) {
    var i = dimension === "width" ? 1 : 0,
      extra = 0,
      delta = 0,
      marginDelta = 0;

    // Adjustment may not be necessary
    if (box === (isBorderBox ? "border" : "content")) {
      return 0;
    }
    for (; i < 4; i += 2) {
      // Both box models exclude margin
      // Count margin delta separately to only add it after scroll gutter adjustment.
      // This is needed to make negative margins work with `outerHeight( true )` (gh-3982).
      if (box === "margin") {
        marginDelta += jQuery.css(elem, box + cssExpand[i], true, styles);
      }

      // If we get here with a content-box, we're seeking "padding" or "border" or "margin"
      if (!isBorderBox) {
        // Add padding
        delta += jQuery.css(elem, "padding" + cssExpand[i], true, styles);

        // For "border" or "margin", add border
        if (box !== "padding") {
          delta += jQuery.css(elem, "border" + cssExpand[i] + "Width", true, styles);

          // But still keep track of it otherwise
        } else {
          extra += jQuery.css(elem, "border" + cssExpand[i] + "Width", true, styles);
        }

        // If we get here with a border-box (content + padding + border), we're seeking "content" or
        // "padding" or "margin"
      } else {
        // For "content", subtract padding
        if (box === "content") {
          delta -= jQuery.css(elem, "padding" + cssExpand[i], true, styles);
        }

        // For "content" or "padding", subtract border
        if (box !== "margin") {
          delta -= jQuery.css(elem, "border" + cssExpand[i] + "Width", true, styles);
        }
      }
    }

    // Account for positive content-box scroll gutter when requested by providing computedVal
    if (!isBorderBox && computedVal >= 0) {
      // offsetWidth/offsetHeight is a rounded sum of content, padding, scroll gutter, and border
      // Assuming integer scroll gutter, subtract the rest and round down
      delta += Math.max(0, Math.ceil(elem["offset" + dimension[0].toUpperCase() + dimension.slice(1)] - computedVal - delta - extra - 0.5

      // If offsetWidth/offsetHeight is unknown, then we can't determine content-box scroll gutter
      // Use an explicit zero to avoid NaN (gh-3964)
      )) || 0;
    }
    return delta + marginDelta;
  }
  function getWidthOrHeight(elem, dimension, extra) {
    // Start with computed style
    var styles = getStyles(elem),
      // To avoid forcing a reflow, only fetch boxSizing if we need it (gh-4322).
      // Fake content-box until we know it's needed to know the true value.
      boxSizingNeeded = !support.boxSizingReliable() || extra,
      isBorderBox = boxSizingNeeded && jQuery.css(elem, "boxSizing", false, styles) === "border-box",
      valueIsBorderBox = isBorderBox,
      val = curCSS(elem, dimension, styles),
      offsetProp = "offset" + dimension[0].toUpperCase() + dimension.slice(1);

    // Support: Firefox <=54
    // Return a confounding non-pixel value or feign ignorance, as appropriate.
    if (rnumnonpx.test(val)) {
      if (!extra) {
        return val;
      }
      val = "auto";
    }

    // Support: IE 9 - 11 only
    // Use offsetWidth/offsetHeight for when box sizing is unreliable.
    // In those cases, the computed value can be trusted to be border-box.
    if ((!support.boxSizingReliable() && isBorderBox ||
    // Support: IE 10 - 11+, Edge 15 - 18+
    // IE/Edge misreport `getComputedStyle` of table rows with width/height
    // set in CSS while `offset*` properties report correct values.
    // Interestingly, in some cases IE 9 doesn't suffer from this issue.
    !support.reliableTrDimensions() && nodeName(elem, "tr") ||
    // Fall back to offsetWidth/offsetHeight when value is "auto"
    // This happens for inline elements with no explicit setting (gh-3571)
    val === "auto" ||
    // Support: Android <=4.1 - 4.3 only
    // Also use offsetWidth/offsetHeight for misreported inline dimensions (gh-3602)
    !parseFloat(val) && jQuery.css(elem, "display", false, styles) === "inline") &&
    // Make sure the element is visible & connected
    elem.getClientRects().length) {
      isBorderBox = jQuery.css(elem, "boxSizing", false, styles) === "border-box";

      // Where available, offsetWidth/offsetHeight approximate border box dimensions.
      // Where not available (e.g., SVG), assume unreliable box-sizing and interpret the
      // retrieved value as a content box dimension.
      valueIsBorderBox = offsetProp in elem;
      if (valueIsBorderBox) {
        val = elem[offsetProp];
      }
    }

    // Normalize "" and auto
    val = parseFloat(val) || 0;

    // Adjust for the element's box model
    return val + boxModelAdjustment(elem, dimension, extra || (isBorderBox ? "border" : "content"), valueIsBorderBox, styles,
    // Provide the current computed size to request scroll gutter calculation (gh-3589)
    val) + "px";
  }
  jQuery.extend({
    // Add in style property hooks for overriding the default
    // behavior of getting and setting a style property
    cssHooks: {
      opacity: {
        get: function (elem, computed) {
          if (computed) {
            // We should always get a number back from opacity
            var ret = curCSS(elem, "opacity");
            return ret === "" ? "1" : ret;
          }
        }
      }
    },
    // Don't automatically add "px" to these possibly-unitless properties
    cssNumber: {
      animationIterationCount: true,
      aspectRatio: true,
      borderImageSlice: true,
      columnCount: true,
      flexGrow: true,
      flexShrink: true,
      fontWeight: true,
      gridArea: true,
      gridColumn: true,
      gridColumnEnd: true,
      gridColumnStart: true,
      gridRow: true,
      gridRowEnd: true,
      gridRowStart: true,
      lineHeight: true,
      opacity: true,
      order: true,
      orphans: true,
      scale: true,
      widows: true,
      zIndex: true,
      zoom: true,
      // SVG-related
      fillOpacity: true,
      floodOpacity: true,
      stopOpacity: true,
      strokeMiterlimit: true,
      strokeOpacity: true
    },
    // Add in properties whose names you wish to fix before
    // setting or getting the value
    cssProps: {},
    // Get and set the style property on a DOM Node
    style: function (elem, name, value, extra) {
      // Don't set styles on text and comment nodes
      if (!elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style) {
        return;
      }

      // Make sure that we're working with the right name
      var ret,
        type,
        hooks,
        origName = camelCase(name),
        isCustomProp = rcustomProp.test(name),
        style = elem.style;

      // Make sure that we're working with the right name. We don't
      // want to query the value if it is a CSS custom property
      // since they are user-defined.
      if (!isCustomProp) {
        name = finalPropName(origName);
      }

      // Gets hook for the prefixed version, then unprefixed version
      hooks = jQuery.cssHooks[name] || jQuery.cssHooks[origName];

      // Check if we're setting a value
      if (value !== undefined) {
        type = typeof value;

        // Convert "+=" or "-=" to relative numbers (trac-7345)
        if (type === "string" && (ret = rcssNum.exec(value)) && ret[1]) {
          value = adjustCSS(elem, name, ret);

          // Fixes bug trac-9237
          type = "number";
        }

        // Make sure that null and NaN values aren't set (trac-7116)
        if (value == null || value !== value) {
          return;
        }

        // If a number was passed in, add the unit (except for certain CSS properties)
        // The isCustomProp check can be removed in jQuery 4.0 when we only auto-append
        // "px" to a few hardcoded values.
        if (type === "number" && !isCustomProp) {
          value += ret && ret[3] || (jQuery.cssNumber[origName] ? "" : "px");
        }

        // background-* props affect original clone's values
        if (!support.clearCloneStyle && value === "" && name.indexOf("background") === 0) {
          style[name] = "inherit";
        }

        // If a hook was provided, use that value, otherwise just set the specified value
        if (!hooks || !("set" in hooks) || (value = hooks.set(elem, value, extra)) !== undefined) {
          if (isCustomProp) {
            style.setProperty(name, value);
          } else {
            style[name] = value;
          }
        }
      } else {
        // If a hook was provided get the non-computed value from there
        if (hooks && "get" in hooks && (ret = hooks.get(elem, false, extra)) !== undefined) {
          return ret;
        }

        // Otherwise just get the value from the style object
        return style[name];
      }
    },
    css: function (elem, name, extra, styles) {
      var val,
        num,
        hooks,
        origName = camelCase(name),
        isCustomProp = rcustomProp.test(name);

      // Make sure that we're working with the right name. We don't
      // want to modify the value if it is a CSS custom property
      // since they are user-defined.
      if (!isCustomProp) {
        name = finalPropName(origName);
      }

      // Try prefixed name followed by the unprefixed name
      hooks = jQuery.cssHooks[name] || jQuery.cssHooks[origName];

      // If a hook was provided get the computed value from there
      if (hooks && "get" in hooks) {
        val = hooks.get(elem, true, extra);
      }

      // Otherwise, if a way to get the computed value exists, use that
      if (val === undefined) {
        val = curCSS(elem, name, styles);
      }

      // Convert "normal" to computed value
      if (val === "normal" && name in cssNormalTransform) {
        val = cssNormalTransform[name];
      }

      // Make numeric if forced or a qualifier was provided and val looks numeric
      if (extra === "" || extra) {
        num = parseFloat(val);
        return extra === true || isFinite(num) ? num || 0 : val;
      }
      return val;
    }
  });
  jQuery.each(["height", "width"], function (_i, dimension) {
    jQuery.cssHooks[dimension] = {
      get: function (elem, computed, extra) {
        if (computed) {
          // Certain elements can have dimension info if we invisibly show them
          // but it must have a current display style that would benefit
          return rdisplayswap.test(jQuery.css(elem, "display")) && (
          // Support: Safari 8+
          // Table columns in Safari have non-zero offsetWidth & zero
          // getBoundingClientRect().width unless display is changed.
          // Support: IE <=11 only
          // Running getBoundingClientRect on a disconnected node
          // in IE throws an error.
          !elem.getClientRects().length || !elem.getBoundingClientRect().width) ? swap(elem, cssShow, function () {
            return getWidthOrHeight(elem, dimension, extra);
          }) : getWidthOrHeight(elem, dimension, extra);
        }
      },
      set: function (elem, value, extra) {
        var matches,
          styles = getStyles(elem),
          // Only read styles.position if the test has a chance to fail
          // to avoid forcing a reflow.
          scrollboxSizeBuggy = !support.scrollboxSize() && styles.position === "absolute",
          // To avoid forcing a reflow, only fetch boxSizing if we need it (gh-3991)
          boxSizingNeeded = scrollboxSizeBuggy || extra,
          isBorderBox = boxSizingNeeded && jQuery.css(elem, "boxSizing", false, styles) === "border-box",
          subtract = extra ? boxModelAdjustment(elem, dimension, extra, isBorderBox, styles) : 0;

        // Account for unreliable border-box dimensions by comparing offset* to computed and
        // faking a content-box to get border and padding (gh-3699)
        if (isBorderBox && scrollboxSizeBuggy) {
          subtract -= Math.ceil(elem["offset" + dimension[0].toUpperCase() + dimension.slice(1)] - parseFloat(styles[dimension]) - boxModelAdjustment(elem, dimension, "border", false, styles) - 0.5);
        }

        // Convert to pixels if value adjustment is needed
        if (subtract && (matches = rcssNum.exec(value)) && (matches[3] || "px") !== "px") {
          elem.style[dimension] = value;
          value = jQuery.css(elem, dimension);
        }
        return setPositiveNumber(elem, value, subtract);
      }
    };
  });
  jQuery.cssHooks.marginLeft = addGetHookIf(support.reliableMarginLeft, function (elem, computed) {
    if (computed) {
      return (parseFloat(curCSS(elem, "marginLeft")) || elem.getBoundingClientRect().left - swap(elem, {
        marginLeft: 0
      }, function () {
        return elem.getBoundingClientRect().left;
      })) + "px";
    }
  });

  // These hooks are used by animate to expand properties
  jQuery.each({
    margin: "",
    padding: "",
    border: "Width"
  }, function (prefix, suffix) {
    jQuery.cssHooks[prefix + suffix] = {
      expand: function (value) {
        var i = 0,
          expanded = {},
          // Assumes a single number if not a string
          parts = typeof value === "string" ? value.split(" ") : [value];
        for (; i < 4; i++) {
          expanded[prefix + cssExpand[i] + suffix] = parts[i] || parts[i - 2] || parts[0];
        }
        return expanded;
      }
    };
    if (prefix !== "margin") {
      jQuery.cssHooks[prefix + suffix].set = setPositiveNumber;
    }
  });
  jQuery.fn.extend({
    css: function (name, value) {
      return access(this, function (elem, name, value) {
        var styles,
          len,
          map = {},
          i = 0;
        if (Array.isArray(name)) {
          styles = getStyles(elem);
          len = name.length;
          for (; i < len; i++) {
            map[name[i]] = jQuery.css(elem, name[i], false, styles);
          }
          return map;
        }
        return value !== undefined ? jQuery.style(elem, name, value) : jQuery.css(elem, name);
      }, name, value, arguments.length > 1);
    }
  });
  function Tween(elem, options, prop, end, easing) {
    return new Tween.prototype.init(elem, options, prop, end, easing);
  }
  jQuery.Tween = Tween;
  Tween.prototype = {
    constructor: Tween,
    init: function (elem, options, prop, end, easing, unit) {
      this.elem = elem;
      this.prop = prop;
      this.easing = easing || jQuery.easing._default;
      this.options = options;
      this.start = this.now = this.cur();
      this.end = end;
      this.unit = unit || (jQuery.cssNumber[prop] ? "" : "px");
    },
    cur: function () {
      var hooks = Tween.propHooks[this.prop];
      return hooks && hooks.get ? hooks.get(this) : Tween.propHooks._default.get(this);
    },
    run: function (percent) {
      var eased,
        hooks = Tween.propHooks[this.prop];
      if (this.options.duration) {
        this.pos = eased = jQuery.easing[this.easing](percent, this.options.duration * percent, 0, 1, this.options.duration);
      } else {
        this.pos = eased = percent;
      }
      this.now = (this.end - this.start) * eased + this.start;
      if (this.options.step) {
        this.options.step.call(this.elem, this.now, this);
      }
      if (hooks && hooks.set) {
        hooks.set(this);
      } else {
        Tween.propHooks._default.set(this);
      }
      return this;
    }
  };
  Tween.prototype.init.prototype = Tween.prototype;
  Tween.propHooks = {
    _default: {
      get: function (tween) {
        var result;

        // Use a property on the element directly when it is not a DOM element,
        // or when there is no matching style property that exists.
        if (tween.elem.nodeType !== 1 || tween.elem[tween.prop] != null && tween.elem.style[tween.prop] == null) {
          return tween.elem[tween.prop];
        }

        // Passing an empty string as a 3rd parameter to .css will automatically
        // attempt a parseFloat and fallback to a string if the parse fails.
        // Simple values such as "10px" are parsed to Float;
        // complex values such as "rotate(1rad)" are returned as-is.
        result = jQuery.css(tween.elem, tween.prop, "");

        // Empty strings, null, undefined and "auto" are converted to 0.
        return !result || result === "auto" ? 0 : result;
      },
      set: function (tween) {
        // Use step hook for back compat.
        // Use cssHook if its there.
        // Use .style if available and use plain properties where available.
        if (jQuery.fx.step[tween.prop]) {
          jQuery.fx.step[tween.prop](tween);
        } else if (tween.elem.nodeType === 1 && (jQuery.cssHooks[tween.prop] || tween.elem.style[finalPropName(tween.prop)] != null)) {
          jQuery.style(tween.elem, tween.prop, tween.now + tween.unit);
        } else {
          tween.elem[tween.prop] = tween.now;
        }
      }
    }
  };

  // Support: IE <=9 only
  // Panic based approach to setting things on disconnected nodes
  Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
    set: function (tween) {
      if (tween.elem.nodeType && tween.elem.parentNode) {
        tween.elem[tween.prop] = tween.now;
      }
    }
  };
  jQuery.easing = {
    linear: function (p) {
      return p;
    },
    swing: function (p) {
      return 0.5 - Math.cos(p * Math.PI) / 2;
    },
    _default: "swing"
  };
  jQuery.fx = Tween.prototype.init;

  // Back compat <1.8 extension point
  jQuery.fx.step = {};
  var fxNow,
    inProgress,
    rfxtypes = /^(?:toggle|show|hide)$/,
    rrun = /queueHooks$/;
  function schedule() {
    if (inProgress) {
      if (document.hidden === false && window.requestAnimationFrame) {
        window.requestAnimationFrame(schedule);
      } else {
        window.setTimeout(schedule, jQuery.fx.interval);
      }
      jQuery.fx.tick();
    }
  }

  // Animations created synchronously will run synchronously
  function createFxNow() {
    window.setTimeout(function () {
      fxNow = undefined;
    });
    return fxNow = Date.now();
  }

  // Generate parameters to create a standard animation
  function genFx(type, includeWidth) {
    var which,
      i = 0,
      attrs = {
        height: type
      };

    // If we include width, step value is 1 to do all cssExpand values,
    // otherwise step value is 2 to skip over Left and Right
    includeWidth = includeWidth ? 1 : 0;
    for (; i < 4; i += 2 - includeWidth) {
      which = cssExpand[i];
      attrs["margin" + which] = attrs["padding" + which] = type;
    }
    if (includeWidth) {
      attrs.opacity = attrs.width = type;
    }
    return attrs;
  }
  function createTween(value, prop, animation) {
    var tween,
      collection = (Animation.tweeners[prop] || []).concat(Animation.tweeners["*"]),
      index = 0,
      length = collection.length;
    for (; index < length; index++) {
      if (tween = collection[index].call(animation, prop, value)) {
        // We're done with this property
        return tween;
      }
    }
  }
  function defaultPrefilter(elem, props, opts) {
    var prop,
      value,
      toggle,
      hooks,
      oldfire,
      propTween,
      restoreDisplay,
      display,
      isBox = "width" in props || "height" in props,
      anim = this,
      orig = {},
      style = elem.style,
      hidden = elem.nodeType && isHiddenWithinTree(elem),
      dataShow = dataPriv.get(elem, "fxshow");

    // Queue-skipping animations hijack the fx hooks
    if (!opts.queue) {
      hooks = jQuery._queueHooks(elem, "fx");
      if (hooks.unqueued == null) {
        hooks.unqueued = 0;
        oldfire = hooks.empty.fire;
        hooks.empty.fire = function () {
          if (!hooks.unqueued) {
            oldfire();
          }
        };
      }
      hooks.unqueued++;
      anim.always(function () {
        // Ensure the complete handler is called before this completes
        anim.always(function () {
          hooks.unqueued--;
          if (!jQuery.queue(elem, "fx").length) {
            hooks.empty.fire();
          }
        });
      });
    }

    // Detect show/hide animations
    for (prop in props) {
      value = props[prop];
      if (rfxtypes.test(value)) {
        delete props[prop];
        toggle = toggle || value === "toggle";
        if (value === (hidden ? "hide" : "show")) {
          // Pretend to be hidden if this is a "show" and
          // there is still data from a stopped show/hide
          if (value === "show" && dataShow && dataShow[prop] !== undefined) {
            hidden = true;

            // Ignore all other no-op show/hide data
          } else {
            continue;
          }
        }
        orig[prop] = dataShow && dataShow[prop] || jQuery.style(elem, prop);
      }
    }

    // Bail out if this is a no-op like .hide().hide()
    propTween = !jQuery.isEmptyObject(props);
    if (!propTween && jQuery.isEmptyObject(orig)) {
      return;
    }

    // Restrict "overflow" and "display" styles during box animations
    if (isBox && elem.nodeType === 1) {
      // Support: IE <=9 - 11, Edge 12 - 15
      // Record all 3 overflow attributes because IE does not infer the shorthand
      // from identically-valued overflowX and overflowY and Edge just mirrors
      // the overflowX value there.
      opts.overflow = [style.overflow, style.overflowX, style.overflowY];

      // Identify a display type, preferring old show/hide data over the CSS cascade
      restoreDisplay = dataShow && dataShow.display;
      if (restoreDisplay == null) {
        restoreDisplay = dataPriv.get(elem, "display");
      }
      display = jQuery.css(elem, "display");
      if (display === "none") {
        if (restoreDisplay) {
          display = restoreDisplay;
        } else {
          // Get nonempty value(s) by temporarily forcing visibility
          showHide([elem], true);
          restoreDisplay = elem.style.display || restoreDisplay;
          display = jQuery.css(elem, "display");
          showHide([elem]);
        }
      }

      // Animate inline elements as inline-block
      if (display === "inline" || display === "inline-block" && restoreDisplay != null) {
        if (jQuery.css(elem, "float") === "none") {
          // Restore the original display value at the end of pure show/hide animations
          if (!propTween) {
            anim.done(function () {
              style.display = restoreDisplay;
            });
            if (restoreDisplay == null) {
              display = style.display;
              restoreDisplay = display === "none" ? "" : display;
            }
          }
          style.display = "inline-block";
        }
      }
    }
    if (opts.overflow) {
      style.overflow = "hidden";
      anim.always(function () {
        style.overflow = opts.overflow[0];
        style.overflowX = opts.overflow[1];
        style.overflowY = opts.overflow[2];
      });
    }

    // Implement show/hide animations
    propTween = false;
    for (prop in orig) {
      // General show/hide setup for this element animation
      if (!propTween) {
        if (dataShow) {
          if ("hidden" in dataShow) {
            hidden = dataShow.hidden;
          }
        } else {
          dataShow = dataPriv.access(elem, "fxshow", {
            display: restoreDisplay
          });
        }

        // Store hidden/visible for toggle so `.stop().toggle()` "reverses"
        if (toggle) {
          dataShow.hidden = !hidden;
        }

        // Show elements before animating them
        if (hidden) {
          showHide([elem], true);
        }

        /* eslint-disable no-loop-func */

        anim.done(function () {
          /* eslint-enable no-loop-func */

          // The final step of a "hide" animation is actually hiding the element
          if (!hidden) {
            showHide([elem]);
          }
          dataPriv.remove(elem, "fxshow");
          for (prop in orig) {
            jQuery.style(elem, prop, orig[prop]);
          }
        });
      }

      // Per-property setup
      propTween = createTween(hidden ? dataShow[prop] : 0, prop, anim);
      if (!(prop in dataShow)) {
        dataShow[prop] = propTween.start;
        if (hidden) {
          propTween.end = propTween.start;
          propTween.start = 0;
        }
      }
    }
  }
  function propFilter(props, specialEasing) {
    var index, name, easing, value, hooks;

    // camelCase, specialEasing and expand cssHook pass
    for (index in props) {
      name = camelCase(index);
      easing = specialEasing[name];
      value = props[index];
      if (Array.isArray(value)) {
        easing = value[1];
        value = props[index] = value[0];
      }
      if (index !== name) {
        props[name] = value;
        delete props[index];
      }
      hooks = jQuery.cssHooks[name];
      if (hooks && "expand" in hooks) {
        value = hooks.expand(value);
        delete props[name];

        // Not quite $.extend, this won't overwrite existing keys.
        // Reusing 'index' because we have the correct "name"
        for (index in value) {
          if (!(index in props)) {
            props[index] = value[index];
            specialEasing[index] = easing;
          }
        }
      } else {
        specialEasing[name] = easing;
      }
    }
  }
  function Animation(elem, properties, options) {
    var result,
      stopped,
      index = 0,
      length = Animation.prefilters.length,
      deferred = jQuery.Deferred().always(function () {
        // Don't match elem in the :animated selector
        delete tick.elem;
      }),
      tick = function () {
        if (stopped) {
          return false;
        }
        var currentTime = fxNow || createFxNow(),
          remaining = Math.max(0, animation.startTime + animation.duration - currentTime),
          // Support: Android 2.3 only
          // Archaic crash bug won't allow us to use `1 - ( 0.5 || 0 )` (trac-12497)
          temp = remaining / animation.duration || 0,
          percent = 1 - temp,
          index = 0,
          length = animation.tweens.length;
        for (; index < length; index++) {
          animation.tweens[index].run(percent);
        }
        deferred.notifyWith(elem, [animation, percent, remaining]);

        // If there's more to do, yield
        if (percent < 1 && length) {
          return remaining;
        }

        // If this was an empty animation, synthesize a final progress notification
        if (!length) {
          deferred.notifyWith(elem, [animation, 1, 0]);
        }

        // Resolve the animation and report its conclusion
        deferred.resolveWith(elem, [animation]);
        return false;
      },
      animation = deferred.promise({
        elem: elem,
        props: jQuery.extend({}, properties),
        opts: jQuery.extend(true, {
          specialEasing: {},
          easing: jQuery.easing._default
        }, options),
        originalProperties: properties,
        originalOptions: options,
        startTime: fxNow || createFxNow(),
        duration: options.duration,
        tweens: [],
        createTween: function (prop, end) {
          var tween = jQuery.Tween(elem, animation.opts, prop, end, animation.opts.specialEasing[prop] || animation.opts.easing);
          animation.tweens.push(tween);
          return tween;
        },
        stop: function (gotoEnd) {
          var index = 0,
            // If we are going to the end, we want to run all the tweens
            // otherwise we skip this part
            length = gotoEnd ? animation.tweens.length : 0;
          if (stopped) {
            return this;
          }
          stopped = true;
          for (; index < length; index++) {
            animation.tweens[index].run(1);
          }

          // Resolve when we played the last frame; otherwise, reject
          if (gotoEnd) {
            deferred.notifyWith(elem, [animation, 1, 0]);
            deferred.resolveWith(elem, [animation, gotoEnd]);
          } else {
            deferred.rejectWith(elem, [animation, gotoEnd]);
          }
          return this;
        }
      }),
      props = animation.props;
    propFilter(props, animation.opts.specialEasing);
    for (; index < length; index++) {
      result = Animation.prefilters[index].call(animation, elem, props, animation.opts);
      if (result) {
        if (isFunction(result.stop)) {
          jQuery._queueHooks(animation.elem, animation.opts.queue).stop = result.stop.bind(result);
        }
        return result;
      }
    }
    jQuery.map(props, createTween, animation);
    if (isFunction(animation.opts.start)) {
      animation.opts.start.call(elem, animation);
    }

    // Attach callbacks from options
    animation.progress(animation.opts.progress).done(animation.opts.done, animation.opts.complete).fail(animation.opts.fail).always(animation.opts.always);
    jQuery.fx.timer(jQuery.extend(tick, {
      elem: elem,
      anim: animation,
      queue: animation.opts.queue
    }));
    return animation;
  }
  jQuery.Animation = jQuery.extend(Animation, {
    tweeners: {
      "*": [function (prop, value) {
        var tween = this.createTween(prop, value);
        adjustCSS(tween.elem, prop, rcssNum.exec(value), tween);
        return tween;
      }]
    },
    tweener: function (props, callback) {
      if (isFunction(props)) {
        callback = props;
        props = ["*"];
      } else {
        props = props.match(rnothtmlwhite);
      }
      var prop,
        index = 0,
        length = props.length;
      for (; index < length; index++) {
        prop = props[index];
        Animation.tweeners[prop] = Animation.tweeners[prop] || [];
        Animation.tweeners[prop].unshift(callback);
      }
    },
    prefilters: [defaultPrefilter],
    prefilter: function (callback, prepend) {
      if (prepend) {
        Animation.prefilters.unshift(callback);
      } else {
        Animation.prefilters.push(callback);
      }
    }
  });
  jQuery.speed = function (speed, easing, fn) {
    var opt = speed && typeof speed === "object" ? jQuery.extend({}, speed) : {
      complete: fn || !fn && easing || isFunction(speed) && speed,
      duration: speed,
      easing: fn && easing || easing && !isFunction(easing) && easing
    };

    // Go to the end state if fx are off
    if (jQuery.fx.off) {
      opt.duration = 0;
    } else {
      if (typeof opt.duration !== "number") {
        if (opt.duration in jQuery.fx.speeds) {
          opt.duration = jQuery.fx.speeds[opt.duration];
        } else {
          opt.duration = jQuery.fx.speeds._default;
        }
      }
    }

    // Normalize opt.queue - true/undefined/null -> "fx"
    if (opt.queue == null || opt.queue === true) {
      opt.queue = "fx";
    }

    // Queueing
    opt.old = opt.complete;
    opt.complete = function () {
      if (isFunction(opt.old)) {
        opt.old.call(this);
      }
      if (opt.queue) {
        jQuery.dequeue(this, opt.queue);
      }
    };
    return opt;
  };
  jQuery.fn.extend({
    fadeTo: function (speed, to, easing, callback) {
      // Show any hidden elements after setting opacity to 0
      return this.filter(isHiddenWithinTree).css("opacity", 0).show()

      // Animate to the value specified
      .end().animate({
        opacity: to
      }, speed, easing, callback);
    },
    animate: function (prop, speed, easing, callback) {
      var empty = jQuery.isEmptyObject(prop),
        optall = jQuery.speed(speed, easing, callback),
        doAnimation = function () {
          // Operate on a copy of prop so per-property easing won't be lost
          var anim = Animation(this, jQuery.extend({}, prop), optall);

          // Empty animations, or finishing resolves immediately
          if (empty || dataPriv.get(this, "finish")) {
            anim.stop(true);
          }
        };
      doAnimation.finish = doAnimation;
      return empty || optall.queue === false ? this.each(doAnimation) : this.queue(optall.queue, doAnimation);
    },
    stop: function (type, clearQueue, gotoEnd) {
      var stopQueue = function (hooks) {
        var stop = hooks.stop;
        delete hooks.stop;
        stop(gotoEnd);
      };
      if (typeof type !== "string") {
        gotoEnd = clearQueue;
        clearQueue = type;
        type = undefined;
      }
      if (clearQueue) {
        this.queue(type || "fx", []);
      }
      return this.each(function () {
        var dequeue = true,
          index = type != null && type + "queueHooks",
          timers = jQuery.timers,
          data = dataPriv.get(this);
        if (index) {
          if (data[index] && data[index].stop) {
            stopQueue(data[index]);
          }
        } else {
          for (index in data) {
            if (data[index] && data[index].stop && rrun.test(index)) {
              stopQueue(data[index]);
            }
          }
        }
        for (index = timers.length; index--;) {
          if (timers[index].elem === this && (type == null || timers[index].queue === type)) {
            timers[index].anim.stop(gotoEnd);
            dequeue = false;
            timers.splice(index, 1);
          }
        }

        // Start the next in the queue if the last step wasn't forced.
        // Timers currently will call their complete callbacks, which
        // will dequeue but only if they were gotoEnd.
        if (dequeue || !gotoEnd) {
          jQuery.dequeue(this, type);
        }
      });
    },
    finish: function (type) {
      if (type !== false) {
        type = type || "fx";
      }
      return this.each(function () {
        var index,
          data = dataPriv.get(this),
          queue = data[type + "queue"],
          hooks = data[type + "queueHooks"],
          timers = jQuery.timers,
          length = queue ? queue.length : 0;

        // Enable finishing flag on private data
        data.finish = true;

        // Empty the queue first
        jQuery.queue(this, type, []);
        if (hooks && hooks.stop) {
          hooks.stop.call(this, true);
        }

        // Look for any active animations, and finish them
        for (index = timers.length; index--;) {
          if (timers[index].elem === this && timers[index].queue === type) {
            timers[index].anim.stop(true);
            timers.splice(index, 1);
          }
        }

        // Look for any animations in the old queue and finish them
        for (index = 0; index < length; index++) {
          if (queue[index] && queue[index].finish) {
            queue[index].finish.call(this);
          }
        }

        // Turn off finishing flag
        delete data.finish;
      });
    }
  });
  jQuery.each(["toggle", "show", "hide"], function (_i, name) {
    var cssFn = jQuery.fn[name];
    jQuery.fn[name] = function (speed, easing, callback) {
      return speed == null || typeof speed === "boolean" ? cssFn.apply(this, arguments) : this.animate(genFx(name, true), speed, easing, callback);
    };
  });

  // Generate shortcuts for custom animations
  jQuery.each({
    slideDown: genFx("show"),
    slideUp: genFx("hide"),
    slideToggle: genFx("toggle"),
    fadeIn: {
      opacity: "show"
    },
    fadeOut: {
      opacity: "hide"
    },
    fadeToggle: {
      opacity: "toggle"
    }
  }, function (name, props) {
    jQuery.fn[name] = function (speed, easing, callback) {
      return this.animate(props, speed, easing, callback);
    };
  });
  jQuery.timers = [];
  jQuery.fx.tick = function () {
    var timer,
      i = 0,
      timers = jQuery.timers;
    fxNow = Date.now();
    for (; i < timers.length; i++) {
      timer = timers[i];

      // Run the timer and safely remove it when done (allowing for external removal)
      if (!timer() && timers[i] === timer) {
        timers.splice(i--, 1);
      }
    }
    if (!timers.length) {
      jQuery.fx.stop();
    }
    fxNow = undefined;
  };
  jQuery.fx.timer = function (timer) {
    jQuery.timers.push(timer);
    jQuery.fx.start();
  };
  jQuery.fx.interval = 13;
  jQuery.fx.start = function () {
    if (inProgress) {
      return;
    }
    inProgress = true;
    schedule();
  };
  jQuery.fx.stop = function () {
    inProgress = null;
  };
  jQuery.fx.speeds = {
    slow: 600,
    fast: 200,
    // Default speed
    _default: 400
  };

  // Based off of the plugin by Clint Helfers, with permission.
  jQuery.fn.delay = function (time, type) {
    time = jQuery.fx ? jQuery.fx.speeds[time] || time : time;
    type = type || "fx";
    return this.queue(type, function (next, hooks) {
      var timeout = window.setTimeout(next, time);
      hooks.stop = function () {
        window.clearTimeout(timeout);
      };
    });
  };
  (function () {
    var input = document.createElement("input"),
      select = document.createElement("select"),
      opt = select.appendChild(document.createElement("option"));
    input.type = "checkbox";

    // Support: Android <=4.3 only
    // Default value for a checkbox should be "on"
    support.checkOn = input.value !== "";

    // Support: IE <=11 only
    // Must access selectedIndex to make default options select
    support.optSelected = opt.selected;

    // Support: IE <=11 only
    // An input loses its value after becoming a radio
    input = document.createElement("input");
    input.value = "t";
    input.type = "radio";
    support.radioValue = input.value === "t";
  })();
  var boolHook,
    attrHandle = jQuery.expr.attrHandle;
  jQuery.fn.extend({
    attr: function (name, value) {
      return access(this, jQuery.attr, name, value, arguments.length > 1);
    },
    removeAttr: function (name) {
      return this.each(function () {
        jQuery.removeAttr(this, name);
      });
    }
  });
  jQuery.extend({
    attr: function (elem, name, value) {
      var ret,
        hooks,
        nType = elem.nodeType;

      // Don't get/set attributes on text, comment and attribute nodes
      if (nType === 3 || nType === 8 || nType === 2) {
        return;
      }

      // Fallback to prop when attributes are not supported
      if (typeof elem.getAttribute === "undefined") {
        return jQuery.prop(elem, name, value);
      }

      // Attribute hooks are determined by the lowercase version
      // Grab necessary hook if one is defined
      if (nType !== 1 || !jQuery.isXMLDoc(elem)) {
        hooks = jQuery.attrHooks[name.toLowerCase()] || (jQuery.expr.match.bool.test(name) ? boolHook : undefined);
      }
      if (value !== undefined) {
        if (value === null) {
          jQuery.removeAttr(elem, name);
          return;
        }
        if (hooks && "set" in hooks && (ret = hooks.set(elem, value, name)) !== undefined) {
          return ret;
        }
        elem.setAttribute(name, value + "");
        return value;
      }
      if (hooks && "get" in hooks && (ret = hooks.get(elem, name)) !== null) {
        return ret;
      }
      ret = jQuery.find.attr(elem, name);

      // Non-existent attributes return null, we normalize to undefined
      return ret == null ? undefined : ret;
    },
    attrHooks: {
      type: {
        set: function (elem, value) {
          if (!support.radioValue && value === "radio" && nodeName(elem, "input")) {
            var val = elem.value;
            elem.setAttribute("type", value);
            if (val) {
              elem.value = val;
            }
            return value;
          }
        }
      }
    },
    removeAttr: function (elem, value) {
      var name,
        i = 0,
        // Attribute names can contain non-HTML whitespace characters
        // https://html.spec.whatwg.org/multipage/syntax.html#attributes-2
        attrNames = value && value.match(rnothtmlwhite);
      if (attrNames && elem.nodeType === 1) {
        while (name = attrNames[i++]) {
          elem.removeAttribute(name);
        }
      }
    }
  });

  // Hooks for boolean attributes
  boolHook = {
    set: function (elem, value, name) {
      if (value === false) {
        // Remove boolean attributes when set to false
        jQuery.removeAttr(elem, name);
      } else {
        elem.setAttribute(name, name);
      }
      return name;
    }
  };
  jQuery.each(jQuery.expr.match.bool.source.match(/\w+/g), function (_i, name) {
    var getter = attrHandle[name] || jQuery.find.attr;
    attrHandle[name] = function (elem, name, isXML) {
      var ret,
        handle,
        lowercaseName = name.toLowerCase();
      if (!isXML) {
        // Avoid an infinite loop by temporarily removing this function from the getter
        handle = attrHandle[lowercaseName];
        attrHandle[lowercaseName] = ret;
        ret = getter(elem, name, isXML) != null ? lowercaseName : null;
        attrHandle[lowercaseName] = handle;
      }
      return ret;
    };
  });
  var rfocusable = /^(?:input|select|textarea|button)$/i,
    rclickable = /^(?:a|area)$/i;
  jQuery.fn.extend({
    prop: function (name, value) {
      return access(this, jQuery.prop, name, value, arguments.length > 1);
    },
    removeProp: function (name) {
      return this.each(function () {
        delete this[jQuery.propFix[name] || name];
      });
    }
  });
  jQuery.extend({
    prop: function (elem, name, value) {
      var ret,
        hooks,
        nType = elem.nodeType;

      // Don't get/set properties on text, comment and attribute nodes
      if (nType === 3 || nType === 8 || nType === 2) {
        return;
      }
      if (nType !== 1 || !jQuery.isXMLDoc(elem)) {
        // Fix name and attach hooks
        name = jQuery.propFix[name] || name;
        hooks = jQuery.propHooks[name];
      }
      if (value !== undefined) {
        if (hooks && "set" in hooks && (ret = hooks.set(elem, value, name)) !== undefined) {
          return ret;
        }
        return elem[name] = value;
      }
      if (hooks && "get" in hooks && (ret = hooks.get(elem, name)) !== null) {
        return ret;
      }
      return elem[name];
    },
    propHooks: {
      tabIndex: {
        get: function (elem) {
          // Support: IE <=9 - 11 only
          // elem.tabIndex doesn't always return the
          // correct value when it hasn't been explicitly set
          // Use proper attribute retrieval (trac-12072)
          var tabindex = jQuery.find.attr(elem, "tabindex");
          if (tabindex) {
            return parseInt(tabindex, 10);
          }
          if (rfocusable.test(elem.nodeName) || rclickable.test(elem.nodeName) && elem.href) {
            return 0;
          }
          return -1;
        }
      }
    },
    propFix: {
      "for": "htmlFor",
      "class": "className"
    }
  });

  // Support: IE <=11 only
  // Accessing the selectedIndex property
  // forces the browser to respect setting selected
  // on the option
  // The getter ensures a default option is selected
  // when in an optgroup
  // eslint rule "no-unused-expressions" is disabled for this code
  // since it considers such accessions noop
  if (!support.optSelected) {
    jQuery.propHooks.selected = {
      get: function (elem) {
        /* eslint no-unused-expressions: "off" */

        var parent = elem.parentNode;
        if (parent && parent.parentNode) {
          parent.parentNode.selectedIndex;
        }
        return null;
      },
      set: function (elem) {
        /* eslint no-unused-expressions: "off" */

        var parent = elem.parentNode;
        if (parent) {
          parent.selectedIndex;
          if (parent.parentNode) {
            parent.parentNode.selectedIndex;
          }
        }
      }
    };
  }
  jQuery.each(["tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable"], function () {
    jQuery.propFix[this.toLowerCase()] = this;
  });

  // Strip and collapse whitespace according to HTML spec
  // https://infra.spec.whatwg.org/#strip-and-collapse-ascii-whitespace
  function stripAndCollapse(value) {
    var tokens = value.match(rnothtmlwhite) || [];
    return tokens.join(" ");
  }
  function getClass(elem) {
    return elem.getAttribute && elem.getAttribute("class") || "";
  }
  function classesToArray(value) {
    if (Array.isArray(value)) {
      return value;
    }
    if (typeof value === "string") {
      return value.match(rnothtmlwhite) || [];
    }
    return [];
  }
  jQuery.fn.extend({
    addClass: function (value) {
      var classNames, cur, curValue, className, i, finalValue;
      if (isFunction(value)) {
        return this.each(function (j) {
          jQuery(this).addClass(value.call(this, j, getClass(this)));
        });
      }
      classNames = classesToArray(value);
      if (classNames.length) {
        return this.each(function () {
          curValue = getClass(this);
          cur = this.nodeType === 1 && " " + stripAndCollapse(curValue) + " ";
          if (cur) {
            for (i = 0; i < classNames.length; i++) {
              className = classNames[i];
              if (cur.indexOf(" " + className + " ") < 0) {
                cur += className + " ";
              }
            }

            // Only assign if different to avoid unneeded rendering.
            finalValue = stripAndCollapse(cur);
            if (curValue !== finalValue) {
              this.setAttribute("class", finalValue);
            }
          }
        });
      }
      return this;
    },
    removeClass: function (value) {
      var classNames, cur, curValue, className, i, finalValue;
      if (isFunction(value)) {
        return this.each(function (j) {
          jQuery(this).removeClass(value.call(this, j, getClass(this)));
        });
      }
      if (!arguments.length) {
        return this.attr("class", "");
      }
      classNames = classesToArray(value);
      if (classNames.length) {
        return this.each(function () {
          curValue = getClass(this);

          // This expression is here for better compressibility (see addClass)
          cur = this.nodeType === 1 && " " + stripAndCollapse(curValue) + " ";
          if (cur) {
            for (i = 0; i < classNames.length; i++) {
              className = classNames[i];

              // Remove *all* instances
              while (cur.indexOf(" " + className + " ") > -1) {
                cur = cur.replace(" " + className + " ", " ");
              }
            }

            // Only assign if different to avoid unneeded rendering.
            finalValue = stripAndCollapse(cur);
            if (curValue !== finalValue) {
              this.setAttribute("class", finalValue);
            }
          }
        });
      }
      return this;
    },
    toggleClass: function (value, stateVal) {
      var classNames,
        className,
        i,
        self,
        type = typeof value,
        isValidValue = type === "string" || Array.isArray(value);
      if (isFunction(value)) {
        return this.each(function (i) {
          jQuery(this).toggleClass(value.call(this, i, getClass(this), stateVal), stateVal);
        });
      }
      if (typeof stateVal === "boolean" && isValidValue) {
        return stateVal ? this.addClass(value) : this.removeClass(value);
      }
      classNames = classesToArray(value);
      return this.each(function () {
        if (isValidValue) {
          // Toggle individual class names
          self = jQuery(this);
          for (i = 0; i < classNames.length; i++) {
            className = classNames[i];

            // Check each className given, space separated list
            if (self.hasClass(className)) {
              self.removeClass(className);
            } else {
              self.addClass(className);
            }
          }

          // Toggle whole class name
        } else if (value === undefined || type === "boolean") {
          className = getClass(this);
          if (className) {
            // Store className if set
            dataPriv.set(this, "__className__", className);
          }

          // If the element has a class name or if we're passed `false`,
          // then remove the whole classname (if there was one, the above saved it).
          // Otherwise bring back whatever was previously saved (if anything),
          // falling back to the empty string if nothing was stored.
          if (this.setAttribute) {
            this.setAttribute("class", className || value === false ? "" : dataPriv.get(this, "__className__") || "");
          }
        }
      });
    },
    hasClass: function (selector) {
      var className,
        elem,
        i = 0;
      className = " " + selector + " ";
      while (elem = this[i++]) {
        if (elem.nodeType === 1 && (" " + stripAndCollapse(getClass(elem)) + " ").indexOf(className) > -1) {
          return true;
        }
      }
      return false;
    }
  });
  var rreturn = /\r/g;
  jQuery.fn.extend({
    val: function (value) {
      var hooks,
        ret,
        valueIsFunction,
        elem = this[0];
      if (!arguments.length) {
        if (elem) {
          hooks = jQuery.valHooks[elem.type] || jQuery.valHooks[elem.nodeName.toLowerCase()];
          if (hooks && "get" in hooks && (ret = hooks.get(elem, "value")) !== undefined) {
            return ret;
          }
          ret = elem.value;

          // Handle most common string cases
          if (typeof ret === "string") {
            return ret.replace(rreturn, "");
          }

          // Handle cases where value is null/undef or number
          return ret == null ? "" : ret;
        }
        return;
      }
      valueIsFunction = isFunction(value);
      return this.each(function (i) {
        var val;
        if (this.nodeType !== 1) {
          return;
        }
        if (valueIsFunction) {
          val = value.call(this, i, jQuery(this).val());
        } else {
          val = value;
        }

        // Treat null/undefined as ""; convert numbers to string
        if (val == null) {
          val = "";
        } else if (typeof val === "number") {
          val += "";
        } else if (Array.isArray(val)) {
          val = jQuery.map(val, function (value) {
            return value == null ? "" : value + "";
          });
        }
        hooks = jQuery.valHooks[this.type] || jQuery.valHooks[this.nodeName.toLowerCase()];

        // If set returns undefined, fall back to normal setting
        if (!hooks || !("set" in hooks) || hooks.set(this, val, "value") === undefined) {
          this.value = val;
        }
      });
    }
  });
  jQuery.extend({
    valHooks: {
      option: {
        get: function (elem) {
          var val = jQuery.find.attr(elem, "value");
          return val != null ? val :
          // Support: IE <=10 - 11 only
          // option.text throws exceptions (trac-14686, trac-14858)
          // Strip and collapse whitespace
          // https://html.spec.whatwg.org/#strip-and-collapse-whitespace
          stripAndCollapse(jQuery.text(elem));
        }
      },
      select: {
        get: function (elem) {
          var value,
            option,
            i,
            options = elem.options,
            index = elem.selectedIndex,
            one = elem.type === "select-one",
            values = one ? null : [],
            max = one ? index + 1 : options.length;
          if (index < 0) {
            i = max;
          } else {
            i = one ? index : 0;
          }

          // Loop through all the selected options
          for (; i < max; i++) {
            option = options[i];

            // Support: IE <=9 only
            // IE8-9 doesn't update selected after form reset (trac-2551)
            if ((option.selected || i === index) &&
            // Don't return options that are disabled or in a disabled optgroup
            !option.disabled && (!option.parentNode.disabled || !nodeName(option.parentNode, "optgroup"))) {
              // Get the specific value for the option
              value = jQuery(option).val();

              // We don't need an array for one selects
              if (one) {
                return value;
              }

              // Multi-Selects return an array
              values.push(value);
            }
          }
          return values;
        },
        set: function (elem, value) {
          var optionSet,
            option,
            options = elem.options,
            values = jQuery.makeArray(value),
            i = options.length;
          while (i--) {
            option = options[i];

            /* eslint-disable no-cond-assign */

            if (option.selected = jQuery.inArray(jQuery.valHooks.option.get(option), values) > -1) {
              optionSet = true;
            }

            /* eslint-enable no-cond-assign */
          }

          // Force browsers to behave consistently when non-matching value is set
          if (!optionSet) {
            elem.selectedIndex = -1;
          }
          return values;
        }
      }
    }
  });

  // Radios and checkboxes getter/setter
  jQuery.each(["radio", "checkbox"], function () {
    jQuery.valHooks[this] = {
      set: function (elem, value) {
        if (Array.isArray(value)) {
          return elem.checked = jQuery.inArray(jQuery(elem).val(), value) > -1;
        }
      }
    };
    if (!support.checkOn) {
      jQuery.valHooks[this].get = function (elem) {
        return elem.getAttribute("value") === null ? "on" : elem.value;
      };
    }
  });

  // Return jQuery for attributes-only inclusion
  var location = window.location;
  var nonce = {
    guid: Date.now()
  };
  var rquery = /\?/;

  // Cross-browser xml parsing
  jQuery.parseXML = function (data) {
    var xml, parserErrorElem;
    if (!data || typeof data !== "string") {
      return null;
    }

    // Support: IE 9 - 11 only
    // IE throws on parseFromString with invalid input.
    try {
      xml = new window.DOMParser().parseFromString(data, "text/xml");
    } catch (e) {}
    parserErrorElem = xml && xml.getElementsByTagName("parsererror")[0];
    if (!xml || parserErrorElem) {
      jQuery.error("Invalid XML: " + (parserErrorElem ? jQuery.map(parserErrorElem.childNodes, function (el) {
        return el.textContent;
      }).join("\n") : data));
    }
    return xml;
  };
  var rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
    stopPropagationCallback = function (e) {
      e.stopPropagation();
    };
  jQuery.extend(jQuery.event, {
    trigger: function (event, data, elem, onlyHandlers) {
      var i,
        cur,
        tmp,
        bubbleType,
        ontype,
        handle,
        special,
        lastElement,
        eventPath = [elem || document],
        type = hasOwn.call(event, "type") ? event.type : event,
        namespaces = hasOwn.call(event, "namespace") ? event.namespace.split(".") : [];
      cur = lastElement = tmp = elem = elem || document;

      // Don't do events on text and comment nodes
      if (elem.nodeType === 3 || elem.nodeType === 8) {
        return;
      }

      // focus/blur morphs to focusin/out; ensure we're not firing them right now
      if (rfocusMorph.test(type + jQuery.event.triggered)) {
        return;
      }
      if (type.indexOf(".") > -1) {
        // Namespaced trigger; create a regexp to match event type in handle()
        namespaces = type.split(".");
        type = namespaces.shift();
        namespaces.sort();
      }
      ontype = type.indexOf(":") < 0 && "on" + type;

      // Caller can pass in a jQuery.Event object, Object, or just an event type string
      event = event[jQuery.expando] ? event : new jQuery.Event(type, typeof event === "object" && event);

      // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true)
      event.isTrigger = onlyHandlers ? 2 : 3;
      event.namespace = namespaces.join(".");
      event.rnamespace = event.namespace ? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)") : null;

      // Clean up the event in case it is being reused
      event.result = undefined;
      if (!event.target) {
        event.target = elem;
      }

      // Clone any incoming data and prepend the event, creating the handler arg list
      data = data == null ? [event] : jQuery.makeArray(data, [event]);

      // Allow special events to draw outside the lines
      special = jQuery.event.special[type] || {};
      if (!onlyHandlers && special.trigger && special.trigger.apply(elem, data) === false) {
        return;
      }

      // Determine event propagation path in advance, per W3C events spec (trac-9951)
      // Bubble up to document, then to window; watch for a global ownerDocument var (trac-9724)
      if (!onlyHandlers && !special.noBubble && !isWindow(elem)) {
        bubbleType = special.delegateType || type;
        if (!rfocusMorph.test(bubbleType + type)) {
          cur = cur.parentNode;
        }
        for (; cur; cur = cur.parentNode) {
          eventPath.push(cur);
          tmp = cur;
        }

        // Only add window if we got to document (e.g., not plain obj or detached DOM)
        if (tmp === (elem.ownerDocument || document)) {
          eventPath.push(tmp.defaultView || tmp.parentWindow || window);
        }
      }

      // Fire handlers on the event path
      i = 0;
      while ((cur = eventPath[i++]) && !event.isPropagationStopped()) {
        lastElement = cur;
        event.type = i > 1 ? bubbleType : special.bindType || type;

        // jQuery handler
        handle = (dataPriv.get(cur, "events") || Object.create(null))[event.type] && dataPriv.get(cur, "handle");
        if (handle) {
          handle.apply(cur, data);
        }

        // Native handler
        handle = ontype && cur[ontype];
        if (handle && handle.apply && acceptData(cur)) {
          event.result = handle.apply(cur, data);
          if (event.result === false) {
            event.preventDefault();
          }
        }
      }
      event.type = type;

      // If nobody prevented the default action, do it now
      if (!onlyHandlers && !event.isDefaultPrevented()) {
        if ((!special._default || special._default.apply(eventPath.pop(), data) === false) && acceptData(elem)) {
          // Call a native DOM method on the target with the same name as the event.
          // Don't do default actions on window, that's where global variables be (trac-6170)
          if (ontype && isFunction(elem[type]) && !isWindow(elem)) {
            // Don't re-trigger an onFOO event when we call its FOO() method
            tmp = elem[ontype];
            if (tmp) {
              elem[ontype] = null;
            }

            // Prevent re-triggering of the same event, since we already bubbled it above
            jQuery.event.triggered = type;
            if (event.isPropagationStopped()) {
              lastElement.addEventListener(type, stopPropagationCallback);
            }
            elem[type]();
            if (event.isPropagationStopped()) {
              lastElement.removeEventListener(type, stopPropagationCallback);
            }
            jQuery.event.triggered = undefined;
            if (tmp) {
              elem[ontype] = tmp;
            }
          }
        }
      }
      return event.result;
    },
    // Piggyback on a donor event to simulate a different one
    // Used only for `focus(in | out)` events
    simulate: function (type, elem, event) {
      var e = jQuery.extend(new jQuery.Event(), event, {
        type: type,
        isSimulated: true
      });
      jQuery.event.trigger(e, null, elem);
    }
  });
  jQuery.fn.extend({
    trigger: function (type, data) {
      return this.each(function () {
        jQuery.event.trigger(type, data, this);
      });
    },
    triggerHandler: function (type, data) {
      var elem = this[0];
      if (elem) {
        return jQuery.event.trigger(type, data, elem, true);
      }
    }
  });
  var rbracket = /\[\]$/,
    rCRLF = /\r?\n/g,
    rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
    rsubmittable = /^(?:input|select|textarea|keygen)/i;
  function buildParams(prefix, obj, traditional, add) {
    var name;
    if (Array.isArray(obj)) {
      // Serialize array item.
      jQuery.each(obj, function (i, v) {
        if (traditional || rbracket.test(prefix)) {
          // Treat each array item as a scalar.
          add(prefix, v);
        } else {
          // Item is non-scalar (array or object), encode its numeric index.
          buildParams(prefix + "[" + (typeof v === "object" && v != null ? i : "") + "]", v, traditional, add);
        }
      });
    } else if (!traditional && toType(obj) === "object") {
      // Serialize object item.
      for (name in obj) {
        buildParams(prefix + "[" + name + "]", obj[name], traditional, add);
      }
    } else {
      // Serialize scalar item.
      add(prefix, obj);
    }
  }

  // Serialize an array of form elements or a set of
  // key/values into a query string
  jQuery.param = function (a, traditional) {
    var prefix,
      s = [],
      add = function (key, valueOrFunction) {
        // If value is a function, invoke it and use its return value
        var value = isFunction(valueOrFunction) ? valueOrFunction() : valueOrFunction;
        s[s.length] = encodeURIComponent(key) + "=" + encodeURIComponent(value == null ? "" : value);
      };
    if (a == null) {
      return "";
    }

    // If an array was passed in, assume that it is an array of form elements.
    if (Array.isArray(a) || a.jquery && !jQuery.isPlainObject(a)) {
      // Serialize the form elements
      jQuery.each(a, function () {
        add(this.name, this.value);
      });
    } else {
      // If traditional, encode the "old" way (the way 1.3.2 or older
      // did it), otherwise encode params recursively.
      for (prefix in a) {
        buildParams(prefix, a[prefix], traditional, add);
      }
    }

    // Return the resulting serialization
    return s.join("&");
  };
  jQuery.fn.extend({
    serialize: function () {
      return jQuery.param(this.serializeArray());
    },
    serializeArray: function () {
      return this.map(function () {
        // Can add propHook for "elements" to filter or add form elements
        var elements = jQuery.prop(this, "elements");
        return elements ? jQuery.makeArray(elements) : this;
      }).filter(function () {
        var type = this.type;

        // Use .is( ":disabled" ) so that fieldset[disabled] works
        return this.name && !jQuery(this).is(":disabled") && rsubmittable.test(this.nodeName) && !rsubmitterTypes.test(type) && (this.checked || !rcheckableType.test(type));
      }).map(function (_i, elem) {
        var val = jQuery(this).val();
        if (val == null) {
          return null;
        }
        if (Array.isArray(val)) {
          return jQuery.map(val, function (val) {
            return {
              name: elem.name,
              value: val.replace(rCRLF, "\r\n")
            };
          });
        }
        return {
          name: elem.name,
          value: val.replace(rCRLF, "\r\n")
        };
      }).get();
    }
  });
  var r20 = /%20/g,
    rhash = /#.*$/,
    rantiCache = /([?&])_=[^&]*/,
    rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg,
    // trac-7653, trac-8125, trac-8152: local protocol detection
    rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
    rnoContent = /^(?:GET|HEAD)$/,
    rprotocol = /^\/\//,
    /* Prefilters
     * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
     * 2) These are called:
     *    - BEFORE asking for a transport
     *    - AFTER param serialization (s.data is a string if s.processData is true)
     * 3) key is the dataType
     * 4) the catchall symbol "*" can be used
     * 5) execution will start with transport dataType and THEN continue down to "*" if needed
     */
    prefilters = {},
    /* Transports bindings
     * 1) key is the dataType
     * 2) the catchall symbol "*" can be used
     * 3) selection will start with transport dataType and THEN go to "*" if needed
     */
    transports = {},
    // Avoid comment-prolog char sequence (trac-10098); must appease lint and evade compression
    allTypes = "*/".concat("*"),
    // Anchor tag for parsing the document origin
    originAnchor = document.createElement("a");
  originAnchor.href = location.href;

  // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
  function addToPrefiltersOrTransports(structure) {
    // dataTypeExpression is optional and defaults to "*"
    return function (dataTypeExpression, func) {
      if (typeof dataTypeExpression !== "string") {
        func = dataTypeExpression;
        dataTypeExpression = "*";
      }
      var dataType,
        i = 0,
        dataTypes = dataTypeExpression.toLowerCase().match(rnothtmlwhite) || [];
      if (isFunction(func)) {
        // For each dataType in the dataTypeExpression
        while (dataType = dataTypes[i++]) {
          // Prepend if requested
          if (dataType[0] === "+") {
            dataType = dataType.slice(1) || "*";
            (structure[dataType] = structure[dataType] || []).unshift(func);

            // Otherwise append
          } else {
            (structure[dataType] = structure[dataType] || []).push(func);
          }
        }
      }
    };
  }

  // Base inspection function for prefilters and transports
  function inspectPrefiltersOrTransports(structure, options, originalOptions, jqXHR) {
    var inspected = {},
      seekingTransport = structure === transports;
    function inspect(dataType) {
      var selected;
      inspected[dataType] = true;
      jQuery.each(structure[dataType] || [], function (_, prefilterOrFactory) {
        var dataTypeOrTransport = prefilterOrFactory(options, originalOptions, jqXHR);
        if (typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[dataTypeOrTransport]) {
          options.dataTypes.unshift(dataTypeOrTransport);
          inspect(dataTypeOrTransport);
          return false;
        } else if (seekingTransport) {
          return !(selected = dataTypeOrTransport);
        }
      });
      return selected;
    }
    return inspect(options.dataTypes[0]) || !inspected["*"] && inspect("*");
  }

  // A special extend for ajax options
  // that takes "flat" options (not to be deep extended)
  // Fixes trac-9887
  function ajaxExtend(target, src) {
    var key,
      deep,
      flatOptions = jQuery.ajaxSettings.flatOptions || {};
    for (key in src) {
      if (src[key] !== undefined) {
        (flatOptions[key] ? target : deep || (deep = {}))[key] = src[key];
      }
    }
    if (deep) {
      jQuery.extend(true, target, deep);
    }
    return target;
  }

  /* Handles responses to an ajax request:
   * - finds the right dataType (mediates between content-type and expected dataType)
   * - returns the corresponding response
   */
  function ajaxHandleResponses(s, jqXHR, responses) {
    var ct,
      type,
      finalDataType,
      firstDataType,
      contents = s.contents,
      dataTypes = s.dataTypes;

    // Remove auto dataType and get content-type in the process
    while (dataTypes[0] === "*") {
      dataTypes.shift();
      if (ct === undefined) {
        ct = s.mimeType || jqXHR.getResponseHeader("Content-Type");
      }
    }

    // Check if we're dealing with a known content-type
    if (ct) {
      for (type in contents) {
        if (contents[type] && contents[type].test(ct)) {
          dataTypes.unshift(type);
          break;
        }
      }
    }

    // Check to see if we have a response for the expected dataType
    if (dataTypes[0] in responses) {
      finalDataType = dataTypes[0];
    } else {
      // Try convertible dataTypes
      for (type in responses) {
        if (!dataTypes[0] || s.converters[type + " " + dataTypes[0]]) {
          finalDataType = type;
          break;
        }
        if (!firstDataType) {
          firstDataType = type;
        }
      }

      // Or just use first one
      finalDataType = finalDataType || firstDataType;
    }

    // If we found a dataType
    // We add the dataType to the list if needed
    // and return the corresponding response
    if (finalDataType) {
      if (finalDataType !== dataTypes[0]) {
        dataTypes.unshift(finalDataType);
      }
      return responses[finalDataType];
    }
  }

  /* Chain conversions given the request and the original response
   * Also sets the responseXXX fields on the jqXHR instance
   */
  function ajaxConvert(s, response, jqXHR, isSuccess) {
    var conv2,
      current,
      conv,
      tmp,
      prev,
      converters = {},
      // Work with a copy of dataTypes in case we need to modify it for conversion
      dataTypes = s.dataTypes.slice();

    // Create converters map with lowercased keys
    if (dataTypes[1]) {
      for (conv in s.converters) {
        converters[conv.toLowerCase()] = s.converters[conv];
      }
    }
    current = dataTypes.shift();

    // Convert to each sequential dataType
    while (current) {
      if (s.responseFields[current]) {
        jqXHR[s.responseFields[current]] = response;
      }

      // Apply the dataFilter if provided
      if (!prev && isSuccess && s.dataFilter) {
        response = s.dataFilter(response, s.dataType);
      }
      prev = current;
      current = dataTypes.shift();
      if (current) {
        // There's only work to do if current dataType is non-auto
        if (current === "*") {
          current = prev;

          // Convert response if prev dataType is non-auto and differs from current
        } else if (prev !== "*" && prev !== current) {
          // Seek a direct converter
          conv = converters[prev + " " + current] || converters["* " + current];

          // If none found, seek a pair
          if (!conv) {
            for (conv2 in converters) {
              // If conv2 outputs current
              tmp = conv2.split(" ");
              if (tmp[1] === current) {
                // If prev can be converted to accepted input
                conv = converters[prev + " " + tmp[0]] || converters["* " + tmp[0]];
                if (conv) {
                  // Condense equivalence converters
                  if (conv === true) {
                    conv = converters[conv2];

                    // Otherwise, insert the intermediate dataType
                  } else if (converters[conv2] !== true) {
                    current = tmp[0];
                    dataTypes.unshift(tmp[1]);
                  }
                  break;
                }
              }
            }
          }

          // Apply converter (if not an equivalence)
          if (conv !== true) {
            // Unless errors are allowed to bubble, catch and return them
            if (conv && s.throws) {
              response = conv(response);
            } else {
              try {
                response = conv(response);
              } catch (e) {
                return {
                  state: "parsererror",
                  error: conv ? e : "No conversion from " + prev + " to " + current
                };
              }
            }
          }
        }
      }
    }
    return {
      state: "success",
      data: response
    };
  }
  jQuery.extend({
    // Counter for holding the number of active queries
    active: 0,
    // Last-Modified header cache for next request
    lastModified: {},
    etag: {},
    ajaxSettings: {
      url: location.href,
      type: "GET",
      isLocal: rlocalProtocol.test(location.protocol),
      global: true,
      processData: true,
      async: true,
      contentType: "application/x-www-form-urlencoded; charset=UTF-8",
      /*
      timeout: 0,
      data: null,
      dataType: null,
      username: null,
      password: null,
      cache: null,
      throws: false,
      traditional: false,
      headers: {},
      */

      accepts: {
        "*": allTypes,
        text: "text/plain",
        html: "text/html",
        xml: "application/xml, text/xml",
        json: "application/json, text/javascript"
      },
      contents: {
        xml: /\bxml\b/,
        html: /\bhtml/,
        json: /\bjson\b/
      },
      responseFields: {
        xml: "responseXML",
        text: "responseText",
        json: "responseJSON"
      },
      // Data converters
      // Keys separate source (or catchall "*") and destination types with a single space
      converters: {
        // Convert anything to text
        "* text": String,
        // Text to html (true = no transformation)
        "text html": true,
        // Evaluate text as a json expression
        "text json": JSON.parse,
        // Parse text as xml
        "text xml": jQuery.parseXML
      },
      // For options that shouldn't be deep extended:
      // you can add your own custom options here if
      // and when you create one that shouldn't be
      // deep extended (see ajaxExtend)
      flatOptions: {
        url: true,
        context: true
      }
    },
    // Creates a full fledged settings object into target
    // with both ajaxSettings and settings fields.
    // If target is omitted, writes into ajaxSettings.
    ajaxSetup: function (target, settings) {
      return settings ?
      // Building a settings object
      ajaxExtend(ajaxExtend(target, jQuery.ajaxSettings), settings) :
      // Extending ajaxSettings
      ajaxExtend(jQuery.ajaxSettings, target);
    },
    ajaxPrefilter: addToPrefiltersOrTransports(prefilters),
    ajaxTransport: addToPrefiltersOrTransports(transports),
    // Main method
    ajax: function (url, options) {
      // If url is an object, simulate pre-1.5 signature
      if (typeof url === "object") {
        options = url;
        url = undefined;
      }

      // Force options to be an object
      options = options || {};
      var transport,
        // URL without anti-cache param
        cacheURL,
        // Response headers
        responseHeadersString,
        responseHeaders,
        // timeout handle
        timeoutTimer,
        // Url cleanup var
        urlAnchor,
        // Request state (becomes false upon send and true upon completion)
        completed,
        // To know if global events are to be dispatched
        fireGlobals,
        // Loop variable
        i,
        // uncached part of the url
        uncached,
        // Create the final options object
        s = jQuery.ajaxSetup({}, options),
        // Callbacks context
        callbackContext = s.context || s,
        // Context for global events is callbackContext if it is a DOM node or jQuery collection
        globalEventContext = s.context && (callbackContext.nodeType || callbackContext.jquery) ? jQuery(callbackContext) : jQuery.event,
        // Deferreds
        deferred = jQuery.Deferred(),
        completeDeferred = jQuery.Callbacks("once memory"),
        // Status-dependent callbacks
        statusCode = s.statusCode || {},
        // Headers (they are sent all at once)
        requestHeaders = {},
        requestHeadersNames = {},
        // Default abort message
        strAbort = "canceled",
        // Fake xhr
        jqXHR = {
          readyState: 0,
          // Builds headers hashtable if needed
          getResponseHeader: function (key) {
            var match;
            if (completed) {
              if (!responseHeaders) {
                responseHeaders = {};
                while (match = rheaders.exec(responseHeadersString)) {
                  responseHeaders[match[1].toLowerCase() + " "] = (responseHeaders[match[1].toLowerCase() + " "] || []).concat(match[2]);
                }
              }
              match = responseHeaders[key.toLowerCase() + " "];
            }
            return match == null ? null : match.join(", ");
          },
          // Raw string
          getAllResponseHeaders: function () {
            return completed ? responseHeadersString : null;
          },
          // Caches the header
          setRequestHeader: function (name, value) {
            if (completed == null) {
              name = requestHeadersNames[name.toLowerCase()] = requestHeadersNames[name.toLowerCase()] || name;
              requestHeaders[name] = value;
            }
            return this;
          },
          // Overrides response content-type header
          overrideMimeType: function (type) {
            if (completed == null) {
              s.mimeType = type;
            }
            return this;
          },
          // Status-dependent callbacks
          statusCode: function (map) {
            var code;
            if (map) {
              if (completed) {
                // Execute the appropriate callbacks
                jqXHR.always(map[jqXHR.status]);
              } else {
                // Lazy-add the new callbacks in a way that preserves old ones
                for (code in map) {
                  statusCode[code] = [statusCode[code], map[code]];
                }
              }
            }
            return this;
          },
          // Cancel the request
          abort: function (statusText) {
            var finalText = statusText || strAbort;
            if (transport) {
              transport.abort(finalText);
            }
            done(0, finalText);
            return this;
          }
        };

      // Attach deferreds
      deferred.promise(jqXHR);

      // Add protocol if not provided (prefilters might expect it)
      // Handle falsy url in the settings object (trac-10093: consistency with old signature)
      // We also use the url parameter if available
      s.url = ((url || s.url || location.href) + "").replace(rprotocol, location.protocol + "//");

      // Alias method option to type as per ticket trac-12004
      s.type = options.method || options.type || s.method || s.type;

      // Extract dataTypes list
      s.dataTypes = (s.dataType || "*").toLowerCase().match(rnothtmlwhite) || [""];

      // A cross-domain request is in order when the origin doesn't match the current origin.
      if (s.crossDomain == null) {
        urlAnchor = document.createElement("a");

        // Support: IE <=8 - 11, Edge 12 - 15
        // IE throws exception on accessing the href property if url is malformed,
        // e.g. http://example.com:80x/
        try {
          urlAnchor.href = s.url;

          // Support: IE <=8 - 11 only
          // Anchor's host property isn't correctly set when s.url is relative
          urlAnchor.href = urlAnchor.href;
          s.crossDomain = originAnchor.protocol + "//" + originAnchor.host !== urlAnchor.protocol + "//" + urlAnchor.host;
        } catch (e) {
          // If there is an error parsing the URL, assume it is crossDomain,
          // it can be rejected by the transport if it is invalid
          s.crossDomain = true;
        }
      }

      // Convert data if not already a string
      if (s.data && s.processData && typeof s.data !== "string") {
        s.data = jQuery.param(s.data, s.traditional);
      }

      // Apply prefilters
      inspectPrefiltersOrTransports(prefilters, s, options, jqXHR);

      // If request was aborted inside a prefilter, stop there
      if (completed) {
        return jqXHR;
      }

      // We can fire global events as of now if asked to
      // Don't fire events if jQuery.event is undefined in an AMD-usage scenario (trac-15118)
      fireGlobals = jQuery.event && s.global;

      // Watch for a new set of requests
      if (fireGlobals && jQuery.active++ === 0) {
        jQuery.event.trigger("ajaxStart");
      }

      // Uppercase the type
      s.type = s.type.toUpperCase();

      // Determine if request has content
      s.hasContent = !rnoContent.test(s.type);

      // Save the URL in case we're toying with the If-Modified-Since
      // and/or If-None-Match header later on
      // Remove hash to simplify url manipulation
      cacheURL = s.url.replace(rhash, "");

      // More options handling for requests with no content
      if (!s.hasContent) {
        // Remember the hash so we can put it back
        uncached = s.url.slice(cacheURL.length);

        // If data is available and should be processed, append data to url
        if (s.data && (s.processData || typeof s.data === "string")) {
          cacheURL += (rquery.test(cacheURL) ? "&" : "?") + s.data;

          // trac-9682: remove data so that it's not used in an eventual retry
          delete s.data;
        }

        // Add or update anti-cache param if needed
        if (s.cache === false) {
          cacheURL = cacheURL.replace(rantiCache, "$1");
          uncached = (rquery.test(cacheURL) ? "&" : "?") + "_=" + nonce.guid++ + uncached;
        }

        // Put hash and anti-cache on the URL that will be requested (gh-1732)
        s.url = cacheURL + uncached;

        // Change '%20' to '+' if this is encoded form body content (gh-2658)
      } else if (s.data && s.processData && (s.contentType || "").indexOf("application/x-www-form-urlencoded") === 0) {
        s.data = s.data.replace(r20, "+");
      }

      // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
      if (s.ifModified) {
        if (jQuery.lastModified[cacheURL]) {
          jqXHR.setRequestHeader("If-Modified-Since", jQuery.lastModified[cacheURL]);
        }
        if (jQuery.etag[cacheURL]) {
          jqXHR.setRequestHeader("If-None-Match", jQuery.etag[cacheURL]);
        }
      }

      // Set the correct header, if data is being sent
      if (s.data && s.hasContent && s.contentType !== false || options.contentType) {
        jqXHR.setRequestHeader("Content-Type", s.contentType);
      }

      // Set the Accepts header for the server, depending on the dataType
      jqXHR.setRequestHeader("Accept", s.dataTypes[0] && s.accepts[s.dataTypes[0]] ? s.accepts[s.dataTypes[0]] + (s.dataTypes[0] !== "*" ? ", " + allTypes + "; q=0.01" : "") : s.accepts["*"]);

      // Check for headers option
      for (i in s.headers) {
        jqXHR.setRequestHeader(i, s.headers[i]);
      }

      // Allow custom headers/mimetypes and early abort
      if (s.beforeSend && (s.beforeSend.call(callbackContext, jqXHR, s) === false || completed)) {
        // Abort if not done already and return
        return jqXHR.abort();
      }

      // Aborting is no longer a cancellation
      strAbort = "abort";

      // Install callbacks on deferreds
      completeDeferred.add(s.complete);
      jqXHR.done(s.success);
      jqXHR.fail(s.error);

      // Get transport
      transport = inspectPrefiltersOrTransports(transports, s, options, jqXHR);

      // If no transport, we auto-abort
      if (!transport) {
        done(-1, "No Transport");
      } else {
        jqXHR.readyState = 1;

        // Send global event
        if (fireGlobals) {
          globalEventContext.trigger("ajaxSend", [jqXHR, s]);
        }

        // If request was aborted inside ajaxSend, stop there
        if (completed) {
          return jqXHR;
        }

        // Timeout
        if (s.async && s.timeout > 0) {
          timeoutTimer = window.setTimeout(function () {
            jqXHR.abort("timeout");
          }, s.timeout);
        }
        try {
          completed = false;
          transport.send(requestHeaders, done);
        } catch (e) {
          // Rethrow post-completion exceptions
          if (completed) {
            throw e;
          }

          // Propagate others as results
          done(-1, e);
        }
      }

      // Callback for when everything is done
      function done(status, nativeStatusText, responses, headers) {
        var isSuccess,
          success,
          error,
          response,
          modified,
          statusText = nativeStatusText;

        // Ignore repeat invocations
        if (completed) {
          return;
        }
        completed = true;

        // Clear timeout if it exists
        if (timeoutTimer) {
          window.clearTimeout(timeoutTimer);
        }

        // Dereference transport for early garbage collection
        // (no matter how long the jqXHR object will be used)
        transport = undefined;

        // Cache response headers
        responseHeadersString = headers || "";

        // Set readyState
        jqXHR.readyState = status > 0 ? 4 : 0;

        // Determine if successful
        isSuccess = status >= 200 && status < 300 || status === 304;

        // Get response data
        if (responses) {
          response = ajaxHandleResponses(s, jqXHR, responses);
        }

        // Use a noop converter for missing script but not if jsonp
        if (!isSuccess && jQuery.inArray("script", s.dataTypes) > -1 && jQuery.inArray("json", s.dataTypes) < 0) {
          s.converters["text script"] = function () {};
        }

        // Convert no matter what (that way responseXXX fields are always set)
        response = ajaxConvert(s, response, jqXHR, isSuccess);

        // If successful, handle type chaining
        if (isSuccess) {
          // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
          if (s.ifModified) {
            modified = jqXHR.getResponseHeader("Last-Modified");
            if (modified) {
              jQuery.lastModified[cacheURL] = modified;
            }
            modified = jqXHR.getResponseHeader("etag");
            if (modified) {
              jQuery.etag[cacheURL] = modified;
            }
          }

          // if no content
          if (status === 204 || s.type === "HEAD") {
            statusText = "nocontent";

            // if not modified
          } else if (status === 304) {
            statusText = "notmodified";

            // If we have data, let's convert it
          } else {
            statusText = response.state;
            success = response.data;
            error = response.error;
            isSuccess = !error;
          }
        } else {
          // Extract error from statusText and normalize for non-aborts
          error = statusText;
          if (status || !statusText) {
            statusText = "error";
            if (status < 0) {
              status = 0;
            }
          }
        }

        // Set data for the fake xhr object
        jqXHR.status = status;
        jqXHR.statusText = (nativeStatusText || statusText) + "";

        // Success/Error
        if (isSuccess) {
          deferred.resolveWith(callbackContext, [success, statusText, jqXHR]);
        } else {
          deferred.rejectWith(callbackContext, [jqXHR, statusText, error]);
        }

        // Status-dependent callbacks
        jqXHR.statusCode(statusCode);
        statusCode = undefined;
        if (fireGlobals) {
          globalEventContext.trigger(isSuccess ? "ajaxSuccess" : "ajaxError", [jqXHR, s, isSuccess ? success : error]);
        }

        // Complete
        completeDeferred.fireWith(callbackContext, [jqXHR, statusText]);
        if (fireGlobals) {
          globalEventContext.trigger("ajaxComplete", [jqXHR, s]);

          // Handle the global AJAX counter
          if (! --jQuery.active) {
            jQuery.event.trigger("ajaxStop");
          }
        }
      }
      return jqXHR;
    },
    getJSON: function (url, data, callback) {
      return jQuery.get(url, data, callback, "json");
    },
    getScript: function (url, callback) {
      return jQuery.get(url, undefined, callback, "script");
    }
  });
  jQuery.each(["get", "post"], function (_i, method) {
    jQuery[method] = function (url, data, callback, type) {
      // Shift arguments if data argument was omitted
      if (isFunction(data)) {
        type = type || callback;
        callback = data;
        data = undefined;
      }

      // The url can be an options object (which then must have .url)
      return jQuery.ajax(jQuery.extend({
        url: url,
        type: method,
        dataType: type,
        data: data,
        success: callback
      }, jQuery.isPlainObject(url) && url));
    };
  });
  jQuery.ajaxPrefilter(function (s) {
    var i;
    for (i in s.headers) {
      if (i.toLowerCase() === "content-type") {
        s.contentType = s.headers[i] || "";
      }
    }
  });
  jQuery._evalUrl = function (url, options, doc) {
    return jQuery.ajax({
      url: url,
      // Make this explicit, since user can override this through ajaxSetup (trac-11264)
      type: "GET",
      dataType: "script",
      cache: true,
      async: false,
      global: false,
      // Only evaluate the response if it is successful (gh-4126)
      // dataFilter is not invoked for failure responses, so using it instead
      // of the default converter is kludgy but it works.
      converters: {
        "text script": function () {}
      },
      dataFilter: function (response) {
        jQuery.globalEval(response, options, doc);
      }
    });
  };
  jQuery.fn.extend({
    wrapAll: function (html) {
      var wrap;
      if (this[0]) {
        if (isFunction(html)) {
          html = html.call(this[0]);
        }

        // The elements to wrap the target around
        wrap = jQuery(html, this[0].ownerDocument).eq(0).clone(true);
        if (this[0].parentNode) {
          wrap.insertBefore(this[0]);
        }
        wrap.map(function () {
          var elem = this;
          while (elem.firstElementChild) {
            elem = elem.firstElementChild;
          }
          return elem;
        }).append(this);
      }
      return this;
    },
    wrapInner: function (html) {
      if (isFunction(html)) {
        return this.each(function (i) {
          jQuery(this).wrapInner(html.call(this, i));
        });
      }
      return this.each(function () {
        var self = jQuery(this),
          contents = self.contents();
        if (contents.length) {
          contents.wrapAll(html);
        } else {
          self.append(html);
        }
      });
    },
    wrap: function (html) {
      var htmlIsFunction = isFunction(html);
      return this.each(function (i) {
        jQuery(this).wrapAll(htmlIsFunction ? html.call(this, i) : html);
      });
    },
    unwrap: function (selector) {
      this.parent(selector).not("body").each(function () {
        jQuery(this).replaceWith(this.childNodes);
      });
      return this;
    }
  });
  jQuery.expr.pseudos.hidden = function (elem) {
    return !jQuery.expr.pseudos.visible(elem);
  };
  jQuery.expr.pseudos.visible = function (elem) {
    return !!(elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length);
  };
  jQuery.ajaxSettings.xhr = function () {
    try {
      return new window.XMLHttpRequest();
    } catch (e) {}
  };
  var xhrSuccessStatus = {
      // File protocol always yields status code 0, assume 200
      0: 200,
      // Support: IE <=9 only
      // trac-1450: sometimes IE returns 1223 when it should be 204
      1223: 204
    },
    xhrSupported = jQuery.ajaxSettings.xhr();
  support.cors = !!xhrSupported && "withCredentials" in xhrSupported;
  support.ajax = xhrSupported = !!xhrSupported;
  jQuery.ajaxTransport(function (options) {
    var callback, errorCallback;

    // Cross domain only allowed if supported through XMLHttpRequest
    if (support.cors || xhrSupported && !options.crossDomain) {
      return {
        send: function (headers, complete) {
          var i,
            xhr = options.xhr();
          xhr.open(options.type, options.url, options.async, options.username, options.password);

          // Apply custom fields if provided
          if (options.xhrFields) {
            for (i in options.xhrFields) {
              xhr[i] = options.xhrFields[i];
            }
          }

          // Override mime type if needed
          if (options.mimeType && xhr.overrideMimeType) {
            xhr.overrideMimeType(options.mimeType);
          }

          // X-Requested-With header
          // For cross-domain requests, seeing as conditions for a preflight are
          // akin to a jigsaw puzzle, we simply never set it to be sure.
          // (it can always be set on a per-request basis or even using ajaxSetup)
          // For same-domain requests, won't change header if already provided.
          if (!options.crossDomain && !headers["X-Requested-With"]) {
            headers["X-Requested-With"] = "XMLHttpRequest";
          }

          // Set headers
          for (i in headers) {
            xhr.setRequestHeader(i, headers[i]);
          }

          // Callback
          callback = function (type) {
            return function () {
              if (callback) {
                callback = errorCallback = xhr.onload = xhr.onerror = xhr.onabort = xhr.ontimeout = xhr.onreadystatechange = null;
                if (type === "abort") {
                  xhr.abort();
                } else if (type === "error") {
                  // Support: IE <=9 only
                  // On a manual native abort, IE9 throws
                  // errors on any property access that is not readyState
                  if (typeof xhr.status !== "number") {
                    complete(0, "error");
                  } else {
                    complete(
                    // File: protocol always yields status 0; see trac-8605, trac-14207
                    xhr.status, xhr.statusText);
                  }
                } else {
                  complete(xhrSuccessStatus[xhr.status] || xhr.status, xhr.statusText,
                  // Support: IE <=9 only
                  // IE9 has no XHR2 but throws on binary (trac-11426)
                  // For XHR2 non-text, let the caller handle it (gh-2498)
                  (xhr.responseType || "text") !== "text" || typeof xhr.responseText !== "string" ? {
                    binary: xhr.response
                  } : {
                    text: xhr.responseText
                  }, xhr.getAllResponseHeaders());
                }
              }
            };
          };

          // Listen to events
          xhr.onload = callback();
          errorCallback = xhr.onerror = xhr.ontimeout = callback("error");

          // Support: IE 9 only
          // Use onreadystatechange to replace onabort
          // to handle uncaught aborts
          if (xhr.onabort !== undefined) {
            xhr.onabort = errorCallback;
          } else {
            xhr.onreadystatechange = function () {
              // Check readyState before timeout as it changes
              if (xhr.readyState === 4) {
                // Allow onerror to be called first,
                // but that will not handle a native abort
                // Also, save errorCallback to a variable
                // as xhr.onerror cannot be accessed
                window.setTimeout(function () {
                  if (callback) {
                    errorCallback();
                  }
                });
              }
            };
          }

          // Create the abort callback
          callback = callback("abort");
          try {
            // Do send the request (this may raise an exception)
            xhr.send(options.hasContent && options.data || null);
          } catch (e) {
            // trac-14683: Only rethrow if this hasn't been notified as an error yet
            if (callback) {
              throw e;
            }
          }
        },
        abort: function () {
          if (callback) {
            callback();
          }
        }
      };
    }
  });

  // Prevent auto-execution of scripts when no explicit dataType was provided (See gh-2432)
  jQuery.ajaxPrefilter(function (s) {
    if (s.crossDomain) {
      s.contents.script = false;
    }
  });

  // Install script dataType
  jQuery.ajaxSetup({
    accepts: {
      script: "text/javascript, application/javascript, " + "application/ecmascript, application/x-ecmascript"
    },
    contents: {
      script: /\b(?:java|ecma)script\b/
    },
    converters: {
      "text script": function (text) {
        jQuery.globalEval(text);
        return text;
      }
    }
  });

  // Handle cache's special case and crossDomain
  jQuery.ajaxPrefilter("script", function (s) {
    if (s.cache === undefined) {
      s.cache = false;
    }
    if (s.crossDomain) {
      s.type = "GET";
    }
  });

  // Bind script tag hack transport
  jQuery.ajaxTransport("script", function (s) {
    // This transport only deals with cross domain or forced-by-attrs requests
    if (s.crossDomain || s.scriptAttrs) {
      var script, callback;
      return {
        send: function (_, complete) {
          script = jQuery("<script>").attr(s.scriptAttrs || {}).prop({
            charset: s.scriptCharset,
            src: s.url
          }).on("load error", callback = function (evt) {
            script.remove();
            callback = null;
            if (evt) {
              complete(evt.type === "error" ? 404 : 200, evt.type);
            }
          });

          // Use native DOM manipulation to avoid our domManip AJAX trickery
          document.head.appendChild(script[0]);
        },
        abort: function () {
          if (callback) {
            callback();
          }
        }
      };
    }
  });
  var oldCallbacks = [],
    rjsonp = /(=)\?(?=&|$)|\?\?/;

  // Default jsonp settings
  jQuery.ajaxSetup({
    jsonp: "callback",
    jsonpCallback: function () {
      var callback = oldCallbacks.pop() || jQuery.expando + "_" + nonce.guid++;
      this[callback] = true;
      return callback;
    }
  });

  // Detect, normalize options and install callbacks for jsonp requests
  jQuery.ajaxPrefilter("json jsonp", function (s, originalSettings, jqXHR) {
    var callbackName,
      overwritten,
      responseContainer,
      jsonProp = s.jsonp !== false && (rjsonp.test(s.url) ? "url" : typeof s.data === "string" && (s.contentType || "").indexOf("application/x-www-form-urlencoded") === 0 && rjsonp.test(s.data) && "data");

    // Handle iff the expected data type is "jsonp" or we have a parameter to set
    if (jsonProp || s.dataTypes[0] === "jsonp") {
      // Get callback name, remembering preexisting value associated with it
      callbackName = s.jsonpCallback = isFunction(s.jsonpCallback) ? s.jsonpCallback() : s.jsonpCallback;

      // Insert callback into url or form data
      if (jsonProp) {
        s[jsonProp] = s[jsonProp].replace(rjsonp, "$1" + callbackName);
      } else if (s.jsonp !== false) {
        s.url += (rquery.test(s.url) ? "&" : "?") + s.jsonp + "=" + callbackName;
      }

      // Use data converter to retrieve json after script execution
      s.converters["script json"] = function () {
        if (!responseContainer) {
          jQuery.error(callbackName + " was not called");
        }
        return responseContainer[0];
      };

      // Force json dataType
      s.dataTypes[0] = "json";

      // Install callback
      overwritten = window[callbackName];
      window[callbackName] = function () {
        responseContainer = arguments;
      };

      // Clean-up function (fires after converters)
      jqXHR.always(function () {
        // If previous value didn't exist - remove it
        if (overwritten === undefined) {
          jQuery(window).removeProp(callbackName);

          // Otherwise restore preexisting value
        } else {
          window[callbackName] = overwritten;
        }

        // Save back as free
        if (s[callbackName]) {
          // Make sure that re-using the options doesn't screw things around
          s.jsonpCallback = originalSettings.jsonpCallback;

          // Save the callback name for future use
          oldCallbacks.push(callbackName);
        }

        // Call if it was a function and we have a response
        if (responseContainer && isFunction(overwritten)) {
          overwritten(responseContainer[0]);
        }
        responseContainer = overwritten = undefined;
      });

      // Delegate to script
      return "script";
    }
  });

  // Support: Safari 8 only
  // In Safari 8 documents created via document.implementation.createHTMLDocument
  // collapse sibling forms: the second one becomes a child of the first one.
  // Because of that, this security measure has to be disabled in Safari 8.
  // https://bugs.webkit.org/show_bug.cgi?id=137337
  support.createHTMLDocument = function () {
    var body = document.implementation.createHTMLDocument("").body;
    body.innerHTML = "<form></form><form></form>";
    return body.childNodes.length === 2;
  }();

  // Argument "data" should be string of html
  // context (optional): If specified, the fragment will be created in this context,
  // defaults to document
  // keepScripts (optional): If true, will include scripts passed in the html string
  jQuery.parseHTML = function (data, context, keepScripts) {
    if (typeof data !== "string") {
      return [];
    }
    if (typeof context === "boolean") {
      keepScripts = context;
      context = false;
    }
    var base, parsed, scripts;
    if (!context) {
      // Stop scripts or inline event handlers from being executed immediately
      // by using document.implementation
      if (support.createHTMLDocument) {
        context = document.implementation.createHTMLDocument("");

        // Set the base href for the created document
        // so any parsed elements with URLs
        // are based on the document's URL (gh-2965)
        base = context.createElement("base");
        base.href = document.location.href;
        context.head.appendChild(base);
      } else {
        context = document;
      }
    }
    parsed = rsingleTag.exec(data);
    scripts = !keepScripts && [];

    // Single tag
    if (parsed) {
      return [context.createElement(parsed[1])];
    }
    parsed = buildFragment([data], context, scripts);
    if (scripts && scripts.length) {
      jQuery(scripts).remove();
    }
    return jQuery.merge([], parsed.childNodes);
  };

  /**
   * Load a url into a page
   */
  jQuery.fn.load = function (url, params, callback) {
    var selector,
      type,
      response,
      self = this,
      off = url.indexOf(" ");
    if (off > -1) {
      selector = stripAndCollapse(url.slice(off));
      url = url.slice(0, off);
    }

    // If it's a function
    if (isFunction(params)) {
      // We assume that it's the callback
      callback = params;
      params = undefined;

      // Otherwise, build a param string
    } else if (params && typeof params === "object") {
      type = "POST";
    }

    // If we have elements to modify, make the request
    if (self.length > 0) {
      jQuery.ajax({
        url: url,
        // If "type" variable is undefined, then "GET" method will be used.
        // Make value of this field explicit since
        // user can override it through ajaxSetup method
        type: type || "GET",
        dataType: "html",
        data: params
      }).done(function (responseText) {
        // Save response for use in complete callback
        response = arguments;
        self.html(selector ?
        // If a selector was specified, locate the right elements in a dummy div
        // Exclude scripts to avoid IE 'Permission Denied' errors
        jQuery("<div>").append(jQuery.parseHTML(responseText)).find(selector) :
        // Otherwise use the full result
        responseText);

        // If the request succeeds, this function gets "data", "status", "jqXHR"
        // but they are ignored because response was set above.
        // If it fails, this function gets "jqXHR", "status", "error"
      }).always(callback && function (jqXHR, status) {
        self.each(function () {
          callback.apply(this, response || [jqXHR.responseText, status, jqXHR]);
        });
      });
    }
    return this;
  };
  jQuery.expr.pseudos.animated = function (elem) {
    return jQuery.grep(jQuery.timers, function (fn) {
      return elem === fn.elem;
    }).length;
  };
  jQuery.offset = {
    setOffset: function (elem, options, i) {
      var curPosition,
        curLeft,
        curCSSTop,
        curTop,
        curOffset,
        curCSSLeft,
        calculatePosition,
        position = jQuery.css(elem, "position"),
        curElem = jQuery(elem),
        props = {};

      // Set position first, in-case top/left are set even on static elem
      if (position === "static") {
        elem.style.position = "relative";
      }
      curOffset = curElem.offset();
      curCSSTop = jQuery.css(elem, "top");
      curCSSLeft = jQuery.css(elem, "left");
      calculatePosition = (position === "absolute" || position === "fixed") && (curCSSTop + curCSSLeft).indexOf("auto") > -1;

      // Need to be able to calculate position if either
      // top or left is auto and position is either absolute or fixed
      if (calculatePosition) {
        curPosition = curElem.position();
        curTop = curPosition.top;
        curLeft = curPosition.left;
      } else {
        curTop = parseFloat(curCSSTop) || 0;
        curLeft = parseFloat(curCSSLeft) || 0;
      }
      if (isFunction(options)) {
        // Use jQuery.extend here to allow modification of coordinates argument (gh-1848)
        options = options.call(elem, i, jQuery.extend({}, curOffset));
      }
      if (options.top != null) {
        props.top = options.top - curOffset.top + curTop;
      }
      if (options.left != null) {
        props.left = options.left - curOffset.left + curLeft;
      }
      if ("using" in options) {
        options.using.call(elem, props);
      } else {
        curElem.css(props);
      }
    }
  };
  jQuery.fn.extend({
    // offset() relates an element's border box to the document origin
    offset: function (options) {
      // Preserve chaining for setter
      if (arguments.length) {
        return options === undefined ? this : this.each(function (i) {
          jQuery.offset.setOffset(this, options, i);
        });
      }
      var rect,
        win,
        elem = this[0];
      if (!elem) {
        return;
      }

      // Return zeros for disconnected and hidden (display: none) elements (gh-2310)
      // Support: IE <=11 only
      // Running getBoundingClientRect on a
      // disconnected node in IE throws an error
      if (!elem.getClientRects().length) {
        return {
          top: 0,
          left: 0
        };
      }

      // Get document-relative position by adding viewport scroll to viewport-relative gBCR
      rect = elem.getBoundingClientRect();
      win = elem.ownerDocument.defaultView;
      return {
        top: rect.top + win.pageYOffset,
        left: rect.left + win.pageXOffset
      };
    },
    // position() relates an element's margin box to its offset parent's padding box
    // This corresponds to the behavior of CSS absolute positioning
    position: function () {
      if (!this[0]) {
        return;
      }
      var offsetParent,
        offset,
        doc,
        elem = this[0],
        parentOffset = {
          top: 0,
          left: 0
        };

      // position:fixed elements are offset from the viewport, which itself always has zero offset
      if (jQuery.css(elem, "position") === "fixed") {
        // Assume position:fixed implies availability of getBoundingClientRect
        offset = elem.getBoundingClientRect();
      } else {
        offset = this.offset();

        // Account for the *real* offset parent, which can be the document or its root element
        // when a statically positioned element is identified
        doc = elem.ownerDocument;
        offsetParent = elem.offsetParent || doc.documentElement;
        while (offsetParent && (offsetParent === doc.body || offsetParent === doc.documentElement) && jQuery.css(offsetParent, "position") === "static") {
          offsetParent = offsetParent.parentNode;
        }
        if (offsetParent && offsetParent !== elem && offsetParent.nodeType === 1) {
          // Incorporate borders into its offset, since they are outside its content origin
          parentOffset = jQuery(offsetParent).offset();
          parentOffset.top += jQuery.css(offsetParent, "borderTopWidth", true);
          parentOffset.left += jQuery.css(offsetParent, "borderLeftWidth", true);
        }
      }

      // Subtract parent offsets and element margins
      return {
        top: offset.top - parentOffset.top - jQuery.css(elem, "marginTop", true),
        left: offset.left - parentOffset.left - jQuery.css(elem, "marginLeft", true)
      };
    },
    // This method will return documentElement in the following cases:
    // 1) For the element inside the iframe without offsetParent, this method will return
    //    documentElement of the parent window
    // 2) For the hidden or detached element
    // 3) For body or html element, i.e. in case of the html node - it will return itself
    //
    // but those exceptions were never presented as a real life use-cases
    // and might be considered as more preferable results.
    //
    // This logic, however, is not guaranteed and can change at any point in the future
    offsetParent: function () {
      return this.map(function () {
        var offsetParent = this.offsetParent;
        while (offsetParent && jQuery.css(offsetParent, "position") === "static") {
          offsetParent = offsetParent.offsetParent;
        }
        return offsetParent || documentElement;
      });
    }
  });

  // Create scrollLeft and scrollTop methods
  jQuery.each({
    scrollLeft: "pageXOffset",
    scrollTop: "pageYOffset"
  }, function (method, prop) {
    var top = "pageYOffset" === prop;
    jQuery.fn[method] = function (val) {
      return access(this, function (elem, method, val) {
        // Coalesce documents and windows
        var win;
        if (isWindow(elem)) {
          win = elem;
        } else if (elem.nodeType === 9) {
          win = elem.defaultView;
        }
        if (val === undefined) {
          return win ? win[prop] : elem[method];
        }
        if (win) {
          win.scrollTo(!top ? val : win.pageXOffset, top ? val : win.pageYOffset);
        } else {
          elem[method] = val;
        }
      }, method, val, arguments.length);
    };
  });

  // Support: Safari <=7 - 9.1, Chrome <=37 - 49
  // Add the top/left cssHooks using jQuery.fn.position
  // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
  // Blink bug: https://bugs.chromium.org/p/chromium/issues/detail?id=589347
  // getComputedStyle returns percent when specified for top/left/bottom/right;
  // rather than make the css module depend on the offset module, just check for it here
  jQuery.each(["top", "left"], function (_i, prop) {
    jQuery.cssHooks[prop] = addGetHookIf(support.pixelPosition, function (elem, computed) {
      if (computed) {
        computed = curCSS(elem, prop);

        // If curCSS returns percentage, fallback to offset
        return rnumnonpx.test(computed) ? jQuery(elem).position()[prop] + "px" : computed;
      }
    });
  });

  // Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
  jQuery.each({
    Height: "height",
    Width: "width"
  }, function (name, type) {
    jQuery.each({
      padding: "inner" + name,
      content: type,
      "": "outer" + name
    }, function (defaultExtra, funcName) {
      // Margin is only for outerHeight, outerWidth
      jQuery.fn[funcName] = function (margin, value) {
        var chainable = arguments.length && (defaultExtra || typeof margin !== "boolean"),
          extra = defaultExtra || (margin === true || value === true ? "margin" : "border");
        return access(this, function (elem, type, value) {
          var doc;
          if (isWindow(elem)) {
            // $( window ).outerWidth/Height return w/h including scrollbars (gh-1729)
            return funcName.indexOf("outer") === 0 ? elem["inner" + name] : elem.document.documentElement["client" + name];
          }

          // Get document width or height
          if (elem.nodeType === 9) {
            doc = elem.documentElement;

            // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height],
            // whichever is greatest
            return Math.max(elem.body["scroll" + name], doc["scroll" + name], elem.body["offset" + name], doc["offset" + name], doc["client" + name]);
          }
          return value === undefined ?
          // Get width or height on the element, requesting but not forcing parseFloat
          jQuery.css(elem, type, extra) :
          // Set width or height on the element
          jQuery.style(elem, type, value, extra);
        }, type, chainable ? margin : undefined, chainable);
      };
    });
  });
  jQuery.each(["ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend"], function (_i, type) {
    jQuery.fn[type] = function (fn) {
      return this.on(type, fn);
    };
  });
  jQuery.fn.extend({
    bind: function (types, data, fn) {
      return this.on(types, null, data, fn);
    },
    unbind: function (types, fn) {
      return this.off(types, null, fn);
    },
    delegate: function (selector, types, data, fn) {
      return this.on(types, selector, data, fn);
    },
    undelegate: function (selector, types, fn) {
      // ( namespace ) or ( selector, types [, fn] )
      return arguments.length === 1 ? this.off(selector, "**") : this.off(types, selector || "**", fn);
    },
    hover: function (fnOver, fnOut) {
      return this.on("mouseenter", fnOver).on("mouseleave", fnOut || fnOver);
    }
  });
  jQuery.each(("blur focus focusin focusout resize scroll click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup contextmenu").split(" "), function (_i, name) {
    // Handle event binding
    jQuery.fn[name] = function (data, fn) {
      return arguments.length > 0 ? this.on(name, null, data, fn) : this.trigger(name);
    };
  });

  // Support: Android <=4.0 only
  // Make sure we trim BOM and NBSP
  // Require that the "whitespace run" starts from a non-whitespace
  // to avoid O(N^2) behavior when the engine would try matching "\s+$" at each space position.
  var rtrim = /^[\s\uFEFF\xA0]+|([^\s\uFEFF\xA0])[\s\uFEFF\xA0]+$/g;

  // Bind a function to a context, optionally partially applying any
  // arguments.
  // jQuery.proxy is deprecated to promote standards (specifically Function#bind)
  // However, it is not slated for removal any time soon
  jQuery.proxy = function (fn, context) {
    var tmp, args, proxy;
    if (typeof context === "string") {
      tmp = fn[context];
      context = fn;
      fn = tmp;
    }

    // Quick check to determine if target is callable, in the spec
    // this throws a TypeError, but we will just return undefined.
    if (!isFunction(fn)) {
      return undefined;
    }

    // Simulated bind
    args = slice.call(arguments, 2);
    proxy = function () {
      return fn.apply(context || this, args.concat(slice.call(arguments)));
    };

    // Set the guid of unique handler to the same of original handler, so it can be removed
    proxy.guid = fn.guid = fn.guid || jQuery.guid++;
    return proxy;
  };
  jQuery.holdReady = function (hold) {
    if (hold) {
      jQuery.readyWait++;
    } else {
      jQuery.ready(true);
    }
  };
  jQuery.isArray = Array.isArray;
  jQuery.parseJSON = JSON.parse;
  jQuery.nodeName = nodeName;
  jQuery.isFunction = isFunction;
  jQuery.isWindow = isWindow;
  jQuery.camelCase = camelCase;
  jQuery.type = toType;
  jQuery.now = Date.now;
  jQuery.isNumeric = function (obj) {
    // As of jQuery 3.0, isNumeric is limited to
    // strings and numbers (primitives or objects)
    // that can be coerced to finite numbers (gh-2662)
    var type = jQuery.type(obj);
    return (type === "number" || type === "string") &&
    // parseFloat NaNs numeric-cast false positives ("")
    // ...but misinterprets leading-number strings, particularly hex literals ("0x...")
    // subtraction forces infinities to NaN
    !isNaN(obj - parseFloat(obj));
  };
  jQuery.trim = function (text) {
    return text == null ? "" : (text + "").replace(rtrim, "$1");
  };
  var
    // Map over jQuery in case of overwrite
    _jQuery = window.jQuery,
    // Map over the $ in case of overwrite
    _$ = window.$;
  jQuery.noConflict = function (deep) {
    if (window.$ === jQuery) {
      window.$ = _$;
    }
    if (deep && window.jQuery === jQuery) {
      window.jQuery = _jQuery;
    }
    return jQuery;
  };

  // Expose jQuery and $ identifiers, even in AMD
  // (trac-7102#comment:10, https://github.com/jquery/jquery/pull/557)
  // and CommonJS for browser emulators (trac-13566)
  if (typeof noGlobal === "undefined") {
    window.jQuery = window.$ = jQuery;
  }
  return jQuery;
});
});

var recorder_mp3_min = createCommonjsModule(function (module) {
/*
录音
https://github.com/xiangyuecn/Recorder
src: recorder-core.js,engine/mp3.js,engine/mp3-engine.js
*/
!function (e) {
  var t = "object" == typeof window && !!window.document,
    a = t ? window : Object;
  !function (e, w) {

    var S = function () {},
      f = function (e) {
        return "number" == typeof e;
      },
      N = function (e) {
        return new l(e);
      },
      M = N.LM = "2024-04-09 19:15",
      y = "https://github.com/xiangyuecn/Recorder",
      R = "Recorder",
      A = "getUserMedia",
      V = "srcSampleRate",
      D = "sampleRate",
      i = "bitRate",
      x = "catch",
      t = e[R];
    if (t && t.LM == M) return t.CLog(t.i18n.$T("K8zP::重复导入{1}", 0, R), 3);
    N.IsOpen = function () {
      var e = N.Stream;
      if (e) {
        var t = e.getTracks && e.getTracks() || e.audioTracks || [],
          a = t[0];
        if (a) {
          var n = a.readyState;
          return "live" == n || n == a.LIVE;
        }
      }
      return !1;
    }, N.BufferSize = 4096, N.Destroy = function () {
      for (var e in O(R + " Destroy"), L(), a) a[e]();
    };
    var a = {};
    N.BindDestroy = function (e, t) {
      a[e] = t;
    }, N.Support = function () {
      if (!w) return !1;
      var e = navigator.mediaDevices || {};
      return e[A] || (e = navigator)[A] || (e[A] = e.webkitGetUserMedia || e.mozGetUserMedia || e.msGetUserMedia), !!e[A] && (N.Scope = e, !!N.GetContext());
    }, N.GetContext = function (e) {
      if (!w) return null;
      var t = window.AudioContext;
      if (t || (t = window.webkitAudioContext), !t) return null;
      var a = N.Ctx;
      if (a && "closed" != a.state || (a = N.Ctx = new t(), N.NewCtxs = N.NewCtxs || [], N.BindDestroy("Ctx", function () {
        var e = N.Ctx;
        e && e.close && (s(e), N.Ctx = 0);
        var t = N.NewCtxs;
        N.NewCtxs = [];
        for (var a = 0; a < t.length; a++) s(t[a]);
      })), e && a.close) try {
        a = new t(), N.NewCtxs.push(a);
      } catch (e) {
        O("GetContext tryNew Error", 1, e);
      }
      return a;
    }, N.CloseNewCtx = function (e) {
      if (e && e != N.Ctx) {
        s(e);
        for (var t = N.NewCtxs || [], a = t.length, n = 0; n < t.length; n++) if (t[n] == e) {
          t.splice(n, 1);
          break;
        }
        O(z("mSxV::剩{1}个GetContext未close", 0, a + "-1=" + t.length), t.length ? 3 : 0);
      }
    };
    var s = function (e) {
        if (e && e.close) {
          e._isC = 1;
          try {
            e.close();
          } catch (e) {
            O("ctx close err", 1, e);
          }
        }
      },
      B = N.ResumeCtx = function (a, n, s, r) {
        var i = 0,
          o = 0,
          _ = 0,
          l = 0,
          f = "EventListener",
          c = "ResumeCtx ",
          u = function (e, t) {
            o && h(), i || (i = 1, e && r(e, l), t && s(l)), t && (!a._LsSC && a["add" + f] && a["add" + f]("statechange", b), a._LsSC = 1, _ = 1);
          },
          h = function (e) {
            if (!e || !o) {
              o = e ? 1 : 0;
              for (var t = ["focus", "mousedown", "mouseup", "touchstart", "touchend"], a = 0; a < t.length; a++) window[(e ? "add" : "remove") + f](t[a], b, !0);
            }
          },
          b = function () {
            var e = a.state,
              t = p(e);
            if (!i && !n(t ? ++l : l)) return u();
            t ? (_ && O(c + "sc " + e, 3), h(1), a.resume().then(function () {
              _ && O(c + "sc " + a.state), u(0, 1);
            })[x](function (e) {
              O(c + "error", 1, e), p(a.state) || u(e.message || "error");
            })) : "closed" == e ? (_ && !a._isC && O(c + "sc " + e, 1), u("ctx closed")) : u(0, 1);
          };
        b();
      },
      p = N.CtxSpEnd = function (e) {
        return "suspended" == e || "interrupted" == e;
      },
      k = function (e) {
        var t = e.state,
          a = "ctx.state=" + t;
        return p(t) && (a += z("nMIy::（注意：ctx不是running状态，rec.open和start至少要有一个在用户操作(触摸、点击等)时进行调用，否则将在rec.start时尝试进行ctx.resume，可能会产生兼容性问题(仅iOS)，请参阅文档中runningContext配置）")), a;
      },
      T = "ConnectEnableWebM";
    N[T] = !0;
    var E = "ConnectEnableWorklet";
    N[E] = !1;
    var C = function (e, _) {
        var l = e.BufferSize || N.BufferSize,
          f = e.Stream,
          c = f._RC || f._c || N.GetContext(!0);
        f._c = c;
        var u,
          a,
          h,
          i = function (e) {
            var t = f._m = c.createMediaStreamSource(f),
              a = c.destination,
              n = "createMediaStreamDestination";
            c[n] && (a = f._d = c[n]()), t.connect(e), e.connect(a);
          },
          b = "",
          p = f._call,
          m = function (e) {
            for (var t in p) {
              for (var a = e.length, n = new Int16Array(a), s = 0, r = 0; r < a; r++) {
                var i = Math.max(-1, Math.min(1, e[r]));
                i = i < 0 ? 32768 * i : 32767 * i, n[r] = i, s += Math.abs(i);
              }
              for (var o in p) p[o](n, s);
              return;
            }
          },
          v = "ScriptProcessor",
          d = "audioWorklet",
          o = R + " " + d,
          g = "RecProc",
          w = "MediaRecorder",
          S = w + ".WebM.PCM",
          M = c.createScriptProcessor || c.createJavaScriptNode,
          y = z("ZGlf::。由于{1}内部1秒375次回调，在移动端可能会有性能问题导致回调丢失录音变短，PC端无影响，暂不建议开启{1}。", 0, d),
          A = function () {
            a = f.isWorklet = !1, n(f), O(z("7TU0::Connect采用老的{1}，", 0, v) + Y.get(z(N[E] ? "JwCL::但已设置{1}尝试启用{2}" : "VGjB::可设置{1}尝试启用{2}", 2), [R + "." + E + "=true", d]) + b + y, 3);
            var e = f._p = M.call(c, l, 1, 1);
            i(e), e.onaudioprocess = function (e) {
              var t = e.inputBuffer.getChannelData(0);
              m(t);
            };
          },
          k = function () {
            u = f.isWebM = !1, I(f), a = f.isWorklet = !M || N[E];
            var t = window.AudioWorkletNode;
            if (a && c[d] && t) {
              var n = function () {
                  return a && f._na;
                },
                s = f._na = function () {
                  "" !== h && (clearTimeout(h), h = setTimeout(function () {
                    h = 0, n() && (O(z("MxX1::{1}未返回任何音频，恢复使用{2}", 0, d, v), 3), M && A());
                  }, 500));
                },
                r = function () {
                  if (n()) {
                    var e = f._n = new t(c, g, {
                      processorOptions: {
                        bufferSize: l
                      }
                    });
                    i(e), e.port.onmessage = function (e) {
                      h && (clearTimeout(h), h = ""), n() ? m(e.data.val) : a || O(z("XUap::{1}多余回调", 0, d), 3);
                    }, O(z("yOta::Connect采用{1}，设置{2}可恢复老式{3}", 0, d, R + "." + E + "=false", v) + b + y, 3);
                  }
                },
                e = function () {
                  if (n()) if (c[g]) r();else {
                    var e,
                      t,
                      a = (t = "class " + g + " extends AudioWorkletProcessor{", t += "constructor " + (e = function (e) {
                        return e.toString().replace(/^function|DEL_/g, "").replace(/\$RA/g, o);
                      })(function (e) {
                        DEL_super(e);
                        var t = this,
                          a = e.processorOptions.bufferSize;
                        t.bufferSize = a, t.buffer = new Float32Array(2 * a), t.pos = 0, t.port.onmessage = function (e) {
                          e.data.kill && (t.kill = !0, $C.log("$RA kill call"));
                        }, $C.log("$RA .ctor call", e);
                      }), t += "process " + e(function (e, t, a) {
                        var n = this,
                          s = n.bufferSize,
                          r = n.buffer,
                          i = n.pos;
                        if ((e = (e[0] || [])[0] || []).length) {
                          r.set(e, i);
                          var o = ~~((i += e.length) / s) * s;
                          if (o) {
                            this.port.postMessage({
                              val: r.slice(0, o)
                            });
                            var _ = r.subarray(o, i);
                            (r = new Float32Array(2 * s)).set(_), i = _.length, n.buffer = r;
                          }
                          n.pos = i;
                        }
                        return !n.kill;
                      }), t = (t += '}try{registerProcessor("' + g + '", ' + g + ')}catch(e){$C.error("' + o + ' Reg Error",e)}').replace(/\$C\./g, "console."), "data:text/javascript;base64," + btoa(unescape(encodeURIComponent(t))));
                    c[d].addModule(a).then(function (e) {
                      n() && (c[g] = 1, r(), h && s());
                    })[x](function (e) {
                      O(d + ".addModule Error", 1, e), n() && A();
                    });
                  }
                };
              B(c, function () {
                return n();
              }, e, e);
            } else A();
          };
        !function () {
          var e = window[w],
            t = "ondataavailable",
            a = "audio/webm; codecs=pcm";
          u = f.isWebM = N[T];
          var n = e && t in e.prototype && e.isTypeSupported(a);
          if (b = n ? "" : z("VwPd::（此浏览器不支持{1}）", 0, S), !_ || !u || !n) return k();
          var s = function () {
              return u && f._ra;
            },
            r = (f._ra = function () {
              "" !== h && (clearTimeout(h), h = setTimeout(function () {
                s() && (O(z("vHnb::{1}未返回任何音频，降级使用{2}", 0, w, d), 3), k());
              }, 500));
            }, Object.assign({
              mimeType: a
            }, N.ConnectWebMOptions)),
            i = f._r = new e(f, r),
            o = f._rd = {
              sampleRate: c[D]
            };
          i[t] = function (e) {
            var t = new FileReader();
            t.onloadend = function () {
              if (s()) {
                var e = P(new Uint8Array(t.result), o);
                if (!e) return;
                if (-1 == e) return void k();
                h && (clearTimeout(h), h = ""), m(e);
              } else u || O(z("O9P7::{1}多余回调", 0, w), 3);
            }, t.readAsArrayBuffer(e.data);
          }, i.start(~~(l / 48)), O(z("LMEm::Connect采用{1}，设置{2}可恢复使用{3}或老式{4}", 0, S, R + "." + T + "=false", d, v));
        }();
      },
      r = function (e) {
        e._na && e._na(), e._ra && e._ra();
      },
      n = function (e) {
        e._na = null, e._n && (e._n.port.postMessage({
          kill: !0
        }), e._n.disconnect(), e._n = null);
      },
      I = function (e) {
        if (e._ra = null, e._r) {
          try {
            e._r.stop();
          } catch (e) {
            O("mr stop err", 1, e);
          }
          e._r = null;
        }
      },
      L = function (e) {
        var t = (e = e || N) == N,
          a = e.Stream;
        a && (a._m && (a._m.disconnect(), a._m = null), !a._RC && a._c && N.CloseNewCtx(a._c), a._RC = null, a._c = null, a._d && (o(a._d.stream), a._d = null), a._p && (a._p.disconnect(), a._p.onaudioprocess = a._p = null), n(a), I(a), t && o(a)), e.Stream = 0;
      },
      o = N.StopS_ = function (e) {
        for (var t = e.getTracks && e.getTracks() || e.audioTracks || [], a = 0; a < t.length; a++) {
          var n = t[a];
          n.stop && n.stop();
        }
        e.stop && e.stop();
      };
    N.SampleData = function (e, t, a, n, s) {
      var r = "SampleData";
      n || (n = {});
      var i = n.index || 0,
        o = n.offset || 0,
        _ = n.filter;
      if (_ && _.fn && _.sr != t && (_ = null, O(z("d48C::{1}的filter采样率变了，重设滤波", 0, r), 3)), !_) {
        var l = 3 * t / 4 < a ? 0 : a / 2 * 3 / 4;
        _ = {
          fn: l ? N.IIRFilter(!0, t, l) : 0
        };
      }
      _.sr = t;
      var f = _.fn,
        c = n.frameNext || [];
      s || (s = {});
      var u = s.frameSize || 1;
      s.frameType && (u = "mp3" == s.frameType ? 1152 : 1);
      var h = e.length;
      h + 1 < i && O(z("tlbC::{1}似乎传入了未重置chunk {2}", 0, r, i + ">" + h), 3);
      for (var b = 0, p = i; p < h; p++) b += e[p].length;
      b = Math.max(0, b - Math.floor(o));
      var m = t / a;
      1 < m ? b = Math.floor(b / m) : (m = 1, a = t), b += c.length;
      for (var v = new Int16Array(b), d = 0, p = 0; p < c.length; p++) v[d] = c[p], d++;
      for (; i < h; i++) {
        for (var g = e[i], p = o, w = g.length, S = f && f.Embed, M = 0, y = 0, A = 0, k = 0, R = 0, x = 0; R < w; R++, x++) if (x < w && (S ? (A = g[x], k = S.b0 * A + S.b1 * S.x1 + S.b0 * S.x2 - S.a1 * S.y1 - S.a2 * S.y2, S.x2 = S.x1, S.x1 = A, S.y2 = S.y1, S.y1 = k) : k = f ? f(g[x]) : g[x]), M = y, y = k, 0 != x) {
          var B = Math.floor(p);
          if (R == B) {
            var T = Math.ceil(p),
              E = p - B,
              C = M,
              I = T < w ? y : C,
              L = C + (I - C) * E;
            32767 < L ? L = 32767 : L < -32768 && (L = -32768), v[d] = L, d++, p += m;
          }
        } else R--;
        o = Math.max(0, p - w);
      }
      c = null;
      var P = v.length % u;
      if (0 < P) {
        var H = 2 * (v.length - P);
        c = new Int16Array(v.buffer.slice(H)), v = new Int16Array(v.buffer.slice(0, H));
      }
      return {
        index: i,
        offset: o,
        filter: _,
        frameNext: c,
        sampleRate: a,
        data: v
      };
    }, N.IIRFilter = function (e, t, a) {
      var n = 2 * Math.PI * a / t,
        s = Math.sin(n),
        r = Math.cos(n),
        i = s / 2,
        o = 1 + i,
        _ = -2 * r / o,
        l = (1 - i) / o;
      if (e) var f = (1 - r) / 2 / o,
        c = (1 - r) / o;else var f = (1 + r) / 2 / o,
        c = -(1 + r) / o;
      var u = 0,
        h = 0,
        b = 0,
        p = 0,
        m = 0,
        v = function (e) {
          return b = f * e + c * u + f * h - _ * p - l * m, h = u, u = e, m = p, p = b;
        };
      return v.Embed = {
        x1: 0,
        x2: 0,
        y1: 0,
        y2: 0,
        b0: f,
        b1: c,
        a1: _,
        a2: l
      }, v;
    }, N.PowerLevel = function (e, t) {
      var a = e / t || 0;
      return a < 1251 ? Math.round(a / 1250 * 10) : Math.round(Math.min(100, Math.max(0, 100 * (1 + Math.log(a / 1e4) / Math.log(10)))));
    }, N.PowerDBFS = function (e) {
      var t = Math.max(.1, e || 0);
      return t = Math.min(t, 32767), t = 20 * Math.log(t / 32767) / Math.log(10), Math.max(-100, Math.round(t));
    }, N.CLog = function (e, t) {
      if ("object" == typeof console) {
        var a = new Date(),
          n = ("0" + a.getMinutes()).substr(-2) + ":" + ("0" + a.getSeconds()).substr(-2) + "." + ("00" + a.getMilliseconds()).substr(-3),
          s = this && this.envIn && this.envCheck && this.id,
          r = ["[" + n + " " + R + (s ? ":" + s : "") + "]" + e],
          i = arguments,
          o = N.CLog,
          _ = 2,
          l = o.log || console.log;
        for (f(t) ? l = 1 == t ? o.error || console.error : 3 == t ? o.warn || console.warn : l : _ = 1; _ < i.length; _++) r.push(i[_]);
        c ? l && l("[IsLoser]" + r[0], 1 < r.length ? r : "") : l.apply(console, r);
      }
    };
    var O = function () {
        N.CLog.apply(this, arguments);
      },
      c = !0;
    try {
      c = !console.log.apply;
    } catch (e) {}
    var _ = 0;
    function l(e) {
      var t = this;
      t.id = ++_, u();
      var a = {
        type: "mp3",
        onProcess: S
      };
      for (var n in e) a[n] = e[n];
      var s = (t.set = a)[i],
        r = a[D];
      (s && !f(s) || r && !f(r)) && t.CLog(z.G("IllegalArgs-1", [z("VtS4::{1}和{2}必须是数值", 0, D, i)]), 1, e), a[i] = +s || 16, a[D] = +r || 16e3, t.state = 0, t._S = 9, t.Sync = {
        O: 9,
        C: 9
      };
    }
    N.Sync = {
      O: 9,
      C: 9
    }, N.prototype = l.prototype = {
      CLog: O,
      _streamStore: function () {
        return this.set.sourceStream ? this : N;
      },
      _streamCtx: function () {
        var e = this._streamStore().Stream;
        return e && e._c;
      },
      open: function (e, a) {
        var n = this,
          s = n.set,
          r = n._streamStore(),
          i = 0;
        e = e || S;
        var o = function (e, t) {
          t = !!t, n.CLog(z("5tWi::录音open失败：") + e + ",isUserNotAllow:" + t, 1), i && N.CloseNewCtx(i), a && a(e, t);
        };
        n._streamTag = A;
        var _ = function () {
            n.CLog("open ok, id:" + n.id + " stream:" + n._streamTag), e(), n._SO = 0;
          },
          l = r.Sync,
          f = ++l.O,
          c = l.C;
        n._O = n._O_ = f, n._SO = n._S;
        if (w) {
          var t = n.envCheck({
            envName: "H5",
            canProcess: !0
          });
          if (t) o(z("A5bm::不能录音：") + t);else if (s.sourceStream) {
            if (n._streamTag = "set.sourceStream", !N.GetContext()) return void o(z("1iU7::不支持此浏览器从流中获取录音"));
            L(r);
            var u = n.Stream = s.sourceStream;
            u._RC = s.runningContext, u._call = {};
            try {
              C(r);
            } catch (e) {
              return L(r), void o(z("BTW2::从流中打开录音失败：") + e.message);
            }
            _();
          } else {
            var h = function (e, t) {
              try {
                window.top.a;
              } catch (e) {
                return void o(z("Nclz::无权录音(跨域，请尝试给iframe添加麦克风访问策略，如{1})", 0, 'allow="camera;microphone"'));
              }
              /Permission|Allow/i.test(e) ? o(z("gyO5::用户拒绝了录音权限"), !0) : !1 === window.isSecureContext ? o(z("oWNo::浏览器禁止不安全页面录音，可开启https解决")) : /Found/i.test(e) ? o(t + z("jBa9::，无可用麦克风")) : o(t);
            };
            if (N.IsOpen()) _();else if (N.Support()) {
              var b = s.runningContext;
              b || (b = i = N.GetContext(!0));
              var p = function (t) {
                  setTimeout(function () {
                    t._call = {};
                    var e = N.Stream;
                    e && (L(), t._call = e._call), (N.Stream = t)._c = b, t._RC = s.runningContext, function () {
                      if (c != l.C || !n._O) {
                        var e = z("dFm8::open被取消");
                        return f == l.O ? n.close() : e = z("VtJO::open被中断"), o(e), !0;
                      }
                    }() || (N.IsOpen() ? (e && n.CLog(z("upb8::发现同时多次调用open"), 1), C(r, 1), _()) : o(z("Q1GA::录音功能无效：无音频流")));
                  }, 100);
                },
                m = function (e) {
                  var t = e.name || e.message || e.code + ":" + e;
                  n.CLog(z("xEQR::请求录音权限错误"), 1, e), h(t, z("bDOG::无法录音：") + t);
                },
                v = s.audioTrackSet || {};
              v[D] = b[D];
              var d = {
                audio: v
              };
              try {
                var g = N.Scope[A](d, p, m);
              } catch (e) {
                n.CLog(A, 3, e), d = {
                  audio: !0
                }, g = N.Scope[A](d, p, m);
              }
              n.CLog(A + "(" + JSON.stringify(d) + ") " + k(b) + z("RiWe::，未配置noiseSuppression和echoCancellation时浏览器可能会自动打开降噪和回声消除，移动端可能会降低系统播放音量（关闭录音后可恢复），请参阅文档中audioTrackSet配置") + "(" + y + ") LM:" + M + " UA:" + navigator.userAgent), g && g.then && g.then(p)[x](m);
            } else h("", z("COxc::此浏览器不支持录音"));
          }
        } else o(z.G("NonBrowser-1", ["open"]) + z("EMJq::，可尝试使用RecordApp解决方案") + "(" + y + "/tree/master/app-support-sample)");
      },
      close: function (e) {
        e = e || S;
        var t = this,
          a = t._streamStore();
        t._stop();
        var n = " stream:" + t._streamTag,
          s = a.Sync;
        if (t._O = 0, t._O_ != s.O) return t.CLog(z("hWVz::close被忽略（因为同时open了多个rec，只有最后一个会真正close）") + n, 3), void e();
        s.C++, L(a), t.CLog("close," + n), e();
      },
      mock: function (e, t) {
        var a = this;
        return a._stop(), a.isMock = 1, a.mockEnvInfo = null, a.buffers = [e], a.recSize = e.length, a._setSrcSR(t), a._streamTag = "mock", a;
      },
      _setSrcSR: function (e) {
        var t = this.set,
          a = t[D];
        e < a ? t[D] = e : a = 0, this[V] = e, this.CLog(V + ": " + e + " set." + D + ": " + t[D] + (a ? " " + z("UHvm::忽略") + ": " + a : ""), a ? 3 : 0);
      },
      envCheck: function (e) {
        var t,
          a = this.set,
          n = "CPU_BE";
        if (t || N[n] || "function" != typeof Int8Array || new Int8Array(new Int32Array([1]).buffer)[0] || (u(n), t = z("Essp::不支持{1}架构", 0, n)), !t) {
          var s = a.type,
            r = this[s + "_envCheck"];
          a.takeoffEncodeChunk && (r ? e.canProcess || (t = z("7uMV::{1}环境不支持实时处理", 0, e.envName)) : t = z("2XBl::{1}类型不支持设置takeoffEncodeChunk", 0, s) + (this[s] ? "" : z("LG7e::(未加载编码器)"))), !t && r && (t = this[s + "_envCheck"](e, a));
        }
        return t || "";
      },
      envStart: function (e, t) {
        var a = this,
          n = a.set;
        if (a.isMock = e ? 1 : 0, a.mockEnvInfo = e, a.buffers = [], a.recSize = 0, e && (a._streamTag = "env$" + e.envName), a.state = 1, a.envInLast = 0, a.envInFirst = 0, a.envInFix = 0, a.envInFixTs = [], a._setSrcSR(t), a.engineCtx = 0, a[n.type + "_start"]) {
          var s = a.engineCtx = a[n.type + "_start"](n);
          s && (s.pcmDatas = [], s.pcmSize = 0);
        }
      },
      envResume: function () {
        this.envInFixTs = [];
      },
      envIn: function (e, t) {
        var s = this,
          r = s.set,
          i = s.engineCtx;
        if (1 == s.state) {
          var a = s[V],
            n = e.length,
            o = N.PowerLevel(t, n),
            _ = s.buffers,
            l = _.length;
          _.push(e);
          var f = _,
            c = l,
            u = Date.now(),
            h = Math.round(n / a * 1e3);
          s.envInLast = u, 1 == s.buffers.length && (s.envInFirst = u - h);
          var b = s.envInFixTs;
          b.splice(0, 0, {
            t: u,
            d: h
          });
          for (var p = u, m = 0, v = 0; v < b.length; v++) {
            var d = b[v];
            if (3e3 < u - d.t) {
              b.length = v;
              break;
            }
            p = d.t, m += d.d;
          }
          var g = b[1],
            w = u - p,
            S = w - m;
          if (w / 3 < S && (g && 1e3 < w || 6 <= b.length)) {
            var M = u - g.t - h;
            if (h / 5 < M) {
              var y = !r.disableEnvInFix;
              if (s.CLog("[" + u + "]" + Y.get(z(y ? "4Kfd::补偿{1}ms" : "bM5i::未补偿{1}ms", 1), [M]), 3), s.envInFix += M, y) {
                var A = new Int16Array(M * a / 1e3);
                n += A.length, _.push(A);
              }
            }
          }
          var k = s.recSize,
            R = n,
            x = k + R;
          if (s.recSize = x, i) {
            var B = N.SampleData(_, a, r[D], i.chunkInfo);
            i.chunkInfo = B, k = i.pcmSize, R = B.data.length, x = k + R, i.pcmSize = x, _ = i.pcmDatas, l = _.length, _.push(B.data), a = B[D];
          }
          var T = Math.round(x / a * 1e3),
            E = _.length,
            C = f.length,
            I = function () {
              for (var e = L ? 0 : -R, t = null == _[0], a = l; a < E; a++) {
                var n = _[a];
                null == n ? t = 1 : (e += n.length, i && n.length && s[r.type + "_encode"](i, n));
              }
              if (t && i) {
                var a = c;
                for (f[0] && (a = 0); a < C; a++) f[a] = null;
              }
              t && (e = L ? R : 0, _[0] = null), i ? i.pcmSize += e : s.recSize += e;
            },
            L = 0,
            P = "rec.set.onProcess";
          try {
            L = r.onProcess(_, o, T, a, l, I);
          } catch (e) {
            console.error(P + z("gFUF::回调出错是不允许的，需保证不会抛异常"), e);
          }
          var H = Date.now() - u;
          if (10 < H && 1e3 < s.envInFirst - u && s.CLog(P + z("2ghS::低性能，耗时{1}ms", 0, H), 3), !0 === L) {
            for (var O = 0, v = l; v < E; v++) null == _[v] ? O = 1 : _[v] = new Int16Array(0);
            O ? s.CLog(z("ufqH::未进入异步前不能清除buffers"), 3) : i ? i.pcmSize -= R : s.recSize -= R;
          } else I();
        } else s.state || s.CLog("envIn at state=0", 3);
      },
      start: function () {
        var t = this,
          e = 1;
        if (t.set.sourceStream ? t.Stream || (e = 0) : N.IsOpen() || (e = 0), e) {
          var a = t._streamCtx();
          if (t.CLog(z("kLDN::start 开始录音，") + k(a) + " stream:" + t._streamTag), t._stop(), t.envStart(null, a[D]), t.state = 3, t._SO && t._SO + 1 != t._S) t.CLog(z("Bp2y::start被中断"), 3);else {
            t._SO = 0;
            var n = function () {
                3 == t.state && (t.state = 1, t.resume());
              },
              s = "AudioContext resume: ";
            B(a, function (e) {
              return e && t.CLog(s + "wait..."), 3 == t.state;
            }, function (e) {
              e && t.CLog(s + a.state), n();
            }, function (e) {
              t.CLog(s + a.state + z("upkE::，可能无法录音：") + e, 1), n();
            });
          }
        } else t.CLog(z("6WmN::start失败：未open"), 1);
      },
      pause: function () {
        var e = this,
          t = e._streamStore().Stream;
        e.state && (e.state = 2, e.CLog("pause"), t && delete t._call[e.id]);
      },
      resume: function () {
        var a = this,
          t = a._streamStore().Stream,
          n = "resume(wait ctx)";
        if (3 == a.state) a.CLog(n);else if (a.state) {
          a.state = 1, a.CLog("resume"), a.envResume(), t && (t._call[a.id] = function (e, t) {
            1 == a.state && a.envIn(e, t);
          }, r(t));
          var s = a._streamCtx();
          s && B(s, function (e) {
            return e && a.CLog(n + "..."), 1 == a.state;
          }, function (e) {
            e && a.CLog(n + s.state), r(t);
          }, function (e) {
            a.CLog(n + s.state + "[err]" + e, 1);
          });
        }
      },
      _stop: function (e) {
        var t = this,
          a = t.set;
        t.isMock || t._S++, t.state && (t.pause(), t.state = 0), !e && t[a.type + "_stop"] && (t[a.type + "_stop"](t.engineCtx), t.engineCtx = 0);
      },
      stop: function (c, t, e) {
        var u,
          h = this,
          b = h.set,
          a = h.envInLast - h.envInFirst,
          n = a && h.buffers.length;
        h.CLog(z("Xq4s::stop 和start时差:") + (a ? a + "ms " + z("3CQP::补偿:") + h.envInFix + "ms envIn:" + n + " fps:" + (n / a * 1e3).toFixed(1) : "-") + " stream:" + h._streamTag + " (" + y + ") LM:" + M);
        var p = function () {
            h._stop(), e && h.close();
          },
          m = function (e) {
            h.CLog(z("u8JG::结束录音失败：") + e, 1), t && t(e), p();
          },
          s = function (e, t, a) {
            var n = "arraybuffer",
              s = "dataType",
              r = "DefaultDataType",
              i = h[s] || N[r] || "blob",
              o = s + "=" + i,
              _ = e instanceof ArrayBuffer,
              l = 0,
              f = _ ? e.byteLength : e.size;
            if (i == n ? _ || (l = 1) : "blob" == i ? "function" != typeof Blob ? l = z.G("NonBrowser-1", [o]) + z("1skY::，请设置{1}", 0, R + "." + r + '="' + n + '"') : (_ && (e = new Blob([e], {
              type: t
            })), e instanceof Blob || (l = 1), t = e.type || t) : l = z.G("NotSupport-1", [o]), h.CLog(z("Wv7l::结束录音 编码花{1}ms 音频时长{2}ms 文件大小{3}b", 0, Date.now() - u, a, f) + " " + o + "," + t), l) m(1 != l ? l : z("Vkbd::{1}编码器返回的不是{2}", 0, b.type, i) + ", " + o);else {
              if (b.takeoffEncodeChunk) h.CLog(z("QWnr::启用takeoffEncodeChunk后stop返回的blob长度为0不提供音频数据"), 3);else if (f < Math.max(50, a / 5)) return void m(z("Sz2H::生成的{1}无效", 0, b.type));
              c && c(e, a, t), p();
            }
          };
        if (!h.isMock) {
          var r = 3 == h.state;
          if (!h.state || r) return void m(z("wf9t::未开始录音") + (r ? z("Dl2c::，开始录音前无用户交互导致AudioContext未运行") : ""));
        }
        h._stop(!0);
        var i = h.recSize;
        if (i) {
          if (h[b.type]) {
            if (h.isMock) {
              var o = h.envCheck(h.mockEnvInfo || {
                envName: "mock",
                canProcess: !1
              });
              if (o) return void m(z("AxOH::录音错误：") + o);
            }
            var _ = h.engineCtx;
            if (h[b.type + "_complete"] && _) {
              var l = Math.round(_.pcmSize / b[D] * 1e3);
              return u = Date.now(), void h[b.type + "_complete"](_, function (e, t) {
                s(e, t, l);
              }, m);
            }
            if (u = Date.now(), h.buffers[0]) {
              var f = N.SampleData(h.buffers, h[V], b[D]);
              b[D] = f[D];
              var v = f.data,
                l = Math.round(v.length / b[D] * 1e3);
              h.CLog(z("CxeT::采样:{1} 花:{2}ms", 0, i + "->" + v.length, Date.now() - u)), setTimeout(function () {
                u = Date.now(), h[b.type](v, function (e, t) {
                  s(e, t, l);
                }, function (e) {
                  m(e);
                });
              });
            } else m(z("xkKd::音频buffers被释放"));
          } else m(z("xGuI::未加载{1}编码器，请尝试到{2}的src/engine内找到{1}的编码器并加载", 0, b.type, R));
        } else m(z("Ltz3::未采集到录音"));
      }
    };
    var P = function (e, t) {
        t.pos || (t.pos = [0], t.tracks = {}, t.bytes = []);
        var a = t.tracks,
          n = [t.pos[0]],
          s = function () {
            t.pos[0] = n[0];
          },
          r = t.bytes.length,
          i = new Uint8Array(r + e.length);
        if (i.set(t.bytes), i.set(e, r), t.bytes = i, !t._ht) {
          if (j(i, n), X(i, n), !H(j(i, n), [24, 83, 128, 103])) return;
          for (j(i, n); n[0] < i.length;) {
            var o = j(i, n),
              _ = X(i, n),
              l = [0],
              f = 0;
            if (!_) return;
            if (H(o, [22, 84, 174, 107])) {
              for (; l[0] < _.length;) {
                var c = j(_, l),
                  u = X(_, l),
                  h = [0],
                  b = {
                    channels: 0,
                    sampleRate: 0
                  };
                if (H(c, [174])) for (; h[0] < u.length;) {
                  var p = j(u, h),
                    m = X(u, h),
                    v = [0];
                  if (H(p, [215])) {
                    var d = F(m);
                    b.number = d, a[d] = b;
                  } else if (H(p, [131])) {
                    var d = F(m);
                    1 == d ? b.type = "video" : 2 == d ? (b.type = "audio", f || (t.track0 = b), b.idx = f++) : b.type = "Type-" + d;
                  } else if (H(p, [134])) {
                    for (var g = "", w = 0; w < m.length; w++) g += String.fromCharCode(m[w]);
                    b.codec = g;
                  } else if (H(p, [225])) for (; v[0] < m.length;) {
                    var S = j(m, v),
                      M = X(m, v);
                    if (H(S, [181])) {
                      var d = 0,
                        y = new Uint8Array(M.reverse()).buffer;
                      4 == M.length ? d = new Float32Array(y)[0] : 8 == M.length ? d = new Float64Array(y)[0] : O("WebM Track !Float", 1, M), b[D] = Math.round(d);
                    } else H(S, [98, 100]) ? b.bitDepth = F(M) : H(S, [159]) && (b.channels = F(M));
                  }
                }
              }
              t._ht = 1, O("WebM Tracks", a), s();
              break;
            }
          }
        }
        var A = t.track0;
        if (A) {
          if (16 == A.bitDepth && /FLOAT/i.test(A.codec) && (A.bitDepth = 32, O("WebM 16->32 bit", 3)), A[D] != t[D] || 32 != A.bitDepth || A.channels < 1 || !/(\b|_)PCM\b/i.test(A.codec)) return t.bytes = [], t.bad || O("WebM Track Unexpected", 3, t), -(t.bad = 1);
          for (var k = [], R = 0; n[0] < i.length;) {
            var c = j(i, n),
              u = X(i, n);
            if (!u) break;
            if (H(c, [163])) {
              var x = 15 & u[0],
                b = a[x];
              if (b) {
                if (0 === b.idx) {
                  for (var B = new Uint8Array(u.length - 4), w = 4; w < u.length; w++) B[w - 4] = u[w];
                  k.push(B), R += B.length;
                }
              } else O("WebM !Track" + x, 1, a);
            }
            s();
          }
          if (R) {
            var T = new Uint8Array(i.length - t.pos[0]);
            T.set(i.subarray(t.pos[0])), t.bytes = T, t.pos[0] = 0;
            for (var B = new Uint8Array(R), w = 0, E = 0; w < k.length; w++) B.set(k[w], E), E += k[w].length;
            var y = new Float32Array(B.buffer);
            if (1 < A.channels) {
              for (var C = [], w = 0; w < y.length;) C.push(y[w]), w += A.channels;
              y = new Float32Array(C);
            }
            return y;
          }
        }
      },
      H = function (e, t) {
        if (!e || e.length != t.length) return !1;
        if (1 == e.length) return e[0] == t[0];
        for (var a = 0; a < e.length; a++) if (e[a] != t[a]) return !1;
        return !0;
      },
      F = function (e) {
        for (var t = "", a = 0; a < e.length; a++) {
          var n = e[a];
          t += (n < 16 ? "0" : "") + n.toString(16);
        }
        return parseInt(t, 16) || 0;
      },
      j = function (e, t, a) {
        var n = t[0];
        if (!(n >= e.length)) {
          var s = e[n],
            r = ("0000000" + s.toString(2)).substr(-8),
            i = /^(0*1)(\d*)$/.exec(r);
          if (i) {
            var o = i[1].length,
              _ = [];
            if (!(n + o > e.length)) {
              for (var l = 0; l < o; l++) _[l] = e[n], n++;
              return a && (_[0] = parseInt(i[2] || "0", 2)), t[0] = n, _;
            }
          }
        }
      },
      X = function (e, t) {
        var a = j(e, t, 1);
        if (a) {
          var n = F(a),
            s = t[0],
            r = [];
          if (n < 2147483647) {
            if (s + n > e.length) return;
            for (var i = 0; i < n; i++) r[i] = e[s], s++;
          }
          return t[0] = s, r;
        }
      },
      Y = N.i18n = {
        lang: "zh-CN",
        alias: {
          "zh-CN": "zh",
          "en-US": "en"
        },
        locales: {},
        data: {},
        put: function (e, t) {
          var a = R + ".i18n.put: ",
            n = e.overwrite;
          n = null == n || n;
          var s = e.lang;
          if (!(s = Y.alias[s] || s)) throw new Error(a + "set.lang?");
          var r = Y.locales[s];
          r || (r = {}, Y.locales[s] = r);
          for (var i, o = /^([\w\-]+):/, _ = 0; _ < t.length; _++) {
            var l = t[_];
            if (i = o.exec(l)) {
              var f = i[1],
                l = l.substr(f.length + 1);
              !n && r[f] || (r[f] = l);
            } else O(a + "'key:'? " + l, 3, e);
          }
        },
        get: function () {
          return Y.v_G.apply(null, arguments);
        },
        v_G: function (n, s, e) {
          s = s || [], e = e || Y.lang, e = Y.alias[e] || e;
          var t = Y.locales[e],
            r = t && t[n] || "";
          return r || "zh" == e ? (Y.lastLang = e, "=Empty" == r ? "" : r.replace(/\{(\d+)(\!?)\}/g, function (e, t, a) {
            return e = s[(t = +t || 0) - 1], (t < 1 || t > s.length) && (e = "{?}", O("i18n[" + n + "] no {" + t + "}: " + r, 3)), a ? "" : e;
          })) : "en" == e ? Y.v_G(n, s, "zh") : Y.v_G(n, s, "en");
        },
        $T: function () {
          return Y.v_T.apply(null, arguments);
        },
        v_T: function () {
          for (var e, t = arguments, a = "", n = [], s = 0, r = R + ".i18n.$T:", i = /^([\w\-]*):/, o = 0; o < t.length; o++) {
            var _ = t[o];
            if (0 == o) {
              if (e = i.exec(_), !(a = e && e[1])) throw new Error(r + "0 'key:'?");
              _ = _.substr(a.length + 1);
            }
            if (-1 === s) n.push(_);else {
              if (s) throw new Error(r + " bad args");
              if (0 === _) s = -1;else if (f(_)) {
                if (_ < 1) throw new Error(r + " bad args");
                s = _;
              } else {
                var l = 1 == o ? "en" : o ? "" : "zh";
                if ((e = i.exec(_)) && (l = e[1] || l, _ = _.substr(e[1].length + 1)), !e || !l) throw new Error(r + o + " 'lang:'?");
                Y.put({
                  lang: l,
                  overwrite: !1
                }, [a + ":" + _]);
              }
            }
          }
          return a ? 0 < s ? a : Y.v_G(a, n) : "";
        }
      },
      z = Y.$T;
    z.G = Y.get, z("NonBrowser-1::非浏览器环境，不支持{1}", 1), z("IllegalArgs-1::参数错误：{1}", 1), z("NeedImport-2::调用{1}需要先导入{2}", 2), z("NotSupport-1::不支持：{1}", 1), N.TrafficImgUrl = "//ia.51.la/go1?id=20469973&pvFlag=1";
    var u = N.Traffic = function (e) {
      if (w) {
        e = e ? "/" + R + "/Report/" + e : "";
        var t = N.TrafficImgUrl;
        if (t) {
          var a = N.Traffic,
            n = /^(https?:..[^\/#]*\/?)[^#]*/i.exec(location.href) || [],
            s = n[1] || "http://file/",
            r = (n[0] || s) + e;
          if (0 == t.indexOf("//") && (t = /^https:/i.test(r) ? "https:" + t : "http:" + t), e && (t = t + "&cu=" + encodeURIComponent(s + e)), !a[r]) {
            a[r] = 1;
            var i = new Image();
            i.src = t, O("Traffic Analysis Image: " + (e || R + ".TrafficImgUrl=" + N.TrafficImgUrl));
          }
        }
      }
    };
    t && (O(z("8HO5::覆盖导入{1}", 0, R), 1), t.Destroy());
    e[R] = N;
  }(a, t), module.exports && (module.exports = a.Recorder);
}(), function (e) {
  var t = "object" == typeof window && !!window.document,
    a = (t ? window : Object).Recorder,
    n = a.i18n;
  !function (m, e, u, t) {

    var o = "48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000",
      _ = "8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, 192, 224, 256, 320";
    m.prototype.enc_mp3 = {
      stable: !0,
      takeEC: "full",
      getTestMsg: function () {
        return u("Zm7L::采样率范围：{1}；比特率范围：{2}（不同比特率支持的采样率范围不同，小于32kbps时采样率需小于32000）", 0, o, _);
      }
    };
    var h,
      v = function (e) {
        var t = e.bitRate,
          a = e.sampleRate,
          n = a;
        if (-1 == (" " + _ + ",").indexOf(" " + t + ",") && m.CLog(u("eGB9::{1}不在mp3支持的取值范围：{2}", 0, "bitRate=" + t, _), 3), -1 == (" " + o + ",").indexOf(" " + a + ",")) {
          for (var s = o.split(", "), r = [], i = 0; i < s.length; i++) r.push({
            v: +s[i],
            s: Math.abs(s[i] - a)
          });
          r.sort(function (e, t) {
            return e.s - t.s;
          }), n = r[0].v, e.sampleRate = n, m.CLog(u("zLTa::sampleRate已更新为{1}，因为{2}不在mp3支持的取值范围：{3}", 0, n, a, o), 3);
        }
      },
      n = function () {
        return u.G("NeedImport-2", ["mp3.js", "src/engine/mp3-engine.js"]);
      },
      d = t && "function" == typeof Worker;
    m.prototype.mp3 = function (r, i, o) {
      var e = this,
        _ = e.set,
        l = r.length;
      if (m.lamejs) {
        if (d) {
          var t = e.mp3_start(_);
          if (t) {
            if (t.isW) return e.mp3_encode(t, r), void e.mp3_complete(t, i, o, 1);
            e.mp3_stop(t);
          }
        }
        v(_);
        var f = new m.lamejs.Mp3Encoder(1, _.sampleRate, _.bitRate),
          c = new Int8Array(5e5),
          u = 0,
          h = 0,
          b = 0,
          p = function () {
            try {
              if (h < l) var e = f.encodeBuffer(r.subarray(h, h + 57600));else {
                b = 1;
                var e = f.flush();
              }
            } catch (e) {
              if (console.error(e), !b) try {
                f.flush();
              } catch (e) {
                console.error(e);
              }
              return void o("MP3 Encoder: " + e.message);
            }
            var t = e.length;
            if (0 < t) {
              if (u + t > c.length) {
                var a = new Int8Array(c.length + Math.max(5e5, t));
                a.set(c.subarray(0, u)), c = a;
              }
              c.set(e, u), u += t;
            }
            if (h < l) h += 57600, setTimeout(p);else {
              var n = [c.buffer.slice(0, u)],
                s = g.fn(n, u, l, _.sampleRate);
              w(s, _), i(n[0] || new ArrayBuffer(0), "audio/mp3");
            }
          };
        p();
      } else o(n());
    }, m.BindDestroy("mp3Worker", function () {
      h && (m.CLog("mp3Worker Destroy"), h.terminate(), h = null);
    }), m.prototype.mp3_envCheck = function (e, t) {
      var a = "";
      return t.takeoffEncodeChunk && (p() || (a = u("yhUs::当前浏览器版本太低，无法实时处理"))), a || m.lamejs || (a = n()), a;
    }, m.prototype.mp3_start = function (e) {
      return p(e);
    };
    var b = {
        id: 0
      },
      p = function (t, e) {
        var f,
          a = function (e) {
            var t = e.data,
              a = f.wkScope.wk_ctxs,
              n = f.wkScope.wk_lame,
              s = f.wkScope.wk_mp3TrimFix,
              r = a[t.id];
            if ("init" == t.action) a[t.id] = {
              sampleRate: t.sampleRate,
              bitRate: t.bitRate,
              takeoff: t.takeoff,
              pcmSize: 0,
              memory: new Int8Array(5e5),
              mOffset: 0,
              encObj: new n.Mp3Encoder(1, t.sampleRate, t.bitRate)
            };else if (!r) return;
            var i = function (e) {
              var t = e.length;
              if (r.mOffset + t > r.memory.length) {
                var a = new Int8Array(r.memory.length + Math.max(5e5, t));
                a.set(r.memory.subarray(0, r.mOffset)), r.memory = a;
              }
              r.memory.set(e, r.mOffset), r.mOffset += t;
            };
            switch (t.action) {
              case "stop":
                if (!r.isCp) try {
                  r.encObj.flush();
                } catch (e) {
                  console.error(e);
                }
                r.encObj = null, delete a[t.id];
                break;
              case "encode":
                if (r.isCp) break;
                r.pcmSize += t.pcm.length;
                try {
                  var o = r.encObj.encodeBuffer(t.pcm);
                } catch (e) {
                  r.err = e, console.error(e);
                }
                o && 0 < o.length && (r.takeoff ? c.onmessage({
                  action: "takeoff",
                  id: t.id,
                  chunk: o
                }) : i(o));
                break;
              case "complete":
                r.isCp = 1;
                try {
                  var o = r.encObj.flush();
                } catch (e) {
                  r.err = e, console.error(e);
                }
                if (o && 0 < o.length && (r.takeoff ? c.onmessage({
                  action: "takeoff",
                  id: t.id,
                  chunk: o
                }) : i(o)), r.err) {
                  c.onmessage({
                    action: t.action,
                    id: t.id,
                    err: "MP3 Encoder: " + r.err.message
                  });
                  break;
                }
                var _ = [r.memory.buffer.slice(0, r.mOffset)],
                  l = s.fn(_, r.mOffset, r.pcmSize, r.sampleRate);
                c.onmessage({
                  action: t.action,
                  id: t.id,
                  blob: _[0] || new ArrayBuffer(0),
                  meta: l
                });
            }
          },
          n = function (n) {
            c.onmessage = function (e) {
              var t = e;
              n && (t = e.data);
              var a = b[t.id];
              a && ("takeoff" == t.action ? a.set.takeoffEncodeChunk(new Uint8Array(t.chunk.buffer)) : (a.call && a.call(t), a.call = null));
            };
          },
          s = function () {
            var e = {
              worker: c,
              set: t
            };
            return t ? (e.id = ++b.id, b[e.id] = e, v(t), c.postMessage({
              action: "init",
              id: e.id,
              sampleRate: t.sampleRate,
              bitRate: t.bitRate,
              takeoff: !!t.takeoffEncodeChunk,
              x: new Int16Array(5)
            })) : c.postMessage({
              x: new Int16Array(5)
            }), e;
          },
          c = h;
        if (e || !d) return m.CLog(u("k9PT::当前环境不支持Web Worker，mp3实时编码器运行在主线程中"), 3), c = {
          postMessage: function (e) {
            a({
              data: e
            });
          }
        }, f = {
          wkScope: {
            wk_ctxs: {},
            wk_lame: m.lamejs,
            wk_mp3TrimFix: g
          }
        }, n(), s();
        try {
          if (!c) {
            var r = (a + "").replace(/[\w\$]+\.onmessage/g, "self.postMessage"),
              i = ");wk_lame();self.onmessage=" + (r = r.replace(/[\w\$]+\.wkScope/g, "wkScope"));
            i += ";var wkScope={ wk_ctxs:{},wk_lame:wk_lame", i += ",wk_mp3TrimFix:{rm:" + g.rm + ",fn:" + g.fn + "} }";
            var o = m.lamejs.toString(),
              _ = (window.URL || webkitURL).createObjectURL(new Blob(["var wk_lame=(", o, i], {
                type: "text/javascript"
              }));
            c = new Worker(_), setTimeout(function () {
              (window.URL || webkitURL).revokeObjectURL(_);
            }, 1e4), n(1);
          }
          var l = s();
          return l.isW = 1, h = c, l;
        } catch (e) {
          return c && c.terminate(), console.error(e), p(t, 1);
        }
      };
    m.prototype.mp3_stop = function (e) {
      if (e && e.worker) {
        e.worker.postMessage({
          action: "stop",
          id: e.id
        }), e.worker = null, delete b[e.id];
        var t = -1;
        for (var a in b) t++;
        t && m.CLog(u("fT6M::mp3 worker剩{1}个未stop", 0, t), 3);
      }
    }, m.prototype.mp3_encode = function (e, t) {
      e && e.worker && e.worker.postMessage({
        action: "encode",
        id: e.id,
        pcm: t
      });
    }, m.prototype.mp3_complete = function (t, a, n, s) {
      var r = this;
      t && t.worker ? (t.call = function (e) {
        s && r.mp3_stop(t), e.err ? n(e.err) : (w(e.meta, t.set), a(e.blob, "audio/mp3"));
      }, t.worker.postMessage({
        action: "complete",
        id: t.id
      })) : n(u("mPxH::mp3编码器未start"));
    }, m.mp3ReadMeta = function (e, t) {
      var a = "undefined" != typeof window && window.parseInt || "undefined" != typeof self && self.parseInt || parseInt,
        n = new Uint8Array(e[0] || []);
      if (n.length < 4) return null;
      var s = function (e, t) {
          return ("0000000" + ((t || n)[e] || 0).toString(2)).substr(-8);
        },
        r = s(0) + s(1),
        i = s(2) + s(3);
      if (!/^1{11}/.test(r)) return null;
      var o = {
          "00": 2.5,
          10: 2,
          11: 1
        }[r.substr(11, 2)],
        _ = {
          "01": 3
        }[r.substr(13, 2)],
        l = {
          1: [44100, 48e3, 32e3],
          2: [22050, 24e3, 16e3],
          2.5: [11025, 12e3, 8e3]
        }[o];
      l && (l = l[a(i.substr(4, 2), 2)]);
      var f = [[0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160], [0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320]][1 == o ? 1 : 0][a(i.substr(0, 4), 2)];
      if (!(o && _ && f && l)) return null;
      for (var c = Math.round(8 * t / f), u = 1 == _ ? 384 : 2 == _ ? 1152 : 1 == o ? 1152 : 576, h = u / l * 1e3, b = Math.floor(u * f / 8 / l * 1e3), p = 0, m = 0, v = 0; v < e.length; v++) {
        var d = e[v];
        if (m += d.byteLength, b + 3 <= m) {
          var g = new Uint8Array(d),
            w = d.byteLength - (m - (b + 3) + 1),
            S = s(w, g);
          p = "1" == S.charAt(6);
          break;
        }
      }
      return p && b++, {
        version: o,
        layer: _,
        sampleRate: l,
        bitRate: f,
        duration: c,
        size: t,
        hasPadding: p,
        frameSize: b,
        frameDurationFloat: h
      };
    };
    var g = {
        rm: m.mp3ReadMeta,
        fn: function (e, t, a, n) {
          var s = this.rm(e, t);
          if (!s) return {
            err: "mp3 unknown format"
          };
          var r = Math.round(a / n * 1e3),
            i = Math.floor((s.duration - r) / s.frameDurationFloat);
          if (0 < i) {
            var o = i * s.frameSize - (s.hasPadding ? 1 : 0);
            t -= o;
            for (var _ = 0, l = [], f = 0; f < e.length; f++) {
              var c = e[f];
              if (o <= 0) break;
              o >= c.byteLength ? (o -= c.byteLength, l.push(c), e.splice(f, 1), f--) : (e[f] = c.slice(o), _ = c, o = 0);
            }
            var u = this.rm(e, t);
            if (!u) {
              _ && (e[0] = _);
              for (var f = 0; f < l.length; f++) e.splice(f, 0, l[f]);
              s.err = "mp3 fix error: 已还原，错误原因不明";
            }
            var h = s.trimFix = {};
            h.remove = i, h.removeDuration = Math.round(i * s.frameDurationFloat), h.duration = Math.round(8 * t / s.bitRate);
          }
          return s;
        }
      },
      w = function (e, t) {
        var a = "MP3 Info: ";
        (e.sampleRate && e.sampleRate != t.sampleRate || e.bitRate && e.bitRate != t.bitRate) && (m.CLog(a + u("uY9i::和设置的不匹配{1}，已更新成{2}", 0, "set:" + t.bitRate + "kbps " + t.sampleRate + "hz", "set:" + e.bitRate + "kbps " + e.sampleRate + "hz"), 3, t), t.sampleRate = e.sampleRate, t.bitRate = e.bitRate);
        var n = e.trimFix;
        n ? (a += u("iMSm::Fix移除{1}帧", 0, n.remove) + " " + n.removeDuration + "ms -> " + n.duration + "ms", 2 < n.remove && (e.err = (e.err ? e.err + ", " : "") + u("b9zm::移除帧数过多"))) : a += (e.duration || "-") + "ms", e.err ? m.CLog(a, 1, e.err, e) : m.CLog(a, e);
      };
  }(a, 0, n.$T, t);
}(), function (e) {

  function t() {
    var d = function (e) {
        return Math.log(e) / Math.log(10);
      },
      me = function (e) {
        throw new Error("abort(" + e + ")");
      };
    function S(e) {
      return new Int8Array(e);
    }
    function s(e) {
      return new Int16Array(e);
    }
    function ve(e) {
      return new Int32Array(e);
    }
    function de(e) {
      return new Float32Array(e);
    }
    function n(e) {
      return new Float64Array(e);
    }
    function ge(e) {
      if (1 == e.length) return de(e[0]);
      var t = e[0];
      e = e.slice(1);
      for (var a = [], n = 0; n < t; n++) a.push(ge(e));
      return a;
    }
    function w(e) {
      if (1 == e.length) return ve(e[0]);
      var t = e[0];
      e = e.slice(1);
      for (var a = [], n = 0; n < t; n++) a.push(w(e));
      return a;
    }
    function M(e) {
      if (1 == e.length) return s(e[0]);
      var t = e[0];
      e = e.slice(1);
      for (var a = [], n = 0; n < t; n++) a.push(M(e));
      return a;
    }
    function E(e) {
      if (1 == e.length) return new Array(e[0]);
      var t = e[0];
      e = e.slice(1);
      for (var a = [], n = 0; n < t; n++) a.push(E(e));
      return a;
    }
    var we = {
        fill: function (e, t, a, n) {
          if (2 == arguments.length) for (var s = 0; s < e.length; s++) e[s] = t;else for (var s = t; s < a; s++) e[s] = n;
        }
      },
      I = {
        arraycopy: function (e, t, a, n, s) {
          for (var r = t + s; t < r;) a[n++] = e[t++];
        }
      },
      V = {};
    function Se(e) {
      this.ordinal = e;
    }
    V.SQRT2 = 1.4142135623730951, V.FAST_LOG10 = function (e) {
      return d(e);
    }, V.FAST_LOG10_X = function (e, t) {
      return d(e) * t;
    }, Se.short_block_allowed = new Se(0), Se.short_block_coupled = new Se(1), Se.short_block_dispensed = new Se(2), Se.short_block_forced = new Se(3);
    var D = {};
    function Me(e) {
      this.ordinal = e;
    }
    function ye(e) {
      var t = e;
      this.ordinal = function () {
        return t;
      };
    }
    function A() {
      var S = null;
      function v(e) {
        this.bits = 0 | e;
      }
      this.qupvt = null, this.setModules = function (e) {
        this.qupvt = e, S = e;
      };
      var s = [[0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 1], [1, 1], [1, 1], [1, 2], [2, 2], [2, 3], [2, 3], [3, 4], [3, 4], [3, 4], [4, 5], [4, 5], [4, 6], [5, 6], [5, 6], [5, 7], [6, 7], [6, 7]];
      function M(e, t, a, n, s, r) {
        var i = .5946 / t;
        for (e >>= 1; 0 != e--;) s[r++] = i > a[n++] ? 0 : 1, s[r++] = i > a[n++] ? 0 : 1;
      }
      function y(e, t, a, n, s, r) {
        var i = (e >>= 1) % 2;
        for (e >>= 1; 0 != e--;) {
          var o, _, l, f, c, u, h, b;
          o = a[n++] * t, _ = a[n++] * t, c = 0 | o, l = a[n++] * t, u = 0 | _, f = a[n++] * t, h = 0 | l, o += S.adj43[c], b = 0 | f, _ += S.adj43[u], s[r++] = 0 | o, l += S.adj43[h], s[r++] = 0 | _, f += S.adj43[b], s[r++] = 0 | l, s[r++] = 0 | f;
        }
        0 != i && (o = a[n++] * t, _ = a[n++] * t, c = 0 | o, u = 0 | _, o += S.adj43[c], _ += S.adj43[u], s[r++] = 0 | o, s[r++] = 0 | _);
      }
      var o = [1, 2, 5, 7, 7, 10, 10, 13, 13, 13, 13, 13, 13, 13, 13];
      function d(e, t, a, n) {
        var s = function (e, t, a) {
          var n = 0,
            s = 0;
          do {
            var r = e[t++],
              i = e[t++];
            n < r && (n = r), s < i && (s = i);
          } while (t < a);
          return n < s && (n = s), n;
        }(e, t, a);
        switch (s) {
          case 0:
            return s;
          case 1:
            return function (e, t, a, n) {
              var s = 0,
                r = k.ht[1].hlen;
              do {
                var i = 2 * e[t + 0] + e[t + 1];
                t += 2, s += r[i];
              } while (t < a);
              return n.bits += s, 1;
            }(e, t, a, n);
          case 2:
          case 3:
            return function (e, t, a, n, s) {
              var r,
                i,
                o = 0,
                _ = k.ht[n].xlen;
              i = 2 == n ? k.table23 : k.table56;
              do {
                var l = e[t + 0] * _ + e[t + 1];
                t += 2, o += i[l];
              } while (t < a);
              return (r = 65535 & o) < (o >>= 16) && (o = r, n++), s.bits += o, n;
            }(e, t, a, o[s - 1], n);
          case 4:
          case 5:
          case 6:
          case 7:
          case 8:
          case 9:
          case 10:
          case 11:
          case 12:
          case 13:
          case 14:
          case 15:
            return function (e, t, a, n, s) {
              var r = 0,
                i = 0,
                o = 0,
                _ = k.ht[n].xlen,
                l = k.ht[n].hlen,
                f = k.ht[n + 1].hlen,
                c = k.ht[n + 2].hlen;
              do {
                var u = e[t + 0] * _ + e[t + 1];
                t += 2, r += l[u], i += f[u], o += c[u];
              } while (t < a);
              var h = n;
              return i < r && (r = i, h++), o < r && (r = o, h = n + 2), s.bits += r, h;
            }(e, t, a, o[s - 1], n);
          default:
            var r, i;
            for (T.IXMAX_VAL < s && me(), s -= 15, r = 24; r < 32 && !(k.ht[r].linmax >= s); r++);
            for (i = r - 8; i < 24 && !(k.ht[i].linmax >= s); i++);
            return function (e, t, a, n, s, r) {
              var i,
                o = 65536 * k.ht[n].xlen + k.ht[s].xlen,
                _ = 0;
              do {
                var l = e[t++],
                  f = e[t++];
                0 != l && (14 < l && (l = 15, _ += o), l *= 16), 0 != f && (14 < f && (f = 15, _ += o), l += f), _ += k.largetbl[l];
              } while (t < a);
              return (i = 65535 & _) < (_ >>= 16) && (_ = i, n = s), r.bits += _, n;
            }(e, t, a, i, r, n);
        }
      }
      function h(e, t, a, n, s, r, i, o) {
        for (var _ = t.big_values, l = 2; l < Ae.SBMAX_l + 1; l++) {
          var f = e.scalefac_band.l[l];
          if (_ <= f) break;
          var c = s[l - 2] + t.count1bits;
          if (a.part2_3_length <= c) break;
          var u = new v(c),
            h = d(n, f, _, u);
          c = u.bits, a.part2_3_length <= c || (a.assign(t), a.part2_3_length = c, a.region0_count = r[l - 2], a.region1_count = l - 2 - r[l - 2], a.table_select[0] = i[l - 2], a.table_select[1] = o[l - 2], a.table_select[2] = h);
        }
      }
      this.noquant_count_bits = function (e, t, a) {
        var n = t.l3_enc,
          s = Math.min(576, t.max_nonzero_coeff + 2 >> 1 << 1);
        for (null != a && (a.sfb_count1 = 0); 1 < s && 0 == (n[s - 1] | n[s - 2]); s -= 2);
        t.count1 = s;
        for (var r = 0, i = 0; 3 < s; s -= 4) {
          var o;
          if (1 < (2147483647 & (n[s - 1] | n[s - 2] | n[s - 3] | n[s - 4]))) break;
          o = 2 * (2 * (2 * n[s - 4] + n[s - 3]) + n[s - 2]) + n[s - 1], r += k.t32l[o], i += k.t33l[o];
        }
        var _ = r;
        if (t.count1table_select = 0, i < r && (_ = i, t.count1table_select = 1), t.count1bits = _, 0 == (t.big_values = s)) return _;
        if (t.block_type == Ae.SHORT_TYPE) (r = 3 * e.scalefac_band.s[3]) > t.big_values && (r = t.big_values), i = t.big_values;else if (t.block_type == Ae.NORM_TYPE) {
          if (r = t.region0_count = e.bv_scf[s - 2], i = t.region1_count = e.bv_scf[s - 1], i = e.scalefac_band.l[r + i + 2], r = e.scalefac_band.l[r + 1], i < s) {
            var l = new v(_);
            t.table_select[2] = d(n, i, s, l), _ = l.bits;
          }
        } else t.region0_count = 7, t.region1_count = Ae.SBMAX_l - 1 - 7 - 1, r = e.scalefac_band.l[8], (i = s) < r && (r = i);
        if (r = Math.min(r, s), i = Math.min(i, s), 0 < r) {
          var l = new v(_);
          t.table_select[0] = d(n, 0, r, l), _ = l.bits;
        }
        if (r < i) {
          var l = new v(_);
          t.table_select[1] = d(n, r, i, l), _ = l.bits;
        }
        if (2 == e.use_best_huffman && me(), null != a && t.block_type == Ae.NORM_TYPE) {
          for (var f = 0; e.scalefac_band.l[f] < t.big_values;) f++;
          a.sfb_count1 = f;
        }
        return _;
      }, this.count_bits = function (e, t, a, n) {
        var s = a.l3_enc,
          r = T.IXMAX_VAL / S.IPOW20(a.global_gain);
        return a.xrpow_max > r ? T.LARGE_BITS : (function (e, t, a, n, s) {
          var r,
            i,
            o,
            _ = 0,
            l = 0,
            f = 0,
            c = 0,
            u = t,
            h = 0,
            b = u,
            p = 0,
            m = e,
            v = 0;
          for (o = null != s && n.global_gain == s.global_gain, i = n.block_type == Ae.SHORT_TYPE ? 38 : 21, r = 0; r <= i; r++) {
            var d = -1;
            if ((o || n.block_type == Ae.NORM_TYPE) && (d = n.global_gain - (n.scalefac[r] + (0 != n.preflag ? S.pretab[r] : 0) << n.scalefac_scale + 1) - 8 * n.subblock_gain[n.window[r]]), o && s.step[r] == d) 0 != l && (y(l, a, m, v, b, p), l = 0), 0 != f && me();else {
              var g,
                w = n.width[r];
              if (_ + n.width[r] > n.max_nonzero_coeff && (g = n.max_nonzero_coeff - _ + 1, we.fill(t, n.max_nonzero_coeff, 576, 0), (w = g) < 0 && (w = 0), r = i + 1), 0 == l && 0 == f && (b = u, p = h, m = e, v = c), null != s && 0 < s.sfb_count1 && r >= s.sfb_count1 && 0 < s.step[r] && d >= s.step[r] ? (0 != l && (y(l, a, m, v, b, p), l = 0, b = u, p = h, m = e, v = c), f += w) : (0 != f && (M(f, a, m, v, b, p), f = 0, b = u, p = h, m = e, v = c), l += w), w <= 0) {
                0 != f && me(), 0 != l && me();
                break;
              }
            }
            r <= i && (h += n.width[r], c += n.width[r], _ += n.width[r]);
          }
          0 != l && (y(l, a, m, v, b, p), l = 0), 0 != f && me();
        }(t, s, S.IPOW20(a.global_gain), a, n), 0 != (2 & e.substep_shaping) && me(), this.noquant_count_bits(e, a, n));
      }, this.best_huffman_divide = function (e, t) {
        var a = new B(),
          n = t.l3_enc,
          s = ve(23),
          r = ve(23),
          i = ve(23),
          o = ve(23);
        if (t.block_type != Ae.SHORT_TYPE || 1 != e.mode_gr) {
          a.assign(t), t.block_type == Ae.NORM_TYPE && (function (e, t, a, n, s, r, i) {
            for (var o = t.big_values, _ = 0; _ <= 22; _++) n[_] = T.LARGE_BITS;
            for (var _ = 0; _ < 16; _++) {
              var l = e.scalefac_band.l[_ + 1];
              if (o <= l) break;
              var f = 0,
                c = new v(f),
                u = d(a, 0, l, c);
              f = c.bits;
              for (var h = 0; h < 8; h++) {
                var b = e.scalefac_band.l[_ + h + 2];
                if (o <= b) break;
                var p = f;
                c = new v(p);
                var m = d(a, l, b, c);
                p = c.bits, n[_ + h] > p && (n[_ + h] = p, s[_ + h] = _, r[_ + h] = u, i[_ + h] = m);
              }
            }
          }(e, t, n, s, r, i, o), h(e, a, t, n, s, r, i, o));
          var _ = a.big_values;
          if (!(0 == _ || 1 < (n[_ - 2] | n[_ - 1]) || 576 < (_ = t.count1 + 2))) {
            a.assign(t), a.count1 = _;
            for (var l = 0, f = 0; _ > a.big_values; _ -= 4) {
              var c = 2 * (2 * (2 * n[_ - 4] + n[_ - 3]) + n[_ - 2]) + n[_ - 1];
              l += k.t32l[c], f += k.t33l[c];
            }
            if (a.big_values = _, a.count1table_select = 0, f < l && (l = f, a.count1table_select = 1), a.count1bits = l, a.block_type == Ae.NORM_TYPE) h(e, a, t, n, s, r, i, o);else {
              if (a.part2_3_length = l, l = e.scalefac_band.l[8], _ < l && (l = _), 0 < l) {
                var u = new v(a.part2_3_length);
                a.table_select[0] = d(n, 0, l, u), a.part2_3_length = u.bits;
              }
              if (l < _) {
                var u = new v(a.part2_3_length);
                a.table_select[1] = d(n, l, _, u), a.part2_3_length = u.bits;
              }
              t.part2_3_length > a.part2_3_length && t.assign(a);
            }
          }
        }
      };
      var u = [1, 1, 1, 1, 8, 2, 2, 2, 4, 4, 4, 8, 8, 8, 16, 16],
        b = [1, 2, 4, 8, 1, 2, 4, 8, 2, 4, 8, 2, 4, 8, 4, 8],
        p = [0, 0, 0, 0, 3, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4],
        m = [0, 1, 2, 3, 0, 1, 2, 3, 1, 2, 3, 1, 2, 3, 2, 3];
      A.slen1_tab = p, A.slen2_tab = m, this.best_scalefac_store = function (e, t, a, n) {
        var s,
          r,
          i,
          o,
          _ = n.tt[t][a],
          l = 0;
        for (s = i = 0; s < _.sfbmax; s++) {
          var f = _.width[s];
          for (i += f, o = -f; o < 0 && 0 == _.l3_enc[o + i]; o++);
          0 == o && (_.scalefac[s] = l = -2);
        }
        if (0 == _.scalefac_scale && 0 == _.preflag) {
          var c = 0;
          for (s = 0; s < _.sfbmax; s++) 0 < _.scalefac[s] && (c |= _.scalefac[s]);
          if (0 == (1 & c) && 0 != c) {
            for (s = 0; s < _.sfbmax; s++) 0 < _.scalefac[s] && (_.scalefac[s] >>= 1);
            _.scalefac_scale = l = 1;
          }
        }
        if (0 == _.preflag && _.block_type != Ae.SHORT_TYPE && 2 == e.mode_gr) {
          for (s = 11; s < Ae.SBPSY_l && !(_.scalefac[s] < S.pretab[s] && -2 != _.scalefac[s]); s++);
          if (s == Ae.SBPSY_l) {
            for (s = 11; s < Ae.SBPSY_l; s++) 0 < _.scalefac[s] && (_.scalefac[s] -= S.pretab[s]);
            _.preflag = l = 1;
          }
        }
        for (r = 0; r < 4; r++) n.scfsi[a][r] = 0;
        for (2 == e.mode_gr && 1 == t && n.tt[0][a].block_type != Ae.SHORT_TYPE && n.tt[1][a].block_type != Ae.SHORT_TYPE && (function (e, t) {
          for (var a, n = t.tt[1][e], s = t.tt[0][e], r = 0; r < k.scfsi_band.length - 1; r++) {
            for (a = k.scfsi_band[r]; a < k.scfsi_band[r + 1] && !(s.scalefac[a] != n.scalefac[a] && 0 <= n.scalefac[a]); a++);
            if (a == k.scfsi_band[r + 1]) {
              for (a = k.scfsi_band[r]; a < k.scfsi_band[r + 1]; a++) n.scalefac[a] = -1;
              t.scfsi[e][r] = 1;
            }
          }
          var i = 0,
            o = 0;
          for (a = 0; a < 11; a++) -1 != n.scalefac[a] && (o++, i < n.scalefac[a] && (i = n.scalefac[a]));
          for (var _ = 0, l = 0; a < Ae.SBPSY_l; a++) -1 != n.scalefac[a] && (l++, _ < n.scalefac[a] && (_ = n.scalefac[a]));
          for (var r = 0; r < 16; r++) if (i < u[r] && _ < b[r]) {
            var f = p[r] * o + m[r] * l;
            n.part2_length > f && (n.part2_length = f, n.scalefac_compress = r);
          }
        }(a, n), l = 0), s = 0; s < _.sfbmax; s++) -2 == _.scalefac[s] && (_.scalefac[s] = 0);
        0 != l && (2 == e.mode_gr ? this.scale_bitcount(_) : this.scale_bitcount_lsf(e, _));
      };
      var _ = [0, 18, 36, 54, 54, 36, 54, 72, 54, 72, 90, 72, 90, 108, 108, 126],
        l = [0, 18, 36, 54, 51, 35, 53, 71, 52, 70, 88, 69, 87, 105, 104, 122],
        f = [0, 10, 20, 30, 33, 21, 31, 41, 32, 42, 52, 43, 53, 63, 64, 74];
      this.scale_bitcount = function (e) {
        var t,
          a,
          n,
          s = 0,
          r = 0,
          i = e.scalefac;
        if (e.block_type == Ae.SHORT_TYPE) n = _, 0 != e.mixed_block_flag && (n = l);else if (n = f, 0 == e.preflag) {
          for (a = 11; a < Ae.SBPSY_l && !(i[a] < S.pretab[a]); a++);
          if (a == Ae.SBPSY_l) for (e.preflag = 1, a = 11; a < Ae.SBPSY_l; a++) i[a] -= S.pretab[a];
        }
        for (a = 0; a < e.sfbdivide; a++) s < i[a] && (s = i[a]);
        for (; a < e.sfbmax; a++) r < i[a] && (r = i[a]);
        for (e.part2_length = T.LARGE_BITS, t = 0; t < 16; t++) s < u[t] && r < b[t] && e.part2_length > n[t] && (e.part2_length = n[t], e.scalefac_compress = t);
        return e.part2_length == T.LARGE_BITS;
      };
      var g = [[15, 15, 7, 7], [15, 15, 7, 0], [7, 3, 0, 0], [15, 31, 31, 0], [7, 7, 7, 0], [3, 3, 0, 0]];
      this.scale_bitcount_lsf = function (e, t) {
        var a,
          n,
          s,
          r,
          i,
          o,
          _,
          l,
          f = ve(4),
          c = t.scalefac;
        for (a = 0 != t.preflag ? 2 : 0, _ = 0; _ < 4; _++) f[_] = 0;
        if (t.block_type == Ae.SHORT_TYPE) {
          n = 1;
          var u = S.nr_of_sfb_block[a][n];
          for (s = l = 0; s < 4; s++) for (r = u[s] / 3, _ = 0; _ < r; _++, l++) for (i = 0; i < 3; i++) c[3 * l + i] > f[s] && (f[s] = c[3 * l + i]);
        } else {
          n = 0;
          var u = S.nr_of_sfb_block[a][n];
          for (s = l = 0; s < 4; s++) for (r = u[s], _ = 0; _ < r; _++, l++) c[l] > f[s] && (f[s] = c[l]);
        }
        for (o = !1, s = 0; s < 4; s++) f[s] > g[a][s] && (o = !0);
        if (!o) {
          var h, b, p, m;
          for (t.sfb_partition_table = S.nr_of_sfb_block[a][n], s = 0; s < 4; s++) t.slen[s] = w[f[s]];
          switch (h = t.slen[0], b = t.slen[1], p = t.slen[2], m = t.slen[3], a) {
            case 0:
              t.scalefac_compress = (5 * h + b << 4) + (p << 2) + m;
              break;
            case 1:
              t.scalefac_compress = 400 + (5 * h + b << 2) + p;
              break;
            case 2:
              t.scalefac_compress = 500 + 3 * h + b;
          }
        }
        if (!o) for (t.part2_length = 0, s = 0; s < 4; s++) t.part2_length += t.slen[s] * t.sfb_partition_table[s];
        return o;
      };
      var w = [0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4];
      this.huffman_init = function (e) {
        for (var t = 2; t <= 576; t += 2) {
          for (var a, n = 0; e.scalefac_band.l[++n] < t;);
          for (a = s[n][0]; e.scalefac_band.l[a + 1] > t;) a--;
          for (a < 0 && (a = s[n][0]), e.bv_scf[t - 2] = a, a = s[n][1]; e.scalefac_band.l[a + e.bv_scf[t - 2] + 2] > t;) a--;
          a < 0 && (a = s[n][1]), e.bv_scf[t - 1] = a;
        }
      };
    }
    function O() {}
    function y() {
      this.setModules = function (e, t, a) {};
      var o = [0, 49345, 49537, 320, 49921, 960, 640, 49729, 50689, 1728, 1920, 51009, 1280, 50625, 50305, 1088, 52225, 3264, 3456, 52545, 3840, 53185, 52865, 3648, 2560, 51905, 52097, 2880, 51457, 2496, 2176, 51265, 55297, 6336, 6528, 55617, 6912, 56257, 55937, 6720, 7680, 57025, 57217, 8e3, 56577, 7616, 7296, 56385, 5120, 54465, 54657, 5440, 55041, 6080, 5760, 54849, 53761, 4800, 4992, 54081, 4352, 53697, 53377, 4160, 61441, 12480, 12672, 61761, 13056, 62401, 62081, 12864, 13824, 63169, 63361, 14144, 62721, 13760, 13440, 62529, 15360, 64705, 64897, 15680, 65281, 16320, 16e3, 65089, 64001, 15040, 15232, 64321, 14592, 63937, 63617, 14400, 10240, 59585, 59777, 10560, 60161, 11200, 10880, 59969, 60929, 11968, 12160, 61249, 11520, 60865, 60545, 11328, 58369, 9408, 9600, 58689, 9984, 59329, 59009, 9792, 8704, 58049, 58241, 9024, 57601, 8640, 8320, 57409, 40961, 24768, 24960, 41281, 25344, 41921, 41601, 25152, 26112, 42689, 42881, 26432, 42241, 26048, 25728, 42049, 27648, 44225, 44417, 27968, 44801, 28608, 28288, 44609, 43521, 27328, 27520, 43841, 26880, 43457, 43137, 26688, 30720, 47297, 47489, 31040, 47873, 31680, 31360, 47681, 48641, 32448, 32640, 48961, 32e3, 48577, 48257, 31808, 46081, 29888, 30080, 46401, 30464, 47041, 46721, 30272, 29184, 45761, 45953, 29504, 45313, 29120, 28800, 45121, 20480, 37057, 37249, 20800, 37633, 21440, 21120, 37441, 38401, 22208, 22400, 38721, 21760, 38337, 38017, 21568, 39937, 23744, 23936, 40257, 24320, 40897, 40577, 24128, 23040, 39617, 39809, 23360, 39169, 22976, 22656, 38977, 34817, 18624, 18816, 35137, 19200, 35777, 35457, 19008, 19968, 36545, 36737, 20288, 36097, 19904, 19584, 35905, 17408, 33985, 34177, 17728, 34561, 18368, 18048, 34369, 33281, 17088, 17280, 33601, 16640, 33217, 32897, 16448];
      this.updateMusicCRC = function (e, t, a, n) {
        for (var s = 0; s < n; ++s) e[0] = (r = t[a + s], i = (i = e[0]) >> 8 ^ o[255 & (i ^ r)]);
        var r, i;
      };
    }
    function N() {
      var i = this,
        r = null,
        o = null;
      this.setModules = function (e, t, a, n) {
        r = a, o = n;
      };
      var _ = null,
        l = 0,
        f = 0,
        c = 0;
      function v(e, t, a) {
        for (; 0 < a;) {
          var n;
          0 == c && (c = 8, f++, e.header[e.w_ptr].write_timing == l && (s = e, I.arraycopy(s.header[s.w_ptr].buf, 0, _, f, s.sideinfo_len), f += s.sideinfo_len, l += 8 * s.sideinfo_len, s.w_ptr = s.w_ptr + 1 & j.MAX_HEADER_BUF - 1), _[f] = 0), n = Math.min(a, c), a -= n, c -= n, _[f] |= t >> a << c, l += n;
        }
        var s;
      }
      function u(e, t) {
        var a,
          n = e.internal_flags;
        if (8 <= t && (v(n, 76, 8), t -= 8), 8 <= t && (v(n, 65, 8), t -= 8), 8 <= t && (v(n, 77, 8), t -= 8), 8 <= t && (v(n, 69, 8), t -= 8), 32 <= t) {
          var s = r.getLameShortVersion();
          if (32 <= t) for (a = 0; a < s.length && 8 <= t; ++a) t -= 8, v(n, s.charCodeAt(a), 8);
        }
        for (; 1 <= t; t -= 1) v(n, n.ancillary_flag, 1), n.ancillary_flag ^= e.disable_reservoir ? 0 : 1;
      }
      function h(e, t, a) {
        for (var n = e.header[e.h_ptr].ptr; 0 < a;) {
          var s = Math.min(a, 8 - (7 & n));
          a -= s, e.header[e.h_ptr].buf[n >> 3] |= t >> a << 8 - (7 & n) - s, n += s;
        }
        e.header[e.h_ptr].ptr = n;
      }
      function m(e, t) {
        var a,
          n = k.ht[t.count1table_select + 32],
          s = 0,
          r = t.big_values,
          i = t.big_values;
        for (a = (t.count1 - t.big_values) / 4; 0 < a; --a) {
          var o = 0,
            _ = 0;
          0 != t.l3_enc[r + 0] && (_ += 8, t.xr[i + 0] < 0 && o++), 0 != t.l3_enc[r + 1] && (_ += 4, o *= 2, t.xr[i + 1] < 0 && o++), 0 != t.l3_enc[r + 2] && (_ += 2, o *= 2, t.xr[i + 2] < 0 && o++), 0 != t.l3_enc[r + 3] && (_++, o *= 2, t.xr[i + 3] < 0 && o++), r += 4, i += 4, v(e, o + n.table[_], n.hlen[_]), s += n.hlen[_];
        }
        return s;
      }
      function b(e, t, a, n, s) {
        var r = k.ht[t],
          i = 0;
        if (0 == t) return i;
        for (var o = a; o < n; o += 2) {
          var _ = 0,
            l = 0,
            f = r.xlen,
            c = r.xlen,
            u = 0,
            h = s.l3_enc[o],
            b = s.l3_enc[o + 1];
          if (0 != h && (s.xr[o] < 0 && u++, _--), 15 < t) {
            if (14 < h) {
              var p = h - 15;
              u |= p << 1, l = f, h = 15;
            }
            if (14 < b) {
              var m = b - 15;
              u <<= f, u |= m, l += f, b = 15;
            }
            c = 16;
          }
          0 != b && (u <<= 1, s.xr[o + 1] < 0 && u++, _--), h = h * c + b, l -= _, _ += r.hlen[h], v(e, r.table[h], _), v(e, u, l), i += _ + l;
        }
        return i;
      }
      function d(e, t) {
        var a = 3 * e.scalefac_band.s[3];
        a > t.big_values && (a = t.big_values);
        var n = b(e, t.table_select[0], 0, a, t);
        return n += b(e, t.table_select[1], a, t.big_values, t);
      }
      function g(e, t) {
        var a, n, s, r;
        a = t.big_values;
        var i = t.region0_count + 1;
        return s = e.scalefac_band.l[i], i += t.region1_count + 1, r = e.scalefac_band.l[i], a < s && (s = a), a < r && (r = a), n = b(e, t.table_select[0], 0, s, t), n += b(e, t.table_select[1], s, r, t), n += b(e, t.table_select[2], r, a, t);
      }
      function p() {
        this.total = 0;
      }
      function w(e, t) {
        var a,
          n,
          s,
          r = e.internal_flags;
        return r.w_ptr, -1 == (s = r.h_ptr - 1) && (s = j.MAX_HEADER_BUF - 1), a = r.header[s].write_timing - l, 0 <= (t.total = a) && me(), n = i.getframebits(e), a += n, t.total += n, t.total % 8 != 0 ? t.total = 1 + t.total / 8 : t.total = t.total / 8, t.total += f + 1, a;
      }
      this.getframebits = function (e) {
        var t,
          a = e.internal_flags;
        t = 0 != a.bitrate_index ? k.bitrate_table[e.version][a.bitrate_index] : e.brate;
        var n = 0 | 72e3 * (e.version + 1) * t / e.out_samplerate + a.padding;
        return 8 * n;
      }, this.flush_bitstream = function (e) {
        var t,
          a,
          n = e.internal_flags;
          n.h_ptr - 1;
        t = n.l3_side, (a = w(e, new p())) < 0 || (u(e, a), n.ResvSize = 0, t.main_data_begin = 0, n.findReplayGain && me(), n.findPeakSample && me());
      }, this.format_bitstream = function (e) {
        var t,
          a = e.internal_flags;
        t = a.l3_side;
        var n = this.getframebits(e);
        u(e, t.resvDrain_pre), function (e, t) {
          var a,
            n,
            s,
            r = e.internal_flags;
          if (a = r.l3_side, r.header[r.h_ptr].ptr = 0, we.fill(r.header[r.h_ptr].buf, 0, r.sideinfo_len, 0), e.out_samplerate < 16e3 ? h(r, 4094, 12) : h(r, 4095, 12), h(r, e.version, 1), h(r, 1, 2), h(r, e.error_protection ? 0 : 1, 1), h(r, r.bitrate_index, 4), h(r, r.samplerate_index, 2), h(r, r.padding, 1), h(r, e.extension, 1), h(r, e.mode.ordinal(), 2), h(r, r.mode_ext, 2), h(r, e.copyright, 1), h(r, e.original, 1), h(r, e.emphasis, 2), e.error_protection && h(r, 0, 16), 1 == e.version) {
            for (h(r, a.main_data_begin, 9), 2 == r.channels_out ? h(r, a.private_bits, 3) : h(r, a.private_bits, 5), s = 0; s < r.channels_out; s++) {
              var i;
              for (i = 0; i < 4; i++) h(r, a.scfsi[s][i], 1);
            }
            for (n = 0; n < 2; n++) for (s = 0; s < r.channels_out; s++) {
              var o = a.tt[n][s];
              h(r, o.part2_3_length + o.part2_length, 12), h(r, o.big_values / 2, 9), h(r, o.global_gain, 8), h(r, o.scalefac_compress, 4), o.block_type != Ae.NORM_TYPE ? (h(r, 1, 1), h(r, o.block_type, 2), h(r, o.mixed_block_flag, 1), 14 == o.table_select[0] && (o.table_select[0] = 16), h(r, o.table_select[0], 5), 14 == o.table_select[1] && (o.table_select[1] = 16), h(r, o.table_select[1], 5), h(r, o.subblock_gain[0], 3), h(r, o.subblock_gain[1], 3), h(r, o.subblock_gain[2], 3)) : (h(r, 0, 1), 14 == o.table_select[0] && (o.table_select[0] = 16), h(r, o.table_select[0], 5), 14 == o.table_select[1] && (o.table_select[1] = 16), h(r, o.table_select[1], 5), 14 == o.table_select[2] && (o.table_select[2] = 16), h(r, o.table_select[2], 5), h(r, o.region0_count, 4), h(r, o.region1_count, 3)), h(r, o.preflag, 1), h(r, o.scalefac_scale, 1), h(r, o.count1table_select, 1);
            }
          } else for (h(r, a.main_data_begin, 8), h(r, a.private_bits, r.channels_out), s = n = 0; s < r.channels_out; s++) {
            var o = a.tt[n][s];
            h(r, o.part2_3_length + o.part2_length, 12), h(r, o.big_values / 2, 9), h(r, o.global_gain, 8), h(r, o.scalefac_compress, 9), o.block_type != Ae.NORM_TYPE ? (h(r, 1, 1), h(r, o.block_type, 2), h(r, o.mixed_block_flag, 1), 14 == o.table_select[0] && (o.table_select[0] = 16), h(r, o.table_select[0], 5), 14 == o.table_select[1] && (o.table_select[1] = 16), h(r, o.table_select[1], 5), h(r, o.subblock_gain[0], 3), h(r, o.subblock_gain[1], 3), h(r, o.subblock_gain[2], 3)) : (h(r, 0, 1), 14 == o.table_select[0] && (o.table_select[0] = 16), h(r, o.table_select[0], 5), 14 == o.table_select[1] && (o.table_select[1] = 16), h(r, o.table_select[1], 5), 14 == o.table_select[2] && (o.table_select[2] = 16), h(r, o.table_select[2], 5), h(r, o.region0_count, 4), h(r, o.region1_count, 3)), h(r, o.scalefac_scale, 1), h(r, o.count1table_select, 1);
          }
          e.error_protection && me();
          var _ = r.h_ptr;
          r.h_ptr = _ + 1 & j.MAX_HEADER_BUF - 1, r.header[r.h_ptr].write_timing = r.header[_].write_timing + t, r.h_ptr, r.w_ptr;
        }(e, n);
        var s = 8 * a.sideinfo_len;
        if (s += function (e) {
          var t,
            a,
            n,
            s,
            r = 0,
            i = e.internal_flags,
            o = i.l3_side;
          if (1 == e.version) for (t = 0; t < 2; t++) for (a = 0; a < i.channels_out; a++) {
            var _ = o.tt[t][a],
              l = A.slen1_tab[_.scalefac_compress],
              f = A.slen2_tab[_.scalefac_compress];
            for (n = s = 0; n < _.sfbdivide; n++) -1 != _.scalefac[n] && (v(i, _.scalefac[n], l), s += l);
            for (; n < _.sfbmax; n++) -1 != _.scalefac[n] && (v(i, _.scalefac[n], f), s += f);
            _.block_type == Ae.SHORT_TYPE ? s += d(i, _) : s += g(i, _), s += m(i, _), r += s;
          } else for (a = t = 0; a < i.channels_out; a++) {
            var c,
              u,
              _ = o.tt[t][a],
              h = 0;
            if (u = n = s = 0, _.block_type == Ae.SHORT_TYPE) {
              for (; u < 4; u++) {
                var b = _.sfb_partition_table[u] / 3,
                  p = _.slen[u];
                for (c = 0; c < b; c++, n++) v(i, Math.max(_.scalefac[3 * n + 0], 0), p), v(i, Math.max(_.scalefac[3 * n + 1], 0), p), v(i, Math.max(_.scalefac[3 * n + 2], 0), p), h += 3 * p;
              }
              s += d(i, _);
            } else {
              for (; u < 4; u++) {
                var b = _.sfb_partition_table[u],
                  p = _.slen[u];
                for (c = 0; c < b; c++, n++) v(i, Math.max(_.scalefac[n], 0), p), h += p;
              }
              s += g(i, _);
            }
            s += m(i, _), r += h + s;
          }
          return r;
        }(e), u(e, t.resvDrain_post), s += t.resvDrain_post, t.main_data_begin += (n - s) / 8, w(e, new p()), a.ResvSize, 8 * t.main_data_begin != a.ResvSize && (a.ResvSize = 8 * t.main_data_begin), 1e9 < l) {
          var r;
          for (r = 0; r < j.MAX_HEADER_BUF; ++r) a.header[r].write_timing -= l;
          l = 0;
        }
        return 0;
      }, this.copy_buffer = function (e, t, a, n, s) {
        var r = f + 1;
        if (r <= 0) return 0;
        if (0 != n && n < r) return -1;
        if (I.arraycopy(_, 0, t, a, r), f = -1, (c = 0) != s) {
          var i = ve(1);
          i[0] = e.nMusicCRC, o.updateMusicCRC(i, t, a, r), e.nMusicCRC = i[0], 0 < r && (e.VBR_seek_table.nBytesWritten += r), e.decode_on_the_fly && me();
        }
        return r;
      }, this.init_bit_stream_w = function (e) {
        _ = S(Y.LAME_MAXMP3BUFFER), e.h_ptr = e.w_ptr = 0, e.header[e.h_ptr].write_timing = 0, f = -1, l = c = 0;
      };
    }
    function e(e, t, a, n) {
      this.xlen = e, this.linmax = t, this.table = a, this.hlen = n;
    }
    D.MAX_VALUE = 3.4028235e38, Me.vbr_off = new Me(0), Me.vbr_mt = new Me(1), Me.vbr_rh = new Me(2), Me.vbr_abr = new Me(3), Me.vbr_mtrh = new Me(4), Me.vbr_default = Me.vbr_mtrh, ye.STEREO = new ye(0), ye.JOINT_STEREO = new ye(1), ye.DUAL_CHANNEL = new ye(2), ye.MONO = new ye(3), ye.NOT_SET = new ye(4), O.STEPS_per_dB = 100, O.MAX_dB = 120, O.GAIN_NOT_ENOUGH_SAMPLES = -24601, O.GAIN_ANALYSIS_ERROR = 0, O.GAIN_ANALYSIS_OK = 1, O.INIT_GAIN_ANALYSIS_ERROR = 0, O.INIT_GAIN_ANALYSIS_OK = 1, O.MAX_ORDER = O.YULE_ORDER = 10, O.MAX_SAMPLES_PER_WINDOW = (O.MAX_SAMP_FREQ = 48e3) * (O.RMS_WINDOW_TIME_NUMERATOR = 1) / (O.RMS_WINDOW_TIME_DENOMINATOR = 20) + 1, y.NUMTOCENTRIES = 100, y.MAXFRAMESIZE = 2880, N.EQ = function (e, t) {
      return Math.abs(e) > Math.abs(t) ? Math.abs(e - t) <= 1e-6 * Math.abs(e) : Math.abs(e - t) <= 1e-6 * Math.abs(t);
    }, N.NEQ = function (e, t) {
      return !N.EQ(e, t);
    };
    var k = {};
    function R(e) {
      this.bits = e;
    }
    function x() {
      this.over_noise = 0, this.tot_noise = 0, this.max_noise = 0, this.over_count = 0, this.over_SSD = 0, this.bits = 0;
    }
    function r(e, t, a, n) {
      this.l = ve(1 + Ae.SBMAX_l), this.s = ve(1 + Ae.SBMAX_s), this.psfb21 = ve(1 + Ae.PSFB21), this.psfb12 = ve(1 + Ae.PSFB12);
      var s = this.l,
        r = this.s;
      4 == arguments.length && (this.arrL = e, this.arrS = t, this.arr21 = a, this.arr12 = n, I.arraycopy(this.arrL, 0, s, 0, Math.min(this.arrL.length, this.l.length)), I.arraycopy(this.arrS, 0, r, 0, Math.min(this.arrS.length, this.s.length)), I.arraycopy(this.arr21, 0, this.psfb21, 0, Math.min(this.arr21.length, this.psfb21.length)), I.arraycopy(this.arr12, 0, this.psfb12, 0, Math.min(this.arr12.length, this.psfb12.length)));
    }
    function T() {
      var l = null,
        b = null,
        n = null;
      this.setModules = function (e, t, a) {
        l = e, b = t, n = a;
      }, this.IPOW20 = function (e) {
        return h[e];
      };
      var B = 2.220446049250313e-16,
        e = T.IXMAX_VAL,
        f = e + 2,
        c = T.Q_MAX,
        u = T.Q_MAX2,
        s = 100;
      this.nr_of_sfb_block = [[[6, 5, 5, 5], [9, 9, 9, 9], [6, 9, 9, 9]], [[6, 5, 7, 3], [9, 9, 12, 6], [6, 9, 12, 6]], [[11, 10, 0, 0], [18, 18, 0, 0], [15, 18, 0, 0]], [[7, 7, 7, 0], [12, 12, 12, 0], [6, 15, 12, 0]], [[6, 6, 6, 3], [12, 9, 9, 6], [6, 12, 9, 6]], [[8, 8, 5, 0], [15, 12, 9, 0], [6, 18, 9, 0]]];
      var M = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 3, 3, 3, 2, 0];
      this.pretab = M, this.sfBandIndex = [new r([0, 6, 12, 18, 24, 30, 36, 44, 54, 66, 80, 96, 116, 140, 168, 200, 238, 284, 336, 396, 464, 522, 576], [0, 4, 8, 12, 18, 24, 32, 42, 56, 74, 100, 132, 174, 192], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]), new r([0, 6, 12, 18, 24, 30, 36, 44, 54, 66, 80, 96, 114, 136, 162, 194, 232, 278, 332, 394, 464, 540, 576], [0, 4, 8, 12, 18, 26, 36, 48, 62, 80, 104, 136, 180, 192], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]), new r([0, 6, 12, 18, 24, 30, 36, 44, 54, 66, 80, 96, 116, 140, 168, 200, 238, 284, 336, 396, 464, 522, 576], [0, 4, 8, 12, 18, 26, 36, 48, 62, 80, 104, 134, 174, 192], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]), new r([0, 4, 8, 12, 16, 20, 24, 30, 36, 44, 52, 62, 74, 90, 110, 134, 162, 196, 238, 288, 342, 418, 576], [0, 4, 8, 12, 16, 22, 30, 40, 52, 66, 84, 106, 136, 192], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]), new r([0, 4, 8, 12, 16, 20, 24, 30, 36, 42, 50, 60, 72, 88, 106, 128, 156, 190, 230, 276, 330, 384, 576], [0, 4, 8, 12, 16, 22, 28, 38, 50, 64, 80, 100, 126, 192], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]), new r([0, 4, 8, 12, 16, 20, 24, 30, 36, 44, 54, 66, 82, 102, 126, 156, 194, 240, 296, 364, 448, 550, 576], [0, 4, 8, 12, 16, 22, 30, 42, 58, 78, 104, 138, 180, 192], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]), new r([0, 6, 12, 18, 24, 30, 36, 44, 54, 66, 80, 96, 116, 140, 168, 200, 238, 284, 336, 396, 464, 522, 576], [0, 4, 8, 12, 18, 26, 36, 48, 62, 80, 104, 134, 174, 192], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]), new r([0, 6, 12, 18, 24, 30, 36, 44, 54, 66, 80, 96, 116, 140, 168, 200, 238, 284, 336, 396, 464, 522, 576], [0, 4, 8, 12, 18, 26, 36, 48, 62, 80, 104, 134, 174, 192], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]), new r([0, 12, 24, 36, 48, 60, 72, 88, 108, 132, 160, 192, 232, 280, 336, 400, 476, 566, 568, 570, 572, 574, 576], [0, 8, 16, 24, 36, 52, 72, 96, 124, 160, 162, 164, 166, 192], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0])];
      var y = de(c + u + 1),
        h = de(c),
        p = de(f),
        m = de(f);
      function v(e, t) {
        var a = n.ATHformula(t, e);
        return a -= s, a = Math.pow(10, a / 10 + e.ATHlower);
      }
      function A(e) {
        this.s = e;
      }
      this.adj43 = m, this.iteration_init = function (e) {
        var t,
          a = e.internal_flags,
          n = a.l3_side;
        if (0 == a.iteration_init_init) {
          for (a.iteration_init_init = 1, n.main_data_begin = 0, function (e) {
            for (var t = e.internal_flags.ATH.l, a = e.internal_flags.ATH.psfb21, n = e.internal_flags.ATH.s, s = e.internal_flags.ATH.psfb12, r = e.internal_flags, i = e.out_samplerate, o = 0; o < Ae.SBMAX_l; o++) {
              var _ = r.scalefac_band.l[o],
                l = r.scalefac_band.l[o + 1];
              t[o] = D.MAX_VALUE;
              for (var f = _; f < l; f++) {
                var c = f * i / 1152,
                  u = v(e, c);
                t[o] = Math.min(t[o], u);
              }
            }
            for (var o = 0; o < Ae.PSFB21; o++) {
              var _ = r.scalefac_band.psfb21[o],
                l = r.scalefac_band.psfb21[o + 1];
              a[o] = D.MAX_VALUE;
              for (var f = _; f < l; f++) {
                var c = f * i / 1152,
                  u = v(e, c);
                a[o] = Math.min(a[o], u);
              }
            }
            for (var o = 0; o < Ae.SBMAX_s; o++) {
              var _ = r.scalefac_band.s[o],
                l = r.scalefac_band.s[o + 1];
              n[o] = D.MAX_VALUE;
              for (var f = _; f < l; f++) {
                var c = f * i / 384,
                  u = v(e, c);
                n[o] = Math.min(n[o], u);
              }
              n[o] *= r.scalefac_band.s[o + 1] - r.scalefac_band.s[o];
            }
            for (var o = 0; o < Ae.PSFB12; o++) {
              var _ = r.scalefac_band.psfb12[o],
                l = r.scalefac_band.psfb12[o + 1];
              s[o] = D.MAX_VALUE;
              for (var f = _; f < l; f++) {
                var c = f * i / 384,
                  u = v(e, c);
                s[o] = Math.min(s[o], u);
              }
              s[o] *= r.scalefac_band.s[13] - r.scalefac_band.s[12];
            }
            e.noATH && me(), r.ATH.floor = 10 * d(v(e, -1));
          }(e), p[0] = 0, t = 1; t < f; t++) p[t] = Math.pow(t, 4 / 3);
          for (t = 0; t < f - 1; t++) m[t] = t + 1 - Math.pow(.5 * (p[t] + p[t + 1]), .75);
          for (m[t] = .5, t = 0; t < c; t++) h[t] = Math.pow(2, -.1875 * (t - 210));
          for (t = 0; t <= c + u; t++) y[t] = Math.pow(2, .25 * (t - 210 - u));
          var s, r, i, o;
          for (l.huffman_init(a), 32 <= (t = e.exp_nspsytune >> 2 & 63) && (t -= 64), s = Math.pow(10, t / 4 / 10), 32 <= (t = e.exp_nspsytune >> 8 & 63) && (t -= 64), r = Math.pow(10, t / 4 / 10), 32 <= (t = e.exp_nspsytune >> 14 & 63) && (t -= 64), i = Math.pow(10, t / 4 / 10), 32 <= (t = e.exp_nspsytune >> 20 & 63) && (t -= 64), o = i * Math.pow(10, t / 4 / 10), t = 0; t < Ae.SBMAX_l; t++) _ = t <= 6 ? s : t <= 13 ? r : t <= 20 ? i : o, a.nsPsy.longfact[t] = _;
          for (t = 0; t < Ae.SBMAX_s; t++) {
            var _;
            _ = t <= 5 ? s : t <= 10 ? r : t <= 11 ? i : o, a.nsPsy.shortfact[t] = _;
          }
        }
      }, this.on_pe = function (e, t, a, n, s, r) {
        var i,
          o,
          _ = e.internal_flags,
          l = 0,
          f = ve(2),
          c = new R(l),
          u = b.ResvMaxBits(e, n, c, r),
          h = (l = c.bits) + u;
        for (j.MAX_BITS_PER_GRANULE < h && (h = j.MAX_BITS_PER_GRANULE), o = i = 0; o < _.channels_out; ++o) a[o] = Math.min(j.MAX_BITS_PER_CHANNEL, l / _.channels_out), f[o] = 0 | a[o] * t[s][o] / 700 - a[o], f[o] > 3 * n / 4 && (f[o] = 3 * n / 4), f[o] < 0 && (f[o] = 0), f[o] + a[o] > j.MAX_BITS_PER_CHANNEL && (f[o] = Math.max(0, j.MAX_BITS_PER_CHANNEL - a[o])), i += f[o];
        if (u < i) for (o = 0; o < _.channels_out; ++o) f[o] = u * f[o] / i;
        for (o = 0; o < _.channels_out; ++o) a[o] += f[o], u -= f[o];
        for (o = i = 0; o < _.channels_out; ++o) i += a[o];
        return j.MAX_BITS_PER_GRANULE < i && me(), h;
      }, this.athAdjust = function (e, t, a) {
        var n = 90.30873362,
          s = V.FAST_LOG10_X(t, 10),
          r = e * e,
          i = 0;
        return s -= a, 1e-20 < r && (i = 1 + V.FAST_LOG10_X(r, 10 / n)), i < 0 && (i = 0), s *= i, s += a + n - 94.82444863, Math.pow(10, .1 * s);
      }, this.calc_xmin = function (e, t, a, n) {
        var s,
          r = 0,
          i = e.internal_flags,
          o = 0,
          _ = 0,
          l = i.ATH,
          f = a.xr,
          c = e.VBR == Me.vbr_mtrh ? 1 : 0,
          u = i.masking_lower;
        for (e.VBR != Me.vbr_mtrh && e.VBR != Me.vbr_mt || (u = 1), s = 0; s < a.psy_lmax; s++) {
          for (w = e.VBR == Me.vbr_rh || e.VBR == Me.vbr_mtrh ? athAdjust(l.adjust, l.l[s], l.floor) : l.adjust * l.l[s], v = a.width[s], S = w / v, M = B, A = v >> 1, y = 0; k = f[o] * f[o], y += k, M += k < S ? k : S, R = f[++o] * f[o], y += R, M += R < S ? R : S, o++, 0 < --A;);
          if (w < y && _++, s == Ae.SBPSY_l && me(), 0 != c && (w = M), !e.ATHonly) {
            var h = t.en.l[s];
            0 < h && (x = y * t.thm.l[s] * u / h, 0 != c && (x *= i.nsPsy.longfact[s]), w < x && (w = x));
          }
          n[r++] = 0 != c ? w : w * i.nsPsy.longfact[s];
        }
        var b = 575;
        if (a.block_type != Ae.SHORT_TYPE) for (var p = 576; 0 != p-- && N.EQ(f[p], 0);) b = p;
        a.max_nonzero_coeff = b;
        for (var m = a.sfb_smin; s < a.psymax; m++, s += 3) {
          var v, d, g;
          for (g = e.VBR == Me.vbr_rh || e.VBR == Me.vbr_mtrh ? athAdjust(l.adjust, l.s[m], l.floor) : l.adjust * l.s[m], v = a.width[s], d = 0; d < 3; d++) {
            var w,
              S,
              M,
              y = 0,
              A = v >> 1;
            S = g / v, M = B;
            do {
              var k, R;
              k = f[o] * f[o], y += k, M += k < S ? k : S, R = f[++o] * f[o], y += R, M += R < S ? R : S, o++;
            } while (0 < --A);
            if (g < y && _++, m == Ae.SBPSY_s && me(), w = 0 != c ? M : g, !e.ATHonly && !e.ATHshort) {
              var x,
                h = t.en.s[m][d];
              0 < h && (x = y * t.thm.s[m][d] * u / h, 0 != c && (x *= i.nsPsy.shortfact[m]), w < x && (w = x));
            }
            n[r++] = 0 != c ? w : w * i.nsPsy.shortfact[m];
          }
          e.useTemporal && (n[r - 3] > n[r - 3 + 1] && (n[r - 3 + 1] += (n[r - 3] - n[r - 3 + 1]) * i.decay), n[r - 3 + 1] > n[r - 3 + 2] && (n[r - 3 + 2] += (n[r - 3 + 1] - n[r - 3 + 2]) * i.decay));
        }
        return _;
      }, this.calc_noise_core = function (e, t, a, n) {
        var s = 0,
          r = t.s,
          i = e.l3_enc;
        if (r > e.count1) for (; 0 != a--;) _ = e.xr[r], r++, s += _ * _, _ = e.xr[r], r++, s += _ * _;else if (r > e.big_values) {
          var o = de(2);
          for (o[0] = 0, o[1] = n; 0 != a--;) _ = Math.abs(e.xr[r]) - o[i[r]], r++, s += _ * _, _ = Math.abs(e.xr[r]) - o[i[r]], r++, s += _ * _;
        } else for (; 0 != a--;) {
          var _;
          _ = Math.abs(e.xr[r]) - p[i[r]] * n, r++, s += _ * _, _ = Math.abs(e.xr[r]) - p[i[r]] * n, r++, s += _ * _;
        }
        return t.s = r, s;
      }, this.calc_noise = function (e, t, a, n, s) {
        var r,
          i,
          o = 0,
          _ = 0,
          l = 0,
          f = 0,
          c = 0,
          u = -20,
          h = 0,
          b = e.scalefac,
          p = 0;
        for (n.over_SSD = 0, r = 0; r < e.psymax; r++) {
          var m,
            v = e.global_gain - (b[p++] + (0 != e.preflag ? M[r] : 0) << e.scalefac_scale + 1) - 8 * e.subblock_gain[e.window[r]],
            d = 0;
          if (null != s && s.step[r] == v) d = s.noise[r], h += e.width[r], a[o++] = d / t[_++], d = s.noise_log[r];else {
            var g,
              w = y[v + T.Q_MAX2];
            i = e.width[r] >> 1, h + e.width[r] > e.max_nonzero_coeff && (g = e.max_nonzero_coeff - h + 1, i = 0 < g ? g >> 1 : 0);
            var S = new A(h);
            d = this.calc_noise_core(e, S, i, w), h = S.s, null != s && (s.step[r] = v, s.noise[r] = d), d = a[o++] = d / t[_++], d = V.FAST_LOG10(Math.max(d, 1e-20)), null != s && (s.noise_log[r] = d);
          }
          null != s && (s.global_gain = e.global_gain), c += d, 0 < d && (m = Math.max(0 | 10 * d + .5, 1), n.over_SSD += m * m, l++, f += d), u = Math.max(u, d);
        }
        return n.over_count = l, n.tot_noise = c, n.over_noise = f, n.max_noise = u, l;
      };
    }
    function B() {
      this.xr = de(576), this.l3_enc = ve(576), this.scalefac = ve(F.SFBMAX), this.xrpow_max = 0, this.part2_3_length = 0, this.big_values = 0, this.count1 = 0, this.global_gain = 0, this.scalefac_compress = 0, this.block_type = 0, this.mixed_block_flag = 0, this.table_select = ve(3), this.subblock_gain = ve(4), this.region0_count = 0, this.region1_count = 0, this.preflag = 0, this.scalefac_scale = 0, this.count1table_select = 0, this.part2_length = 0, this.sfb_lmax = 0, this.sfb_smin = 0, this.psy_lmax = 0, this.sfbmax = 0, this.psymax = 0, this.sfbdivide = 0, this.width = ve(F.SFBMAX), this.window = ve(F.SFBMAX), this.count1bits = 0, this.sfb_partition_table = null, this.slen = ve(4), this.max_nonzero_coeff = 0;
      var a = this;
      function n(e) {
        return new Int32Array(e);
      }
      this.assign = function (e) {
        var t;
        a.xr = (t = e.xr, new Float32Array(t)), a.l3_enc = n(e.l3_enc), a.scalefac = n(e.scalefac), a.xrpow_max = e.xrpow_max, a.part2_3_length = e.part2_3_length, a.big_values = e.big_values, a.count1 = e.count1, a.global_gain = e.global_gain, a.scalefac_compress = e.scalefac_compress, a.block_type = e.block_type, a.mixed_block_flag = e.mixed_block_flag, a.table_select = n(e.table_select), a.subblock_gain = n(e.subblock_gain), a.region0_count = e.region0_count, a.region1_count = e.region1_count, a.preflag = e.preflag, a.scalefac_scale = e.scalefac_scale, a.count1table_select = e.count1table_select, a.part2_length = e.part2_length, a.sfb_lmax = e.sfb_lmax, a.sfb_smin = e.sfb_smin, a.psy_lmax = e.psy_lmax, a.sfbmax = e.sfbmax, a.psymax = e.psymax, a.sfbdivide = e.sfbdivide, a.width = n(e.width), a.window = n(e.window), a.count1bits = e.count1bits, a.sfb_partition_table = e.sfb_partition_table.slice(0), a.slen = n(e.slen), a.max_nonzero_coeff = e.max_nonzero_coeff;
      };
    }
    k.t1HB = [1, 1, 1, 0], k.t2HB = [1, 2, 1, 3, 1, 1, 3, 2, 0], k.t3HB = [3, 2, 1, 1, 1, 1, 3, 2, 0], k.t5HB = [1, 2, 6, 5, 3, 1, 4, 4, 7, 5, 7, 1, 6, 1, 1, 0], k.t6HB = [7, 3, 5, 1, 6, 2, 3, 2, 5, 4, 4, 1, 3, 3, 2, 0], k.t7HB = [1, 2, 10, 19, 16, 10, 3, 3, 7, 10, 5, 3, 11, 4, 13, 17, 8, 4, 12, 11, 18, 15, 11, 2, 7, 6, 9, 14, 3, 1, 6, 4, 5, 3, 2, 0], k.t8HB = [3, 4, 6, 18, 12, 5, 5, 1, 2, 16, 9, 3, 7, 3, 5, 14, 7, 3, 19, 17, 15, 13, 10, 4, 13, 5, 8, 11, 5, 1, 12, 4, 4, 1, 1, 0], k.t9HB = [7, 5, 9, 14, 15, 7, 6, 4, 5, 5, 6, 7, 7, 6, 8, 8, 8, 5, 15, 6, 9, 10, 5, 1, 11, 7, 9, 6, 4, 1, 14, 4, 6, 2, 6, 0], k.t10HB = [1, 2, 10, 23, 35, 30, 12, 17, 3, 3, 8, 12, 18, 21, 12, 7, 11, 9, 15, 21, 32, 40, 19, 6, 14, 13, 22, 34, 46, 23, 18, 7, 20, 19, 33, 47, 27, 22, 9, 3, 31, 22, 41, 26, 21, 20, 5, 3, 14, 13, 10, 11, 16, 6, 5, 1, 9, 8, 7, 8, 4, 4, 2, 0], k.t11HB = [3, 4, 10, 24, 34, 33, 21, 15, 5, 3, 4, 10, 32, 17, 11, 10, 11, 7, 13, 18, 30, 31, 20, 5, 25, 11, 19, 59, 27, 18, 12, 5, 35, 33, 31, 58, 30, 16, 7, 5, 28, 26, 32, 19, 17, 15, 8, 14, 14, 12, 9, 13, 14, 9, 4, 1, 11, 4, 6, 6, 6, 3, 2, 0], k.t12HB = [9, 6, 16, 33, 41, 39, 38, 26, 7, 5, 6, 9, 23, 16, 26, 11, 17, 7, 11, 14, 21, 30, 10, 7, 17, 10, 15, 12, 18, 28, 14, 5, 32, 13, 22, 19, 18, 16, 9, 5, 40, 17, 31, 29, 17, 13, 4, 2, 27, 12, 11, 15, 10, 7, 4, 1, 27, 12, 8, 12, 6, 3, 1, 0], k.t13HB = [1, 5, 14, 21, 34, 51, 46, 71, 42, 52, 68, 52, 67, 44, 43, 19, 3, 4, 12, 19, 31, 26, 44, 33, 31, 24, 32, 24, 31, 35, 22, 14, 15, 13, 23, 36, 59, 49, 77, 65, 29, 40, 30, 40, 27, 33, 42, 16, 22, 20, 37, 61, 56, 79, 73, 64, 43, 76, 56, 37, 26, 31, 25, 14, 35, 16, 60, 57, 97, 75, 114, 91, 54, 73, 55, 41, 48, 53, 23, 24, 58, 27, 50, 96, 76, 70, 93, 84, 77, 58, 79, 29, 74, 49, 41, 17, 47, 45, 78, 74, 115, 94, 90, 79, 69, 83, 71, 50, 59, 38, 36, 15, 72, 34, 56, 95, 92, 85, 91, 90, 86, 73, 77, 65, 51, 44, 43, 42, 43, 20, 30, 44, 55, 78, 72, 87, 78, 61, 46, 54, 37, 30, 20, 16, 53, 25, 41, 37, 44, 59, 54, 81, 66, 76, 57, 54, 37, 18, 39, 11, 35, 33, 31, 57, 42, 82, 72, 80, 47, 58, 55, 21, 22, 26, 38, 22, 53, 25, 23, 38, 70, 60, 51, 36, 55, 26, 34, 23, 27, 14, 9, 7, 34, 32, 28, 39, 49, 75, 30, 52, 48, 40, 52, 28, 18, 17, 9, 5, 45, 21, 34, 64, 56, 50, 49, 45, 31, 19, 12, 15, 10, 7, 6, 3, 48, 23, 20, 39, 36, 35, 53, 21, 16, 23, 13, 10, 6, 1, 4, 2, 16, 15, 17, 27, 25, 20, 29, 11, 17, 12, 16, 8, 1, 1, 0, 1], k.t15HB = [7, 12, 18, 53, 47, 76, 124, 108, 89, 123, 108, 119, 107, 81, 122, 63, 13, 5, 16, 27, 46, 36, 61, 51, 42, 70, 52, 83, 65, 41, 59, 36, 19, 17, 15, 24, 41, 34, 59, 48, 40, 64, 50, 78, 62, 80, 56, 33, 29, 28, 25, 43, 39, 63, 55, 93, 76, 59, 93, 72, 54, 75, 50, 29, 52, 22, 42, 40, 67, 57, 95, 79, 72, 57, 89, 69, 49, 66, 46, 27, 77, 37, 35, 66, 58, 52, 91, 74, 62, 48, 79, 63, 90, 62, 40, 38, 125, 32, 60, 56, 50, 92, 78, 65, 55, 87, 71, 51, 73, 51, 70, 30, 109, 53, 49, 94, 88, 75, 66, 122, 91, 73, 56, 42, 64, 44, 21, 25, 90, 43, 41, 77, 73, 63, 56, 92, 77, 66, 47, 67, 48, 53, 36, 20, 71, 34, 67, 60, 58, 49, 88, 76, 67, 106, 71, 54, 38, 39, 23, 15, 109, 53, 51, 47, 90, 82, 58, 57, 48, 72, 57, 41, 23, 27, 62, 9, 86, 42, 40, 37, 70, 64, 52, 43, 70, 55, 42, 25, 29, 18, 11, 11, 118, 68, 30, 55, 50, 46, 74, 65, 49, 39, 24, 16, 22, 13, 14, 7, 91, 44, 39, 38, 34, 63, 52, 45, 31, 52, 28, 19, 14, 8, 9, 3, 123, 60, 58, 53, 47, 43, 32, 22, 37, 24, 17, 12, 15, 10, 2, 1, 71, 37, 34, 30, 28, 20, 17, 26, 21, 16, 10, 6, 8, 6, 2, 0], k.t16HB = [1, 5, 14, 44, 74, 63, 110, 93, 172, 149, 138, 242, 225, 195, 376, 17, 3, 4, 12, 20, 35, 62, 53, 47, 83, 75, 68, 119, 201, 107, 207, 9, 15, 13, 23, 38, 67, 58, 103, 90, 161, 72, 127, 117, 110, 209, 206, 16, 45, 21, 39, 69, 64, 114, 99, 87, 158, 140, 252, 212, 199, 387, 365, 26, 75, 36, 68, 65, 115, 101, 179, 164, 155, 264, 246, 226, 395, 382, 362, 9, 66, 30, 59, 56, 102, 185, 173, 265, 142, 253, 232, 400, 388, 378, 445, 16, 111, 54, 52, 100, 184, 178, 160, 133, 257, 244, 228, 217, 385, 366, 715, 10, 98, 48, 91, 88, 165, 157, 148, 261, 248, 407, 397, 372, 380, 889, 884, 8, 85, 84, 81, 159, 156, 143, 260, 249, 427, 401, 392, 383, 727, 713, 708, 7, 154, 76, 73, 141, 131, 256, 245, 426, 406, 394, 384, 735, 359, 710, 352, 11, 139, 129, 67, 125, 247, 233, 229, 219, 393, 743, 737, 720, 885, 882, 439, 4, 243, 120, 118, 115, 227, 223, 396, 746, 742, 736, 721, 712, 706, 223, 436, 6, 202, 224, 222, 218, 216, 389, 386, 381, 364, 888, 443, 707, 440, 437, 1728, 4, 747, 211, 210, 208, 370, 379, 734, 723, 714, 1735, 883, 877, 876, 3459, 865, 2, 377, 369, 102, 187, 726, 722, 358, 711, 709, 866, 1734, 871, 3458, 870, 434, 0, 12, 10, 7, 11, 10, 17, 11, 9, 13, 12, 10, 7, 5, 3, 1, 3], k.t24HB = [15, 13, 46, 80, 146, 262, 248, 434, 426, 669, 653, 649, 621, 517, 1032, 88, 14, 12, 21, 38, 71, 130, 122, 216, 209, 198, 327, 345, 319, 297, 279, 42, 47, 22, 41, 74, 68, 128, 120, 221, 207, 194, 182, 340, 315, 295, 541, 18, 81, 39, 75, 70, 134, 125, 116, 220, 204, 190, 178, 325, 311, 293, 271, 16, 147, 72, 69, 135, 127, 118, 112, 210, 200, 188, 352, 323, 306, 285, 540, 14, 263, 66, 129, 126, 119, 114, 214, 202, 192, 180, 341, 317, 301, 281, 262, 12, 249, 123, 121, 117, 113, 215, 206, 195, 185, 347, 330, 308, 291, 272, 520, 10, 435, 115, 111, 109, 211, 203, 196, 187, 353, 332, 313, 298, 283, 531, 381, 17, 427, 212, 208, 205, 201, 193, 186, 177, 169, 320, 303, 286, 268, 514, 377, 16, 335, 199, 197, 191, 189, 181, 174, 333, 321, 305, 289, 275, 521, 379, 371, 11, 668, 184, 183, 179, 175, 344, 331, 314, 304, 290, 277, 530, 383, 373, 366, 10, 652, 346, 171, 168, 164, 318, 309, 299, 287, 276, 263, 513, 375, 368, 362, 6, 648, 322, 316, 312, 307, 302, 292, 284, 269, 261, 512, 376, 370, 364, 359, 4, 620, 300, 296, 294, 288, 282, 273, 266, 515, 380, 374, 369, 365, 361, 357, 2, 1033, 280, 278, 274, 267, 264, 259, 382, 378, 372, 367, 363, 360, 358, 356, 0, 43, 20, 19, 17, 15, 13, 11, 9, 7, 6, 4, 7, 5, 3, 1, 3], k.t32HB = [1, 10, 8, 20, 12, 20, 16, 32, 14, 12, 24, 0, 28, 16, 24, 16], k.t33HB = [15, 28, 26, 48, 22, 40, 36, 64, 14, 24, 20, 32, 12, 16, 8, 0], k.t1l = [1, 4, 3, 5], k.t2l = [1, 4, 7, 4, 5, 7, 6, 7, 8], k.t3l = [2, 3, 7, 4, 4, 7, 6, 7, 8], k.t5l = [1, 4, 7, 8, 4, 5, 8, 9, 7, 8, 9, 10, 8, 8, 9, 10], k.t6l = [3, 4, 6, 8, 4, 4, 6, 7, 5, 6, 7, 8, 7, 7, 8, 9], k.t7l = [1, 4, 7, 9, 9, 10, 4, 6, 8, 9, 9, 10, 7, 7, 9, 10, 10, 11, 8, 9, 10, 11, 11, 11, 8, 9, 10, 11, 11, 12, 9, 10, 11, 12, 12, 12], k.t8l = [2, 4, 7, 9, 9, 10, 4, 4, 6, 10, 10, 10, 7, 6, 8, 10, 10, 11, 9, 10, 10, 11, 11, 12, 9, 9, 10, 11, 12, 12, 10, 10, 11, 11, 13, 13], k.t9l = [3, 4, 6, 7, 9, 10, 4, 5, 6, 7, 8, 10, 5, 6, 7, 8, 9, 10, 7, 7, 8, 9, 9, 10, 8, 8, 9, 9, 10, 11, 9, 9, 10, 10, 11, 11], k.t10l = [1, 4, 7, 9, 10, 10, 10, 11, 4, 6, 8, 9, 10, 11, 10, 10, 7, 8, 9, 10, 11, 12, 11, 11, 8, 9, 10, 11, 12, 12, 11, 12, 9, 10, 11, 12, 12, 12, 12, 12, 10, 11, 12, 12, 13, 13, 12, 13, 9, 10, 11, 12, 12, 12, 13, 13, 10, 10, 11, 12, 12, 13, 13, 13], k.t11l = [2, 4, 6, 8, 9, 10, 9, 10, 4, 5, 6, 8, 10, 10, 9, 10, 6, 7, 8, 9, 10, 11, 10, 10, 8, 8, 9, 11, 10, 12, 10, 11, 9, 10, 10, 11, 11, 12, 11, 12, 9, 10, 11, 12, 12, 13, 12, 13, 9, 9, 9, 10, 11, 12, 12, 12, 9, 9, 10, 11, 12, 12, 12, 12], k.t12l = [4, 4, 6, 8, 9, 10, 10, 10, 4, 5, 6, 7, 9, 9, 10, 10, 6, 6, 7, 8, 9, 10, 9, 10, 7, 7, 8, 8, 9, 10, 10, 10, 8, 8, 9, 9, 10, 10, 10, 11, 9, 9, 10, 10, 10, 11, 10, 11, 9, 9, 9, 10, 10, 11, 11, 12, 10, 10, 10, 11, 11, 11, 11, 12], k.t13l = [1, 5, 7, 8, 9, 10, 10, 11, 10, 11, 12, 12, 13, 13, 14, 14, 4, 6, 8, 9, 10, 10, 11, 11, 11, 11, 12, 12, 13, 14, 14, 14, 7, 8, 9, 10, 11, 11, 12, 12, 11, 12, 12, 13, 13, 14, 15, 15, 8, 9, 10, 11, 11, 12, 12, 12, 12, 13, 13, 13, 13, 14, 15, 15, 9, 9, 11, 11, 12, 12, 13, 13, 12, 13, 13, 14, 14, 15, 15, 16, 10, 10, 11, 12, 12, 12, 13, 13, 13, 13, 14, 13, 15, 15, 16, 16, 10, 11, 12, 12, 13, 13, 13, 13, 13, 14, 14, 14, 15, 15, 16, 16, 11, 11, 12, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 16, 18, 18, 10, 10, 11, 12, 12, 13, 13, 14, 14, 14, 14, 15, 15, 16, 17, 17, 11, 11, 12, 12, 13, 13, 13, 15, 14, 15, 15, 16, 16, 16, 18, 17, 11, 12, 12, 13, 13, 14, 14, 15, 14, 15, 16, 15, 16, 17, 18, 19, 12, 12, 12, 13, 14, 14, 14, 14, 15, 15, 15, 16, 17, 17, 17, 18, 12, 13, 13, 14, 14, 15, 14, 15, 16, 16, 17, 17, 17, 18, 18, 18, 13, 13, 14, 15, 15, 15, 16, 16, 16, 16, 16, 17, 18, 17, 18, 18, 14, 14, 14, 15, 15, 15, 17, 16, 16, 19, 17, 17, 17, 19, 18, 18, 13, 14, 15, 16, 16, 16, 17, 16, 17, 17, 18, 18, 21, 20, 21, 18], k.t15l = [3, 5, 6, 8, 8, 9, 10, 10, 10, 11, 11, 12, 12, 12, 13, 14, 5, 5, 7, 8, 9, 9, 10, 10, 10, 11, 11, 12, 12, 12, 13, 13, 6, 7, 7, 8, 9, 9, 10, 10, 10, 11, 11, 12, 12, 13, 13, 13, 7, 8, 8, 9, 9, 10, 10, 11, 11, 11, 12, 12, 12, 13, 13, 13, 8, 8, 9, 9, 10, 10, 11, 11, 11, 11, 12, 12, 12, 13, 13, 13, 9, 9, 9, 10, 10, 10, 11, 11, 11, 11, 12, 12, 13, 13, 13, 14, 10, 9, 10, 10, 10, 11, 11, 11, 11, 12, 12, 12, 13, 13, 14, 14, 10, 10, 10, 11, 11, 11, 11, 12, 12, 12, 12, 12, 13, 13, 13, 14, 10, 10, 10, 11, 11, 11, 11, 12, 12, 12, 12, 13, 13, 14, 14, 14, 10, 10, 11, 11, 11, 11, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 11, 11, 11, 11, 12, 12, 12, 12, 12, 13, 13, 13, 13, 14, 15, 14, 11, 11, 11, 11, 12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 15, 12, 12, 11, 12, 12, 12, 13, 13, 13, 13, 13, 13, 14, 14, 15, 15, 12, 12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 14, 15, 15, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 14, 15, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 15, 15, 15, 15], k.t16_5l = [1, 5, 7, 9, 10, 10, 11, 11, 12, 12, 12, 13, 13, 13, 14, 11, 4, 6, 8, 9, 10, 11, 11, 11, 12, 12, 12, 13, 14, 13, 14, 11, 7, 8, 9, 10, 11, 11, 12, 12, 13, 12, 13, 13, 13, 14, 14, 12, 9, 9, 10, 11, 11, 12, 12, 12, 13, 13, 14, 14, 14, 15, 15, 13, 10, 10, 11, 11, 12, 12, 13, 13, 13, 14, 14, 14, 15, 15, 15, 12, 10, 10, 11, 11, 12, 13, 13, 14, 13, 14, 14, 15, 15, 15, 16, 13, 11, 11, 11, 12, 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 16, 13, 11, 11, 12, 12, 13, 13, 13, 14, 14, 15, 15, 15, 15, 17, 17, 13, 11, 12, 12, 13, 13, 13, 14, 14, 15, 15, 15, 15, 16, 16, 16, 13, 12, 12, 12, 13, 13, 14, 14, 15, 15, 15, 15, 16, 15, 16, 15, 14, 12, 13, 12, 13, 14, 14, 14, 14, 15, 16, 16, 16, 17, 17, 16, 13, 13, 13, 13, 13, 14, 14, 15, 16, 16, 16, 16, 16, 16, 15, 16, 14, 13, 14, 14, 14, 14, 15, 15, 15, 15, 17, 16, 16, 16, 16, 18, 14, 15, 14, 14, 14, 15, 15, 16, 16, 16, 18, 17, 17, 17, 19, 17, 14, 14, 15, 13, 14, 16, 16, 15, 16, 16, 17, 18, 17, 19, 17, 16, 14, 11, 11, 11, 12, 12, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 12], k.t16l = [1, 5, 7, 9, 10, 10, 11, 11, 12, 12, 12, 13, 13, 13, 14, 10, 4, 6, 8, 9, 10, 11, 11, 11, 12, 12, 12, 13, 14, 13, 14, 10, 7, 8, 9, 10, 11, 11, 12, 12, 13, 12, 13, 13, 13, 14, 14, 11, 9, 9, 10, 11, 11, 12, 12, 12, 13, 13, 14, 14, 14, 15, 15, 12, 10, 10, 11, 11, 12, 12, 13, 13, 13, 14, 14, 14, 15, 15, 15, 11, 10, 10, 11, 11, 12, 13, 13, 14, 13, 14, 14, 15, 15, 15, 16, 12, 11, 11, 11, 12, 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 16, 12, 11, 11, 12, 12, 13, 13, 13, 14, 14, 15, 15, 15, 15, 17, 17, 12, 11, 12, 12, 13, 13, 13, 14, 14, 15, 15, 15, 15, 16, 16, 16, 12, 12, 12, 12, 13, 13, 14, 14, 15, 15, 15, 15, 16, 15, 16, 15, 13, 12, 13, 12, 13, 14, 14, 14, 14, 15, 16, 16, 16, 17, 17, 16, 12, 13, 13, 13, 13, 14, 14, 15, 16, 16, 16, 16, 16, 16, 15, 16, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 17, 16, 16, 16, 16, 18, 13, 15, 14, 14, 14, 15, 15, 16, 16, 16, 18, 17, 17, 17, 19, 17, 13, 14, 15, 13, 14, 16, 16, 15, 16, 16, 17, 18, 17, 19, 17, 16, 13, 10, 10, 10, 11, 11, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 10], k.t24l = [4, 5, 7, 8, 9, 10, 10, 11, 11, 12, 12, 12, 12, 12, 13, 10, 5, 6, 7, 8, 9, 10, 10, 11, 11, 11, 12, 12, 12, 12, 12, 10, 7, 7, 8, 9, 9, 10, 10, 11, 11, 11, 11, 12, 12, 12, 13, 9, 8, 8, 9, 9, 10, 10, 10, 11, 11, 11, 11, 12, 12, 12, 12, 9, 9, 9, 9, 10, 10, 10, 10, 11, 11, 11, 12, 12, 12, 12, 13, 9, 10, 9, 10, 10, 10, 10, 11, 11, 11, 11, 12, 12, 12, 12, 12, 9, 10, 10, 10, 10, 10, 11, 11, 11, 11, 12, 12, 12, 12, 12, 13, 9, 11, 10, 10, 10, 11, 11, 11, 11, 12, 12, 12, 12, 12, 13, 13, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 13, 13, 10, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 13, 13, 13, 10, 12, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 10, 12, 12, 11, 11, 11, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 10, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 10, 13, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 6], k.t32l = [1, 5, 5, 7, 5, 8, 7, 9, 5, 7, 7, 9, 7, 9, 9, 10], k.t33l = [4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8], k.ht = [new e(0, 0, null, null), new e(2, 0, k.t1HB, k.t1l), new e(3, 0, k.t2HB, k.t2l), new e(3, 0, k.t3HB, k.t3l), new e(0, 0, null, null), new e(4, 0, k.t5HB, k.t5l), new e(4, 0, k.t6HB, k.t6l), new e(6, 0, k.t7HB, k.t7l), new e(6, 0, k.t8HB, k.t8l), new e(6, 0, k.t9HB, k.t9l), new e(8, 0, k.t10HB, k.t10l), new e(8, 0, k.t11HB, k.t11l), new e(8, 0, k.t12HB, k.t12l), new e(16, 0, k.t13HB, k.t13l), new e(0, 0, null, k.t16_5l), new e(16, 0, k.t15HB, k.t15l), new e(1, 1, k.t16HB, k.t16l), new e(2, 3, k.t16HB, k.t16l), new e(3, 7, k.t16HB, k.t16l), new e(4, 15, k.t16HB, k.t16l), new e(6, 63, k.t16HB, k.t16l), new e(8, 255, k.t16HB, k.t16l), new e(10, 1023, k.t16HB, k.t16l), new e(13, 8191, k.t16HB, k.t16l), new e(4, 15, k.t24HB, k.t24l), new e(5, 31, k.t24HB, k.t24l), new e(6, 63, k.t24HB, k.t24l), new e(7, 127, k.t24HB, k.t24l), new e(8, 255, k.t24HB, k.t24l), new e(9, 511, k.t24HB, k.t24l), new e(11, 2047, k.t24HB, k.t24l), new e(13, 8191, k.t24HB, k.t24l), new e(0, 0, k.t32HB, k.t32l), new e(0, 0, k.t33HB, k.t33l)], k.largetbl = [65540, 327685, 458759, 589832, 655369, 655370, 720906, 720907, 786443, 786444, 786444, 851980, 851980, 851980, 917517, 655370, 262149, 393222, 524295, 589832, 655369, 720906, 720906, 720907, 786443, 786443, 786444, 851980, 917516, 851980, 917516, 655370, 458759, 524295, 589832, 655369, 720905, 720906, 786442, 786443, 851979, 786443, 851979, 851980, 851980, 917516, 917517, 720905, 589832, 589832, 655369, 720905, 720906, 786442, 786442, 786443, 851979, 851979, 917515, 917516, 917516, 983052, 983052, 786441, 655369, 655369, 720905, 720906, 786442, 786442, 851978, 851979, 851979, 917515, 917516, 917516, 983052, 983052, 983053, 720905, 655370, 655369, 720906, 720906, 786442, 851978, 851979, 917515, 851979, 917515, 917516, 983052, 983052, 983052, 1048588, 786441, 720906, 720906, 720906, 786442, 851978, 851979, 851979, 851979, 917515, 917516, 917516, 917516, 983052, 983052, 1048589, 786441, 720907, 720906, 786442, 786442, 851979, 851979, 851979, 917515, 917516, 983052, 983052, 983052, 983052, 1114125, 1114125, 786442, 720907, 786443, 786443, 851979, 851979, 851979, 917515, 917515, 983051, 983052, 983052, 983052, 1048588, 1048589, 1048589, 786442, 786443, 786443, 786443, 851979, 851979, 917515, 917515, 983052, 983052, 983052, 983052, 1048588, 983053, 1048589, 983053, 851978, 786444, 851979, 786443, 851979, 917515, 917516, 917516, 917516, 983052, 1048588, 1048588, 1048589, 1114125, 1114125, 1048589, 786442, 851980, 851980, 851979, 851979, 917515, 917516, 983052, 1048588, 1048588, 1048588, 1048588, 1048589, 1048589, 983053, 1048589, 851978, 851980, 917516, 917516, 917516, 917516, 983052, 983052, 983052, 983052, 1114124, 1048589, 1048589, 1048589, 1048589, 1179661, 851978, 983052, 917516, 917516, 917516, 983052, 983052, 1048588, 1048588, 1048589, 1179661, 1114125, 1114125, 1114125, 1245197, 1114125, 851978, 917517, 983052, 851980, 917516, 1048588, 1048588, 983052, 1048589, 1048589, 1114125, 1179661, 1114125, 1245197, 1114125, 1048589, 851978, 655369, 655369, 655369, 720905, 720905, 786441, 786441, 786441, 851977, 851977, 851977, 851978, 851978, 851978, 851978, 655366], k.table23 = [65538, 262147, 458759, 262148, 327684, 458759, 393222, 458759, 524296], k.table56 = [65539, 262148, 458758, 524296, 262148, 327684, 524294, 589831, 458757, 524294, 589831, 655368, 524295, 524295, 589832, 655369], k.bitrate_table = [[0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, -1], [0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, -1], [0, 8, 16, 24, 32, 40, 48, 56, 64, -1, -1, -1, -1, -1, -1, -1]], k.samplerate_table = [[22050, 24e3, 16e3, -1], [44100, 48e3, 32e3, -1], [11025, 12e3, 8e3, -1]], k.scfsi_band = [0, 6, 11, 16, 21], T.Q_MAX = 257, T.Q_MAX2 = 116, T.LARGE_BITS = 1e5, T.IXMAX_VAL = 8206;
    var F = {};
    function C() {
      var r, g;
      this.rv = null, this.qupvt = null;
      var w,
        s = new function () {
          this.setModules = function (e, t) {};
        }();
      function S(e) {
        this.ordinal = e;
      }
      function o(e) {
        for (var t = 0; t < e.sfbmax; t++) if (e.scalefac[t] + e.subblock_gain[e.window[t]] == 0) return !1;
        return !0;
      }
      function M(e, t, a, n, s) {
        var r;
        switch (e) {
          default:
          case 9:
            0 < t.over_count ? (r = a.over_SSD <= t.over_SSD, a.over_SSD == t.over_SSD && (r = a.bits < t.bits)) : r = a.max_noise < 0 && 10 * a.max_noise + a.bits <= 10 * t.max_noise + t.bits;
            break;
          case 0:
            r = a.over_count < t.over_count || a.over_count == t.over_count && a.over_noise < t.over_noise || a.over_count == t.over_count && N.EQ(a.over_noise, t.over_noise) && a.tot_noise < t.tot_noise;
            break;
          case 8:
            me();
          case 1:
            r = a.max_noise < t.max_noise;
            break;
          case 2:
            r = a.tot_noise < t.tot_noise;
            break;
          case 3:
            r = a.tot_noise < t.tot_noise && a.max_noise < t.max_noise;
            break;
          case 4:
            r = a.max_noise <= 0 && .2 < t.max_noise || a.max_noise <= 0 && t.max_noise < 0 && t.max_noise > a.max_noise - .2 && a.tot_noise < t.tot_noise || a.max_noise <= 0 && 0 < t.max_noise && t.max_noise > a.max_noise - .2 && a.tot_noise < t.tot_noise + t.over_noise || 0 < a.max_noise && -.05 < t.max_noise && t.max_noise > a.max_noise - .1 && a.tot_noise + a.over_noise < t.tot_noise + t.over_noise || 0 < a.max_noise && -.1 < t.max_noise && t.max_noise > a.max_noise - .15 && a.tot_noise + a.over_noise + a.over_noise < t.tot_noise + t.over_noise + t.over_noise;
            break;
          case 5:
            r = a.over_noise < t.over_noise || N.EQ(a.over_noise, t.over_noise) && a.tot_noise < t.tot_noise;
            break;
          case 6:
            r = a.over_noise < t.over_noise || N.EQ(a.over_noise, t.over_noise) && (a.max_noise < t.max_noise || N.EQ(a.max_noise, t.max_noise) && a.tot_noise <= t.tot_noise);
            break;
          case 7:
            r = a.over_count < t.over_count || a.over_noise < t.over_noise;
        }
        return 0 == t.over_count && (r = r && a.bits < t.bits), r;
      }
      function y(e, t, a, n, s) {
        var r = e.internal_flags;
        !function (e, t, a, n, s) {
          var r,
            i = e.internal_flags;
          r = 0 == t.scalefac_scale ? 1.2968395546510096 : 1.6817928305074292;
          for (var o = 0, _ = 0; _ < t.sfbmax; _++) o < a[_] && (o = a[_]);
          var l = i.noise_shaping_amp;
          switch (3 == l && me(), l) {
            case 2:
              break;
            case 1:
              1 < o ? o = Math.pow(o, .5) : o *= .95;
              break;
            case 0:
            default:
              1 < o ? o = 1 : o *= .95;
          }
          for (var f = 0, _ = 0; _ < t.sfbmax; _++) {
            var c,
              u = t.width[_];
            if (f += u, !(a[_] < o)) {
              for (0 != (2 & i.substep_shaping) && me(), t.scalefac[_]++, c = -u; c < 0; c++) n[f + c] *= r, n[f + c] > t.xrpow_max && (t.xrpow_max = n[f + c]);
              if (2 == i.noise_shaping_amp) return;
            }
          }
        }(e, t, a, n);
        var i = o(t);
        return !(i || (i = 2 == r.mode_gr ? w.scale_bitcount(t) : w.scale_bitcount_lsf(r, t)) && (1 < r.noise_shaping && (we.fill(r.pseudohalf, 0), 0 == t.scalefac_scale ? (function (e, t) {
          for (var a = 0, n = 0; n < e.sfbmax; n++) {
            var s = e.width[n],
              r = e.scalefac[n];
            if (0 != e.preflag && (r += g.pretab[n]), a += s, 0 != (1 & r)) {
              r++;
              for (var i = -s; i < 0; i++) t[a + i] *= 1.2968395546510096, t[a + i] > e.xrpow_max && (e.xrpow_max = t[a + i]);
            }
            e.scalefac[n] = r >> 1;
          }
          e.preflag = 0, e.scalefac_scale = 1;
        }(t, n), i = !1) : t.block_type == Ae.SHORT_TYPE && 0 < r.subblock_gain && (i = function (e, t, a) {
          var n,
            s = t.scalefac;
          for (n = 0; n < t.sfb_lmax; n++) if (16 <= s[n]) return !0;
          for (var r = 0; r < 3; r++) {
            var i = 0,
              o = 0;
            for (n = t.sfb_lmax + r; n < t.sfbdivide; n += 3) i < s[n] && (i = s[n]);
            for (; n < t.sfbmax; n += 3) o < s[n] && (o = s[n]);
            if (!(i < 16 && o < 8)) {
              if (7 <= t.subblock_gain[r]) return !0;
              t.subblock_gain[r]++;
              var _ = e.scalefac_band.l[t.sfb_lmax];
              for (n = t.sfb_lmax + r; n < t.sfbmax; n += 3) {
                var l = t.width[n],
                  f = s[n];
                if (0 <= (f -= 4 >> t.scalefac_scale)) s[n] = f, _ += 3 * l;else {
                  s[n] = 0;
                  var c = 210 + (f << t.scalefac_scale + 1);
                  h = g.IPOW20(c), _ += l * (r + 1);
                  for (var u = -l; u < 0; u++) a[_ + u] *= h, a[_ + u] > t.xrpow_max && (t.xrpow_max = a[_ + u]);
                  _ += l * (3 - r - 1);
                }
              }
              var h = g.IPOW20(202);
              _ += t.width[n] * (r + 1);
              for (var u = -t.width[n]; u < 0; u++) a[_ + u] *= h, a[_ + u] > t.xrpow_max && (t.xrpow_max = a[_ + u]);
            }
          }
          return !1;
        }(r, t, n) || o(t))), i || (i = 2 == r.mode_gr ? w.scale_bitcount(t) : w.scale_bitcount_lsf(r, t)), i));
      }
      this.setModules = function (e, t, a, n) {
        r = t, this.rv = t, g = a, this.qupvt = a, w = n, s.setModules(g, w);
      }, this.init_xrpow = function (e, t, a) {
        var n = 0,
          s = 0 | t.max_nonzero_coeff;
        if (t.xrpow_max = 0, we.fill(a, s, 576, 0), 1e-20 < (n = function (e, t, a, n) {
          for (var s = n = 0; s <= a; ++s) {
            var r = Math.abs(e.xr[s]);
            n += r, t[s] = Math.sqrt(r * Math.sqrt(r)), t[s] > e.xrpow_max && (e.xrpow_max = t[s]);
          }
          return n;
        }(t, a, s, n))) {
          var r = 0;
          0 != (2 & e.substep_shaping) && (r = 1);
          for (var i = 0; i < t.psymax; i++) e.pseudohalf[i] = r;
          return !0;
        }
        return we.fill(t.l3_enc, 0, 576, 0), !1;
      }, this.init_outer_loop = function (e, t) {
        t.part2_3_length = 0, t.big_values = 0, t.count1 = 0, t.global_gain = 210, t.scalefac_compress = 0, t.table_select[0] = 0, t.table_select[1] = 0, t.table_select[2] = 0, t.subblock_gain[0] = 0, t.subblock_gain[1] = 0, t.subblock_gain[2] = 0, t.subblock_gain[3] = 0, t.region0_count = 0, t.region1_count = 0, t.preflag = 0, t.scalefac_scale = 0, t.count1table_select = 0, t.part2_length = 0, t.sfb_lmax = Ae.SBPSY_l, t.sfb_smin = Ae.SBPSY_s, t.psy_lmax = e.sfb21_extra ? Ae.SBMAX_l : Ae.SBPSY_l, t.psymax = t.psy_lmax, t.sfbmax = t.sfb_lmax, t.sfbdivide = 11;
        for (var a = 0; a < Ae.SBMAX_l; a++) t.width[a] = e.scalefac_band.l[a + 1] - e.scalefac_band.l[a], t.window[a] = 3;
        if (t.block_type == Ae.SHORT_TYPE) {
          var n = de(576);
          t.sfb_smin = 0, (t.sfb_lmax = 0) != t.mixed_block_flag && me(), t.psymax = t.sfb_lmax + 3 * ((e.sfb21_extra ? Ae.SBMAX_s : Ae.SBPSY_s) - t.sfb_smin), t.sfbmax = t.sfb_lmax + 3 * (Ae.SBPSY_s - t.sfb_smin), t.sfbdivide = t.sfbmax - 18, t.psy_lmax = t.sfb_lmax;
          var s = e.scalefac_band.l[t.sfb_lmax];
          I.arraycopy(t.xr, 0, n, 0, 576);
          for (var a = t.sfb_smin; a < Ae.SBMAX_s; a++) for (var r = e.scalefac_band.s[a], i = e.scalefac_band.s[a + 1], o = 0; o < 3; o++) for (var _ = r; _ < i; _++) t.xr[s++] = n[3 * _ + o];
          for (var l = t.sfb_lmax, a = t.sfb_smin; a < Ae.SBMAX_s; a++) t.width[l] = t.width[l + 1] = t.width[l + 2] = e.scalefac_band.s[a + 1] - e.scalefac_band.s[a], t.window[l] = 0, t.window[l + 1] = 1, t.window[l + 2] = 2, l += 3;
        }
        t.count1bits = 0, t.sfb_partition_table = g.nr_of_sfb_block[0][0], t.slen[0] = 0, t.slen[1] = 0, t.slen[2] = 0, t.slen[3] = 0, t.max_nonzero_coeff = 575, we.fill(t.scalefac, 0), function (e, t) {
          var a = e.ATH,
            n = t.xr;
          if (t.block_type != Ae.SHORT_TYPE) for (var s = !1, r = Ae.PSFB21 - 1; 0 <= r && !s; r--) {
            var i = e.scalefac_band.psfb21[r],
              o = e.scalefac_band.psfb21[r + 1],
              _ = g.athAdjust(a.adjust, a.psfb21[r], a.floor);
            1e-12 < e.nsPsy.longfact[21] && (_ *= e.nsPsy.longfact[21]);
            for (var l = o - 1; i <= l; l--) {
              if (!(Math.abs(n[l]) < _)) {
                s = !0;
                break;
              }
              n[l] = 0;
            }
          } else for (var f = 0; f < 3; f++) for (var s = !1, r = Ae.PSFB12 - 1; 0 <= r && !s; r--) {
            var i = 3 * e.scalefac_band.s[12] + (e.scalefac_band.s[13] - e.scalefac_band.s[12]) * f + (e.scalefac_band.psfb12[r] - e.scalefac_band.psfb12[0]),
              o = i + (e.scalefac_band.psfb12[r + 1] - e.scalefac_band.psfb12[r]),
              c = g.athAdjust(a.adjust, a.psfb12[r], a.floor);
            1e-12 < e.nsPsy.shortfact[12] && (c *= e.nsPsy.shortfact[12]);
            for (var l = o - 1; i <= l; l--) {
              if (!(Math.abs(n[l]) < c)) {
                s = !0;
                break;
              }
              n[l] = 0;
            }
          }
        }(e, t);
      }, S.BINSEARCH_NONE = new S(0), S.BINSEARCH_UP = new S(1), S.BINSEARCH_DOWN = new S(2), this.outer_loop = function (e, t, a, n, s, r) {
        var i = e.internal_flags,
          o = new B(),
          _ = de(576),
          l = de(F.SFBMAX),
          f = new x(),
          c = new function () {
            this.global_gain = 0, this.sfb_count1 = 0, this.step = ve(39), this.noise = de(39), this.noise_log = de(39);
          }(),
          u = 9999999,
          h = !1;
        if (function (e, t, a, n, s) {
          var r,
            i = e.CurrentStep[n],
            o = !1,
            _ = e.OldValue[n],
            l = S.BINSEARCH_NONE;
          for (t.global_gain = _, a -= t.part2_length;;) {
            var f;
            if (r = w.count_bits(e, s, t, null), 1 == i || r == a) break;
            a < r ? (l == S.BINSEARCH_DOWN && (o = !0), o && (i /= 2), l = S.BINSEARCH_UP, f = i) : (l == S.BINSEARCH_UP && (o = !0), o && (i /= 2), l = S.BINSEARCH_DOWN, f = -i), t.global_gain += f, t.global_gain < 0 && me(), 255 < t.global_gain && me();
          }
          for (; a < r && t.global_gain < 255;) t.global_gain++, r = w.count_bits(e, s, t, null);
          e.CurrentStep[n] = 4 <= _ - t.global_gain ? 4 : 2, e.OldValue[n] = t.global_gain, t.part2_3_length = r;
        }(i, t, r, s, n), 0 == i.noise_shaping) return 100;
        g.calc_noise(t, a, l, f, c), f.bits = t.part2_3_length, o.assign(t);
        var b = 0;
        for (I.arraycopy(n, 0, _, 0, 576); !h;) {
          do {
            var p,
              m = new x(),
              v = 255;
            if (p = 0 != (2 & i.substep_shaping) ? 20 : 3, i.sfb21_extra && me(), !y(e, o, l, n)) break;
            0 != o.scalefac_scale && (v = 254);
            var d = r - o.part2_length;
            if (d <= 0) break;
            for (; (o.part2_3_length = w.count_bits(i, n, o, c)) > d && o.global_gain <= v;) o.global_gain++;
            if (o.global_gain > v) break;
            if (0 == f.over_count) {
              for (; (o.part2_3_length = w.count_bits(i, n, o, c)) > u && o.global_gain <= v;) o.global_gain++;
              if (o.global_gain > v) break;
            }
            if (g.calc_noise(o, a, l, m, c), m.bits = o.part2_3_length, 0 != (M(t.block_type != Ae.SHORT_TYPE ? e.quant_comp : e.quant_comp_short, f, m) ? 1 : 0)) u = t.part2_3_length, f = m, t.assign(o), b = 0, I.arraycopy(n, 0, _, 0, 576);else if (0 == i.full_outer_loop) {
              if (++b > p && 0 == f.over_count) break;
              i.noise_shaping_amp, i.noise_shaping_amp;
            }
          } while (o.global_gain + o.scalefac_scale < 255);
          3 == i.noise_shaping_amp ? me() : h = !0;
        }
        return e.VBR == Me.vbr_rh || e.VBR == Me.vbr_mtrh ? I.arraycopy(_, 0, n, 0, 576) : 0 != (1 & i.substep_shaping) && me(), f.over_count;
      }, this.iteration_finish_one = function (e, t, a) {
        var n = e.l3_side,
          s = n.tt[t][a];
        w.best_scalefac_store(e, t, a, n), 1 == e.use_best_huffman && w.best_huffman_divide(e, s), r.ResvAdjust(e, s);
      };
    }
    function L() {
      this.thm = new i(), this.en = new i();
    }
    function Ae() {
      var k = Ae.MPG_MD_MS_LR,
        R = null,
        x = this.psy = null,
        B = null;
      this.setModules = function (e, t, a, n) {
        R = e, this.psy = t, x = t, B = n;
      };
      var T = new function () {
        var u = [-.1482523854003001, 32.308141959636465, 296.40344946382766, 883.1344870032432, 11113.947376231741, 1057.2713659324597, 305.7402417275812, 30.825928907280012, 3.8533188138216365, 59.42900443849514, 709.5899960123345, 5281.91112291017, -5829.66483675846, -817.6293103748613, -76.91656988279972, -4.594269939176596, .9063471690191471, .1960342806591213, -.15466694054279598, 34.324387823855965, 301.8067566458425, 817.599602898885, 11573.795901679885, 1181.2520595540152, 321.59731579894424, 31.232021761053772, 3.7107095756221318, 53.650946155329365, 684.167428119626, 5224.56624370173, -6366.391851890084, -908.9766368219582, -89.83068876699639, -5.411397422890401, .8206787908286602, .3901806440322567, -.16070888947830023, 36.147034243915876, 304.11815768187864, 732.7429163887613, 11989.60988270091, 1300.012278487897, 335.28490093152146, 31.48816102859945, 3.373875931311736, 47.232241542899175, 652.7371796173471, 5132.414255594984, -6909.087078780055, -1001.9990371107289, -103.62185754286375, -6.104916304710272, .7416505462720353, .5805693545089249, -.16636367662261495, 37.751650073343995, 303.01103387567713, 627.9747488785183, 12358.763425278165, 1412.2779918482834, 346.7496836825721, 31.598286663170416, 3.1598635433980946, 40.57878626349686, 616.1671130880391, 5007.833007176154, -7454.040671756168, -1095.7960341867115, -118.24411666465777, -6.818469345853504, .6681786379192989, .7653668647301797, -.1716176790982088, 39.11551877123304, 298.3413246578966, 503.5259106886539, 12679.589408408976, 1516.5821921214542, 355.9850766329023, 31.395241710249053, 2.9164211881972335, 33.79716964664243, 574.8943997801362, 4853.234992253242, -7997.57021486075, -1189.7624067269965, -133.6444792601766, -7.7202770609839915, .5993769336819237, .9427934736519954, -.17645823955292173, 40.21879108166477, 289.9982036694474, 359.3226160751053, 12950.259102786438, 1612.1013903507662, 362.85067106591504, 31.045922092242872, 2.822222032597987, 26.988862316190684, 529.8996541764288, 4671.371946949588, -8535.899136645805, -1282.5898586244496, -149.58553632943463, -8.643494270763135, .5345111359507916, 1.111140466039205, -.36174739330527045, 41.04429910497807, 277.5463268268618, 195.6386023135583, 13169.43812144731, 1697.6433561479398, 367.40983966190305, 30.557037410382826, 2.531473372857427, 20.070154905927314, 481.50208566532336, 4464.970341588308, -9065.36882077239, -1373.62841526722, -166.1660487028118, -9.58289321133207, .4729647758913199, 1.268786568327291, -.36970682634889585, 41.393213350082036, 261.2935935556502, 12.935476055240873, 13336.131683328815, 1772.508612059496, 369.76534388639965, 29.751323653701338, 2.4023193045459172, 13.304795348228817, 430.5615775526625, 4237.0568611071185, -9581.931701634761, -1461.6913552409758, -183.12733958476446, -10.718010163869403, .41421356237309503, 1.414213562373095, -.37677560326535325, 41.619486213528496, 241.05423794991074, -187.94665032361226, 13450.063605744153, 1836.153896465782, 369.4908799925761, 29.001847876923147, 2.0714759319987186, 6.779591200894186, 377.7767837205709, 3990.386575512536, -10081.709459700915, -1545.947424837898, -200.3762958015653, -11.864482073055006, .3578057213145241, 1.546020906725474, -.3829366947518991, 41.1516456456653, 216.47684307105183, -406.1569483347166, 13511.136535077321, 1887.8076599260432, 367.3025214564151, 28.136213436723654, 1.913880671464418, .3829366947518991, 323.85365704338597, 3728.1472257487526, -10561.233882199509, -1625.2025997821418, -217.62525175416, -13.015432208941645, .3033466836073424, 1.66293922460509, -.5822628872992417, 40.35639251440489, 188.20071124269245, -640.2706748618148, 13519.21490106562, 1927.6022433578062, 362.8197642637487, 26.968821921868447, 1.7463817695935329, -5.62650678237171, 269.3016715297017, 3453.386536448852, -11016.145278780888, -1698.6569643425091, -234.7658734267683, -14.16351421663124, .2504869601913055, 1.76384252869671, -.5887180101749253, 39.23429103868072, 155.76096234403798, -889.2492977967378, 13475.470561874661, 1955.0535223723712, 356.4450994756727, 25.894952980042156, 1.5695032905781554, -11.181939564328772, 214.80884394039484, 3169.1640829158237, -11443.321309975563, -1765.1588461316153, -251.68908574481912, -15.49755935939164, .198912367379658, 1.847759065022573, -.7912582233652842, 37.39369355329111, 119.699486012458, -1151.0956593239027, 13380.446257078214, 1970.3952110853447, 348.01959814116185, 24.731487364283044, 1.3850130831637748, -16.421408865300393, 161.05030052864092, 2878.3322807850063, -11838.991423510031, -1823.985884688674, -268.2854986386903, -16.81724543849939, .1483359875383474, 1.913880671464418, -.7960642926861912, 35.2322109610459, 80.01928065061526, -1424.0212633405113, 13235.794061869668, 1973.804052543835, 337.9908651258184, 23.289159354463873, 1.3934255946442087, -21.099669467133474, 108.48348407242611, 2583.700758091299, -12199.726194855148, -1874.2780658979746, -284.2467154529415, -18.11369784385905, .09849140335716425, 1.961570560806461, -.998795456205172, 32.56307803611191, 36.958364584370486, -1706.075448829146, 13043.287458812016, 1965.3831106103316, 326.43182772364605, 22.175018750622293, 1.198638339011324, -25.371248002043963, 57.53505923036915, 2288.41886619975, -12522.674544337233, -1914.8400385312243, -299.26241273417224, -19.37805630698734, .04912684976946725, 1.990369453344394, .035780907 * V.SQRT2 * .5 / 2384e-9, .017876148 * V.SQRT2 * .5 / 2384e-9, .003134727 * V.SQRT2 * .5 / 2384e-9, .002457142 * V.SQRT2 * .5 / 2384e-9, 971317e-9 * V.SQRT2 * .5 / 2384e-9, 218868e-9 * V.SQRT2 * .5 / 2384e-9, 101566e-9 * V.SQRT2 * .5 / 2384e-9, 13828e-9 * V.SQRT2 * .5 / 2384e-9, 12804.797818791945, 1945.5515939597317, 313.4244966442953, 49591e-9 / 2384e-9, 1995.1556208053692, 21458e-9 / 2384e-9, -69618e-9 / 2384e-9],
          A = [[2.382191739347913e-13, 6.423305872147834e-13, 9.400849094049688e-13, 1.122435026096556e-12, 1.183840321267481e-12, 1.122435026096556e-12, 9.40084909404969e-13, 6.423305872147839e-13, 2.382191739347918e-13, 5.456116108943412e-12, 4.878985199565852e-12, 4.240448995017367e-12, 3.559909094758252e-12, 2.858043359288075e-12, 2.156177623817898e-12, 1.475637723558783e-12, 8.371015190102974e-13, 2.599706096327376e-13, -5.456116108943412e-12, -4.878985199565852e-12, -4.240448995017367e-12, -3.559909094758252e-12, -2.858043359288076e-12, -2.156177623817898e-12, -1.475637723558783e-12, -8.371015190102975e-13, -2.599706096327376e-13, -2.382191739347923e-13, -6.423305872147843e-13, -9.400849094049696e-13, -1.122435026096556e-12, -1.183840321267481e-12, -1.122435026096556e-12, -9.400849094049694e-13, -6.42330587214784e-13, -2.382191739347918e-13], [2.382191739347913e-13, 6.423305872147834e-13, 9.400849094049688e-13, 1.122435026096556e-12, 1.183840321267481e-12, 1.122435026096556e-12, 9.400849094049688e-13, 6.423305872147841e-13, 2.382191739347918e-13, 5.456116108943413e-12, 4.878985199565852e-12, 4.240448995017367e-12, 3.559909094758253e-12, 2.858043359288075e-12, 2.156177623817898e-12, 1.475637723558782e-12, 8.371015190102975e-13, 2.599706096327376e-13, -5.461314069809755e-12, -4.921085770524055e-12, -4.343405037091838e-12, -3.732668368707687e-12, -3.093523840190885e-12, -2.430835727329465e-12, -1.734679010007751e-12, -9.74825365660928e-13, -2.797435120168326e-13, 0, 0, 0, 0, 0, 0, -2.283748241799531e-13, -4.037858874020686e-13, -2.146547464825323e-13], [.1316524975873958, .414213562373095, .7673269879789602, 1.091308501069271, 1.303225372841206, 1.56968557711749, 1.920982126971166, 2.414213562373094, 3.171594802363212, 4.510708503662055, 7.595754112725146, 22.90376554843115, .984807753012208, .6427876096865394, .3420201433256688, .9396926207859084, -.1736481776669303, -.7660444431189779, .8660254037844387, .5, -.5144957554275265, -.4717319685649723, -.3133774542039019, -.1819131996109812, -.09457419252642064, -.04096558288530405, -.01419856857247115, -.003699974673760037, .8574929257125442, .8817419973177052, .9496286491027329, .9833145924917901, .9955178160675857, .9991605581781475, .999899195244447, .9999931550702802], [0, 0, 0, 0, 0, 0, 2.283748241799531e-13, 4.037858874020686e-13, 2.146547464825323e-13, 5.461314069809755e-12, 4.921085770524055e-12, 4.343405037091838e-12, 3.732668368707687e-12, 3.093523840190885e-12, 2.430835727329466e-12, 1.734679010007751e-12, 9.74825365660928e-13, 2.797435120168326e-13, -5.456116108943413e-12, -4.878985199565852e-12, -4.240448995017367e-12, -3.559909094758253e-12, -2.858043359288075e-12, -2.156177623817898e-12, -1.475637723558782e-12, -8.371015190102975e-13, -2.599706096327376e-13, -2.382191739347913e-13, -6.423305872147834e-13, -9.400849094049688e-13, -1.122435026096556e-12, -1.183840321267481e-12, -1.122435026096556e-12, -9.400849094049688e-13, -6.423305872147841e-13, -2.382191739347918e-13]],
          k = A[Ae.SHORT_TYPE],
          S = A[Ae.SHORT_TYPE],
          R = A[Ae.SHORT_TYPE],
          x = A[Ae.SHORT_TYPE],
          B = [0, 1, 16, 17, 8, 9, 24, 25, 4, 5, 20, 21, 12, 13, 28, 29, 2, 3, 18, 19, 10, 11, 26, 27, 6, 7, 22, 23, 14, 15, 30, 31];
        function T(e, t, a) {
          for (var n, s, r, i = 10, o = t + 238 - 14 - 286, _ = -15; _ < 0; _++) {
            var l, f, c;
            l = u[i + -10], f = e[o + -224] * l, c = e[t + 224] * l, l = u[i + -9], f += e[o + -160] * l, c += e[t + 160] * l, l = u[i + -8], f += e[o + -96] * l, c += e[t + 96] * l, l = u[i + -7], f += e[o + -32] * l, c += e[t + 32] * l, l = u[i + -6], f += e[o + 32] * l, c += e[t + -32] * l, l = u[i + -5], f += e[o + 96] * l, c += e[t + -96] * l, l = u[i + -4], f += e[o + 160] * l, c += e[t + -160] * l, l = u[i + -3], f += e[o + 224] * l, c += e[t + -224] * l, l = u[i + -2], f += e[t + -256] * l, c -= e[o + 256] * l, l = u[i + -1], f += e[t + -192] * l, c -= e[o + 192] * l, l = u[i + 0], f += e[t + -128] * l, c -= e[o + 128] * l, l = u[i + 1], f += e[t + -64] * l, c -= e[o + 64] * l, l = u[i + 2], f += e[t + 0] * l, c -= e[o + 0] * l, l = u[i + 3], f += e[t + 64] * l, c -= e[o + -64] * l, l = u[i + 4], f += e[t + 128] * l, c -= e[o + -128] * l, l = u[i + 5], f += e[t + 192] * l, c -= e[o + -192] * l, f *= u[i + 6], l = c - f, a[30 + 2 * _] = c + f, a[31 + 2 * _] = u[i + 7] * l, i += 18, t--, o++;
          }
          c = e[t + -16] * u[i + -10], f = e[t + -32] * u[i + -2], c += (e[t + -48] - e[t + 16]) * u[i + -9], f += e[t + -96] * u[i + -1], c += (e[t + -80] + e[t + 48]) * u[i + -8], f += e[t + -160] * u[i + 0], c += (e[t + -112] - e[t + 80]) * u[i + -7], f += e[t + -224] * u[i + 1], c += (e[t + -144] + e[t + 112]) * u[i + -6], f -= e[t + 32] * u[i + 2], c += (e[t + -176] - e[t + 144]) * u[i + -5], f -= e[t + 96] * u[i + 3], c += (e[t + -208] + e[t + 176]) * u[i + -4], f -= e[t + 160] * u[i + 4], c += (e[t + -240] - e[t + 208]) * u[i + -3], f -= e[t + 224], n = f - c, s = f + c, c = a[14], f = a[15] - c, a[31] = s + c, a[30] = n + f, a[15] = n - f, a[14] = s - c, r = a[28] - a[0], a[0] += a[28], a[28] = r * u[i + -36 + 7], r = a[29] - a[1], a[1] += a[29], a[29] = r * u[i + -36 + 7], r = a[26] - a[2], a[2] += a[26], a[26] = r * u[i + -72 + 7], r = a[27] - a[3], a[3] += a[27], a[27] = r * u[i + -72 + 7], r = a[24] - a[4], a[4] += a[24], a[24] = r * u[i + -108 + 7], r = a[25] - a[5], a[5] += a[25], a[25] = r * u[i + -108 + 7], r = a[22] - a[6], a[6] += a[22], a[22] = r * V.SQRT2, r = a[23] - a[7], a[7] += a[23], a[23] = r * V.SQRT2 - a[7], a[7] -= a[6], a[22] -= a[7], a[23] -= a[22], r = a[6], a[6] = a[31] - r, a[31] = a[31] + r, r = a[7], a[7] = a[30] - r, a[30] = a[30] + r, r = a[22], a[22] = a[15] - r, a[15] = a[15] + r, r = a[23], a[23] = a[14] - r, a[14] = a[14] + r, r = a[20] - a[8], a[8] += a[20], a[20] = r * u[i + -180 + 7], r = a[21] - a[9], a[9] += a[21], a[21] = r * u[i + -180 + 7], r = a[18] - a[10], a[10] += a[18], a[18] = r * u[i + -216 + 7], r = a[19] - a[11], a[11] += a[19], a[19] = r * u[i + -216 + 7], r = a[16] - a[12], a[12] += a[16], a[16] = r * u[i + -252 + 7], r = a[17] - a[13], a[13] += a[17], a[17] = r * u[i + -252 + 7], r = -a[20] + a[24], a[20] += a[24], a[24] = r * u[i + -216 + 7], r = -a[21] + a[25], a[21] += a[25], a[25] = r * u[i + -216 + 7], r = a[4] - a[8], a[4] += a[8], a[8] = r * u[i + -216 + 7], r = a[5] - a[9], a[5] += a[9], a[9] = r * u[i + -216 + 7], r = a[0] - a[12], a[0] += a[12], a[12] = r * u[i + -72 + 7], r = a[1] - a[13], a[1] += a[13], a[13] = r * u[i + -72 + 7], r = a[16] - a[28], a[16] += a[28], a[28] = r * u[i + -72 + 7], r = -a[17] + a[29], a[17] += a[29], a[29] = r * u[i + -72 + 7], r = V.SQRT2 * (a[2] - a[10]), a[2] += a[10], a[10] = r, r = V.SQRT2 * (a[3] - a[11]), a[3] += a[11], a[11] = r, r = V.SQRT2 * (-a[18] + a[26]), a[18] += a[26], a[26] = r - a[18], r = V.SQRT2 * (-a[19] + a[27]), a[19] += a[27], a[27] = r - a[19], r = a[2], a[19] -= a[3], a[3] -= r, a[2] = a[31] - r, a[31] += r, r = a[3], a[11] -= a[19], a[18] -= r, a[3] = a[30] - r, a[30] += r, r = a[18], a[27] -= a[11], a[19] -= r, a[18] = a[15] - r, a[15] += r, r = a[19], a[10] -= r, a[19] = a[14] - r, a[14] += r, r = a[10], a[11] -= r, a[10] = a[23] - r, a[23] += r, r = a[11], a[26] -= r, a[11] = a[22] - r, a[22] += r, r = a[26], a[27] -= r, a[26] = a[7] - r, a[7] += r, r = a[27], a[27] = a[6] - r, a[6] += r, r = V.SQRT2 * (a[0] - a[4]), a[0] += a[4], a[4] = r, r = V.SQRT2 * (a[1] - a[5]), a[1] += a[5], a[5] = r, r = V.SQRT2 * (a[16] - a[20]), a[16] += a[20], a[20] = r, r = V.SQRT2 * (a[17] - a[21]), a[17] += a[21], a[21] = r, r = -V.SQRT2 * (a[8] - a[12]), a[8] += a[12], a[12] = r - a[8], r = -V.SQRT2 * (a[9] - a[13]), a[9] += a[13], a[13] = r - a[9], r = -V.SQRT2 * (a[25] - a[29]), a[25] += a[29], a[29] = r - a[25], r = -V.SQRT2 * (a[24] + a[28]), a[24] -= a[28], a[28] = r - a[24], r = a[24] - a[16], a[24] = r, r = a[20] - r, a[20] = r, r = a[28] - r, a[28] = r, r = a[25] - a[17], a[25] = r, r = a[21] - r, a[21] = r, r = a[29] - r, a[29] = r, r = a[17] - a[1], a[17] = r, r = a[9] - r, a[9] = r, r = a[25] - r, a[25] = r, r = a[5] - r, a[5] = r, r = a[21] - r, a[21] = r, r = a[13] - r, a[13] = r, r = a[29] - r, a[29] = r, r = a[1] - a[0], a[1] = r, r = a[16] - r, a[16] = r, r = a[17] - r, a[17] = r, r = a[8] - r, a[8] = r, r = a[9] - r, a[9] = r, r = a[24] - r, a[24] = r, r = a[25] - r, a[25] = r, r = a[4] - r, a[4] = r, r = a[5] - r, a[5] = r, r = a[20] - r, a[20] = r, r = a[21] - r, a[21] = r, r = a[12] - r, a[12] = r, r = a[13] - r, a[13] = r, r = a[28] - r, a[28] = r, r = a[29] - r, a[29] = r, r = a[0], a[0] += a[31], a[31] -= r, r = a[1], a[1] += a[30], a[30] -= r, r = a[16], a[16] += a[15], a[15] -= r, r = a[17], a[17] += a[14], a[14] -= r, r = a[8], a[8] += a[23], a[23] -= r, r = a[9], a[9] += a[22], a[22] -= r, r = a[24], a[24] += a[7], a[7] -= r, r = a[25], a[25] += a[6], a[6] -= r, r = a[4], a[4] += a[27], a[27] -= r, r = a[5], a[5] += a[26], a[26] -= r, r = a[20], a[20] += a[11], a[11] -= r, r = a[21], a[21] += a[10], a[10] -= r, r = a[12], a[12] += a[19], a[19] -= r, r = a[13], a[13] += a[18], a[18] -= r, r = a[28], a[28] += a[3], a[3] -= r, r = a[29], a[29] += a[2], a[2] -= r;
        }
        function E(e, t) {
          for (var a = 0; a < 3; a++) {
            var n, s, r, i, o, _;
            i = e[t + 6] * A[Ae.SHORT_TYPE][0] - e[t + 15], n = e[t + 0] * A[Ae.SHORT_TYPE][2] - e[t + 9], s = i + n, r = i - n, i = e[t + 15] * A[Ae.SHORT_TYPE][0] + e[t + 6], n = e[t + 9] * A[Ae.SHORT_TYPE][2] + e[t + 0], o = i + n, _ = -i + n, n = 2.069978111953089e-11 * (e[t + 3] * A[Ae.SHORT_TYPE][1] - e[t + 12]), i = 2.069978111953089e-11 * (e[t + 12] * A[Ae.SHORT_TYPE][1] + e[t + 3]), e[t + 0] = 1.90752519173728e-11 * s + n, e[t + 15] = 1.90752519173728e-11 * -o + i, r = .8660254037844387 * r * 1.907525191737281e-11, o = .5 * o * 1.907525191737281e-11 + i, e[t + 3] = r - o, e[t + 6] = r + o, s = .5 * s * 1.907525191737281e-11 - n, _ = .8660254037844387 * _ * 1.907525191737281e-11, e[t + 9] = s + _, e[t + 12] = s - _, t++;
          }
        }
        function C(e, t, a) {
          var n, s, r, i, o, _, l, f, c, u, h, b, p, m, v, d, g, w;
          r = a[17] - a[9], o = a[15] - a[11], _ = a[14] - a[12], l = a[0] + a[8], f = a[1] + a[7], c = a[2] + a[6], u = a[3] + a[5], e[t + 17] = l + c - u - (f - a[4]), s = (l + c - u) * S[19] + (f - a[4]), n = (r - o - _) * S[18], e[t + 5] = n + s, e[t + 6] = n - s, i = (a[16] - a[10]) * S[18], f = f * S[19] + a[4], n = r * S[12] + i + o * S[13] + _ * S[14], s = -l * S[16] + f - c * S[17] + u * S[15], e[t + 1] = n + s, e[t + 2] = n - s, n = r * S[13] - i - o * S[14] + _ * S[12], s = -l * S[17] + f - c * S[15] + u * S[16], e[t + 9] = n + s, e[t + 10] = n - s, n = r * S[14] - i + o * S[12] - _ * S[13], s = l * S[15] - f + c * S[16] - u * S[17], e[t + 13] = n + s, e[t + 14] = n - s, h = a[8] - a[0], p = a[6] - a[2], m = a[5] - a[3], v = a[17] + a[9], d = a[16] + a[10], g = a[15] + a[11], w = a[14] + a[12], e[t + 0] = v + g + w + (d + a[13]), n = (v + g + w) * S[19] - (d + a[13]), s = (h - p + m) * S[18], e[t + 11] = n + s, e[t + 12] = n - s, b = (a[7] - a[1]) * S[18], d = a[13] - d * S[19], n = v * S[15] - d + g * S[16] + w * S[17], s = h * S[14] + b + p * S[12] + m * S[13], e[t + 3] = n + s, e[t + 4] = n - s, n = -v * S[17] + d - g * S[15] - w * S[16], s = h * S[13] + b - p * S[14] - m * S[12], e[t + 7] = n + s, e[t + 8] = n - s, n = -v * S[16] + d - g * S[17] - w * S[15], s = h * S[12] - b + p * S[13] - m * S[14], e[t + 15] = n + s, e[t + 16] = n - s;
        }
        this.mdct_sub48 = function (e, t, a) {
          for (var n = t, s = 286, r = 0; r < e.channels_out; r++) {
            for (var i = 0; i < e.mode_gr; i++) {
              for (var o, _ = e.l3_side.tt[i][r], l = _.xr, f = 0, c = e.sb_sample[r][1 - i], u = 0, h = 0; h < 9; h++) for (T(n, s, c[u]), T(n, s + 32, c[u + 1]), u += 2, s += 64, o = 1; o < 32; o += 2) c[u - 1][o] *= -1;
              for (o = 0; o < 32; o++, f += 18) {
                var b = _.block_type,
                  p = e.sb_sample[r][i],
                  m = e.sb_sample[r][1 - i];
                if (0 != _.mixed_block_flag && o < 2 && (b = 0), e.amp_filter[o] < 1e-12) we.fill(l, f + 0, f + 18, 0);else if (e.amp_filter[o] < 1 && me(), b == Ae.SHORT_TYPE) {
                  for (var h = -3; h < 0; h++) {
                    var v = A[Ae.SHORT_TYPE][h + 3];
                    l[f + 3 * h + 9] = p[9 + h][B[o]] * v - p[8 - h][B[o]], l[f + 3 * h + 18] = p[14 - h][B[o]] * v + p[15 + h][B[o]], l[f + 3 * h + 10] = p[15 + h][B[o]] * v - p[14 - h][B[o]], l[f + 3 * h + 19] = m[2 - h][B[o]] * v + m[3 + h][B[o]], l[f + 3 * h + 11] = m[3 + h][B[o]] * v - m[2 - h][B[o]], l[f + 3 * h + 20] = m[8 - h][B[o]] * v + m[9 + h][B[o]];
                  }
                  E(l, f);
                } else {
                  for (var d = de(18), h = -9; h < 0; h++) {
                    var g, w;
                    g = A[b][h + 27] * m[h + 9][B[o]] + A[b][h + 36] * m[8 - h][B[o]], w = A[b][h + 9] * p[h + 9][B[o]] - A[b][h + 18] * p[8 - h][B[o]], d[h + 9] = g - w * k[3 + h + 9], d[h + 18] = g * k[3 + h + 9] + w;
                  }
                  C(l, f, d);
                }
                if (b != Ae.SHORT_TYPE && 0 != o) for (var h = 7; 0 <= h; --h) {
                  var S, M;
                  S = l[f + h] * R[20 + h] + l[f + -1 - h] * x[28 + h], M = l[f + h] * x[28 + h] - l[f + -1 - h] * R[20 + h], l[f + -1 - h] = S, l[f + h] = M;
                }
              }
            }
            if (n = a, s = 286, 1 == e.mode_gr) for (var y = 0; y < 18; y++) I.arraycopy(e.sb_sample[r][1][y], 0, e.sb_sample[r][0][y], 0, 32);
          }
        };
      }();
      this.lame_encode_mp3_frame = function (e, t, a, n, s, r) {
        var i,
          o = E([2, 2]);
        o[0][0] = new L(), o[0][1] = new L(), o[1][0] = new L(), o[1][1] = new L();
        var _,
          l = E([2, 2]);
        l[0][0] = new L(), l[0][1] = new L(), l[1][0] = new L(), l[1][1] = new L();
        var f,
          c,
          u,
          h = [null, null],
          b = e.internal_flags,
          p = ge([2, 4]),
          m = [[0, 0], [0, 0]],
          v = [[0, 0], [0, 0]];
        if (h[0] = t, h[1] = a, 0 == b.lame_encode_frame_init && function (e, t) {
          var a,
            n,
            s = e.internal_flags;
          if (0 == s.lame_encode_frame_init) {
            var r,
              i,
              o = de(2014),
              _ = de(2014);
            for (s.lame_encode_frame_init = 1, i = r = 0; r < 286 + 576 * (1 + s.mode_gr); ++r) r < 576 * s.mode_gr ? (o[r] = 0, 2 == s.channels_out && (_[r] = 0)) : (o[r] = t[0][i], 2 == s.channels_out && (_[r] = t[1][i]), ++i);
            for (n = 0; n < s.mode_gr; n++) for (a = 0; a < s.channels_out; a++) s.l3_side.tt[n][a].block_type = Ae.SHORT_TYPE;
            T.mdct_sub48(s, o, _);
          }
        }(e, h), b.padding = 0, (b.slot_lag -= b.frac_SpF) < 0 && (b.slot_lag += e.out_samplerate, b.padding = 1), 0 != b.psymodel) {
          var d,
            g = [null, null],
            w = 0,
            S = ve(2);
          for (u = 0; u < b.mode_gr; u++) {
            for (c = 0; c < b.channels_out; c++) g[c] = h[c], w = 576 + 576 * u - Ae.FFTOFFSET;
            if (e.VBR == Me.vbr_mtrh || e.VBR == Me.vbr_mt ? me() : d = x.L3psycho_anal_ns(e, g, w, u, o, l, m[u], v[u], p[u], S), 0 != d) return -4;
            for (e.mode == ye.JOINT_STEREO && me(), c = 0; c < b.channels_out; c++) {
              var M = b.l3_side.tt[u][c];
              M.block_type = S[c], M.mixed_block_flag = 0;
            }
          }
        } else me();
        if (function (e) {
          var t, a;
          if (0 == e.ATH.useAdjust) return e.ATH.adjust = 1;
          if (a = e.loudness_sq[0][0], t = e.loudness_sq[1][0], 2 == e.channels_out ? me() : (a += a, t += t), 2 == e.mode_gr && (a = Math.max(a, t)), a *= .5, .03125 < (a *= e.ATH.aaSensitivityP)) 1 <= e.ATH.adjust ? e.ATH.adjust = 1 : e.ATH.adjust < e.ATH.adjustLimit && (e.ATH.adjust = e.ATH.adjustLimit), e.ATH.adjustLimit = 1;else {
            var n = 31.98 * a + 625e-6;
            e.ATH.adjust >= n ? (e.ATH.adjust *= .075 * n + .925, e.ATH.adjust < n && (e.ATH.adjust = n)) : e.ATH.adjustLimit >= n ? e.ATH.adjust = n : e.ATH.adjust < e.ATH.adjustLimit && (e.ATH.adjust = e.ATH.adjustLimit), e.ATH.adjustLimit = n;
          }
        }(b), T.mdct_sub48(b, h[0], h[1]), b.mode_ext = Ae.MPG_MD_LR_LR, e.force_ms ? b.mode_ext = Ae.MPG_MD_MS_LR : e.mode == ye.JOINT_STEREO && me(), b.mode_ext == k ? (_ = l, f = v) : (_ = o, f = m), e.analysis && null != b.pinfo && me(), e.VBR == Me.vbr_off || e.VBR == Me.vbr_abr) {
          var y, A;
          for (y = 0; y < 18; y++) b.nsPsy.pefirbuf[y] = b.nsPsy.pefirbuf[y + 1];
          for (u = A = 0; u < b.mode_gr; u++) for (c = 0; c < b.channels_out; c++) A += f[u][c];
          for (b.nsPsy.pefirbuf[18] = A, A = b.nsPsy.pefirbuf[9], y = 0; y < 9; y++) A += (b.nsPsy.pefirbuf[y] + b.nsPsy.pefirbuf[18 - y]) * Ae.fircoef[y];
          for (A = 3350 * b.mode_gr * b.channels_out / A, u = 0; u < b.mode_gr; u++) for (c = 0; c < b.channels_out; c++) f[u][c] *= A;
        }
        return b.iteration_loop.iteration_loop(e, f, [.5, .5], _), R.format_bitstream(e), i = R.copy_buffer(b, n, s, r, 1), e.bWriteVbrTag && B.addVbrFrame(e), e.analysis && null != b.pinfo && me(), function (e) {
          var t, a;
          for (e.bitrate_stereoMode_Hist[e.bitrate_index][4]++, e.bitrate_stereoMode_Hist[15][4]++, 2 == e.channels_out && me(), t = 0; t < e.mode_gr; ++t) for (a = 0; a < e.channels_out; ++a) {
            var n = 0 | e.l3_side.tt[t][a].block_type;
            0 != e.l3_side.tt[t][a].mixed_block_flag && (n = 4), e.bitrate_blockType_Hist[e.bitrate_index][n]++, e.bitrate_blockType_Hist[e.bitrate_index][5]++, e.bitrate_blockType_Hist[15][n]++, e.bitrate_blockType_Hist[15][5]++;
          }
        }(b), i;
      };
    }
    function i() {
      this.l = de(Ae.SBMAX_l), this.s = ge([Ae.SBMAX_s, 3]);
      var n = this;
      this.assign = function (e) {
        I.arraycopy(e.l, 0, n.l, 0, Ae.SBMAX_l);
        for (var t = 0; t < Ae.SBMAX_s; t++) for (var a = 0; a < 3; a++) n.s[t][a] = e.s[t][a];
      };
    }
    function j() {
      var e = 40;
      function t() {
        this.write_timing = 0, this.ptr = 0, this.buf = S(e);
      }
      this.Class_ID = 0, this.lame_encode_frame_init = 0, this.iteration_init_init = 0, this.fill_buffer_resample_init = 0, this.mfbuf = ge([2, j.MFSIZE]), this.mode_gr = 0, this.channels_in = 0, this.channels_out = 0, this.resample_ratio = 0, this.mf_samples_to_encode = 0, this.mf_size = 0, this.VBR_min_bitrate = 0, this.VBR_max_bitrate = 0, this.bitrate_index = 0, this.samplerate_index = 0, this.mode_ext = 0, this.lowpass1 = 0, this.lowpass2 = 0, this.highpass1 = 0, this.highpass2 = 0, this.noise_shaping = 0, this.noise_shaping_amp = 0, this.substep_shaping = 0, this.psymodel = 0, this.noise_shaping_stop = 0, this.subblock_gain = 0, this.use_best_huffman = 0, this.full_outer_loop = 0, this.l3_side = new function () {
        this.tt = [[null, null], [null, null]], this.main_data_begin = 0, this.private_bits = 0, this.resvDrain_pre = 0, this.resvDrain_post = 0, this.scfsi = [ve(4), ve(4)];
        for (var e = 0; e < 2; e++) for (var t = 0; t < 2; t++) this.tt[e][t] = new B();
      }(), this.ms_ratio = de(2), this.padding = 0, this.frac_SpF = 0, this.slot_lag = 0, this.tag_spec = null, this.nMusicCRC = 0, this.OldValue = ve(2), this.CurrentStep = ve(2), this.masking_lower = 0, this.bv_scf = ve(576), this.pseudohalf = ve(F.SFBMAX), this.sfb21_extra = !1, this.inbuf_old = new Array(2), this.blackfilt = new Array(2 * j.BPC + 1), this.itime = n(2), this.sideinfo_len = 0, this.sb_sample = ge([2, 2, 18, Ae.SBLIMIT]), this.amp_filter = de(32), this.header = new Array(j.MAX_HEADER_BUF), this.h_ptr = 0, this.w_ptr = 0, this.ancillary_flag = 0, this.ResvSize = 0, this.ResvMax = 0, this.scalefac_band = new r(), this.minval_l = de(Ae.CBANDS), this.minval_s = de(Ae.CBANDS), this.nb_1 = ge([4, Ae.CBANDS]), this.nb_2 = ge([4, Ae.CBANDS]), this.nb_s1 = ge([4, Ae.CBANDS]), this.nb_s2 = ge([4, Ae.CBANDS]), this.s3_ss = null, this.s3_ll = null, this.decay = 0, this.thm = new Array(4), this.en = new Array(4), this.tot_ener = de(4), this.loudness_sq = ge([2, 2]), this.loudness_sq_save = de(2), this.mld_l = de(Ae.SBMAX_l), this.mld_s = de(Ae.SBMAX_s), this.bm_l = ve(Ae.SBMAX_l), this.bo_l = ve(Ae.SBMAX_l), this.bm_s = ve(Ae.SBMAX_s), this.bo_s = ve(Ae.SBMAX_s), this.npart_l = 0, this.npart_s = 0, this.s3ind = w([Ae.CBANDS, 2]), this.s3ind_s = w([Ae.CBANDS, 2]), this.numlines_s = ve(Ae.CBANDS), this.numlines_l = ve(Ae.CBANDS), this.rnumlines_l = de(Ae.CBANDS), this.mld_cb_l = de(Ae.CBANDS), this.mld_cb_s = de(Ae.CBANDS), this.numlines_s_num1 = 0, this.numlines_l_num1 = 0, this.pe = de(4), this.ms_ratio_s_old = 0, this.ms_ratio_l_old = 0, this.ms_ener_ratio_old = 0, this.blocktype_old = ve(2), this.nsPsy = new function () {
        this.last_en_subshort = ge([4, 9]), this.lastAttacks = ve(4), this.pefirbuf = de(19), this.longfact = de(Ae.SBMAX_l), this.shortfact = de(Ae.SBMAX_s), this.attackthre = 0, this.attackthre_s = 0;
      }(), this.VBR_seek_table = new function () {
        this.sum = 0, this.seen = 0, this.want = 0, this.pos = 0, this.size = 0, this.bag = null, this.nVbrNumFrames = 0, this.nBytesWritten = 0, this.TotalFrameSize = 0;
      }(), this.ATH = null, this.PSY = null, this.nogap_total = 0, this.nogap_current = 0, this.decode_on_the_fly = !0, this.findReplayGain = !0, this.findPeakSample = !0, this.PeakSample = 0, this.RadioGain = 0, this.AudiophileGain = 0, this.rgdata = null, this.noclipGainChange = 0, this.noclipScale = 0, this.bitrate_stereoMode_Hist = w([16, 5]), this.bitrate_blockType_Hist = w([16, 6]), this.pinfo = null, this.hip = null, this.in_buffer_nsamples = 0, this.in_buffer_0 = null, this.in_buffer_1 = null, this.iteration_loop = null;
      for (var a = 0; a < this.en.length; a++) this.en[a] = new i();
      for (var a = 0; a < this.thm.length; a++) this.thm[a] = new i();
      for (var a = 0; a < this.header.length; a++) this.header[a] = new t();
    }
    function X() {
      var k = new function () {
          var h = de(Ae.BLKSIZE),
            p = de(Ae.BLKSIZE_s / 2),
            x = [.9238795325112867, .3826834323650898, .9951847266721969, .0980171403295606, .9996988186962042, .02454122852291229, .9999811752826011, .006135884649154475];
          function m(e, t, a) {
            var n,
              s,
              r,
              i = 0,
              o = t + (a <<= 1);
            n = 4;
            do {
              var _, l, f, c, u, h, b;
              for (b = n >> 1, h = (u = (c = n) << 1) + c, n = u << 1, r = (s = t) + b; S = e[s + 0] - e[s + c], w = e[s + 0] + e[s + c], k = e[s + u] - e[s + h], y = e[s + u] + e[s + h], e[s + u] = w - y, e[s + 0] = w + y, e[s + h] = S - k, e[s + c] = S + k, S = e[r + 0] - e[r + c], w = e[r + 0] + e[r + c], k = V.SQRT2 * e[r + h], y = V.SQRT2 * e[r + u], e[r + u] = w - y, e[r + 0] = w + y, e[r + h] = S - k, e[r + c] = S + k, r += n, (s += n) < o;);
              for (l = x[i + 0], _ = x[i + 1], f = 1; f < b; f++) {
                var p, m;
                p = 1 - 2 * _ * _, m = 2 * _ * l, s = t + f, r = t + c - f;
                do {
                  var v, d, g, w, S, M, y, A, k, R;
                  d = m * e[s + c] - p * e[r + c], v = p * e[s + c] + m * e[r + c], S = e[s + 0] - v, w = e[s + 0] + v, M = e[r + 0] - d, g = e[r + 0] + d, d = m * e[s + h] - p * e[r + h], v = p * e[s + h] + m * e[r + h], k = e[s + u] - v, y = e[s + u] + v, R = e[r + u] - d, A = e[r + u] + d, d = _ * y - l * R, v = l * y + _ * R, e[s + u] = w - v, e[s + 0] = w + v, e[r + h] = M - d, e[r + c] = M + d, d = l * A - _ * k, v = _ * A + l * k, e[r + u] = g - v, e[r + 0] = g + v, e[s + h] = S - d, e[s + c] = S + d, r += n, s += n;
                } while (s < o);
                l = (p = l) * x[i + 0] - _ * x[i + 1], _ = p * x[i + 1] + _ * x[i + 0];
              }
              i += 2;
            } while (n < a);
          }
          var v = [0, 128, 64, 192, 32, 160, 96, 224, 16, 144, 80, 208, 48, 176, 112, 240, 8, 136, 72, 200, 40, 168, 104, 232, 24, 152, 88, 216, 56, 184, 120, 248, 4, 132, 68, 196, 36, 164, 100, 228, 20, 148, 84, 212, 52, 180, 116, 244, 12, 140, 76, 204, 44, 172, 108, 236, 28, 156, 92, 220, 60, 188, 124, 252, 2, 130, 66, 194, 34, 162, 98, 226, 18, 146, 82, 210, 50, 178, 114, 242, 10, 138, 74, 202, 42, 170, 106, 234, 26, 154, 90, 218, 58, 186, 122, 250, 6, 134, 70, 198, 38, 166, 102, 230, 22, 150, 86, 214, 54, 182, 118, 246, 14, 142, 78, 206, 46, 174, 110, 238, 30, 158, 94, 222, 62, 190, 126, 254];
          this.fft_short = function (e, t, a, n, s) {
            for (var r = 0; r < 3; r++) {
              var i = Ae.BLKSIZE_s / 2,
                o = 65535 & 192 * (r + 1),
                _ = Ae.BLKSIZE_s / 8 - 1;
              do {
                var l,
                  f,
                  c,
                  u,
                  h,
                  b = 255 & v[_ << 2];
                l = p[b] * n[a][s + b + o], h = p[127 - b] * n[a][s + b + o + 128], f = l - h, l += h, c = p[b + 64] * n[a][s + b + o + 64], h = p[63 - b] * n[a][s + b + o + 192], u = c - h, c += h, i -= 4, t[r][i + 0] = l + c, t[r][i + 2] = l - c, t[r][i + 1] = f + u, t[r][i + 3] = f - u, l = p[b + 1] * n[a][s + b + o + 1], h = p[126 - b] * n[a][s + b + o + 129], f = l - h, l += h, c = p[b + 65] * n[a][s + b + o + 65], h = p[62 - b] * n[a][s + b + o + 193], u = c - h, c += h, t[r][i + Ae.BLKSIZE_s / 2 + 0] = l + c, t[r][i + Ae.BLKSIZE_s / 2 + 2] = l - c, t[r][i + Ae.BLKSIZE_s / 2 + 1] = f + u, t[r][i + Ae.BLKSIZE_s / 2 + 3] = f - u;
              } while (0 <= --_);
              m(t[r], i, Ae.BLKSIZE_s / 2);
            }
          }, this.fft_long = function (e, t, a, n, s) {
            var r = Ae.BLKSIZE / 8 - 1,
              i = Ae.BLKSIZE / 2;
            do {
              var o,
                _,
                l,
                f,
                c,
                u = 255 & v[r];
              o = h[u] * n[a][s + u], c = h[u + 512] * n[a][s + u + 512], _ = o - c, o += c, l = h[u + 256] * n[a][s + u + 256], c = h[u + 768] * n[a][s + u + 768], f = l - c, l += c, t[0 + (i -= 4)] = o + l, t[i + 2] = o - l, t[i + 1] = _ + f, t[i + 3] = _ - f, o = h[u + 1] * n[a][s + u + 1], c = h[u + 513] * n[a][s + u + 513], _ = o - c, o += c, l = h[u + 257] * n[a][s + u + 257], c = h[u + 769] * n[a][s + u + 769], f = l - c, l += c, t[i + Ae.BLKSIZE / 2 + 0] = o + l, t[i + Ae.BLKSIZE / 2 + 2] = o - l, t[i + Ae.BLKSIZE / 2 + 1] = _ + f, t[i + Ae.BLKSIZE / 2 + 3] = _ - f;
            } while (0 <= --r);
            m(t, i, Ae.BLKSIZE / 2);
          }, this.init_fft = function (e) {
            for (var t = 0; t < Ae.BLKSIZE; t++) h[t] = .42 - .5 * Math.cos(2 * Math.PI * (t + .5) / Ae.BLKSIZE) + .08 * Math.cos(4 * Math.PI * (t + .5) / Ae.BLKSIZE);
            for (var t = 0; t < Ae.BLKSIZE_s / 2; t++) p[t] = .5 * (1 - Math.cos(2 * Math.PI * (t + .5) / Ae.BLKSIZE_s));
          };
        }(),
        R = 2.302585092994046,
        d = 2,
        g = 16,
        E = .34,
        v = 1 / 217621504 / (Ae.BLKSIZE / 2),
        w = .2302585093;
      function se(e, t, a, n, s, r, i, o, _, l, f) {
        var c = e.internal_flags;
        _ < 2 ? (k.fft_long(c, n[s], _, l, f), k.fft_short(c, r[i], _, l, f)) : 2 == _ && me(), t[0] = n[s + 0][0], t[0] *= t[0];
        for (var u = Ae.BLKSIZE / 2 - 1; 0 <= u; --u) {
          var h = n[s + 0][Ae.BLKSIZE / 2 - u],
            b = n[s + 0][Ae.BLKSIZE / 2 + u];
          t[Ae.BLKSIZE / 2 - u] = .5 * (h * h + b * b);
        }
        for (var p = 2; 0 <= p; --p) {
          a[p][0] = r[i + 0][p][0], a[p][0] *= a[p][0];
          for (var u = Ae.BLKSIZE_s / 2 - 1; 0 <= u; --u) {
            var h = r[i + 0][p][Ae.BLKSIZE_s / 2 - u],
              b = r[i + 0][p][Ae.BLKSIZE_s / 2 + u];
            a[p][Ae.BLKSIZE_s / 2 - u] = .5 * (h * h + b * b);
          }
        }
        for (var m = 0, u = 11; u < Ae.HBLKSIZE; u++) m += t[u];
        c.tot_ener[_] = m, e.analysis && me(), 2 == e.athaa_loudapprox && _ < 2 && (c.loudness_sq[o][_] = c.loudness_sq_save[_], c.loudness_sq_save[_] = function (e, t) {
          for (var a = 0, n = 0; n < Ae.BLKSIZE / 2; ++n) a += e[n] * t.ATH.eql_w[n];
          return a *= v;
        }(t, c));
      }
      var x,
        B,
        T,
        C = 8,
        I = 23,
        L = 15,
        re = [1, .79433, .63096, .63096, .63096, .63096, .63096, .25119, .11749],
        f = [3.3246 * 3.3246, 3.23837 * 3.23837, 9.9500500969, 9.0247369744, 8.1854926609, 7.0440875649, 2.46209 * 2.46209, 2.284 * 2.284, 4.4892710641, 1.96552 * 1.96552, 1.82335 * 1.82335, 1.69146 * 1.69146, 2.4621061921, 2.1508568964, 1.37074 * 1.37074, 1.31036 * 1.31036, 1.5691069696, 1.4555939904, 1.16203 * 1.16203, 1.2715945225, 1.09428 * 1.09428, 1.0659 * 1.0659, 1.0779838276, 1.0382591025, 1],
        c = [1.7782755904, 1.35879 * 1.35879, 1.38454 * 1.38454, 1.39497 * 1.39497, 1.40548 * 1.40548, 1.3537 * 1.3537, 1.6999465924, 1.22321 * 1.22321, 1.3169398564, 1],
        u = [5.5396212496, 2.29259 * 2.29259, 4.9868695969, 2.12675 * 2.12675, 2.02545 * 2.02545, 1.87894 * 1.87894, 1.74303 * 1.74303, 1.61695 * 1.61695, 2.2499700001, 1.39148 * 1.39148, 1.29083 * 1.29083, 1.19746 * 1.19746, 1.2339655056, 1.0779838276];
      function ie(e, t, a, n, s, r) {
        var i;
        if (e < t) {
          if (!(t < e * B)) return e + t;
          i = t / e;
        } else {
          if (t * B <= e) return e + t;
          i = e / t;
        }
        if (e += t, n + 3 <= 6) {
          if (x <= i) return e;
          var o = 0 | V.FAST_LOG10_X(i, 16);
          return e * c[o];
        }
        var _,
          l,
          o = 0 | V.FAST_LOG10_X(i, 16);
        return t = 0 != r ? s.ATH.cb_s[a] * s.ATH.adjust : s.ATH.cb_l[a] * s.ATH.adjust, e < T * t ? t < e ? (_ = 1, o <= 13 && (_ = u[o]), l = V.FAST_LOG10_X(e / t, 10 / 15), e * ((f[o] - _) * l + _)) : 13 < o ? e : e * u[o] : e * f[o];
      }
      function oe(e, t, a, n, s) {
        var r,
          i,
          o = 0,
          _ = 0;
        for (r = i = 0; r < Ae.SBMAX_s; ++i, ++r) {
          for (var l = e.bo_s[r], f = e.npart_s, c = l < f ? l : f; i < c;) o += t[i], _ += a[i], i++;
          if (e.en[n].s[r][s] = o, e.thm[n].s[r][s] = _, f <= i) {
            ++r;
            break;
          }
          var u = e.PSY.bo_s_weight[r],
            h = 1 - u;
          o = u * t[i], _ = u * a[i], e.en[n].s[r][s] += o, e.thm[n].s[r][s] += _, o = h * t[i], _ = h * a[i];
        }
        for (; r < Ae.SBMAX_s; ++r) e.en[n].s[r][s] = 0, e.thm[n].s[r][s] = 0;
      }
      function _e(e, t, a, n) {
        var s,
          r,
          i = 0,
          o = 0;
        for (s = r = 0; s < Ae.SBMAX_l; ++r, ++s) {
          for (var _ = e.bo_l[s], l = e.npart_l, f = _ < l ? _ : l; r < f;) i += t[r], o += a[r], r++;
          if (e.en[n].l[s] = i, e.thm[n].l[s] = o, l <= r) {
            ++s;
            break;
          }
          var c = e.PSY.bo_l_weight[s],
            u = 1 - c;
          i = c * t[r], o = c * a[r], e.en[n].l[s] += i, e.thm[n].l[s] += o, i = u * t[r], o = u * a[r];
        }
        for (; s < Ae.SBMAX_l; ++s) e.en[n].l[s] = 0, e.thm[n].l[s] = 0;
      }
      function le(e, t, a, n, s, r) {
        var i,
          o,
          _ = e.internal_flags;
        for (o = i = 0; o < _.npart_s; ++o) {
          for (var l = 0, f = 0, c = _.numlines_s[o], u = 0; u < c; ++u, ++i) {
            var h = t[r][i];
            l += h, f < h && (f = h);
          }
          a[o] = l;
        }
        for (i = o = 0; o < _.npart_s; o++) {
          var b = _.s3ind_s[o][0],
            p = _.s3_ss[i++] * a[b];
          for (++b; b <= _.s3ind_s[o][1];) p += _.s3_ss[i] * a[b], ++i, ++b;
          var m = d * _.nb_s1[s][o];
          if (n[o] = Math.min(p, m), _.blocktype_old[1 & s] == Ae.SHORT_TYPE) {
            var m = g * _.nb_s2[s][o],
              v = n[o];
            n[o] = Math.min(m, v);
          }
          _.nb_s2[s][o] = _.nb_s1[s][o], _.nb_s1[s][o] = p;
        }
        for (; o <= Ae.CBANDS; ++o) a[o] = 0, n[o] = 0;
      }
      function fe(e, t, a) {
        return 1 <= a ? e : a <= 0 ? t : 0 < t ? Math.pow(e / t, a) * t : 0;
      }
      var _ = [11.8, 13.6, 17.2, 32, 46.5, 51.3, 57.5, 67.1, 71.5, 84.6, 97.6, 130];
      function ce(e, t) {
        for (var a = 309.07, n = 0; n < Ae.SBMAX_s - 1; n++) for (var s = 0; s < 3; s++) {
          var r = e.thm.s[n][s];
          if (0 < r) {
            var i = r * t,
              o = e.en.s[n][s];
            i < o && (a += 1e10 * i < o ? _[n] * (10 * R) : _[n] * V.FAST_LOG10(o / i));
          }
        }
        return a;
      }
      var o = [6.8, 5.8, 5.8, 6.4, 6.5, 9.9, 12.1, 14.4, 15, 18.9, 21.6, 26.9, 34.2, 40.2, 46.8, 56.5, 60.7, 73.9, 85.7, 93.4, 126.1];
      function ue(e, t) {
        for (var a = 281.0575, n = 0; n < Ae.SBMAX_l - 1; n++) {
          var s = e.thm.l[n];
          if (0 < s) {
            var r = s * t,
              i = e.en.l[n];
            r < i && (a += 1e10 * r < i ? o[n] * (10 * R) : o[n] * V.FAST_LOG10(i / r));
          }
        }
        return a;
      }
      function he(e, t, a, n, s) {
        var r, i;
        for (r = i = 0; r < e.npart_l; ++r) {
          var o,
            _ = 0,
            l = 0;
          for (o = 0; o < e.numlines_l[r]; ++o, ++i) {
            var f = t[i];
            _ += f, l < f && (l = f);
          }
          a[r] = _, n[r] = l, s[r] = _ * e.rnumlines_l[r];
        }
      }
      function be(e, t, a, n) {
        var s = re.length - 1,
          r = 0,
          i = a[r] + a[r + 1];
        if (0 < i) {
          var o = t[r];
          o < t[r + 1] && (o = t[r + 1]);
          var _ = 0 | (i = 20 * (2 * o - i) / (i * (e.numlines_l[r] + e.numlines_l[r + 1] - 1)));
          s < _ && (_ = s), n[r] = _;
        } else n[r] = 0;
        for (r = 1; r < e.npart_l - 1; r++) if (0 < (i = a[r - 1] + a[r] + a[r + 1])) {
          var o = t[r - 1];
          o < t[r] && (o = t[r]), o < t[r + 1] && (o = t[r + 1]);
          var _ = 0 | (i = 20 * (3 * o - i) / (i * (e.numlines_l[r - 1] + e.numlines_l[r] + e.numlines_l[r + 1] - 1)));
          s < _ && (_ = s), n[r] = _;
        } else n[r] = 0;
        if (0 < (i = a[r - 1] + a[r])) {
          var o = t[r - 1];
          o < t[r] && (o = t[r]);
          var _ = 0 | (i = 20 * (2 * o - i) / (i * (e.numlines_l[r - 1] + e.numlines_l[r] - 1)));
          s < _ && (_ = s), n[r] = _;
        } else n[r] = 0;
      }
      var pe = [-1.730326e-17, -.01703172, -1.349528e-17, .0418072, -6.73278e-17, -.0876324, -3.0835e-17, .1863476, -1.104424e-16, -.627638];
      function P(e) {
        return e < 0 && (e = 0), e *= .001, 13 * Math.atan(.76 * e) + 3.5 * Math.atan(e * e / 56.25);
      }
      function H(e, t, a, n, s, r, i, o, _, l, f, c) {
        var u,
          h = de(Ae.CBANDS + 1),
          b = o / (15 < c ? 1152 : 384),
          p = ve(Ae.HBLKSIZE);
        o /= _;
        var m = 0,
          v = 0;
        for (u = 0; u < Ae.CBANDS; u++) {
          var d;
          for (x = P(o * m), h[u] = o * m, d = m; P(o * d) - x < E && d <= _ / 2; d++);
          for (e[u] = d - m, v = u + 1; m < d;) p[m++] = u;
          if (_ / 2 < m) {
            m = _ / 2, ++u;
            break;
          }
        }
        h[u] = o * m;
        for (var g = 0; g < c; g++) {
          var w, S, M, y, A;
          M = l[g], y = l[g + 1], (w = 0 | Math.floor(.5 + f * (M - .5))) < 0 && (w = 0), S = 0 | Math.floor(.5 + f * (y - .5)), _ / 2 < S && (S = _ / 2), a[g] = (p[w] + p[S]) / 2, t[g] = p[S];
          var k = b * y;
          i[g] = (k - h[t[g]]) / (h[t[g] + 1] - h[t[g]]), i[g] < 0 ? i[g] = 0 : 1 < i[g] && (i[g] = 1), A = P(o * l[g] * f), A = Math.min(A, 15.5) / 15.5, r[g] = Math.pow(10, 1.25 * (1 - Math.cos(Math.PI * A)) - 2.5);
        }
        for (var R = m = 0; R < v; R++) {
          var x,
            B,
            T = e[R];
          x = P(o * m), B = P(o * (m + T - 1)), n[R] = .5 * (x + B), x = P(o * (m - .5)), B = P(o * (m + T - .5)), s[R] = B - x, m += T;
        }
        return v;
      }
      function O(e, t, a, n, s, r) {
        var i,
          o,
          _,
          l,
          f,
          c,
          u = ge([Ae.CBANDS, Ae.CBANDS]),
          h = 0;
        if (r) for (var b = 0; b < t; b++) for (i = 0; i < t; i++) {
          var p = (o = a[b] - a[i], c = f = l = _ = void 0, _ = o, l = .5 <= (_ *= 0 <= _ ? 3 : 1.5) && _ <= 2.5 ? 8 * ((c = _ - .5) * c - 2 * c) : 0, ((f = 15.811389 + 7.5 * (_ += .474) - 17.5 * Math.sqrt(1 + _ * _)) <= -60 ? 0 : (_ = Math.exp((l + f) * w), _ /= .6609193)) * n[i]);
          u[b][i] = p * s[b];
        } else me();
        for (var b = 0; b < t; b++) {
          for (i = 0; i < t && !(0 < u[b][i]); i++);
          for (e[b][0] = i, i = t - 1; 0 < i && !(0 < u[b][i]); i--);
          e[b][1] = i, h += e[b][1] - e[b][0] + 1;
        }
        for (var m = de(h), v = 0, b = 0; b < t; b++) for (i = e[b][0]; i <= e[b][1]; i++) m[v++] = u[b][i];
        return m;
      }
      function N(e) {
        var t = P(e);
        return t = Math.min(t, 15.5) / 15.5, Math.pow(10, 1.25 * (1 - Math.cos(Math.PI * t)) - 2.5);
      }
      function n(e, t) {
        e < -.3 && (e = 3410), e /= 1e3, e = Math.max(.1, e);
        var a = 3.64 * Math.pow(e, -.8) - 6.8 * Math.exp(-.6 * Math.pow(e - 3.4, 2)) + 6 * Math.exp(-.15 * Math.pow(e - 8.7, 2)) + .001 * (.6 + .04 * t) * Math.pow(e, 4);
        return a;
      }
      this.L3psycho_anal_ns = function (e, t, a, n, s, r, i, o, _, l) {
        var f,
          c,
          u,
          h,
          b,
          p,
          m,
          v,
          d,
          g = e.internal_flags,
          w = ge([2, Ae.BLKSIZE]),
          S = ge([2, 3, Ae.BLKSIZE_s]),
          M = de(Ae.CBANDS + 1),
          y = de(Ae.CBANDS + 1),
          A = de(Ae.CBANDS + 2),
          k = ve(2),
          R = ve(2),
          x = ge([2, 576]),
          B = ve(Ae.CBANDS + 2),
          T = ve(Ae.CBANDS + 2);
        for (we.fill(T, 0), f = g.channels_out, e.mode == ye.JOINT_STEREO && (f = 4), d = e.VBR == Me.vbr_off ? 0 == g.ResvMax ? 0 : g.ResvSize / g.ResvMax * .5 : e.VBR == Me.vbr_rh || e.VBR == Me.vbr_mtrh || e.VBR == Me.vbr_mt ? .6 : 1, c = 0; c < g.channels_out; c++) {
          var E = t[c],
            C = a + 576 - 350 - 21 + 192;
          for (h = 0; h < 576; h++) {
            var I, L;
            for (I = E[C + h + 10], b = L = 0; b < 9; b += 2) I += pe[b] * (E[C + h + b] + E[C + h + 21 - b]), L += pe[b + 1] * (E[C + h + b + 1] + E[C + h + 21 - b - 1]);
            x[c][h] = I + L;
          }
          s[n][c].en.assign(g.en[c]), s[n][c].thm.assign(g.thm[c]), 2 < f && me();
        }
        for (c = 0; c < f; c++) {
          var P,
            H = de(12),
            O = [0, 0, 0, 0],
            N = de(12),
            V = 1,
            D = de(Ae.CBANDS),
            F = de(Ae.CBANDS),
            j = [0, 0, 0, 0],
            X = de(Ae.HBLKSIZE),
            Y = ge([3, Ae.HBLKSIZE_s]);
          for (h = 0; h < 3; h++) H[h] = g.nsPsy.last_en_subshort[c][h + 6], N[h] = H[h] / g.nsPsy.last_en_subshort[c][h + 4], O[0] += H[h];
          2 == c && me();
          var z = x[1 & c],
            q = 0;
          for (h = 0; h < 9; h++) {
            for (var G = q + 64, U = 1; q < G; q++) U < Math.abs(z[q]) && (U = Math.abs(z[q]));
            g.nsPsy.last_en_subshort[c][h] = H[h + 3] = U, O[1 + h / 3] += U, U > H[h + 3 - 2] ? U /= H[h + 3 - 2] : U = H[h + 3 - 2] > 10 * U ? H[h + 3 - 2] / (10 * U) : 0, N[h + 3] = U;
          }
          for (e.analysis && me(), P = 3 == c ? g.nsPsy.attackthre_s : g.nsPsy.attackthre, h = 0; h < 12; h++) 0 == j[h / 3] && N[h] > P && (j[h / 3] = h % 3 + 1);
          for (h = 1; h < 4; h++) (O[h - 1] > O[h] ? O[h - 1] / O[h] : O[h] / O[h - 1]) < 1.7 && (j[h] = 0, 1 == h && (j[0] = 0));
          for (0 != j[0] && 0 != g.nsPsy.lastAttacks[c] && (j[0] = 0), 3 != g.nsPsy.lastAttacks[c] && j[0] + j[1] + j[2] + j[3] == 0 || ((V = 0) != j[1] && 0 != j[0] && (j[1] = 0), 0 != j[2] && 0 != j[1] && (j[2] = 0), 0 != j[3] && 0 != j[2] && (j[3] = 0)), c < 2 ? R[c] = V : me(), _[c] = g.tot_ener[c], se(e, X, Y, w, 1 & c, S, 1 & c, n, c, t, a), he(g, X, M, D, F), be(g, D, F, B), v = 0; v < 3; v++) {
            var K, Z;
            for (le(e, Y, y, A, c, v), oe(g, y, A, c, v), m = 0; m < Ae.SBMAX_s; m++) {
              if (Z = g.thm[c].s[m][v], Z *= .8, 2 <= j[v] || 1 == j[v + 1]) {
                var W = 0 != v ? v - 1 : 2,
                  U = fe(g.thm[c].s[m][W], Z, .6 * d);
                Z = Math.min(Z, U);
              }
              if (1 == j[v]) {
                var W = 0 != v ? v - 1 : 2,
                  U = fe(g.thm[c].s[m][W], Z, .3 * d);
                Z = Math.min(Z, U);
              } else if (0 != v && 3 == j[v - 1] || 0 == v && 3 == g.nsPsy.lastAttacks[c]) {
                var W = 2 != v ? v + 1 : 0,
                  U = fe(g.thm[c].s[m][W], Z, .3 * d);
                Z = Math.min(Z, U);
              }
              K = H[3 * v + 3] + H[3 * v + 4] + H[3 * v + 5], 6 * H[3 * v + 5] < K && (Z *= .5, 6 * H[3 * v + 4] < K && (Z *= .5)), g.thm[c].s[m][v] = Z;
            }
          }
          for (g.nsPsy.lastAttacks[c] = j[2], u = p = 0; u < g.npart_l; u++) {
            for (var Q = g.s3ind[u][0], $ = M[Q] * re[B[Q]], J = g.s3_ll[p++] * $; ++Q <= g.s3ind[u][1];) $ = M[Q] * re[B[Q]], J = ie(J, g.s3_ll[p++] * $, Q, Q - u, g, 0);
            J *= .158489319246111, g.blocktype_old[1 & c] == Ae.SHORT_TYPE ? A[u] = J : A[u] = fe(Math.min(J, Math.min(2 * g.nb_1[c][u], 16 * g.nb_2[c][u])), J, d), g.nb_2[c][u] = g.nb_1[c][u], g.nb_1[c][u] = J;
          }
          for (; u <= Ae.CBANDS; ++u) M[u] = 0, A[u] = 0;
          _e(g, M, A, c);
        }
        for (e.mode != ye.STEREO && e.mode != ye.JOINT_STEREO || me(), e.mode == ye.JOINT_STEREO && me(), function (e, t, a, n) {
          var s = e.internal_flags;
          e.short_blocks != Se.short_block_coupled || 0 != t[0] && 0 != t[1] || (t[0] = t[1] = 0);
          for (var r = 0; r < s.channels_out; r++) n[r] = Ae.NORM_TYPE, e.short_blocks == Se.short_block_dispensed && (t[r] = 1), e.short_blocks == Se.short_block_forced && (t[r] = 0), 0 != t[r] ? s.blocktype_old[r] == Ae.SHORT_TYPE && (n[r] = Ae.STOP_TYPE) : (n[r] = Ae.SHORT_TYPE, s.blocktype_old[r] == Ae.NORM_TYPE && (s.blocktype_old[r] = Ae.START_TYPE), s.blocktype_old[r] == Ae.STOP_TYPE && (s.blocktype_old[r] = Ae.SHORT_TYPE)), a[r] = s.blocktype_old[r], s.blocktype_old[r] = n[r];
        }(e, R, l, k), c = 0; c < f; c++) {
          var ee,
            te,
            ae,
            ne = 0;
          1 < c ? me() : (ee = i, ne = 0, te = l[c], ae = s[n][c]), ee[ne + c] = te == Ae.SHORT_TYPE ? ce(ae, g.masking_lower) : ue(ae, g.masking_lower), e.analysis && (g.pinfo.pe[n][c] = ee[ne + c]);
        }
        return 0;
      }, this.psymodel_init = function (e) {
        var t,
          a = e.internal_flags,
          n = !0,
          s = 13,
          r = 0,
          i = 0,
          o = -8.25,
          _ = -4.5,
          l = de(Ae.CBANDS),
          f = de(Ae.CBANDS),
          c = de(Ae.CBANDS),
          u = e.out_samplerate;
        switch (e.experimentalZ) {
          default:
          case 0:
            n = !0;
            break;
          case 1:
            n = e.VBR != Me.vbr_mtrh && e.VBR != Me.vbr_mt;
            break;
          case 2:
            n = !1;
            break;
          case 3:
            s = 8, r = -1.75, i = -.0125, o = -8.25, _ = -2.25;
        }
        for (a.ms_ener_ratio_old = .25, a.blocktype_old[0] = a.blocktype_old[1] = Ae.NORM_TYPE, t = 0; t < 4; ++t) {
          for (var h = 0; h < Ae.CBANDS; ++h) a.nb_1[t][h] = 1e20, a.nb_2[t][h] = 1e20, a.nb_s1[t][h] = a.nb_s2[t][h] = 1;
          for (var b = 0; b < Ae.SBMAX_l; b++) a.en[t].l[b] = 1e20, a.thm[t].l[b] = 1e20;
          for (var h = 0; h < 3; ++h) {
            for (var b = 0; b < Ae.SBMAX_s; b++) a.en[t].s[b][h] = 1e20, a.thm[t].s[b][h] = 1e20;
            a.nsPsy.lastAttacks[t] = 0;
          }
          for (var h = 0; h < 9; h++) a.nsPsy.last_en_subshort[t][h] = 10;
        }
        for (a.loudness_sq_save[0] = a.loudness_sq_save[1] = 0, a.npart_l = H(a.numlines_l, a.bo_l, a.bm_l, l, f, a.mld_l, a.PSY.bo_l_weight, u, Ae.BLKSIZE, a.scalefac_band.l, Ae.BLKSIZE / 1152, Ae.SBMAX_l), t = 0; t < a.npart_l; t++) {
          var p = r;
          l[t] >= s && (p = i * (l[t] - s) / (24 - s) + r * (24 - l[t]) / (24 - s)), c[t] = Math.pow(10, p / 10), 0 < a.numlines_l[t] ? a.rnumlines_l[t] = 1 / a.numlines_l[t] : a.rnumlines_l[t] = 0;
        }
        a.s3_ll = O(a.s3ind, a.npart_l, l, f, c, n);
        var m,
          h = 0;
        for (t = 0; t < a.npart_l; t++) {
          g = D.MAX_VALUE;
          for (var v = 0; v < a.numlines_l[t]; v++, h++) {
            var d = u * h / (1e3 * Ae.BLKSIZE);
            w = this.ATHformula(1e3 * d, e) - 20, w = Math.pow(10, .1 * w), (w *= a.numlines_l[t]) < g && (g = w);
          }
          a.ATH.cb_l[t] = g, 6 < (g = 20 * l[t] / 10 - 20) && (g = 100), g < -15 && (g = -15), g -= 8, a.minval_l[t] = Math.pow(10, g / 10) * a.numlines_l[t];
        }
        for (a.npart_s = H(a.numlines_s, a.bo_s, a.bm_s, l, f, a.mld_s, a.PSY.bo_s_weight, u, Ae.BLKSIZE_s, a.scalefac_band.s, Ae.BLKSIZE_s / 384, Ae.SBMAX_s), t = h = 0; t < a.npart_s; t++) {
          var g,
            p = o;
          l[t] >= s && (p = _ * (l[t] - s) / (24 - s) + o * (24 - l[t]) / (24 - s)), c[t] = Math.pow(10, p / 10), g = D.MAX_VALUE;
          for (var v = 0; v < a.numlines_s[t]; v++, h++) {
            var w,
              d = u * h / (1e3 * Ae.BLKSIZE_s);
            w = this.ATHformula(1e3 * d, e) - 20, w = Math.pow(10, .1 * w), (w *= a.numlines_s[t]) < g && (g = w);
          }
          a.ATH.cb_s[t] = g, g = 7 * l[t] / 12 - 7, 12 < l[t] && (g *= 1 + 3.1 * Math.log(1 + g)), l[t] < 12 && (g *= 1 + 2.3 * Math.log(1 - g)), g < -15 && (g = -15), g -= 8, a.minval_s[t] = Math.pow(10, g / 10) * a.numlines_s[t];
        }
        a.s3_ss = O(a.s3ind_s, a.npart_s, l, f, c, n), x = Math.pow(10, (C + 1) / 16), B = Math.pow(10, (I + 1) / 16), T = Math.pow(10, L / 10), k.init_fft(a), a.decay = Math.exp(-1 * R / (.01 * u / 192)), m = 3.5, 0 != (2 & e.exp_nspsytune) && (m = 1), 0 < Math.abs(e.msfix) && (m = e.msfix), e.msfix = m;
        for (var S = 0; S < a.npart_l; S++) a.s3ind[S][1] > a.npart_l - 1 && (a.s3ind[S][1] = a.npart_l - 1);
        var M = 576 * a.mode_gr / u;
        if (a.ATH.decay = Math.pow(10, -1.2 * M), a.ATH.adjust = .01, -(a.ATH.adjustLimit = 1) != e.ATHtype) {
          var y = e.out_samplerate / Ae.BLKSIZE,
            A = 0;
          for (t = d = 0; t < Ae.BLKSIZE / 2; ++t) d += y, a.ATH.eql_w[t] = 1 / Math.pow(10, this.ATHformula(d, e) / 10), A += a.ATH.eql_w[t];
          for (A = 1 / A, t = Ae.BLKSIZE / 2; 0 <= --t;) a.ATH.eql_w[t] *= A;
        }
        for (var S = h = 0; S < a.npart_s; ++S) for (t = 0; t < a.numlines_s[S]; ++t) ++h;
        for (var S = h = 0; S < a.npart_l; ++S) for (t = 0; t < a.numlines_l[S]; ++t) ++h;
        for (t = h = 0; t < a.npart_l; t++) {
          var d = u * (h + a.numlines_l[t] / 2) / (1 * Ae.BLKSIZE);
          a.mld_cb_l[t] = N(d), h += a.numlines_l[t];
        }
        for (; t < Ae.CBANDS; ++t) a.mld_cb_l[t] = 1;
        for (t = h = 0; t < a.npart_s; t++) {
          var d = u * (h + a.numlines_s[t] / 2) / (1 * Ae.BLKSIZE_s);
          a.mld_cb_s[t] = N(d), h += a.numlines_s[t];
        }
        for (; t < Ae.CBANDS; ++t) a.mld_cb_s[t] = 1;
        return 0;
      }, this.ATHformula = function (e, t) {
        var a;
        switch (t.ATHtype) {
          case 0:
            a = n(e, 9);
            break;
          case 1:
            a = n(e, -1);
            break;
          case 2:
            a = n(e, 0);
            break;
          case 3:
            a = n(e, 1) + 6;
            break;
          case 4:
            a = n(e, t.ATHcurve);
            break;
          default:
            a = n(e, 0);
        }
        return a;
      };
    }
    function Y() {
      var T,
        E,
        u,
        h,
        b,
        C = this;
      Y.V9 = 410, Y.V8 = 420, Y.V7 = 430, Y.V6 = 440, Y.V5 = 450, Y.V4 = 460, Y.V3 = 470, Y.V2 = 480, Y.V1 = 490, Y.V0 = 500, Y.R3MIX = 1e3, Y.STANDARD = 1001, Y.EXTREME = 1002, Y.INSANE = 1003, Y.STANDARD_FAST = 1004, Y.EXTREME_FAST = 1005, Y.MEDIUM = 1006, Y.MEDIUM_FAST = 1007, Y.LAME_MAXMP3BUFFER = 147456;
      var p,
        m,
        v = new X();
      function d() {
        this.lowerlimit = 0;
      }
      function s(e, t) {
        this.lowpass = t;
      }
      this.enc = new Ae(), this.setModules = function (e, t, a, n, s, r, i, o, _) {
        T = e, E = t, u = a, h = n, b = s, p = r, m = o, this.enc.setModules(E, v, h, p);
      };
      var I = 4294479419;
      function g(e, t) {
        var a = [new s(8, 2e3), new s(16, 3700), new s(24, 3900), new s(32, 5500), new s(40, 7e3), new s(48, 7500), new s(56, 1e4), new s(64, 11e3), new s(80, 13500), new s(96, 15100), new s(112, 15600), new s(128, 17e3), new s(160, 17500), new s(192, 18600), new s(224, 19400), new s(256, 19700), new s(320, 20500)],
          n = C.nearestBitrateFullIndex(t);
        e.lowerlimit = a[n].lowpass;
      }
      function L(e) {
        var t = Ae.BLKSIZE + e.framesize - Ae.FFTOFFSET;
        return t = Math.max(t, 512 + e.framesize - 32);
      }
      function P() {
        this.n_in = 0, this.n_out = 0;
      }
      function H(e, t, a, n, s, r) {
        var i = e.internal_flags;
        if (i.resample_ratio < .9999 || 1.0001 < i.resample_ratio) me();else {
          r.n_out = Math.min(e.framesize, s), r.n_in = r.n_out;
          for (var o = 0; o < r.n_out; ++o) t[0][i.mf_size + o] = a[0][n + o], 2 == i.channels_out && (t[1][i.mf_size + o] = a[1][n + o]);
        }
      }
      this.lame_init = function () {
        var e,
          t,
          a = new function () {
            this.class_id = 0, this.num_samples = 0, this.num_channels = 0, this.in_samplerate = 0, this.out_samplerate = 0, this.scale = 0, this.scale_left = 0, this.scale_right = 0, this.analysis = !1, this.bWriteVbrTag = !1, this.decode_only = !1, this.quality = 0, this.mode = ye.STEREO, this.force_ms = !1, this.free_format = !1, this.findReplayGain = !1, this.decode_on_the_fly = !1, this.write_id3tag_automatic = !1, this.brate = 0, this.compression_ratio = 0, this.copyright = 0, this.original = 0, this.extension = 0, this.emphasis = 0, this.error_protection = 0, this.strict_ISO = !1, this.disable_reservoir = !1, this.quant_comp = 0, this.quant_comp_short = 0, this.experimentalY = !1, this.experimentalZ = 0, this.exp_nspsytune = 0, this.preset = 0, this.VBR = null, this.VBR_q_frac = 0, this.VBR_q = 0, this.VBR_mean_bitrate_kbps = 0, this.VBR_min_bitrate_kbps = 0, this.VBR_max_bitrate_kbps = 0, this.VBR_hard_min = 0, this.lowpassfreq = 0, this.highpassfreq = 0, this.lowpasswidth = 0, this.highpasswidth = 0, this.maskingadjust = 0, this.maskingadjust_short = 0, this.ATHonly = !1, this.ATHshort = !1, this.noATH = !1, this.ATHtype = 0, this.ATHcurve = 0, this.ATHlower = 0, this.athaa_type = 0, this.athaa_loudapprox = 0, this.athaa_sensitivity = 0, this.short_blocks = null, this.useTemporal = !1, this.interChRatio = 0, this.msfix = 0, this.tune = !1, this.tune_value_a = 0, this.version = 0, this.encoder_delay = 0, this.encoder_padding = 0, this.framesize = 0, this.frameNum = 0, this.lame_allocated_gfp = 0, this.internal_flags = null;
          }(),
          n = ((e = a).class_id = I, t = e.internal_flags = new j(), e.mode = ye.NOT_SET, e.original = 1, e.in_samplerate = 44100, e.num_channels = 2, e.num_samples = -1, e.bWriteVbrTag = !0, e.quality = -1, e.short_blocks = null, t.subblock_gain = -1, e.lowpassfreq = 0, e.highpassfreq = 0, e.lowpasswidth = -1, e.highpasswidth = -1, e.VBR = Me.vbr_off, e.VBR_q = 4, e.ATHcurve = -1, e.VBR_mean_bitrate_kbps = 128, e.VBR_min_bitrate_kbps = 0, e.VBR_max_bitrate_kbps = 0, e.VBR_hard_min = 0, t.VBR_min_bitrate = 1, t.VBR_max_bitrate = 13, e.quant_comp = -1, e.quant_comp_short = -1, e.msfix = -1, t.resample_ratio = 1, t.OldValue[0] = 180, t.OldValue[1] = 180, t.CurrentStep[0] = 4, t.CurrentStep[1] = 4, t.masking_lower = 1, t.nsPsy.attackthre = -1, t.nsPsy.attackthre_s = -1, e.scale = -1, e.athaa_type = -1, e.ATHtype = -1, e.athaa_loudapprox = -1, e.athaa_sensitivity = 0, e.useTemporal = null, e.interChRatio = -1, t.mf_samples_to_encode = Ae.ENCDELAY + Ae.POSTDELAY, e.encoder_padding = 0, t.mf_size = Ae.ENCDELAY - Ae.MDCTDELAY, e.findReplayGain = !1, e.decode_on_the_fly = !1, t.decode_on_the_fly = !1, t.findReplayGain = !1, t.findPeakSample = !1, t.RadioGain = 0, t.AudiophileGain = 0, t.noclipGainChange = 0, t.noclipScale = -1, e.preset = 0, e.write_id3tag_automatic = !0, 0);
        return 0 != n ? null : (a.lame_allocated_gfp = 1, a);
      }, this.nearestBitrateFullIndex = function (e) {
        var t = [8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320],
          a = 0,
          n = 0,
          s = 0,
          r = 0;
        r = t[16], n = t[s = 16], a = 16;
        for (var i = 0; i < 16; i++) if (Math.max(e, t[i + 1]) != e) {
          r = t[i + 1], s = i + 1, n = t[i], a = i;
          break;
        }
        return e - n < r - e ? a : s;
      }, this.lame_init_params = function (e) {
        var t,
          a,
          n = e.internal_flags;
        if (n.Class_ID = 0, null == n.ATH && (n.ATH = new function () {
          this.useAdjust = 0, this.aaSensitivityP = 0, this.adjust = 0, this.adjustLimit = 0, this.decay = 0, this.floor = 0, this.l = de(Ae.SBMAX_l), this.s = de(Ae.SBMAX_s), this.psfb21 = de(Ae.PSFB21), this.psfb12 = de(Ae.PSFB12), this.cb_l = de(Ae.CBANDS), this.cb_s = de(Ae.CBANDS), this.eql_w = de(Ae.BLKSIZE / 2);
        }()), null == n.PSY && (n.PSY = new function () {
          this.mask_adjust = 0, this.mask_adjust_short = 0, this.bo_l_weight = de(Ae.SBMAX_l), this.bo_s_weight = de(Ae.SBMAX_s);
        }()), null == n.rgdata && (n.rgdata = new function () {}()), n.channels_in = e.num_channels, 1 == n.channels_in && (e.mode = ye.MONO), n.channels_out = e.mode == ye.MONO ? 1 : 2, n.mode_ext = Ae.MPG_MD_MS_LR, e.mode == ye.MONO && (e.force_ms = !1), e.VBR == Me.vbr_off && 128 != e.VBR_mean_bitrate_kbps && 0 == e.brate && (e.brate = e.VBR_mean_bitrate_kbps), e.VBR == Me.vbr_off || e.VBR == Me.vbr_mtrh || e.VBR == Me.vbr_mt || (e.free_format = !1), e.VBR == Me.vbr_off && 0 == e.brate && me(), e.VBR == Me.vbr_off && 0 < e.compression_ratio && me(), 0 != e.out_samplerate && (e.out_samplerate < 16e3 ? (e.VBR_mean_bitrate_kbps = Math.max(e.VBR_mean_bitrate_kbps, 8), e.VBR_mean_bitrate_kbps = Math.min(e.VBR_mean_bitrate_kbps, 64)) : e.out_samplerate < 32e3 ? (e.VBR_mean_bitrate_kbps = Math.max(e.VBR_mean_bitrate_kbps, 8), e.VBR_mean_bitrate_kbps = Math.min(e.VBR_mean_bitrate_kbps, 160)) : (e.VBR_mean_bitrate_kbps = Math.max(e.VBR_mean_bitrate_kbps, 32), e.VBR_mean_bitrate_kbps = Math.min(e.VBR_mean_bitrate_kbps, 320))), 0 == e.lowpassfreq) {
          var s = 16e3;
          switch (e.VBR) {
            case Me.vbr_off:
              var r = new d();
              g(r, e.brate), s = r.lowerlimit;
              break;
            case Me.vbr_abr:
              var r = new d();
              g(r, e.VBR_mean_bitrate_kbps), s = r.lowerlimit;
              break;
            case Me.vbr_rh:
              me();
            default:
              me();
          }
          e.mode != ye.MONO || e.VBR != Me.vbr_off && e.VBR != Me.vbr_abr || (s *= 1.5), e.lowpassfreq = 0 | s;
        }
        switch (0 == e.out_samplerate && me(), e.lowpassfreq = Math.min(20500, e.lowpassfreq), e.lowpassfreq = Math.min(e.out_samplerate / 2, e.lowpassfreq), e.VBR == Me.vbr_off && (e.compression_ratio = 16 * e.out_samplerate * n.channels_out / (1e3 * e.brate)), e.VBR == Me.vbr_abr && me(), e.bWriteVbrTag || (e.findReplayGain = !1, e.decode_on_the_fly = !1, n.findPeakSample = !1), n.findReplayGain = e.findReplayGain, n.decode_on_the_fly = e.decode_on_the_fly, n.decode_on_the_fly && (n.findPeakSample = !0), n.findReplayGain && me(), n.decode_on_the_fly && !e.decode_only && me(), n.mode_gr = e.out_samplerate <= 24e3 ? 1 : 2, e.framesize = 576 * n.mode_gr, e.encoder_delay = Ae.ENCDELAY, n.resample_ratio = e.in_samplerate / e.out_samplerate, e.VBR) {
          case Me.vbr_mt:
          case Me.vbr_rh:
          case Me.vbr_mtrh:
            e.compression_ratio = [5.7, 6.5, 7.3, 8.2, 10, 11.9, 13, 14, 15, 16.5][e.VBR_q];
            break;
          case Me.vbr_abr:
            e.compression_ratio = 16 * e.out_samplerate * n.channels_out / (1e3 * e.VBR_mean_bitrate_kbps);
            break;
          default:
            e.compression_ratio = 16 * e.out_samplerate * n.channels_out / (1e3 * e.brate);
        }
        e.mode == ye.NOT_SET && (e.mode = ye.JOINT_STEREO), 0 < e.highpassfreq ? me() : (n.highpass1 = 0, n.highpass2 = 0), 0 < e.lowpassfreq ? (n.lowpass2 = 2 * e.lowpassfreq, 0 <= e.lowpasswidth ? me() : n.lowpass1 = 2 * e.lowpassfreq, n.lowpass1 /= e.out_samplerate, n.lowpass2 /= e.out_samplerate) : me(), function (e) {
          var t,
            a = e.internal_flags,
            n = 32;
          if (0 < a.lowpass1) {
            for (var s = 999, r = 0; r <= 31; r++) {
              var i = r / 31;
              i >= a.lowpass2 && (n = Math.min(n, r)), a.lowpass1 < i && i < a.lowpass2 && (s = Math.min(s, r));
            }
            a.lowpass1 = 999 == s ? (n - .75) / 31 : (s - .75) / 31, a.lowpass2 = n / 31;
          }
          0 < a.highpass2 && me(), 0 < a.highpass2 && me();
          for (var r = 0; r < 32; r++) {
            var o,
              _,
              i = r / 31;
            a.highpass2 > a.highpass1 ? me() : o = 1, _ = a.lowpass2 > a.lowpass1 ? 1 < (t = (i - a.lowpass1) / (a.lowpass2 - a.lowpass1 + 1e-20)) ? 0 : t <= 0 ? 1 : Math.cos(Math.PI / 2 * t) : 1, a.amp_filter[r] = o * _;
          }
        }(e), n.samplerate_index = function (e, t) {
          switch (e) {
            case 44100:
              return t.version = 1, 0;
            case 48e3:
              return t.version = 1;
            case 32e3:
              return t.version = 1, 2;
            case 22050:
              return t.version = 0;
            case 24e3:
              return t.version = 0, 1;
            case 16e3:
              return t.version = 0, 2;
            case 11025:
              return t.version = 0;
            case 12e3:
              return t.version = 0, 1;
            case 8e3:
              return t.version = 0, 2;
            default:
              return t.version = 0, -1;
          }
        }(e.out_samplerate, e), n.samplerate_index < 0 && me(), e.VBR == Me.vbr_off ? e.free_format ? n.bitrate_index = 0 : (e.brate = function (e, t, a) {
          a < 16e3 && (t = 2);
          for (var n = k.bitrate_table[t][1], s = 2; s <= 14; s++) 0 < k.bitrate_table[t][s] && Math.abs(k.bitrate_table[t][s] - e) < Math.abs(n - e) && (n = k.bitrate_table[t][s]);
          return n;
        }(e.brate, e.version, e.out_samplerate), n.bitrate_index = function (e, t, a) {
          a < 16e3 && (t = 2);
          for (var n = 0; n <= 14; n++) if (0 < k.bitrate_table[t][n] && k.bitrate_table[t][n] == e) return n;
          return -1;
        }(e.brate, e.version, e.out_samplerate), n.bitrate_index <= 0 && me()) : n.bitrate_index = 1, e.analysis && (e.bWriteVbrTag = !1), null != n.pinfo && (e.bWriteVbrTag = !1), E.init_bit_stream_w(n);
        for (var i, o = n.samplerate_index + 3 * e.version + 6 * (e.out_samplerate < 16e3 ? 1 : 0), _ = 0; _ < Ae.SBMAX_l + 1; _++) n.scalefac_band.l[_] = h.sfBandIndex[o].l[_];
        for (var _ = 0; _ < Ae.PSFB21 + 1; _++) {
          var l = (n.scalefac_band.l[22] - n.scalefac_band.l[21]) / Ae.PSFB21,
            f = n.scalefac_band.l[21] + _ * l;
          n.scalefac_band.psfb21[_] = f;
        }
        n.scalefac_band.psfb21[Ae.PSFB21] = 576;
        for (var _ = 0; _ < Ae.SBMAX_s + 1; _++) n.scalefac_band.s[_] = h.sfBandIndex[o].s[_];
        for (var _ = 0; _ < Ae.PSFB12 + 1; _++) {
          var l = (n.scalefac_band.s[13] - n.scalefac_band.s[12]) / Ae.PSFB12,
            f = n.scalefac_band.s[12] + _ * l;
          n.scalefac_band.psfb12[_] = f;
        }
        for (n.scalefac_band.psfb12[Ae.PSFB12] = 192, 1 == e.version ? n.sideinfo_len = 1 == n.channels_out ? 21 : 36 : n.sideinfo_len = 1 == n.channels_out ? 13 : 21, e.error_protection && (n.sideinfo_len += 2), a = void 0, a = (t = e).internal_flags, t.frameNum = 0, t.write_id3tag_automatic && m.id3tag_write_v2(t), a.bitrate_stereoMode_Hist = w([16, 5]), a.bitrate_blockType_Hist = w([16, 6]), a.PeakSample = 0, t.bWriteVbrTag && p.InitVbrTag(t), n.Class_ID = I, i = 0; i < 19; i++) n.nsPsy.pefirbuf[i] = 700 * n.mode_gr * n.channels_out;
        switch (-1 == e.ATHtype && (e.ATHtype = 4), e.VBR) {
          case Me.vbr_mt:
            e.VBR = Me.vbr_mtrh;
          case Me.vbr_mtrh:
            null == e.useTemporal && (e.useTemporal = !1), u.apply_preset(e, 500 - 10 * e.VBR_q, 0), e.quality < 0 && (e.quality = LAME_DEFAULT_QUALITY), e.quality < 5 && (e.quality = 0), 5 < e.quality && (e.quality = 5), n.PSY.mask_adjust = e.maskingadjust, n.PSY.mask_adjust_short = e.maskingadjust_short, e.experimentalY ? n.sfb21_extra = !1 : n.sfb21_extra = 44e3 < e.out_samplerate, n.iteration_loop = new VBRNewIterationLoop(b);
            break;
          case Me.vbr_rh:
            u.apply_preset(e, 500 - 10 * e.VBR_q, 0), n.PSY.mask_adjust = e.maskingadjust, n.PSY.mask_adjust_short = e.maskingadjust_short, e.experimentalY ? n.sfb21_extra = !1 : n.sfb21_extra = 44e3 < e.out_samplerate, 6 < e.quality && (e.quality = 6), e.quality < 0 && (e.quality = LAME_DEFAULT_QUALITY), n.iteration_loop = new VBROldIterationLoop(b);
            break;
          default:
            var c;
            n.sfb21_extra = !1, e.quality < 0 && (e.quality = LAME_DEFAULT_QUALITY), (c = e.VBR) == Me.vbr_off && (e.VBR_mean_bitrate_kbps = e.brate), u.apply_preset(e, e.VBR_mean_bitrate_kbps, 0), e.VBR = c, n.PSY.mask_adjust = e.maskingadjust, n.PSY.mask_adjust_short = e.maskingadjust_short, c == Me.vbr_off ? n.iteration_loop = new function (e) {
              var t = e;
              this.quantize = t, this.iteration_loop = function (e, t, a, n) {
                var s = e.internal_flags,
                  r = de(F.SFBMAX),
                  i = de(576),
                  o = ve(2),
                  _ = 0,
                  l = s.l3_side,
                  f = new R(_);
                this.quantize.rv.ResvFrameBegin(e, f), _ = f.bits;
                for (var c = 0; c < s.mode_gr; c++) {
                  this.quantize.qupvt.on_pe(e, t, o, _, c, c), s.mode_ext == Ae.MPG_MD_MS_LR && me();
                  for (var u = 0; u < s.channels_out; u++) {
                    var h,
                      b,
                      p = l.tt[c][u];
                    p.block_type != Ae.SHORT_TYPE ? (h = 0, b = s.PSY.mask_adjust - h) : (h = 0, b = s.PSY.mask_adjust_short - h), s.masking_lower = Math.pow(10, .1 * b), this.quantize.init_outer_loop(s, p), this.quantize.init_xrpow(s, p, i) && (this.quantize.qupvt.calc_xmin(e, n[c][u], p, r), this.quantize.outer_loop(e, p, r, i, u, o[u])), this.quantize.iteration_finish_one(s, c, u);
                  }
                }
                this.quantize.rv.ResvFrameEnd(s, _);
              };
            }(b) : me();
        }
        return e.VBR != Me.vbr_off && me(), e.tune && me(), function (e) {
          var t = e.internal_flags;
          switch (e.quality) {
            default:
            case 9:
              t.psymodel = 0, t.noise_shaping = 0, t.noise_shaping_amp = 0, t.noise_shaping_stop = 0, t.use_best_huffman = 0, t.full_outer_loop = 0;
              break;
            case 8:
              e.quality = 7;
            case 7:
              t.psymodel = 1, t.noise_shaping = 0, t.noise_shaping_amp = 0, t.noise_shaping_stop = 0, t.use_best_huffman = 0, t.full_outer_loop = 0;
              break;
            case 6:
            case 5:
              t.psymodel = 1, 0 == t.noise_shaping && (t.noise_shaping = 1), t.noise_shaping_amp = 0, t.noise_shaping_stop = 0, -1 == t.subblock_gain && (t.subblock_gain = 1), t.use_best_huffman = 0, t.full_outer_loop = 0;
              break;
            case 4:
              t.psymodel = 1, 0 == t.noise_shaping && (t.noise_shaping = 1), t.noise_shaping_amp = 0, t.noise_shaping_stop = 0, -1 == t.subblock_gain && (t.subblock_gain = 1), t.use_best_huffman = 1, t.full_outer_loop = 0;
              break;
            case 3:
              t.psymodel = 1, 0 == t.noise_shaping && (t.noise_shaping = 1), t.noise_shaping_amp = 1, -(t.noise_shaping_stop = 1) == t.subblock_gain && (t.subblock_gain = 1), t.use_best_huffman = 1, t.full_outer_loop = 0;
              break;
            case 2:
              t.psymodel = 1, 0 == t.noise_shaping && (t.noise_shaping = 1), 0 == t.substep_shaping && (t.substep_shaping = 2), t.noise_shaping_amp = 1, -(t.noise_shaping_stop = 1) == t.subblock_gain && (t.subblock_gain = 1), t.use_best_huffman = 1, t.full_outer_loop = 0;
              break;
            case 1:
            case 0:
              t.psymodel = 1, 0 == t.noise_shaping && (t.noise_shaping = 1), 0 == t.substep_shaping && (t.substep_shaping = 2), t.noise_shaping_amp = 2, -(t.noise_shaping_stop = 1) == t.subblock_gain && (t.subblock_gain = 1), t.use_best_huffman = 1, t.full_outer_loop = 0;
          }
        }(e), e.athaa_type < 0 ? n.ATH.useAdjust = 3 : n.ATH.useAdjust = e.athaa_type, n.ATH.aaSensitivityP = Math.pow(10, e.athaa_sensitivity / -10), null == e.short_blocks && (e.short_blocks = Se.short_block_allowed), e.short_blocks != Se.short_block_allowed || e.mode != ye.JOINT_STEREO && e.mode != ye.STEREO || (e.short_blocks = Se.short_block_coupled), e.quant_comp < 0 && (e.quant_comp = 1), e.quant_comp_short < 0 && (e.quant_comp_short = 0), e.msfix < 0 && (e.msfix = 0), e.exp_nspsytune = 1 | e.exp_nspsytune, e.internal_flags.nsPsy.attackthre < 0 && (e.internal_flags.nsPsy.attackthre = X.NSATTACKTHRE), e.internal_flags.nsPsy.attackthre_s < 0 && (e.internal_flags.nsPsy.attackthre_s = X.NSATTACKTHRE_S), e.scale < 0 && (e.scale = 1), e.ATHtype < 0 && (e.ATHtype = 4), e.ATHcurve < 0 && (e.ATHcurve = 4), e.athaa_loudapprox < 0 && (e.athaa_loudapprox = 2), e.interChRatio < 0 && (e.interChRatio = 0), null == e.useTemporal && (e.useTemporal = !0), n.slot_lag = n.frac_SpF = 0, e.VBR == Me.vbr_off && (n.slot_lag = n.frac_SpF = 72e3 * (e.version + 1) * e.brate % e.out_samplerate | 0), h.iteration_init(e), v.psymodel_init(e), 0;
      }, this.lame_encode_flush = function (e, t, a, n) {
        var s,
          r,
          i,
          o,
          _ = e.internal_flags,
          l = M([2, 1152]),
          f = 0,
          c = _.mf_samples_to_encode - Ae.POSTDELAY,
          u = L(e);
        if (_.mf_samples_to_encode < 1) return 0;
        for (s = 0, e.in_samplerate != e.out_samplerate && me(), (i = e.framesize - c % e.framesize) < 576 && (i += e.framesize), e.encoder_padding = i, o = (c + i) / e.framesize; 0 < o && 0 <= f;) {
          var h = u - _.mf_size,
            b = e.frameNum;
          h *= e.in_samplerate, 1152 < (h /= e.out_samplerate) && (h = 1152), h < 1 && (h = 1), r = n - s, 0 == n && (r = 0), f = this.lame_encode_buffer(e, l[0], l[1], h, t, a, r), a += f, s += f, o -= b != e.frameNum ? 1 : 0;
        }
        return _.mf_samples_to_encode = 0, f < 0 ? f : (r = n - s, 0 == n && (r = 0), E.flush_bitstream(e), (f = E.copy_buffer(_, t, a, r, 1)) < 0 ? f : (a += f, r = n - (s += f), 0 == n && (r = 0), e.write_id3tag_automatic && me(), s));
      }, this.lame_encode_buffer = function (e, t, a, n, s, r, i) {
        var o,
          _,
          l = e.internal_flags,
          f = [null, null];
        if (l.Class_ID != I) return -3;
        if (0 == n) return 0;
        _ = n, (null == (o = l).in_buffer_0 || o.in_buffer_nsamples < _) && (o.in_buffer_0 = de(_), o.in_buffer_1 = de(_), o.in_buffer_nsamples = _), f[0] = l.in_buffer_0, f[1] = l.in_buffer_1;
        for (var c = 0; c < n; c++) f[0][c] = t[c], 1 < l.channels_in && (f[1][c] = a[c]);
        return function (e, t, a, n, s, r, i) {
          var o,
            _,
            l,
            f,
            c,
            u = e.internal_flags,
            h = 0,
            b = [null, null],
            p = [null, null];
          if (u.Class_ID != I) return -3;
          if (0 == n) return 0;
          if ((c = E.copy_buffer(u, s, r, i, 0)) < 0) return c;
          if (r += c, h += c, p[0] = t, p[1] = a, N.NEQ(e.scale, 0) && N.NEQ(e.scale, 1)) for (_ = 0; _ < n; ++_) p[0][_] *= e.scale, 2 == u.channels_out && (p[1][_] *= e.scale);
          if (N.NEQ(e.scale_left, 0) && N.NEQ(e.scale_left, 1)) for (_ = 0; _ < n; ++_) p[0][_] *= e.scale_left;
          if (N.NEQ(e.scale_right, 0) && N.NEQ(e.scale_right, 1)) for (_ = 0; _ < n; ++_) p[1][_] *= e.scale_right;
          2 == e.num_channels && 1 == u.channels_out && me(), f = L(e), b[0] = u.mfbuf[0], b[1] = u.mfbuf[1];
          for (var m, v, d, g, w, S, M, y = 0; 0 < n;) {
            var A = [null, null],
              k = 0,
              R = 0;
            A[0] = p[0], A[1] = p[1];
            var x = new P();
            if (H(e, b, A, y, n, x), k = x.n_in, R = x.n_out, u.findReplayGain && !u.decode_on_the_fly && T.AnalyzeSamples(u.rgdata, b[0], u.mf_size, b[1], u.mf_size, R, u.channels_out) == O.GAIN_ANALYSIS_ERROR) return -6;
            if (n -= k, y += k, u.channels_out, u.mf_size += R, u.mf_samples_to_encode < 1 && me(), u.mf_samples_to_encode += R, u.mf_size >= f) {
              var B = i - h;
              if (0 == i && (B = 0), m = e, v = b[0], d = b[1], g = s, w = r, S = B, M = C.enc.lame_encode_mp3_frame(m, v, d, g, w, S), m.frameNum++, (o = M) < 0) return o;
              for (r += o, h += o, u.mf_size -= e.framesize, u.mf_samples_to_encode -= e.framesize, l = 0; l < u.channels_out; l++) for (_ = 0; _ < u.mf_size; _++) b[l][_] = b[l][_ + e.framesize];
            }
          }
          return h;
        }(e, f[0], f[1], n, s, r, i);
      };
    }
    F.SFBMAX = 3 * Ae.SBMAX_s, Ae.ENCDELAY = 576, Ae.POSTDELAY = 1152, Ae.FFTOFFSET = 224 + (Ae.MDCTDELAY = 48), Ae.DECDELAY = 528, Ae.SBLIMIT = 32, Ae.CBANDS = 64, Ae.SBPSY_l = 21, Ae.SBPSY_s = 12, Ae.SBMAX_l = 22, Ae.SBMAX_s = 13, Ae.PSFB21 = 6, Ae.PSFB12 = 6, Ae.HBLKSIZE = (Ae.BLKSIZE = 1024) / 2 + 1, Ae.HBLKSIZE_s = (Ae.BLKSIZE_s = 256) / 2 + 1, Ae.NORM_TYPE = 0, Ae.START_TYPE = 1, Ae.SHORT_TYPE = 2, Ae.STOP_TYPE = 3, Ae.MPG_MD_LR_LR = 0, Ae.MPG_MD_LR_I = 1, Ae.MPG_MD_MS_LR = 2, Ae.MPG_MD_MS_I = 3, Ae.fircoef = [-.1039435, -.1892065, 5 * -.0432472, -.155915, 3.898045e-17, .0467745 * 5, .50455, .756825, .187098 * 5], j.MFSIZE = 3456 + Ae.ENCDELAY - Ae.MDCTDELAY, j.MAX_HEADER_BUF = 256, j.MAX_BITS_PER_CHANNEL = 4095, j.MAX_BITS_PER_GRANULE = 7680, j.BPC = 320, F.SFBMAX = 3 * Ae.SBMAX_s, t.Mp3Encoder = function (n, e, t) {
      1 != n && me("fix cc: only supports mono");
      var s = new Y(),
        a = new function () {
          this.setModules = function (e, t) {};
        }(),
        r = new O(),
        i = new N(),
        o = new function () {
          function e(e, t, a, n, s, r, i, o, _, l, f, c, u, h) {
            this.quant_comp = t, this.quant_comp_s = a, this.safejoint = n, this.nsmsfix = s, this.st_lrm = r, this.st_s = i, this.nsbass = o, this.scale = _, this.masking_adj = l, this.ath_lower = f, this.ath_curve = c, this.interch = u, this.sfscale = h;
          }
          var i;
          function n(e, t, a) {
            me();
          }
          this.setModules = function (e) {
            i = e;
          };
          var o = [new e(8, 9, 9, 0, 0, 6.6, 145, 0, .95, 0, -30, 11, .0012, 1), new e(16, 9, 9, 0, 0, 6.6, 145, 0, .95, 0, -25, 11, .001, 1), new e(24, 9, 9, 0, 0, 6.6, 145, 0, .95, 0, -20, 11, .001, 1), new e(32, 9, 9, 0, 0, 6.6, 145, 0, .95, 0, -15, 11, .001, 1), new e(40, 9, 9, 0, 0, 6.6, 145, 0, .95, 0, -10, 11, 9e-4, 1), new e(48, 9, 9, 0, 0, 6.6, 145, 0, .95, 0, -10, 11, 9e-4, 1), new e(56, 9, 9, 0, 0, 6.6, 145, 0, .95, 0, -6, 11, 8e-4, 1), new e(64, 9, 9, 0, 0, 6.6, 145, 0, .95, 0, -2, 11, 8e-4, 1), new e(80, 9, 9, 0, 0, 6.6, 145, 0, .95, 0, 0, 8, 7e-4, 1), new e(96, 9, 9, 0, 2.5, 6.6, 145, 0, .95, 0, 1, 5.5, 6e-4, 1), new e(112, 9, 9, 0, 2.25, 6.6, 145, 0, .95, 0, 2, 4.5, 5e-4, 1), new e(128, 9, 9, 0, 1.95, 6.4, 140, 0, .95, 0, 3, 4, 2e-4, 1), new e(160, 9, 9, 1, 1.79, 6, 135, 0, .95, -2, 5, 3.5, 0, 1), new e(192, 9, 9, 1, 1.49, 5.6, 125, 0, .97, -4, 7, 3, 0, 0), new e(224, 9, 9, 1, 1.25, 5.2, 125, 0, .98, -6, 9, 2, 0, 0), new e(256, 9, 9, 1, .97, 5.2, 125, 0, 1, -8, 10, 1, 0, 0), new e(320, 9, 9, 1, .9, 5.2, 125, 0, 1, -10, 12, 0, 0, 0)];
          function s(e, t, a) {
            var n = t,
              s = i.nearestBitrateFullIndex(t);
            if (e.VBR = Me.vbr_abr, e.VBR_mean_bitrate_kbps = n, e.VBR_mean_bitrate_kbps = Math.min(e.VBR_mean_bitrate_kbps, 320), e.VBR_mean_bitrate_kbps = Math.max(e.VBR_mean_bitrate_kbps, 8), e.brate = e.VBR_mean_bitrate_kbps, 320 < e.VBR_mean_bitrate_kbps && (e.disable_reservoir = !0), 0 < o[s].safejoint && (e.exp_nspsytune = 2 | e.exp_nspsytune), 0 < o[s].sfscale && (e.internal_flags.noise_shaping = 2), 0 < Math.abs(o[s].nsbass)) {
              var r = int(4 * o[s].nsbass);
              r < 0 && (r += 64), e.exp_nspsytune = e.exp_nspsytune | r << 2;
            }
            return 0 != a ? e.quant_comp = o[s].quant_comp : 0 < Math.abs(e.quant_comp - -1) || (e.quant_comp = o[s].quant_comp), 0 != a ? e.quant_comp_short = o[s].quant_comp_s : 0 < Math.abs(e.quant_comp_short - -1) || (e.quant_comp_short = o[s].quant_comp_s), 0 != a ? e.msfix = o[s].nsmsfix : 0 < Math.abs(e.msfix - -1) || (e.msfix = o[s].nsmsfix), 0 != a ? e.internal_flags.nsPsy.attackthre = o[s].st_lrm : 0 < Math.abs(e.internal_flags.nsPsy.attackthre - -1) || (e.internal_flags.nsPsy.attackthre = o[s].st_lrm), 0 != a ? e.internal_flags.nsPsy.attackthre_s = o[s].st_s : 0 < Math.abs(e.internal_flags.nsPsy.attackthre_s - -1) || (e.internal_flags.nsPsy.attackthre_s = o[s].st_s), 0 != a ? e.scale = o[s].scale : 0 < Math.abs(e.scale - -1) || (e.scale = o[s].scale), 0 != a ? e.maskingadjust = o[s].masking_adj : 0 < Math.abs(e.maskingadjust - 0) || (e.maskingadjust = o[s].masking_adj), 0 < o[s].masking_adj ? 0 != a ? e.maskingadjust_short = .9 * o[s].masking_adj : 0 < Math.abs(e.maskingadjust_short - 0) || (e.maskingadjust_short = .9 * o[s].masking_adj) : 0 != a ? e.maskingadjust_short = 1.1 * o[s].masking_adj : 0 < Math.abs(e.maskingadjust_short - 0) || (e.maskingadjust_short = 1.1 * o[s].masking_adj), 0 != a ? e.ATHlower = -o[s].ath_lower / 10 : 0 < Math.abs(10 * -e.ATHlower - 0) || (e.ATHlower = -o[s].ath_lower / 10), 0 != a ? e.ATHcurve = o[s].ath_curve : 0 < Math.abs(e.ATHcurve - -1) || (e.ATHcurve = o[s].ath_curve), 0 != a ? e.interChRatio = o[s].interch : 0 < Math.abs(e.interChRatio - -1) || (e.interChRatio = o[s].interch), t;
          }
          this.apply_preset = function (e, t, a) {
            switch (t) {
              case Y.R3MIX:
                t = Y.V3, e.VBR = Me.vbr_mtrh;
                break;
              case Y.MEDIUM:
                t = Y.V4, e.VBR = Me.vbr_rh;
                break;
              case Y.MEDIUM_FAST:
                t = Y.V4, e.VBR = Me.vbr_mtrh;
                break;
              case Y.STANDARD:
                t = Y.V2, e.VBR = Me.vbr_rh;
                break;
              case Y.STANDARD_FAST:
                t = Y.V2, e.VBR = Me.vbr_mtrh;
                break;
              case Y.EXTREME:
                t = Y.V0, e.VBR = Me.vbr_rh;
                break;
              case Y.EXTREME_FAST:
                t = Y.V0, e.VBR = Me.vbr_mtrh;
                break;
              case Y.INSANE:
                return t = 320, e.preset = t, s(e, t, a), e.VBR = Me.vbr_off, t;
            }
            switch (e.preset = t) {
              case Y.V9:
                return n(), t;
              case Y.V8:
                return n(), t;
              case Y.V7:
                return n(), t;
              case Y.V6:
                return n(), t;
              case Y.V5:
                return n(), t;
              case Y.V4:
                return n(), t;
              case Y.V3:
                return n(), t;
              case Y.V2:
                return n(), t;
              case Y.V1:
                return n(), t;
              case Y.V0:
                return n(), t;
            }
            return 8 <= t && t <= 320 ? s(e, t, a) : (e.preset = 0, t);
          };
        }(),
        _ = new T(),
        l = new C(),
        f = new y(),
        c = new function () {
          this.getLameShortVersion = function () {
            return "3.98.4";
          };
        }(),
        u = new function () {
          this.setModules = function (e, t) {};
        }(),
        h = new function () {
          var _;
          this.setModules = function (e) {
            _ = e;
          }, this.ResvFrameBegin = function (e, t) {
            var a,
              n = e.internal_flags,
              s = n.l3_side,
              r = _.getframebits(e);
            t.bits = (r - 8 * n.sideinfo_len) / n.mode_gr;
            var i = 2048 * n.mode_gr - 8;
            320 < e.brate ? me() : (a = 11520, e.strict_ISO && me()), n.ResvMax = a - r, n.ResvMax > i && (n.ResvMax = i), (n.ResvMax < 0 || e.disable_reservoir) && (n.ResvMax = 0);
            var o = t.bits * n.mode_gr + Math.min(n.ResvSize, n.ResvMax);
            return a < o && (o = a), s.resvDrain_pre = 0, null != n.pinfo && me(), o;
          }, this.ResvMaxBits = function (e, t, a, n) {
            var s,
              r = e.internal_flags,
              i = r.ResvSize,
              o = r.ResvMax;
            0 != n && (i += t), 0 != (1 & r.substep_shaping) && (o *= .9), a.bits = t, 9 * o < 10 * i ? (s = i - 9 * o / 10, a.bits += s, r.substep_shaping |= 128) : (s = 0, r.substep_shaping &= 127, e.disable_reservoir || 0 != (1 & r.substep_shaping) || (a.bits -= .1 * t));
            var _ = i < 6 * r.ResvMax / 10 ? i : 6 * r.ResvMax / 10;
            return (_ -= s) < 0 && (_ = 0), _;
          }, this.ResvAdjust = function (e, t) {
            e.ResvSize -= t.part2_3_length + t.part2_length;
          }, this.ResvFrameEnd = function (e, t) {
            var a,
              n = e.l3_side;
            e.ResvSize += t * e.mode_gr;
            var s = 0;
            n.resvDrain_post = 0, (n.resvDrain_pre = 0) != (a = e.ResvSize % 8) && (s += a), 0 < (a = e.ResvSize - s - e.ResvMax) && (s += a);
            var r = Math.min(8 * n.main_data_begin, s) / 8;
            n.resvDrain_pre += 8 * r, s -= 8 * r, e.ResvSize -= 8 * r, n.main_data_begin -= r, n.resvDrain_post += s, e.ResvSize -= s;
          };
        }(),
        b = new A(),
        p = new function () {
          this.setModules = function (e, t, a) {};
        }(),
        m = new function () {}();
      s.setModules(r, i, o, _, l, f, c, u, m), i.setModules(r, m, c, f), u.setModules(i, c), o.setModules(s), l.setModules(i, h, _, b), _.setModules(b, h, s.enc.psy), h.setModules(i), b.setModules(_), f.setModules(s, i, c), a.setModules(p, m), p.setModules(c, u, o);
      var v = s.lame_init();
      v.num_channels = n, v.in_samplerate = e, v.out_samplerate = e, v.brate = t, v.mode = ye.STEREO, v.quality = 3, v.bWriteVbrTag = !1, v.disable_reservoir = !0, v.write_id3tag_automatic = !1, s.lame_init_params(v);
      var d = 1152,
        g = 0 | 1.25 * d + 7200,
        w = S(g);
      this.encodeBuffer = function (e, t) {
        1 == n && (t = e), e.length > d && (d = e.length, w = S(g = 0 | 1.25 * d + 7200));
        var a = s.lame_encode_buffer(v, e, t, e.length, w, 0, g);
        return new Int8Array(w.subarray(0, a));
      }, this.flush = function () {
        var e = s.lame_encode_flush(v, w, 0, g);
        return new Int8Array(w.subarray(0, e));
      };
    };
  }
  t(), e.lamejs = t;
}(("object" == typeof window && window.document ? window : Object).Recorder);
});

/*
录音 Recorder扩展，动态波形显示
https://github.com/xiangyuecn/Recorder
*/
(function (factory) {
  var browser = typeof window == "object" && !!window.document;
  var win = browser ? window : Object; //非浏览器环境，Recorder挂载在Object下面
  var rec = win.Recorder,
    ni = rec.i18n;
  factory(rec, ni, ni.$T, browser);
})(function (Recorder, i18n, $T, isBrowser) {

  var WaveView = function (set) {
    return new fn(set);
  };
  var ViewTxt = "WaveView";
  var fn = function (set) {
    var This = this;
    var o = {
      /*
      elem:"css selector" //自动显示到dom，并以此dom大小为显示大小
      	//或者配置显示大小，手动把waveviewObj.elem显示到别的地方
      ,width:0 //显示宽度
      ,height:0 //显示高度
      
      H5环境以上配置二选一
      
      compatibleCanvas: CanvasObject //提供一个兼容H5的canvas对象，需支持getContext("2d")，支持设置width、height，支持drawImage(canvas,...)
      ,width:0 //canvas显示宽度
      ,height:0 //canvas显示高度
      非H5环境使用以上配置
      */

      scale: 2 //缩放系数，应为正整数，使用2(3? no!)倍宽高进行绘制，避免移动端绘制模糊
      ,
      speed: 9 //移动速度系数，越大越快
      ,
      phase: 21.8 //相位，调整了速度后，调整这个值得到一个看起来舒服的波形
      ,

      fps: 20 //绘制帧率，调整后也需调整phase值
      ,
      keep: true //当停止了input输入时，是否保持波形，设为false停止后将变成一条线
      ,

      lineWidth: 3 //线条基础粗细

      //渐变色配置：[位置，css颜色，...] 位置: 取值0.0-1.0之间
      ,
      linear1: [0, "rgba(150,96,238,1)", 0.2, "rgba(170,79,249,1)", 1, "rgba(53,199,253,1)"] //线条渐变色1，从左到右
      ,
      linear2: [0, "rgba(209,130,255,0.6)", 1, "rgba(53,199,255,0.6)"] //线条渐变色2，从左到右
      ,
      linearBg: [0, "rgba(255,255,255,0.2)", 1, "rgba(54,197,252,0.2)"] //背景渐变色，从上到下
    };
    for (var k in set) {
      o[k] = set[k];
    }
    This.set = set = o;
    var cCanvas = "compatibleCanvas";
    if (set[cCanvas]) {
      var canvas = This.canvas = set[cCanvas];
    } else {
      if (!isBrowser) throw new Error($T.G("NonBrowser-1", [ViewTxt]));
      var elem = set.elem;
      if (elem) {
        if (typeof elem == "string") {
          elem = document.querySelector(elem);
        } else if (elem.length) {
          elem = elem[0];
        }
      }
      if (elem) {
        set.width = elem.offsetWidth;
        set.height = elem.offsetHeight;
      }
      var thisElem = This.elem = document.createElement("div");
      thisElem.style.fontSize = 0;
      thisElem.innerHTML = '<canvas style="width:100%;height:100%;"/>';
      var canvas = This.canvas = thisElem.querySelector("canvas");
      if (elem) {
        elem.innerHTML = "";
        elem.appendChild(thisElem);
      }
    }
    var scale = set.scale;
    var width = set.width * scale;
    var height = set.height * scale;
    if (!width || !height) {
      throw new Error($T.G("IllegalArgs-1", [ViewTxt + " width=0 height=0"]));
    }
    canvas.width = width;
    canvas.height = height;
    var ctx = This.ctx = canvas.getContext("2d");
    This.linear1 = This.genLinear(ctx, width, set.linear1);
    This.linear2 = This.genLinear(ctx, width, set.linear2);
    This.linearBg = This.genLinear(ctx, height, set.linearBg, true);
    This._phase = 0;
  };
  fn.prototype = WaveView.prototype = {
    genLinear: function (ctx, size, colors, top) {
      var rtv = ctx.createLinearGradient(0, 0, top ? 0 : size, top ? size : 0);
      for (var i = 0; i < colors.length;) {
        rtv.addColorStop(colors[i++], colors[i++]);
      }
      return rtv;
    },
    genPath: function (frequency, amplitude, phase) {
      //曲线生成算法参考 https://github.com/HaloMartin/MCVoiceWave/blob/f6dc28975fbe0f7fc6cc4dbc2e61b0aa5574e9bc/MCVoiceWave/MCVoiceWaveView.m#L268
      var rtv = [];
      var This = this,
        set = This.set;
      var scale = set.scale;
      var width = set.width * scale;
      var maxAmplitude = set.height * scale / 2;
      for (var x = 0; x <= width; x += scale) {
        var scaling = (1 + Math.cos(Math.PI + x / width * 2 * Math.PI)) / 2;
        var y = scaling * maxAmplitude * amplitude * Math.sin(2 * Math.PI * (x / width) * frequency + phase) + maxAmplitude;
        rtv.push(y);
      }
      return rtv;
    },
    input: function (pcmData, powerLevel, sampleRate) {
      var This = this;
      This.sampleRate = sampleRate;
      This.pcmData = pcmData;
      This.pcmPos = 0;
      This.inputTime = Date.now();
      This.schedule();
    },
    schedule: function () {
      var This = this,
        set = This.set;
      var interval = Math.floor(1000 / set.fps);
      if (!This.timer) {
        This.timer = setInterval(function () {
          This.schedule();
        }, interval);
      }
      var now = Date.now();
      var drawTime = This.drawTime || 0;
      if (now - drawTime < interval) {
        //没到间隔时间，不绘制
        return;
      }
      This.drawTime = now;

      //切分当前需要的绘制数据
      var bufferSize = This.sampleRate / set.fps;
      var pcm = This.pcmData;
      var pos = This.pcmPos;
      var len = Math.max(0, Math.min(bufferSize, pcm.length - pos));
      var sum = 0;
      for (var i = 0; i < len; i++, pos++) {
        sum += Math.abs(pcm[pos]);
      }
      This.pcmPos = pos;

      //推入绘制
      if (len || !set.keep) {
        This.draw(Recorder.PowerLevel(sum, len));
      }
      if (!len && now - This.inputTime > 1300) {
        //超时没有输入，干掉定时器
        clearInterval(This.timer);
        This.timer = 0;
      }
    },
    draw: function (powerLevel) {
      var This = this,
        set = This.set;
      var ctx = This.ctx;
      var scale = set.scale;
      var width = set.width * scale;
      var height = set.height * scale;
      var speedx = set.speed / set.fps;
      var phase = This._phase -= speedx; //位移速度
      var phase2 = phase + speedx * set.phase;
      var amplitude = powerLevel / 100;
      var path1 = This.genPath(2, amplitude, phase);
      var path2 = This.genPath(1.8, amplitude, phase2);

      //开始绘制图形
      ctx.clearRect(0, 0, width, height);

      //绘制包围背景
      ctx.beginPath();
      for (var i = 0, x = 0; x <= width; i++, x += scale) {
        if (x == 0) {
          ctx.moveTo(x, path1[i]);
        } else {
          ctx.lineTo(x, path1[i]);
        }
      }
      i--;
      for (var x = width - 1; x >= 0; i--, x -= scale) {
        ctx.lineTo(x, path2[i]);
      }
      ctx.closePath();
      ctx.fillStyle = This.linearBg;
      ctx.fill();

      //绘制线
      This.drawPath(path2, This.linear2);
      This.drawPath(path1, This.linear1);
    },
    drawPath: function (path, linear) {
      var This = this,
        set = This.set;
      var ctx = This.ctx;
      var scale = set.scale;
      var width = set.width * scale;
      ctx.beginPath();
      for (var i = 0, x = 0; x <= width; i++, x += scale) {
        if (x == 0) {
          ctx.moveTo(x, path[i]);
        } else {
          ctx.lineTo(x, path[i]);
        }
      }
      ctx.lineWidth = set.lineWidth * scale;
      ctx.strokeStyle = linear;
      ctx.stroke();
    }
  };
  Recorder[ViewTxt] = WaveView;
});

/*
录音 Recorder扩展，频率直方图显示
使用本扩展需要引入src/extensions/lib.fft.js支持，直方图特意优化主要显示0-5khz语音部分（线性），其他高频显示区域较小，不适合用来展示音乐频谱，可通过配置fullFreq来恢复成完整的线性频谱，或自行修改源码修改成倍频程频谱（伯德图、对数频谱）；本可视化插件可以移植到其他语言环境，如需定制可联系作者

https://github.com/xiangyuecn/Recorder

本扩展核心算法主要参考了Java开源库jmp123 版本0.3 的代码：
https://www.iteye.com/topic/851459
https://sourceforge.net/projects/jmp123/files/
*/
(function (factory) {
  var browser = typeof window == "object" && !!window.document;
  var win = browser ? window : Object; //非浏览器环境，Recorder挂载在Object下面
  var rec = win.Recorder,
    ni = rec.i18n;
  factory(rec, ni, ni.$T, browser);
})(function (Recorder, i18n, $T, isBrowser) {

  var FrequencyHistogramView = function (set) {
    return new fn(set);
  };
  var ViewTxt = "FrequencyHistogramView";
  var fn = function (set) {
    var This = this;
    var o = {
      /*
      elem:"css selector" //自动显示到dom，并以此dom大小为显示大小
      	//或者配置显示大小，手动把frequencyObj.elem显示到别的地方
      ,width:0 //显示宽度
      ,height:0 //显示高度
      
      H5环境以上配置二选一
      
      compatibleCanvas: CanvasObject //提供一个兼容H5的canvas对象，需支持getContext("2d")，支持设置width、height，支持drawImage(canvas,...)
      ,width:0 //canvas显示宽度
      ,height:0 //canvas显示高度
      非H5环境使用以上配置
      */

      scale: 2 //缩放系数，应为正整数，使用2(3? no!)倍宽高进行绘制，避免移动端绘制模糊
      ,

      fps: 20 //绘制帧率，不可过高
      ,

      lineCount: 30 //直方图柱子数量，数量的多少对性能影响不大，密集运算集中在FFT算法中
      ,
      widthRatio: 0.6 //柱子线条宽度占比，为所有柱子占用整个视图宽度的比例，剩下的空白区域均匀插入柱子中间；默认值也基本相当于一根柱子占0.6，一根空白占0.4；设为1不留空白，当视图不足容下所有柱子时也不留空白
      ,
      spaceWidth: 0 //柱子间空白固定基础宽度，柱子宽度自适应，当不为0时widthRatio无效，当视图不足容下所有柱子时将不会留空白，允许为负数，让柱子发生重叠
      ,
      minHeight: 0 //柱子保留基础高度，position不为±1时应该保留点高度
      ,
      position: -1 //绘制位置，取值-1到1，-1为最底下，0为中间，1为最顶上，小数为百分比
      ,
      mirrorEnable: false //是否启用镜像，如果启用，视图宽度会分成左右两块，右边这块进行绘制，左边这块进行镜像（以中间这根柱子的中心进行镜像）
      ,

      stripeEnable: true //是否启用柱子顶上的峰值小横条，position不是-1时应当关闭，否则会很丑
      ,
      stripeHeight: 3 //峰值小横条基础高度
      ,
      stripeMargin: 6 //峰值小横条和柱子保持的基础距离
      ,

      fallDuration: 1000 //柱子从最顶上下降到最底部最长时间ms
      ,
      stripeFallDuration: 3500 //峰值小横条从最顶上下降到底部最长时间ms

      //柱子颜色配置：[位置，css颜色，...] 位置: 取值0.0-1.0之间
      ,
      linear: [0, "rgba(0,187,17,1)", 0.5, "rgba(255,215,0,1)", 1, "rgba(255,102,0,1)"]
      //峰值小横条渐变颜色配置，取值格式和linear一致，留空为柱子的渐变颜色
      ,
      stripeLinear: null,
      shadowBlur: 0 //柱子阴影基础大小，设为0不显示阴影，如果柱子数量太多时请勿开启，非常影响性能
      ,
      shadowColor: "#bbb" //柱子阴影颜色
      ,
      stripeShadowBlur: -1 //峰值小横条阴影基础大小，设为0不显示阴影，-1为柱子的大小，如果柱子数量太多时请勿开启，非常影响性能
      ,
      stripeShadowColor: "" //峰值小横条阴影颜色，留空为柱子的阴影颜色
      ,

      fullFreq: false //是否要绘制所有频率；默认false主要绘制5khz以下的频率，高频部分占比很少，此时不同的采样率对频谱显示几乎没有影响；设为true后不同采样率下显示的频谱是不一样的，因为 最大频率=采样率/2 会有差异
      //当发生绘制时会回调此方法，参数为当前绘制的频率数据和采样率，可实现多个直方图同时绘制，只消耗一个input输入和计算时间
      ,
      onDraw: function (frequencyData, sampleRate) {}
    };
    for (var k in set) {
      o[k] = set[k];
    }
    This.set = set = o;
    var cCanvas = "compatibleCanvas";
    if (set[cCanvas]) {
      var canvas = This.canvas = set[cCanvas];
    } else {
      if (!isBrowser) throw new Error($T.G("NonBrowser-1", [ViewTxt]));
      var elem = set.elem;
      if (elem) {
        if (typeof elem == "string") {
          elem = document.querySelector(elem);
        } else if (elem.length) {
          elem = elem[0];
        }
      }
      if (elem) {
        set.width = elem.offsetWidth;
        set.height = elem.offsetHeight;
      }
      var thisElem = This.elem = document.createElement("div");
      thisElem.style.fontSize = 0;
      thisElem.innerHTML = '<canvas style="width:100%;height:100%;"/>';
      var canvas = This.canvas = thisElem.querySelector("canvas");
      if (elem) {
        elem.innerHTML = "";
        elem.appendChild(thisElem);
      }
    }
    var scale = set.scale;
    var width = set.width * scale;
    var height = set.height * scale;
    if (!width || !height) {
      throw new Error($T.G("IllegalArgs-1", [ViewTxt + " width=0 height=0"]));
    }
    canvas.width = width;
    canvas.height = height;
    This.ctx = canvas.getContext("2d");
    if (!Recorder.LibFFT) {
      throw new Error($T.G("NeedImport-2", [ViewTxt, "src/extensions/lib.fft.js"]));
    }
    This.fft = Recorder.LibFFT(1024);

    //柱子所在高度
    This.lastH = [];
    //峰值小横条所在高度
    This.stripesH = [];
  };
  fn.prototype = FrequencyHistogramView.prototype = {
    genLinear: function (ctx, colors, from, to) {
      var rtv = ctx.createLinearGradient(0, from, 0, to);
      for (var i = 0; i < colors.length;) {
        rtv.addColorStop(colors[i++], colors[i++]);
      }
      return rtv;
    },
    input: function (pcmData, powerLevel, sampleRate) {
      var This = this;
      This.sampleRate = sampleRate;
      This.pcmData = pcmData;
      This.pcmPos = 0;
      This.inputTime = Date.now();
      This.schedule();
    },
    schedule: function () {
      var This = this,
        set = This.set;
      var interval = Math.floor(1000 / set.fps);
      if (!This.timer) {
        This.timer = setInterval(function () {
          This.schedule();
        }, interval);
      }
      var now = Date.now();
      var drawTime = This.drawTime || 0;
      if (now - This.inputTime > set.stripeFallDuration * 1.3) {
        //超时没有输入，顶部横条已全部落下，干掉定时器
        clearInterval(This.timer);
        This.timer = 0;
        This.lastH = []; //重置高度再绘制一次，避免定时不准没到底就停了
        This.stripesH = [];
        This.draw(null, This.sampleRate);
        return;
      }
      if (now - drawTime < interval) {
        //没到间隔时间，不绘制
        return;
      }
      This.drawTime = now;

      //调用FFT计算频率数据
      var bufferSize = This.fft.bufferSize;
      var pcm = This.pcmData;
      var pos = This.pcmPos;
      var arr = new Int16Array(bufferSize);
      for (var i = 0; i < bufferSize && pos < pcm.length; i++, pos++) {
        arr[i] = pcm[pos];
      }
      This.pcmPos = pos;
      var frequencyData = This.fft.transform(arr);

      //推入绘制
      This.draw(frequencyData, This.sampleRate);
    },
    draw: function (frequencyData, sampleRate) {
      var This = this,
        set = This.set;
      var ctx = This.ctx;
      var scale = set.scale;
      var width = set.width * scale;
      var height = set.height * scale;
      var lineCount = set.lineCount;
      var bufferSize = This.fft.bufferSize;

      //计算高度位置
      var position = set.position;
      var posAbs = Math.abs(set.position);
      var originY = position == 1 ? 0 : height; //y轴原点
      var heightY = height; //最高的一边高度
      if (posAbs < 1) {
        heightY = heightY / 2;
        originY = heightY;
        heightY = Math.floor(heightY * (1 + posAbs));
        originY = Math.floor(position > 0 ? originY * (1 - posAbs) : originY * (1 + posAbs));
      }
      var lastH = This.lastH;
      var stripesH = This.stripesH;
      var speed = Math.ceil(heightY / (set.fallDuration / (1000 / set.fps)));
      var stripeSpeed = Math.ceil(heightY / (set.stripeFallDuration / (1000 / set.fps)));
      var stripeMargin = set.stripeMargin * scale;
      var Y0 = 1 << (Math.round(Math.log(bufferSize) / Math.log(2) + 3) << 1);
      var logY0 = Math.log(Y0) / Math.log(10);
      var dBmax = 20 * Math.log(0x7fff) / Math.log(10);
      var fftSize = bufferSize / 2,
        fftSize5k = fftSize;
      if (!set.fullFreq) {
        //非绘制所有频率时，计算5khz所在位置，8000采样率及以下最高只有4khz
        fftSize5k = Math.min(fftSize, Math.floor(fftSize * 5000 / (sampleRate / 2)));
      }
      var isFullFreq = fftSize5k == fftSize;
      var line80 = isFullFreq ? lineCount : Math.round(lineCount * 0.8); //80%的柱子位置
      var fftSizeStep1 = fftSize5k / line80;
      var fftSizeStep2 = isFullFreq ? 0 : (fftSize - fftSize5k) / (lineCount - line80);
      var fftIdx = 0;
      for (var i = 0; i < lineCount; i++) {
        // !fullFreq 时不采用jmp123的非线性划分频段，录音语音并不适用于音乐的频率，应当弱化高频部分
        //80%关注0-5khz主要人声部分 20%关注剩下的高频，这样不管什么采样率都能做到大部分频率显示一致。
        var start = Math.ceil(fftIdx);
        if (i < line80) {
          //5khz以下
          fftIdx += fftSizeStep1;
        } else {
          //5khz以上
          fftIdx += fftSizeStep2;
        }
        var end = Math.ceil(fftIdx);
        if (end == start) end++;
        end = Math.min(end, fftSize);

        //参考AudioGUI.java .drawHistogram方法

        //查找当前频段的最大"幅值"
        var maxAmp = 0;
        if (frequencyData) {
          for (var j = start; j < end; j++) {
            maxAmp = Math.max(maxAmp, Math.abs(frequencyData[j]));
          }
        }

        //计算音量
        var dB = maxAmp > Y0 ? Math.floor((Math.log(maxAmp) / Math.log(10) - logY0) * 17) : 0;
        var h = heightY * Math.min(dB / dBmax, 1);

        //使柱子匀速下降
        lastH[i] = (lastH[i] || 0) - speed;
        if (h < lastH[i]) {
          h = lastH[i];
        }
        if (h < 0) {
          h = 0;
        }
        lastH[i] = h;
        var shi = stripesH[i] || 0;
        if (h && h + stripeMargin > shi) {
          stripesH[i] = h + stripeMargin;
        } else {
          //使峰值小横条匀速度下落
          var sh = shi - stripeSpeed;
          if (sh < 0) {
            sh = 0;
          }
          stripesH[i] = sh;
        }
      }

      //开始绘制图形
      ctx.clearRect(0, 0, width, height);
      var linear1 = This.genLinear(ctx, set.linear, originY, originY - heightY); //上半部分的填充
      var stripeLinear1 = set.stripeLinear && This.genLinear(ctx, set.stripeLinear, originY, originY - heightY) || linear1; //上半部分的峰值小横条填充

      var linear2 = This.genLinear(ctx, set.linear, originY, originY + heightY); //下半部分的填充
      var stripeLinear2 = set.stripeLinear && This.genLinear(ctx, set.stripeLinear, originY, originY + heightY) || linear2; //上半部分的峰值小横条填充

      //计算柱子间距
      var mirrorEnable = set.mirrorEnable;
      var mirrorCount = mirrorEnable ? lineCount * 2 - 1 : lineCount; //镜像柱子数量翻一倍-1根

      var widthRatio = set.widthRatio;
      var spaceWidth = set.spaceWidth * scale;
      if (spaceWidth != 0) {
        widthRatio = (width - spaceWidth * (mirrorCount + 1)) / width;
      }
      for (var i = 0; i < 2; i++) {
        var lineFloat = Math.max(1 * scale, width * widthRatio / mirrorCount); //柱子宽度至少1个单位
        var lineWN = Math.floor(lineFloat),
          lineWF = lineFloat - lineWN; //提取出小数部分
        var spaceFloat = (width - mirrorCount * lineFloat) / (mirrorCount + 1); //均匀间隔，首尾都留空，可能为负数，柱子将发生重叠
        if (spaceFloat > 0 && spaceFloat < 1) {
          widthRatio = 1;
          spaceFloat = 0; //不够一个像素，丢弃不绘制间隔，重新计算
        } else break;
      }

      //绘制
      var minHeight = set.minHeight * scale;
      var XFloat = mirrorEnable ? (width - lineWN) / 2 - spaceFloat : 0; //镜像时，中间柱子位于正中心
      for (var iMirror = 0; iMirror < 2; iMirror++) {
        if (iMirror) {
          ctx.save();
          ctx.scale(-1, 1);
        }
        var xMirror = iMirror ? width : 0; //绘制镜像部分，不用drawImage(canvas)进行镜像绘制，提升兼容性（iOS微信小程序bug https://developers.weixin.qq.com/community/develop/doc/000aaca2148dc8a235a0fb8c66b000）

        //绘制柱子
        ctx.shadowBlur = set.shadowBlur * scale;
        ctx.shadowColor = set.shadowColor;
        for (var i = 0, xFloat = XFloat, wFloat = 0, x, y, w, h; i < lineCount; i++) {
          xFloat += spaceFloat;
          x = Math.floor(xFloat) - xMirror;
          w = lineWN;
          wFloat += lineWF;
          if (wFloat >= 1) {
            w++;
            wFloat--;
          } //小数凑够1像素
          h = Math.max(lastH[i], minHeight);

          //绘制上半部分
          if (originY != 0) {
            y = originY - h;
            ctx.fillStyle = linear1;
            ctx.fillRect(x, y, w, h);
          }
          //绘制下半部分
          if (originY != height) {
            ctx.fillStyle = linear2;
            ctx.fillRect(x, originY, w, h);
          }
          xFloat += w;
        }

        //绘制柱子顶上峰值小横条
        if (set.stripeEnable) {
          var stripeShadowBlur = set.stripeShadowBlur;
          ctx.shadowBlur = (stripeShadowBlur == -1 ? set.shadowBlur : stripeShadowBlur) * scale;
          ctx.shadowColor = set.stripeShadowColor || set.shadowColor;
          var stripeHeight = set.stripeHeight * scale;
          for (var i = 0, xFloat = XFloat, wFloat = 0, x, y, w, h; i < lineCount; i++) {
            xFloat += spaceFloat;
            x = Math.floor(xFloat) - xMirror;
            w = lineWN;
            wFloat += lineWF;
            if (wFloat >= 1) {
              w++;
              wFloat--;
            } //小数凑够1像素
            h = stripesH[i];

            //绘制上半部分
            if (originY != 0) {
              y = originY - h - stripeHeight;
              if (y < 0) {
                y = 0;
              }
              ctx.fillStyle = stripeLinear1;
              ctx.fillRect(x, y, w, stripeHeight);
            }
            //绘制下半部分
            if (originY != height) {
              y = originY + h;
              if (y + stripeHeight > height) {
                y = height - stripeHeight;
              }
              ctx.fillStyle = stripeLinear2;
              ctx.fillRect(x, y, w, stripeHeight);
            }
            xFloat += w;
          }
        }
        if (iMirror) {
          ctx.restore();
        }
        if (!mirrorEnable) break;
      }
      if (frequencyData) {
        set.onDraw(frequencyData, sampleRate);
      }
    }
  };
  Recorder[ViewTxt] = FrequencyHistogramView;
});

/*
时域转频域，快速傅里叶变换(FFT)
https://github.com/xiangyuecn/Recorder

var fft=Recorder.LibFFT(bufferSize)
	bufferSize取值2的n次方

fft.bufferSize 实际采用的bufferSize
fft.transform(inBuffer)
	inBuffer:[Int16,...] 数组长度必须是bufferSize
	返回[Float64(Long),...]，长度为bufferSize/2
*/
(function (factory) {
  var browser = typeof window == "object" && !!window.document;
  var win = browser ? window : Object; //非浏览器环境，Recorder挂载在Object下面
  var rec = win.Recorder,
    ni = rec.i18n;
  factory(rec, ni, ni.$T, browser);
})(function (Recorder, i18n, $T, isBrowser) {

  /*
  从FFT.java 移植，Java开源库：jmp123 版本0.3
  https://www.iteye.com/topic/851459
  https://sourceforge.net/projects/jmp123/files/
  */
  Recorder.LibFFT = function (bufferSize) {
    var FFT_N_LOG, FFT_N, MINY;
    var real, imag, sintable, costable;
    var bitReverse;
    var FFT_Fn = function (bufferSize) {
      //bufferSize只能取值2的n次方
      FFT_N_LOG = Math.round(Math.log(bufferSize) / Math.log(2));
      FFT_N = 1 << FFT_N_LOG;
      MINY = (FFT_N << 2) * Math.sqrt(2);
      real = [];
      imag = [];
      sintable = [0];
      costable = [0];
      bitReverse = [];
      var i, j, k, reve;
      for (i = 0; i < FFT_N; i++) {
        k = i;
        for (j = 0, reve = 0; j != FFT_N_LOG; j++) {
          reve <<= 1;
          reve |= k & 1;
          k >>>= 1;
        }
        bitReverse[i] = reve;
      }
      var theta,
        dt = 2 * Math.PI / FFT_N;
      for (i = (FFT_N >> 1) - 1; i > 0; i--) {
        theta = i * dt;
        costable[i] = Math.cos(theta);
        sintable[i] = Math.sin(theta);
      }
    };

    /*
    用于频谱显示的快速傅里叶变换 
       inBuffer 输入FFT_N个实数，返回 FFT_N/2个输出值(复数模的平方)。 
    */
    var getModulus = function (inBuffer) {
      var i,
        j,
        k,
        ir,
        j0 = 1,
        idx = FFT_N_LOG - 1;
      var cosv, sinv, tmpr, tmpi;
      for (i = 0; i != FFT_N; i++) {
        real[i] = inBuffer[bitReverse[i]];
        imag[i] = 0;
      }
      for (i = FFT_N_LOG; i != 0; i--) {
        for (j = 0; j != j0; j++) {
          cosv = costable[j << idx];
          sinv = sintable[j << idx];
          for (k = j; k < FFT_N; k += j0 << 1) {
            ir = k + j0;
            tmpr = cosv * real[ir] - sinv * imag[ir];
            tmpi = cosv * imag[ir] + sinv * real[ir];
            real[ir] = real[k] - tmpr;
            imag[ir] = imag[k] - tmpi;
            real[k] += tmpr;
            imag[k] += tmpi;
          }
        }
        j0 <<= 1;
        idx--;
      }
      j = FFT_N >> 1;
      var outBuffer = new Float64Array(j);
      /*
       * 输出模的平方:
       * for(i = 1; i <= j; i++)
       * 	inBuffer[i-1] = real[i] * real[i] +  imag[i] * imag[i];
       * 
       * 如果FFT只用于频谱显示,可以"淘汰"幅值较小的而减少浮点乘法运算. MINY的值
       * 和Spectrum.Y0,Spectrum.logY0对应.
       */
      sinv = MINY;
      cosv = -MINY;
      for (i = j; i != 0; i--) {
        tmpr = real[i];
        tmpi = imag[i];
        if (tmpr > cosv && tmpr < sinv && tmpi > cosv && tmpi < sinv) outBuffer[i - 1] = 0;else outBuffer[i - 1] = Math.round(tmpr * tmpr + tmpi * tmpi);
      }
      return outBuffer;
    };
    FFT_Fn(bufferSize);
    return {
      transform: getModulus,
      bufferSize: FFT_N
    };
  };
});

var playIcon = "data:image/png;base64, ";

var pauseIcon = "data:image/png;base64, ";

var audioIcon = "data:image/png;base64, ";

var coverLocal = "data:image/png;base64, ";

var playRepeat = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACgAAAAoCAYAAACM/rhtAAAACXBIWXMAAAsTAAALEwEAmpwYAAAFu2lUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPD94cGFja2V0IGJlZ2luPSLvu78iIGlkPSJXNU0wTXBDZWhpSHpyZVN6TlRjemtjOWQiPz4gPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iQWRvYmUgWE1QIENvcmUgOS4wLWMwMDAgNzkuMTcxYzI3ZiwgMjAyMi8wOC8xNi0xODowMjo0MyAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczpkYz0iaHR0cDovL3B1cmwub3JnL2RjL2VsZW1lbnRzLzEuMS8iIHhtbG5zOnBob3Rvc2hvcD0iaHR0cDovL25zLmFkb2JlLmNvbS9waG90b3Nob3AvMS4wLyIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0RXZ0PSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VFdmVudCMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIDI0LjAgKFdpbmRvd3MpIiB4bXA6Q3JlYXRlRGF0ZT0iMjAyNC0wMS0wOFQxNTowNToyNyswODowMCIgeG1wOk1vZGlmeURhdGU9IjIwMjQtMDQtMjhUMTM6NDA6MDYrMDg6MDAiIHhtcDpNZXRhZGF0YURhdGU9IjIwMjQtMDQtMjhUMTM6NDA6MDYrMDg6MDAiIGRjOmZvcm1hdD0iaW1hZ2UvcG5nIiBwaG90b3Nob3A6Q29sb3JNb2RlPSIzIiB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOjFkNmU3NmMwLTE5NWEtY2U0OS1iNGE4LTQ5NzZlY2FiMmRhNSIgeG1wTU06RG9jdW1lbnRJRD0ieG1wLmRpZDo5ZWQ4M2Q3Ny1hMDJjLTA3NGUtYWEyOC0xMWFkMzg3Yzg0ZjAiIHhtcE1NOk9yaWdpbmFsRG9jdW1lbnRJRD0ieG1wLmRpZDo5ZWQ4M2Q3Ny1hMDJjLTA3NGUtYWEyOC0xMWFkMzg3Yzg0ZjAiPiA8eG1wTU06SGlzdG9yeT4gPHJkZjpTZXE+IDxyZGY6bGkgc3RFdnQ6YWN0aW9uPSJjcmVhdGVkIiBzdEV2dDppbnN0YW5jZUlEPSJ4bXAuaWlkOjllZDgzZDc3LWEwMmMtMDc0ZS1hYTI4LTExYWQzODdjODRmMCIgc3RFdnQ6d2hlbj0iMjAyNC0wMS0wOFQxNTowNToyNyswODowMCIgc3RFdnQ6c29mdHdhcmVBZ2VudD0iQWRvYmUgUGhvdG9zaG9wIDI0LjAgKFdpbmRvd3MpIi8+IDxyZGY6bGkgc3RFdnQ6YWN0aW9uPSJzYXZlZCIgc3RFdnQ6aW5zdGFuY2VJRD0ieG1wLmlpZDoxZDZlNzZjMC0xOTVhLWNlNDktYjRhOC00OTc2ZWNhYjJkYTUiIHN0RXZ0OndoZW49IjIwMjQtMDQtMjhUMTM6NDA6MDYrMDg6MDAiIHN0RXZ0OnNvZnR3YXJlQWdlbnQ9IkFkb2JlIFBob3Rvc2hvcCAyNC4wIChXaW5kb3dzKSIgc3RFdnQ6Y2hhbmdlZD0iLyIvPiA8L3JkZjpTZXE+IDwveG1wTU06SGlzdG9yeT4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz77PGlAAAAEZElEQVRYhe3YW0ybZRgH8P/zfv06pOHQopuYRRdnDCMzUYeHYIAPtrHp2LLEK4270ZndOMZhCVcmaDKicmjBzbnEwyQxzmji5hKJiKPgYS6RgcbDhZuZ0YSpbaEwCm2/93m82KYECy1rp1zwT3rRL0/f75ce3ud9SiKCpRz1fwOSZRmYbpaB6WbJAx2JLhJRygtUtQdLmWS7At3BRKsAuQGCMAl+FgNnWKN3sLHg11TWSrTlUcKLKQBLD4d3ZV2K10HRvTKrnCAQEEAABAAEhjLfsUm3+Pd5vrvuQKsztJ60vAbCAyRXDEAvREZE0U/E6g9S+jYRVQTAAqRYREAEGHHy9TUV1F834COdwa0Rph6DGSIAO432aLZ69fTuvHPz3bTCG3pYidQRpBoCzDipN+r01AztoXhGgWsPTFYWuSKnptkAk+NHSGyHv2HlvLC5sXzhZyD2y0aMAYfj608b3fdlDLi9WbKnckMTAjGU4CunWWD11FI0VdzVVDeHakyxT07lAYDjoL/BszcjwE3toQ9E2Tu1mKP+Bvcti4XNTvEnU0/e/O2l14lNsGFa/Q05AwsBk+6DVZ3BUlayUxjQwGPp4ADgh82uN4SzThA0hGK+ZPVJgfGoMSPCE2Ks+PCzBvdAsvpUIpS7WzsIBNxttYbWL1ws8q/HfxGrI3SquiUgG96deGEhS8JOMjsVbWO7bG0f/6LppslMwMoO/FloZKuHiMhvO1GZE5Ai682xfArpHQC659Yv+BFX+UJvK6W7V5jGBasruDoTQGeuOkQs74G5VgwCTdt3UYC/AdFbiernBW70BU6C+fErzctDNkYs79iadIE6ktUtikFAAQSAwu0w5FYAl1IGlrWFj4KlRkDAlW5GQAEJj6T7TvqbXMeZ9TbQ7O86AWxYKQOdxOUaBM3yMQAGKAAgBiBPx5CbDhAABhsLP7LZ3EaXTxQabJT0788fSlSbcKMub4kUUvZ0vpPUFDP/osUYi5Ha6hKO9zW6h9MFXs2WjrAnSpzrr3dfAK6hk2w4Imbe9HhQtJ0TV+bmz+vz+zKFq+oI3B92FQzPPjQsupMM7aE4mI8RAU7hrozhusbXCnAmLxL6LVlt0k4y43C9KFBwkr3untappzIBJK2PAQIRJD1pJwV+WZt1XqAOxoTgMSOHH/TKmnRwle3h50WkRBFhxpH1dNpAAPA3uPcyZBQsZhaPny33Tq67FpzVEWwE2c8KANaq6XStK+kPLuWpzrRzKxjmtFJxtyHR4UpfcEvKsGZxWN6gV4m0KRYQjPf793teSuW1izryl3VFiw09MaBE3SgABNRDGof6p9w9aCaeW7/R9/sqzY4nCKhTkNWaCGzAN1ibeC7JyNBU2npxpVOZrxDhUZK/J7hpAN8DOCukIiK00oAuEeDOf4Y7GtWmem6wNv/IfGtndOy0vIFNILWPRCohcM26zdVVLj8jOm8LHb3oyG89l2RMSBm4lLLk//pYBqabZWC6WQamm78AEV4zMhfNvWEAAAAASUVORK5CYII=";

var playOnce = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABwAAAAgCAMAAAA2a+hwAAAAAXNSR0IArs4c6QAAAlJQTFRFAAAAgID/QID/QID/OY7jRovoO4nrSZLtRIjuPIfwQIzyQJnySZLzRpfzQ4X0QIrqQo7sPo3tEN73RI/wPI3yQZDrPo/sQ4ztQ4zzO4jtQY7tPo7uPYvuQI/vOY3vPo3vPIzrQZHwNqL1QI7wRYTrK4b2QY/uP47uR47yQIvvP43rQI/wP5DwSXz0QozuPYvxQY/uQI3uQY3vQI/yQZDzQpDwQ472QI3uPIn3P4vqQo7vQo3tQI3uQJDuQI7uQI3uQI7sQo7sQpHxQY3sPo7vQI7tQI/xQY7tQY3tQY3vPo7vQo/rP5HuQY3uQJDxQorsQo7sQo7vOI3xQovrQo3rQY7tQY3tQI7tQI3sPY/wN5vvQo7vNKPyQY7tQ43tQY/uQorsQI7sQY3uPJfwQI7wPpPuP4/vQY7tTnTsRJPxP47vQYzsPZDvP43uQo7sO5jvQY3uPZDwQ4ftQI7tQo3uQY7uQo7uQY7tQY7tQ43wQY7tQI3tQI7uQI7tQI/wP4zuQ5DtQY7tRJHsQI7tQY7tQI7tQY7uQI7uQY3uQo7tPpHtQI7tQY/sQY7sQY/tQY7tQY7tQY3sQY/uQI7tQY7tQo7uQo/uSY7tQY/tTXnqQY3tQY7tQY7tQY7tQY7tQY7uQY7tPZXtQY3tQY7tQY7tQY7tQo/tP5LqQI/rQI/sQY3sQY7rQY7sQY7tQY/rQY/sQY/tQZDtQozsQo3rQo3sQo3tQo7qQo7rQo7sQo7tQo/tQ4vsQ4zrQ47qQ47sRIfrRInsRI/rRI/sRYnsR4TqR4fqvnKd/wAAAKd0Uk5TAAIECAkLDQ4PERQUFRYXGBsdHyImJykqKisrLS4wMTEzMzQ0NDs7PT1AQURFRklLS0xOUFNVWFxdYWFlZ2doa2xsbW5vb3BxcnJzdHl5fHx8fH+AgIGCg4iJjIyOjpGSkpOUlZeZm56goaKio6OjpKaqqq6vsLO0t7i5vL7GxsfHyMjLy8zN0tTW2trc4ubn6erq7Ozs7Ozu7vHz9Pb3+Pn6+/v9/v6utNnsAAABnklEQVQYGY3BhVsTcQDH4c8QRbCwu7tbVFQsPLu7u3t2YRfYXRhg7r4GMnYzMPm/nLf7nTjkeXxf/lv7I3OoVP+IllCpvg80l39rNiTrkrQymQpqTD4rV7QriabkRx3tnXdP9tQqkDGAP1IPKXw6qy7ZciYCqbLnY6RdkDKBUVI2MUlL39jr8eQV3elATKdTI4kb+6FsMa7NZY/rkWDw8589ielS8qU3FWwquRoAcu0N+Opg3AxNgFalr2rhSd/3qBuece8vwszvOXjGFEiz8dQOC46GRuNK3iMVaDzG+TBct3vgSpGGrpOFse0rPH3blLhGrdkqC2P5OyhUQ3y7ZWEs/AG31RlfUBbGmiLIdQbiC8rC2P8SNkaW4QvKwrgfhkGhu/h2aRKedsVhqGnb/TAOazqend8OAit0BWP4ycbEdXxR2hJIeRJZS6LArc87+K2Xo2n8Len46xsBXAs+fVxFeU3OhJ61wTNL0XPdMarOkPOwLb7M/GIdGNE8rVr1+n1WX3OcYw0oJ32LnKhcjvKGkaDFohOFirm8PQPPL6EvjEOwGD5qAAAAAElFTkSuQmCC";

var recStartIcon = "data:image/png;base64, ";

var recStopIcon = "data:image/png;base64, ";

var recDelete = "data:image/png;base64, ";

var recMockWave = "data:image/png;base64, ";

//
const uuid = prefix => {
  const s = [];
  const hexDigits = '0123456789abcdef';
  for (let i = 0; i < 36; i += 1) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
  }
  s[14] = '4';
  s[19] = hexDigits.substr(s[19] & 0x3 | 0x8, 1);
  const id = s.join('');
  return prefix ? prefix + '__' + id : id;
};
var script$2 = {
  name: 'RecordPlayer',
  props: {
    //模式：preview 预览 (默认)，editor 编辑
    mode: {
      type: String,
      default: 'editor'
    },
    playStyle: {
      type: String,
      default: 'yuan-wen'
    },
    styleMode: {
      type: String,
      default: 'A'
    },
    url: {
      type: String,
      default: '',
      require: true
    },
    title: {
      type: String,
      default: '音频文件'
    },
    content: {
      type: String,
      default: '暂无简介'
    },
    coverImageUrl: {
      type: String,
      default: ''
    },
    //进度是否能控制
    scheduleControl: {
      type: String,
      default: ''
    },
    loop: {
      type: Boolean,
      default: true
    },
    playMode: {
      type: String,
      default: 'xun-huan'
    },
    targerLink: {
      type: String,
      default: ''
    },
    playerIndex: {
      type: Number,
      default: -1
    }
  },
  data() {
    return {
      playIcon,
      pauseIcon,
      audioIcon,
      coverLocal,
      recStartIcon,
      recStopIcon,
      recDelete,
      recMockWave,
      isPlay: false,
      playTime: 0,
      playDuration: '00:00',
      playCurrentTime: '00:00',
      totalDuration: 0,
      link: {
        type: String,
        default: ''
      },
      //链接地址
      lastOperateTimeStamp: '',
      recordAudio: null,
      permissionDialogVisible: false,
      Rec: recorder_mp3_min,
      type: 'mp3',
      bitRate: 16,
      sampleRate: 16000,
      rec: null,
      recDuration: 0,
      powerLevel: 0,
      logs: [],
      recBolb: null,
      isRecing: false,
      hasInitSuccess: false,
      waveStore: {
        selected: 'Histogram2',
        WaveView: {},
        Histogram2: {},
        Histogram3: {}
      },
      recordDataUrl: '',
      lastAudioStamp: null,
      lastPlayStamp: null,
      waveBoxKey: uuid('wave'),
      recTimestamp: null
    };
  },
  computed: {
    videoAndMusicStop() {
      let playState = sessionStorage.getItem('SET_PLAY_STATE');
      return playState;
    },
    playModeIconSrc() {
      let srcMap = {
        'xun-huan': playRepeat,
        'dan-ci': playOnce
      };
      return srcMap[this.playMode];
    },
    controlStatusText() {
      let text = '';
      if (this.recBolb) {
        text = this.isPlay ? '' : '';
      } else {
        text = this.isRecing ? '结束录音' : '开始录音';
      }
      return text;
    }
  },
  watch: {
    url: {
      handler(newVal) {
        let _this = this;
        this.isPlay = false;
        let ua = navigator.userAgent;
        console.log('浏览器 UA', ua);
        /micromessenger/.test(ua.toLowerCase());
        let isIOS = !!ua.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
        // isWeixin && isIOS && newVal && this.$message({
        //   message: `当前UA为${ua}`,
        //   duration: 3000
        // })
        if (isIOS && newVal) {
          try {
            this.$nextTick(() => {
              _this.$refs.recordAudio.muted = true;
              const playPromise = _this.$refs.recordAudio.play();
              _this.$refs.recordAudio.muted = false;
              if (playPromise) {
                playPromise.then(() => {
                  _this.$refs.recordAudio.pause();
                }).catch(error => {
                  _this.$refs.recordAudio.pause();
                  console.log(error);
                });
              }
            });
          } catch (error) {
            console.log(error);
            this.$message({
              type: 'warning',
              message: error,
              duration: 5000
            });
          }
        }
      },
      immediate: true
    },
    videoAndMusicStop(val) {
      console.log('watch', val);
      let currentPlayStamp = val || '--';
      if (`${this.url}__playTimeStamp__${this.lastOperateTimeStamp}` !== currentPlayStamp) {
        this.recordAudio.pause();
      }
    }
  },
  mounted() {
    // 加载完毕后，先获取<video>标签DOM对象
    this.recordAudio = this.$refs.recordAudio;
    // let _this = this;
    // if(!this.recBolb && !this.isRecing) {
    //   let rec = this.rec = Recorder({
    //       type:_this.type,
    //       bitRate:_this.bitRate,
    //       sampleRate:_this.sampleRate,
    //       onProcess:function(buffers,powerLevel,duration,sampleRate){
    //           _this.recDuration = duration;
    //           _this.powerLevel = powerLevel;
    //           // _this.wave.input(buffers[buffers.length-1],powerLevel,sampleRate);
    //           //可视化图形绘制
    //           $(".recwave").html("").append(_this.waveStore[_this.waveStore.selected].elem);
    //           _this.waveStore[_this.waveStore.selected].input(buffers[buffers.length-1],powerLevel,sampleRate);
    //       }
    //   });

    //   _this.dialogInt=setTimeout(function(){//定时8秒后打开弹窗，用于监测浏览器没有发起权限请求的情况
    //       _this.showDialog();
    //   },8000);

    //   rec.open(function(){
    //       _this.dialogCancel();
    //       // _this.reclog("已打开:"+_this.type+" "+_this.sampleRate+"hz "+_this.bitRate+"kbps",2);

    //       _this.initWaveStore(".recwave");
    //       // rec.start();
    //       _this.hasInitSuccess = true
    //       // _this.isRecing = true
    //   },function(msg,isUserNotAllow){
    //       _this.dialogCancel();
    //       isUserNotAllow && _this.$message.error('启动录音失败，用户拒绝了授权')
    //       // _this.reclog((isUserNotAllow?"UserNotAllow，":"")+"打开失败："+msg,1);
    //   });

    //   _this.waitDialogClickFn=function(){
    //       _this.dialogCancel();
    //       _this.$message.error('启动录音失败，用户忽略了权限请求')
    //       // _this.reclog("打开失败：权限请求被忽略，用户主动点击的弹窗",1);
    //   };
    // }
  },
  methods: {
    changeDuration() {
      this.$nextTick(() => {
        this.playDuration = this.timeFormat(this.$refs.recordAudio.duration);
        this.totalDuration = this.$refs.recordAudio.duration;
      });
    },
    //将单位为秒的的时间转换成mm:ss的形式
    timeFormat(num) {
      let minute = parseInt(num / 60);
      let second = parseInt(num % 60);
      minute = minute >= 10 ? minute : `0${minute}`;
      second = second >= 10 ? second : `0${second}`;
      return `${minute}:${second}`;
    },
    resetRecorder() {
      let audio = this.$refs.recordAudio;
      if (!audio.paused) {
        audio.pause();
      }
      this.recBolb = null;
      this.isPlay = false;
      this.isRecing = false;
      this.playTime = 0;
      this.playDuration = '00:00';
      this.playCurrentTime = '00:00';
      this.totalDuration = 0;
      this.recDuration = 0;
      this.recordDataUrl = '';
      this.lastAudioStamp = null;
      this.lastPlayStamp = null;
    },
    setRecedDuration(ms) {
      this.playDuration = this.timeFormat(ms / 1000);
      this.totalDuration = ms / 1000;
    },
    initWaveStore(elem) {
      this.waveStore.WaveView = recorder_mp3_min.WaveView({
        elem: elem,
        width: 300,
        height: 100
      });
      this.waveStore.Histogram2 = recorder_mp3_min.FrequencyHistogramView({
        elem: elem,
        lineCount: 30,
        position: 0,
        minHeight: 12,
        mirrorEnable: true,
        stripeEnable: false,
        linear: [0, '#8FC1FD', 1, '#8FC1FD']
      });
      this.waveStore.Histogram3 = recorder_mp3_min.FrequencyHistogramView({
        elem: elem,
        lineCount: 20,
        position: 0,
        minHeight: 1,
        fallDuration: 400,
        stripeEnable: false,
        mirrorEnable: true,
        linear: [0, '#0ac', 1, '#0ac']
      });
    },
    toggleRec() {
      let _this = this;
      // if(!this.hasInitSuccess) {
      //   this.$message.warning('当前浏览器不支持或用户未进行授权，组件功能暂无法使用')
      //   return
      // }
      let waveBoxSelector = '#' + _this.waveBoxKey;
      if (!this.recBolb && !this.isRecing) {
        // _this.rec.start();
        // _this.isRecing = true
        if (recorder_mp3_min.IsOpen()) {
          _this.$message.warning('当前存在进行中的录制任务');
          return;
        }
        let rec = this.rec = recorder_mp3_min({
          type: _this.type,
          bitRate: _this.bitRate,
          sampleRate: _this.sampleRate,
          onProcess: function (buffers, powerLevel, duration, sampleRate) {
            _this.recDuration = duration;
            _this.powerLevel = powerLevel;
            // _this.wave.input(buffers[buffers.length-1],powerLevel,sampleRate);
            //可视化图形绘制
            jquery(waveBoxSelector).html('').append(_this.waveStore[_this.waveStore.selected].elem);
            _this.waveStore[_this.waveStore.selected].input(buffers[buffers.length - 1], powerLevel, sampleRate);
          }
        });
        _this.dialogInt = setTimeout(function () {
          //定时8秒后打开弹窗，用于监测浏览器没有发起权限请求的情况
          _this.showDialog();
        }, 15000);
        rec.open(function () {
          _this.dialogCancel();
          // _this.reclog("已打开:"+_this.type+" "+_this.sampleRate+"hz "+_this.bitRate+"kbps",2);

          // _this.wave=Recorder.WaveView({elem:".ctrlProcessWave"});
          _this.initWaveStore(waveBoxSelector);
          rec.start();
          _this.isRecing = true;
          _this.recTimestamp = new Date().getTime();
        }, function (msg, isUserNotAllow) {
          _this.dialogCancel();
          console.log('启动录音错误信息', msg);
          let errMsg = '启动录音失败，当前浏览器不支持';
          if (isUserNotAllow) {
            errMsg = '启动录音失败，用户拒绝了授权';
          }
          if (msg.includes('麦克风')) {
            errMsg = '启动录音失败，无可用 MIC 设备';
          }
          _this.$message.error(errMsg);
          // _this.reclog((isUserNotAllow?"UserNotAllow，":"")+"打开失败："+msg,1);
        });
        _this.waitDialogClickFn = function () {
          _this.dialogCancel();
          _this.$message.error('启动录音失败，用户忽略了权限请求');
          // _this.reclog("打开失败：权限请求被忽略，用户主动点击的弹窗",1);
        };
        // _this.$nextTick(() => {
        //   if(!Recorder.IsOpen()){
        //     _this.$message.error('未获取录音权限')
        //     // this.reclog("未打开录音",1);
        //     return;
        //   }
        //   console.log('当前录音实例配置',_this.rec.set);
        //   rec.start();
        // })
      } else {
        if (!(_this.rec && recorder_mp3_min.IsOpen())) {
          _this.$message.error('录音未启动');
          return;
        }
        let doneTimestamp = new Date().getTime();
        if (!_this.recTimestamp || doneTimestamp - _this.recTimestamp < 5000) {
          _this.$message.warning('至少录制 5s 方可进行保存，请稍候');
          return;
        }
        let rec = _this.rec;
        rec.stop(function (blob, duration) {
          _this.$message.success('录制完成');
          _this.setAudioPath(blob, duration);
          jquery(waveBoxSelector).html('');
          _this.$emit('resData', {
            blob: blob,
            duration: duration
          });
        }, function (msg) {
          _this.recTimestamp = null;
          _this.$message.error(`录音失败：${msg}`);
        }, true); //录音结束时自动调用rec.close方法丢弃所有数据
      }
    },
    // 销毁录音实例
    destruction() {
      this.rec.close();
      this.isRecing = false;
      let waveBoxSelector = '#' + this.waveBoxKey;
      jquery(waveBoxSelector).html('');
    },
    setAudioPath(blob, duration) {
      this.recDuration = duration;
      this.setRecedDuration(duration);
      this.$nextTick(() => {
        this.recBolb = blob;
        this.isRecing = false;
        this.lastAudioStamp = new Date().getTime();
        this.recTimestamp = null;
      });
    },
    play() {
      if (!this.recBolb) {
        this.toggleRec();
      } else {
        // if (this.playStyle === 'yuan-wen') {
        //   this.doPlay()
        // }
        // if (this.playStyle === 'tan-chuang') {
        //   this.$emit('showDialog', { url: this.url, title: this.title, coverFileUrl: this.coverImageUrl, content: this.content, playerIndex: this.playerIndex })
        // }
        this.togglePlay();
      }
    },
    togglePlay() {
      let _this = this;
      let audios = document.querySelectorAll('audio');
      audios.forEach(i => i.pause());
      let video = document.querySelectorAll('video');
      if (video && video.length) {
        video.forEach(i => i.pause());
      }
      let audio = this.$refs.recordAudio;
      if (this.isPlay) {
        !(audio.ended || audio.paused) && audio.pause();
      } else {
        if (!this.lastPlayStamp || this.lastPlayStamp !== this.lastAudioStamp) {
          audio.onerror = function (e) {
            _this.$message.error(audio.error.message);
          };
          audio.currentTime = 0;
          audio.src = typeof _this.recBolb == 'object' ? (window.URL || webkitURL).createObjectURL(_this.recBolb) : _this.recBolb;
          audio.play();
          this.lastPlayStamp = this.lastAudioStamp;
        } else {
          audio.paused && audio.play();
        }
      }
      this.isPlay = !this.isPlay;
    },
    doPlay() {
      let _this = this;
      let rec = this.rec;
      let audio = this.$refs.LogAudioPlayer;
      audio.controls = true;
      if (!(audio.ended || audio.paused)) {
        audio.pause();
      }
      audio.onerror = function (e) {
        _this.$message.error(audio.error.message);
      };
      audio.src = (window.URL || webkitURL).createObjectURL(rec.blob);
      audio.play();
      // console.log('暂停')
      // let audio = document.querySelectorAll('audio')
      // audio.forEach((i) => i.pause())
      // let video = document.querySelectorAll('video')
      // if (video && video.length) {
      //   video.forEach((i) => i.pause())
      // }

      // this.isPlay ? this.$refs.recordAudio.pause() : this.$refs.recordAudio.play()
      // this.isPlay = !this.isPlay
      // let timeStamp = new Date().getTime()
      // this.lastOperateTimeStamp = timeStamp
      // let playStamp = `${this.url}__playTimeStamp__${timeStamp}`
      // // !this.isPlay && this.$store.commit('leaflet/SET_PLAY_STATE', playStamp)
      // // this.$store.commit('leaflet/SET_PLAY_STATE', playStamp)
      // sessionStorage.setItem('SET_PLAY_STATE', playStamp) //存储
    },
    updateTime(e) {
      this.playTime = this.$refs.recordAudio.currentTime;
      this.playCurrentTime = this.timeFormat(this.$refs.recordAudio.currentTime);
      if (!this.loop && this.playTime >= this.totalDuration) {
        this.isPlay = false;
      }
      // this.$emit('timeUpdate', {event:e, time: this.$refs.recordAudio.currentTime })
    },
    changeTime(val) {
      this.$refs.recordAudio.currentTime = val;
    },
    showDialog: function () {
      //选择性的弹一个对话框：为了防止移动端浏览器存在第三种情况：用户忽略，并且（或者国产系统UC系）浏览器没有任何回调
      if (!/mobile/i.test(navigator.userAgent)) {
        return; //只在移动端开启没有权限请求的检测
      }
      this.permissionDialogVisible = true;
    },
    dialogCancel: function () {
      clearTimeout(this.dialogInt);
      this.permissionDialogVisible = false;
    },
    waitDialogClick: function () {
      this.dialogCancel();
      this.waitDialogClickFn();
    }
  }
};

/* script */
const __vue_script__$2 = script$2;

/* template */
var __vue_render__$2 = function () {
  var _vm = this;
  var _h = _vm.$createElement;
  var _c = _vm._self._c || _h;
  return _c(
    "div",
    { class: ["xml-audio-player", _vm.mode] },
    [
      _vm.recBolb
        ? _c("div", { staticClass: "play-mode-wrap" }, [
            _c("img", {
              staticClass: "play-control-image",
              attrs: { src: _vm.playModeIconSrc },
              on: {
                click: function ($event) {
                  _vm.$refs.recordAudio.currentTime = 0;
                },
              },
            }),
            _vm._v(" "),
            _c("img", {
              staticClass: "play-control-image",
              attrs: { src: _vm.recDelete },
              on: { click: _vm.resetRecorder },
            }),
          ])
        : _vm._e(),
      _vm._v(" "),
      _vm.styleMode !== "C"
        ? _c("div", { staticClass: "audio-cover" }, [
            _vm.styleMode === "A"
              ? _c("div", { staticClass: "play-button style-a" }, [
                  _c("img", {
                    staticClass: "button-image",
                    attrs: {
                      src: _vm.recBolb
                        ? _vm.isPlay
                          ? _vm.pauseIcon
                          : _vm.playIcon
                        : _vm.isRecing
                        ? _vm.recStopIcon
                        : _vm.recStartIcon,
                    },
                    on: {
                      click: function ($event) {
                        $event.stopPropagation();
                        return _vm.play.apply(null, arguments)
                      },
                    },
                  }),
                ])
              : _vm._e(),
            _vm._v(" "),
            _vm.controlStatusText
              ? _c("div", { staticClass: "play-text" }, [
                  _vm._v(_vm._s(_vm.controlStatusText)),
                ])
              : _vm._e(),
          ])
        : _vm._e(),
      _vm._v(" "),
      !_vm.recBolb
        ? _c("div", { staticClass: "record-player-control" }, [
            !_vm.recBolb
              ? _c("div", {
                  staticClass: "recwave",
                  staticStyle: { height: "75%", width: "100%" },
                  attrs: { id: _vm.waveBoxKey },
                })
              : _vm._e(),
            _vm._v(" "),
            !_vm.isRecing
              ? _c("div", { staticClass: "mock-wave" }, [
                  _c("img", {
                    staticClass: "button-image",
                    attrs: { src: _vm.recMockWave },
                  }),
                ])
              : _vm._e(),
          ])
        : _c("div", { staticClass: "audio-player-control" }, [
            _c("div", { staticClass: "audio-controls" }, [
              _vm.styleMode !== "A"
                ? _c(
                    "div",
                    { staticClass: "audio-controls__play-button-wrapper" },
                    [
                      _c("div", { staticClass: "play-button" }, [
                        _c("img", {
                          staticClass: "button-image",
                          attrs: {
                            src: _vm.isPlay ? _vm.pauseIcon : _vm.playIcon,
                          },
                          on: {
                            click: function ($event) {
                              $event.stopPropagation();
                              return _vm.play.apply(null, arguments)
                            },
                          },
                        }),
                      ]),
                    ]
                  )
                : _vm._e(),
              _vm._v(" "),
              _c("div", { staticClass: "audio-controls__handler" }, [
                _c(
                  "div",
                  { staticClass: "progress" },
                  [
                    _c("el-slider", {
                      attrs: {
                        max: _vm.totalDuration,
                        disabled: _vm.scheduleControl !== "yes",
                        "show-tooltip": false,
                      },
                      on: { change: _vm.changeTime },
                      model: {
                        value: _vm.playTime,
                        callback: function ($$v) {
                          _vm.playTime = $$v;
                        },
                        expression: "playTime",
                      },
                    }),
                  ],
                  1
                ),
                _vm._v(" "),
                _c("div", { staticClass: "play-times" }, [
                  _c("div", { staticClass: "current-time" }, [
                    _vm._v(_vm._s(_vm.playCurrentTime)),
                  ]),
                  _vm._v(" "),
                  _c("div", { staticClass: "total-time" }, [
                    _vm._v(_vm._s(_vm.playDuration)),
                  ]),
                ]),
              ]),
            ]),
          ]),
      _vm._v(" "),
      _c("audio", {
        ref: "recordAudio",
        staticClass: "audio-component",
        attrs: {
          controls: "",
          preload: "auto",
          src: _vm.recordDataUrl,
          loop: _vm.loop,
          link: _vm.link,
        },
        on: {
          canplay: _vm.changeDuration,
          timeupdate: _vm.updateTime,
          pause: function ($event) {
            _vm.isPlay = false;
          },
        },
      }),
      _vm._v(" "),
      _c(
        "el-dialog",
        {
          attrs: {
            title: "权限请求提醒",
            width: "320px",
            visible: _vm.permissionDialogVisible,
            "custom-class": "info-dialog",
            "append-to-body": "",
          },
          on: {
            "update:visible": function ($event) {
              _vm.permissionDialogVisible = $event;
            },
          },
        },
        [
          _c("div", [
            _c("p", { staticClass: "version-number" }, [
              _vm._v(
                "录音功能需要麦克风权限，请允许；如果未看到任何请求，请点击忽略"
              ),
            ]),
            _vm._v(" "),
            _c(
              "div",
              { staticStyle: { "text-align": "right" } },
              [
                _c(
                  "el-button",
                  { attrs: { plain: "" }, on: { click: _vm.waitDialogClick } },
                  [_vm._v("忽略")]
                ),
              ],
              1
            ),
          ]),
        ]
      ),
    ],
    1
  )
};
var __vue_staticRenderFns__$2 = [];
__vue_render__$2._withStripped = true;

  /* style */
  const __vue_inject_styles__$2 = undefined;
  /* scoped */
  const __vue_scope_id__$2 = undefined;
  /* module identifier */
  const __vue_module_identifier__$2 = undefined;
  /* functional template */
  const __vue_is_functional_template__$2 = false;
  /* style inject */
  
  /* style inject SSR */
  
  /* style inject shadow dom */
  

  
  const __vue_component__$2 = /*#__PURE__*/normalizeComponent(
    { render: __vue_render__$2, staticRenderFns: __vue_staticRenderFns__$2 },
    __vue_inject_styles__$2,
    __vue_script__$2,
    __vue_scope_id__$2,
    __vue_is_functional_template__$2,
    __vue_module_identifier__$2,
    false,
    undefined,
    undefined,
    undefined
  );

//
const _image = '.jpg,.png,.jpeg,.gif,';
const _audio = '.mp3,';
const _video = '.mp4,.MP4';
const _resources = 'application/x-zip-compressed,.zip,';
const _office = '.ppt,.xlsx,.xls,.doc,.docx,.pptx';
var script$1 = {
  components: {
    RecordPlayer: __vue_component__$2
  },
  name: 'addFile',
  props: {
    actionUrl: {
      type: String,
      default: ''
    },
    headers: {
      type: Object,
      default: () => {}
    },
    data: {
      // 上传文件附带的额外参数
      type: Object,
      default: () => {}
    },
    fileSize: {
      // 最大上传文件大小
      type: Number,
      default: 10
    }
  },
  data() {
    return {
      Accept: _image + _audio + _video + _resources + _office,
      fileRules: {
        resourcesName: [{
          required: true,
          message: '请输入资源名称',
          trigger: 'blur'
        }, {
          min: 2,
          max: 30,
          message: '长度在 2 到 30 个字符',
          trigger: 'blur'
        }],
        isDownload: [{
          required: true,
          message: '请选择是否允许下载',
          trigger: 'change'
        }],
        fileUrl: [{
          required: true,
          message: '请上传资源文件',
          trigger: 'change'
        }],
        isStudentShow: [{
          required: true,
          message: '请选择是否对学生可见',
          trigger: 'change'
        }]
      },
      recordedRules: {
        isStudentShow: [{
          required: true,
          message: '请选择是否对学生可见',
          trigger: 'change'
        }]
      },
      noteRules: {
        noteContent: [{
          required: true,
          message: '请输入笔记内容',
          trigger: 'blur'
        }, {
          min: 2,
          max: 1000,
          message: '长度在 2 到 1000 个字符',
          trigger: 'blur'
        }],
        isStudentShow: [{
          required: true,
          message: '请选择是否对学生可见',
          trigger: 'change'
        }]
      },
      fileList: [
        // {
        //   name: 'food.jpeg',
        //   url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
        // },
        // {
        //   name: 'food2.jpeg',
        //   // url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
        //   url:'../../../static/images/defaultCover/audio.png'
        // }
      ],
      fileData: {
        resourcesName: '',
        noteContent: '',
        isDownload: [0],
        fileUrl: '',
        id: '',
        resourcesType: '',
        fileExt: '',
        creationTime: '',
        textBookId: '',
        chapterId: '',
        orderNum: '',
        firstLevelId: '',
        firstLevelLabel: '',
        locationChapterId: '',
        isStudentShow: [0],
        location: '',
        duration: 0
      },
      recordedData: {
        resourcesName: '',
        noteContent: '',
        isDownload: [0],
        fileUrl: '',
        id: '',
        resourcesType: '',
        fileExt: '',
        creationTime: '',
        textBookId: '',
        chapterId: '',
        orderNum: '',
        firstLevelId: '',
        firstLevelLabel: '',
        locationChapterId: '',
        isStudentShow: [0],
        location: '',
        duration: 0
      },
      noteData: {
        resourcesName: '',
        noteContent: '',
        isDownload: [0],
        fileUrl: '',
        id: '',
        resourcesType: '',
        fileExt: '',
        creationTime: '',
        textBookId: '',
        chapterId: '',
        orderNum: '',
        firstLevelId: '',
        firstLevelLabel: '',
        locationChapterId: '',
        isStudentShow: [0],
        location: '',
        duration: 0
      },
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      show: false,
      isEdit: false,
      chapterOrderNum: 1,
      isSwhoUpload: false,
      activeName: 'resource',
      recordedBlob: null,
      loadingInstance: null,
      limit: 1
    };
  },
  methods: {
    open(e) {
      console.log('e', e);
      this.show = true;
      this.recordedBlob = null;
      let fileData = e;
      // fileData.textBookId = e.textBookId
      // fileData.creationTime = e.creationTime
      // fileData.resourcesName = e.resourcesName
      // fileData.noteContent = e.noteContent
      fileData.isDownload = [e.isDownload];
      fileData.isStudentShow = [e.isStudentShow];
      // fileData.id = e.id
      // fileData.resourcesType = e.resourcesType
      // fileData.fileExt = e.fileExt
      // fileData.fileUrl = e.fileUrl
      // fileData.location = e.location
      // fileData.chapterId = e.chapterId
      // fileData.orderNum = e.orderNum
      // fileData.firstLevelId = e.firstLevelId
      // fileData.firstLevelLabel = e.firstLevelLabel
      // fileData.chapterOrderNum = e.chapterOrderNum
      // fileData.locationChapterId = e.locationChapterId
      // fileData.duration = e.duration
      this.isEdit = e.isEdit ? true : false;
      if (!this.isEdit) {
        fileData.id = new Date().getTime();
        fileData.creationTime = new Date();
        fileData.duration = 0;
        fileData.noteContent = '';
      } else {
        if (e.resourcesType == 'recorded') {
          this.activeName = 'recorded';
          this.$nextTick(() => {
            this.$refs.xmlRecordPlayer.setAudioPath(fileData.fileUrl, fileData.duration);
          });
        } else if (e.resourcesType == 'notes') {
          this.activeName = 'notes';
        } else {
          this.activeName = 'resource';
        }
        this.getFileList();
      }
      this.fileData = JSON.parse(JSON.stringify(fileData));
      this.recordedData = JSON.parse(JSON.stringify(fileData));
      this.noteData = JSON.parse(JSON.stringify(fileData));
    },
    setSingleCheckedValue(e, item, value) {
      item.isDownload = [value];
    },
    setSingleCheckedShowValue(e, item, value) {
      item.isStudentShow = [value];
      if (value == 1) {
        // 不显示添加资源
        console.log('不显示添加资源');
      }
    },
    //
    handleBeforeUpload(file) {
      const isPass = file.size / 1024 / 1024 > this.fileSize;
      if (isPass) {
        this.$message.error(`上传文件大小不能超过 ${this.fileSize}MB!`);
        return false;
      }
      let fileType = '';
      let fileExt = file.name.slice(file.name.lastIndexOf('.') + 1).toLowerCase();
      console.log(fileExt);
      if (this.Accept.indexOf('.' + fileExt) === -1) {
        this.$message.error('请上传指定类型文件');
        return false;
      }
      this.loadingInstance = this.$loading({
        lock: true,
        text: 'Loading'
      });
      this.fileData.resourcesName = file.name;
      if (_image.indexOf(fileExt) !== -1) {
        fileType = 'image';
      } else if (_audio.indexOf(fileExt) !== -1) {
        fileType = 'audio';
      } else if (_video.indexOf(fileExt) !== -1) {
        fileType = 'video';
      } else if (_resources.indexOf(fileExt) !== -1) {
        fileType = 'resources';
      } else if (_office.indexOf(fileExt) !== -1) {
        fileType = 'office';
      }
      this.fileData.resourcesType = fileType;
      this.fileData.fileExt = fileExt;
      this.fileData.resourcesName = this.fileData.resourcesName.length > 30 ? this.fileData.resourcesName.slice(0, 30) : this.fileData.resourcesName;
    },
    // 上传成功
    handleSuccess(file, item) {
      item.fileUrl = file.data;
      this.getFileList();
      this.loadingInstance.close();
      console.log(item, 'item'); //有值
      console.log(this.fileData, 'this.fileData1111'); //有值
    },
    getFileList() {
      console.log(this.fileData, 'fileData'); //有值 再次编辑就无值，因为触发了close
      this.fileList = [{
        name: this.fileData.resourcesName,
        url: this.fileData.resourcesType == 'image' ? this.fileData.fileUrl : 'data:image/png;base64, '
      }];
      this.fileList.length > 0 ? this.isSwhoUpload = true : this.isSwhoUpload = false;
    },
    handleRemove(file) {
      this.fileData.fileUrl = '';
      this.fileList = [];
      this.fileList.length > 0 ? this.isSwhoUpload = true : this.isSwhoUpload = false;
      console.log(file);
    },
    handlePictureCardPreview(file) {
      this.fileData.fileUrl = file.url;
      this.dialogVisible = true;
    },
    handleDownload(file) {
      console.log(file);
    },
    submit(type) {
      // if(this.activeName == 'resource' && !this.fileData.fileUrl){
      //   this.$message.error('请上传文件')
      //   return
      // }
      this.$refs[this.activeName + 'RuleForm'].validate(valid => {
        if (valid) {
          if (this.activeName == 'resource') {
            // 添加资源文件
            let fileData = JSON.parse(JSON.stringify(this.fileData)) || {};
            let data = {
              chapterOrderNum: this.chapterOrderNum,
              ...fileData
            };
            data.isDownload = this.fileData.isDownload[0];
            data.isStudentShow = this.fileData.isStudentShow[0];
            // 发送数据
            if (!this.isEdit) {
              this.$emit('addResources', data);
            } else {
              this.$emit('editResources', data);
            }
            setTimeout(() => {
              this.close();
              this.show = false;
            }, 200);
          } else if (this.activeName == 'recorded') {
            // 录音
            if (this.recordedData.duration < 100) {
              this.$message.error('请先录制音频');
              return;
            }
            if (this.recordedBlob) {
              this.addRecorder();
            } else {
              let recordedData = JSON.parse(JSON.stringify(this.recordedData)) || {};
              let data = {
                chapterOrderNum: this.chapterOrderNum,
                ...recordedData
              };
              data.isDownload = this.recordedData.isDownload[0];
              data.isStudentShow = this.recordedData.isStudentShow[0];
              data.resourcesType = 'recorded';
              // 发送数据
              if (!this.isEdit) {
                this.$emit('addResources', data);
              } else {
                this.$emit('editResources', data);
              }
              setTimeout(() => {
                this.close();
                this.show = false;
              }, 800);
            }
          } else if (this.activeName == 'notes') {
            // 教师笔记
            let noteData = JSON.parse(JSON.stringify(this.noteData)) || {};
            let data = {
              chapterOrderNum: this.chapterOrderNum,
              ...noteData
            };
            data.isDownload = this.noteData.isDownload[0];
            data.isStudentShow = this.noteData.isStudentShow[0];
            data.resourcesType = 'notes';
            // 发送数据
            if (!this.isEdit) {
              this.$emit('addTeacherNote', data);
            } else {
              this.$emit('editResources', data);
            }
            setTimeout(() => {
              this.close();
              this.show = false;
            }, 200);
          }

          // if (type === 'continue') {
          //   // 若是点击“保存并继续添加”
          //   // 提示保存成功
          //   this.$message({
          //     message: '保存成功',
          //     type: 'success',
          //     duration: 1500
          //   })

          //   // 清空表单
          //   this.$refs[this.activeName + 'RuleForm'].resetFields()
          //   this.fileData.fileUrl = ''
          //   this.fileList = []
          //   this.isSwhoUpload = false

          //   // 不关闭弹窗
          //   this.show = true
          // } else {
          //   setTimeout(() => {
          //     this.close()
          //     this.show = false
          //   }, 200)
          // }
        }
      });
    },
    close() {
      this.fileData.resourcesName = '';
      this.fileData.isDownload = [0];
      if (this.fileData.resourcesType !== 'image') {
        this.fileData.fileUrl = '';
      }
      this.fileList = [];
      this.show = false;
      // 等待200毫秒，显示添加文件按钮
      setTimeout(() => this.isSwhoUpload = false, 200);
      if (this.activeName == 'recorded') {
        this.$refs.xmlRecordPlayer.destruction();
        this.$refs.xmlRecordPlayer.resetRecorder();
      }
    },
    getresdata({
      blob,
      duration
    }) {
      this.recordedData.duration = duration;
      this.recordedBlob = blob;
    },
    addRecorder() {
      const loading = this.$loading({
        lock: true,
        text: 'Loading'
      });
      let formData = new FormData();
      formData.append('file', this.recordedBlob, new Date().getTime() + '.mp3');
      fetch(this.actionUrl, {
        method: 'post',
        body: formData,
        headers: this.headers
      }).then(data => {
        return data.text();
      }).then(res => {
        let urlData = JSON.parse(res);
        this.recordedData.fileUrl = urlData.data;
        let recordedData = JSON.parse(JSON.stringify(this.recordedData)) || {};
        let data = {
          chapterOrderNum: this.chapterOrderNum,
          ...recordedData
        };
        data.isDownload = this.recordedData.isDownload[0];
        data.isStudentShow = this.recordedData.isStudentShow[0];
        data.resourcesType = 'recorded';
        // 发送数据
        if (!this.isEdit) {
          this.$emit('addResources', data);
        } else {
          this.$emit('editResources', data);
        }
        setTimeout(() => {
          loading.close();
          this.close();
          this.show = false;
        }, 800);
      });
    },
    carriageReturn(event) {
      event.preventDefault(); // 更推荐使用preventDefault来阻止默认行为，适用于现代浏览器
      if (event.keyCode === 13 || event.key === 'Enter' || event.code === 'Enter') {
        this.noteData.noteContent += '\n';
      }
    }
  },
  computed: {
    currentLength() {
      return this.noteData.noteContent.length;
    },
    maxLength() {
      return 1000;
    }
  },
  created() {},
  mounted() {}
};

/* script */
const __vue_script__$1 = script$1;
/* template */
var __vue_render__$1 = function () {
  var _vm = this;
  var _h = _vm.$createElement;
  var _c = _vm._self._c || _h;
  return _c(
    "el-dialog",
    {
      staticClass: "add-teacher-resources-dialog",
      attrs: { "append-to-body": "", visible: _vm.show, width: "665px" },
      on: {
        "update:visible": function ($event) {
          _vm.show = $event;
        },
        close: _vm.close,
      },
    },
    [
      _c("div", { attrs: { slot: "title" }, slot: "title" }, [
        _vm._v(_vm._s(_vm.isEdit ? "编辑" : "添加") + "授课资源"),
      ]),
      _vm._v(" "),
      _c(
        "div",
        [
          _c(
            "el-tabs",
            {
              model: {
                value: _vm.activeName,
                callback: function ($$v) {
                  _vm.activeName = $$v;
                },
                expression: "activeName",
              },
            },
            [
              _c(
                "el-tab-pane",
                {
                  attrs: {
                    disabled: _vm.isEdit,
                    label: "资源上传",
                    name: "resource",
                  },
                },
                [
                  _c(
                    "div",
                    { staticClass: "add-teacher-container" },
                    [
                      _c(
                        "el-form",
                        {
                          ref: "resourceRuleForm",
                          attrs: {
                            "label-position": "left",
                            model: _vm.fileData,
                            rules: _vm.fileRules,
                          },
                        },
                        [
                          _c(
                            "el-form-item",
                            {
                              staticClass: "resouceName addOne",
                              attrs: {
                                "label-width": "96px",
                                label: "资源名称：",
                                prop: "resourcesName",
                              },
                            },
                            [
                              _c("el-input", {
                                staticClass: "inputresource",
                                attrs: { maxlength: "30" },
                                model: {
                                  value: _vm.fileData.resourcesName,
                                  callback: function ($$v) {
                                    _vm.$set(
                                      _vm.fileData,
                                      "resourcesName",
                                      typeof $$v === "string" ? $$v.trim() : $$v
                                    );
                                  },
                                  expression: "fileData.resourcesName",
                                },
                              }),
                            ],
                            1
                          ),
                          _vm._v(" "),
                          _c(
                            "el-form-item",
                            {
                              attrs: {
                                "label-width": "96px",
                                label: "下载设置：",
                                prop: "isDownload",
                              },
                            },
                            [
                              _c(
                                "el-checkbox-group",
                                {
                                  model: {
                                    value: _vm.fileData.isDownload,
                                    callback: function ($$v) {
                                      _vm.$set(_vm.fileData, "isDownload", $$v);
                                    },
                                    expression: "fileData.isDownload",
                                  },
                                },
                                [
                                  _c(
                                    "el-checkbox",
                                    {
                                      attrs: { label: 1 },
                                      on: {
                                        change: function (v) {
                                          return _vm.setSingleCheckedValue(
                                            v,
                                            _vm.fileData,
                                            1
                                          )
                                        },
                                      },
                                    },
                                    [_vm._v("允许学生下载")]
                                  ),
                                  _vm._v(" "),
                                  _c(
                                    "el-checkbox",
                                    {
                                      attrs: { label: 0 },
                                      on: {
                                        change: function (v) {
                                          return _vm.setSingleCheckedValue(
                                            v,
                                            _vm.fileData,
                                            0
                                          )
                                        },
                                      },
                                    },
                                    [_vm._v("不允许学生下载")]
                                  ),
                                ],
                                1
                              ),
                            ],
                            1
                          ),
                          _vm._v(" "),
                          _c(
                            "el-form-item",
                            {
                              attrs: {
                                "label-width": "96px",
                                label: "显示设置：",
                                prop: "isStudentShow",
                              },
                            },
                            [
                              _c(
                                "el-checkbox-group",
                                {
                                  model: {
                                    value: _vm.fileData.isStudentShow,
                                    callback: function ($$v) {
                                      _vm.$set(
                                        _vm.fileData,
                                        "isStudentShow",
                                        $$v
                                      );
                                    },
                                    expression: "fileData.isStudentShow",
                                  },
                                },
                                [
                                  _c(
                                    "el-checkbox",
                                    {
                                      attrs: { label: 0 },
                                      on: {
                                        change: function (v) {
                                          return _vm.setSingleCheckedShowValue(
                                            v,
                                            _vm.fileData,
                                            0
                                          )
                                        },
                                      },
                                    },
                                    [_vm._v("学生可见")]
                                  ),
                                  _vm._v(" "),
                                  _c(
                                    "el-checkbox",
                                    {
                                      attrs: { label: 1 },
                                      on: {
                                        change: function (v) {
                                          return _vm.setSingleCheckedShowValue(
                                            v,
                                            _vm.fileData,
                                            1
                                          )
                                        },
                                      },
                                    },
                                    [_vm._v("学生不可见")]
                                  ),
                                ],
                                1
                              ),
                            ],
                            1
                          ),
                          _vm._v(" "),
                          _c(
                            "el-form-item",
                            { attrs: { label: "文件上传：", prop: "fileUrl" } },
                            [
                              _c(
                                "el-upload",
                                {
                                  staticClass: "upload-demo",
                                  class: _vm.isSwhoUpload ? "disUoloadSty" : "",
                                  attrs: {
                                    action: _vm.actionUrl,
                                    headers: _vm.headers,
                                    data: _vm.data,
                                    "list-type": "picture-card",
                                    multiple: false,
                                    limit: _vm.limit,
                                    "file-list": _vm.fileList,
                                    playMode: "xun-huan",
                                    scheduleControl: "yes",
                                    accept: _vm.Accept,
                                    "on-success": function (e) {
                                      return _vm.handleSuccess(e, _vm.fileData)
                                    },
                                    "before-upload": _vm.handleBeforeUpload,
                                    "on-remove": _vm.handleRemove,
                                  },
                                },
                                [
                                  _c("i", {
                                    staticClass: "el-icon-plus",
                                    attrs: { slot: "default" },
                                    slot: "default",
                                  }),
                                ]
                              ),
                            ],
                            1
                          ),
                        ],
                        1
                      ),
                    ],
                    1
                  ),
                ]
              ),
              _vm._v(" "),
              _c(
                "el-tab-pane",
                {
                  attrs: {
                    disabled: _vm.isEdit,
                    label: "录音",
                    name: "recorded",
                  },
                },
                [
                  _c(
                    "div",
                    { staticClass: "add-teacher-container" },
                    [
                      _c(
                        "el-form",
                        {
                          ref: "recordedRuleForm",
                          attrs: {
                            "label-position": "left",
                            model: _vm.recordedData,
                            rules: _vm.recordedRules,
                          },
                        },
                        [
                          _c("el-form-item", [
                            _c(
                              "div",
                              {
                                staticClass:
                                  "parent-group xml-single-recorder-group",
                              },
                              [
                                _c(
                                  "div",
                                  { staticClass: "xml-recorder-container" },
                                  [
                                    _c(
                                      "div",
                                      {
                                        staticClass: "xml-recorder-player-box",
                                      },
                                      [
                                        _c("record-player", {
                                          ref: "xmlRecordPlayer",
                                          attrs: {
                                            mode: "preview",
                                            loop: false,
                                            "play-mode": "xun-huan",
                                            "play-style": "A",
                                            scheduleControl: "yes",
                                          },
                                          on: { resData: _vm.getresdata },
                                        }),
                                      ],
                                      1
                                    ),
                                  ]
                                ),
                              ]
                            ),
                          ]),
                          _vm._v(" "),
                          _c(
                            "el-form-item",
                            {
                              attrs: {
                                "label-width": "96px",
                                label: "显示设置：",
                                prop: "isStudentShow",
                              },
                            },
                            [
                              _c(
                                "el-checkbox-group",
                                {
                                  model: {
                                    value: _vm.recordedData.isStudentShow,
                                    callback: function ($$v) {
                                      _vm.$set(
                                        _vm.recordedData,
                                        "isStudentShow",
                                        $$v
                                      );
                                    },
                                    expression: "recordedData.isStudentShow",
                                  },
                                },
                                [
                                  _c(
                                    "el-checkbox",
                                    {
                                      attrs: { label: 0 },
                                      on: {
                                        change: function (v) {
                                          return _vm.setSingleCheckedShowValue(
                                            v,
                                            _vm.recordedData,
                                            0
                                          )
                                        },
                                      },
                                    },
                                    [_vm._v("学生可见")]
                                  ),
                                  _vm._v(" "),
                                  _c(
                                    "el-checkbox",
                                    {
                                      attrs: { label: 1 },
                                      on: {
                                        change: function (v) {
                                          return _vm.setSingleCheckedShowValue(
                                            v,
                                            _vm.recordedData,
                                            1
                                          )
                                        },
                                      },
                                    },
                                    [_vm._v("学生不可见")]
                                  ),
                                ],
                                1
                              ),
                            ],
                            1
                          ),
                        ],
                        1
                      ),
                    ],
                    1
                  ),
                ]
              ),
              _vm._v(" "),
              _c(
                "el-tab-pane",
                {
                  attrs: {
                    disabled: _vm.isEdit,
                    label: "教师笔记",
                    name: "notes",
                  },
                },
                [
                  _c(
                    "div",
                    { staticClass: "add-teacher-container" },
                    [
                      _c(
                        "el-form",
                        {
                          ref: "notesRuleForm",
                          attrs: {
                            "label-position": "left",
                            model: _vm.noteData,
                            rules: _vm.noteRules,
                          },
                        },
                        [
                          _c(
                            "el-form-item",
                            {
                              attrs: { label: "笔记内容", prop: "noteContent" },
                            },
                            [
                              _c("el-input", {
                                attrs: {
                                  type: "textarea",
                                  rows: 6,
                                  placeholder: "请输入内容",
                                  maxlength: "1000",
                                },
                                nativeOn: {
                                  keydown: function ($event) {
                                    if (
                                      !$event.type.indexOf("key") &&
                                      _vm._k(
                                        $event.keyCode,
                                        "enter",
                                        13,
                                        $event.key,
                                        "Enter"
                                      )
                                    ) {
                                      return null
                                    }
                                    return _vm.carriageReturn($event)
                                  },
                                },
                                model: {
                                  value: _vm.noteData.noteContent,
                                  callback: function ($$v) {
                                    _vm.$set(
                                      _vm.noteData,
                                      "noteContent",
                                      typeof $$v === "string" ? $$v.trim() : $$v
                                    );
                                  },
                                  expression: "noteData.noteContent",
                                },
                              }),
                              _vm._v(" "),
                              _c("span", { staticClass: "character-count" }, [
                                _vm._v(
                                  _vm._s(_vm.currentLength) +
                                    " / " +
                                    _vm._s(_vm.maxLength)
                                ),
                              ]),
                            ],
                            1
                          ),
                          _vm._v(" "),
                          _c(
                            "el-form-item",
                            {
                              attrs: {
                                "label-width": "96px",
                                label: "显示设置",
                                prop: "isStudentShow",
                              },
                            },
                            [
                              _c(
                                "el-checkbox-group",
                                {
                                  model: {
                                    value: _vm.noteData.isStudentShow,
                                    callback: function ($$v) {
                                      _vm.$set(
                                        _vm.noteData,
                                        "isStudentShow",
                                        $$v
                                      );
                                    },
                                    expression: "noteData.isStudentShow",
                                  },
                                },
                                [
                                  _c(
                                    "el-checkbox",
                                    {
                                      attrs: { label: 0 },
                                      on: {
                                        change: function (v) {
                                          return _vm.setSingleCheckedShowValue(
                                            v,
                                            _vm.noteData,
                                            0
                                          )
                                        },
                                      },
                                    },
                                    [_vm._v("学生可见")]
                                  ),
                                  _vm._v(" "),
                                  _c(
                                    "el-checkbox",
                                    {
                                      attrs: { label: 1 },
                                      on: {
                                        change: function (v) {
                                          return _vm.setSingleCheckedShowValue(
                                            v,
                                            _vm.noteData,
                                            1
                                          )
                                        },
                                      },
                                    },
                                    [_vm._v("学生不可见")]
                                  ),
                                ],
                                1
                              ),
                            ],
                            1
                          ),
                        ],
                        1
                      ),
                    ],
                    1
                  ),
                ]
              ),
            ],
            1
          ),
          _vm._v(" "),
          _c(
            "div",
            { staticClass: "bottom" },
            [
              _c(
                "el-button",
                {
                  attrs: { size: "small" },
                  on: {
                    click: function ($event) {
                      return _vm.close()
                    },
                  },
                },
                [_vm._v("取消")]
              ),
              _vm._v(" "),
              _c(
                "el-button",
                {
                  attrs: { size: "small", type: "primary" },
                  on: {
                    click: function ($event) {
                      return _vm.submit("")
                    },
                  },
                },
                [_vm._v("确认")]
              ),
            ],
            1
          ),
        ],
        1
      ),
    ]
  )
};
var __vue_staticRenderFns__$1 = [];
__vue_render__$1._withStripped = true;

  /* style */
  const __vue_inject_styles__$1 = undefined;
  /* scoped */
  const __vue_scope_id__$1 = undefined;
  /* module identifier */
  const __vue_module_identifier__$1 = undefined;
  /* functional template */
  const __vue_is_functional_template__$1 = false;
  /* style inject */
  
  /* style inject SSR */
  
  /* style inject shadow dom */
  

  
  const __vue_component__$1 = /*#__PURE__*/normalizeComponent(
    { render: __vue_render__$1, staticRenderFns: __vue_staticRenderFns__$1 },
    __vue_inject_styles__$1,
    __vue_script__$1,
    __vue_scope_id__$1,
    __vue_is_functional_template__$1,
    __vue_module_identifier__$1,
    false,
    undefined,
    undefined,
    undefined
  );

var setupDefaults = {
  cookies: {
    path: '/'
  },
  treeOptions: {
    parentKey: 'parentId',
    key: 'id',
    children: 'children'
  },
  parseDateFormat: 'yyyy-MM-dd HH:mm:ss',
  firstDayOfWeek: 1
};
var setupDefaults_1 = setupDefaults;

function arrayEach(list, iterate, context) {
  if (list) {
    if (list.forEach) {
      list.forEach(iterate, context);
    } else {
      for (var index = 0, len = list.length; index < len; index++) {
        iterate.call(context, list[index], index, list);
      }
    }
  }
}
var arrayEach_1 = arrayEach;

var objectToString = Object.prototype.toString;
var staticObjectToString = objectToString;

function helperCreateInInObjectString(type) {
  return function (obj) {
    return '[object ' + type + ']' === staticObjectToString.call(obj);
  };
}
var helperCreateInInObjectString_1 = helperCreateInInObjectString;

/**
  * 判断是否数组
  *
  * @param {Object} obj 对象
  * @return {Boolean}
  */
var isArray = Array.isArray || helperCreateInInObjectString_1('Array');
var isArray_1 = isArray;

/**
  * 判断对象自身属性中是否具有指定的属性
  *
  * @param {Object} obj 对象
  * @param {String/Number} key 键值
  * @return {Boolean}
  */
function hasOwnProp(obj, key) {
  return obj && obj.hasOwnProperty ? obj.hasOwnProperty(key) : false;
}
var hasOwnProp_1 = hasOwnProp;

function objectEach(obj, iterate, context) {
  if (obj) {
    for (var key in obj) {
      if (hasOwnProp_1(obj, key)) {
        iterate.call(context, obj[key], key, obj);
      }
    }
  }
}
var objectEach_1 = objectEach;

/**
  * 迭代器
  *
  * @param {Object} obj 对象/数组
  * @param {Function} iterate(item, index, obj) 回调
  * @param {Object} context 上下文
  * @return {Object}
  */
function each(obj, iterate, context) {
  if (obj) {
    return (isArray_1(obj) ? arrayEach_1 : objectEach_1)(obj, iterate, context);
  }
  return obj;
}
var each_1 = each;

/* eslint-disable valid-typeof */
function helperCreateInTypeof(type) {
  return function (obj) {
    return typeof obj === type;
  };
}
var helperCreateInTypeof_1 = helperCreateInTypeof;

/**
  * 判断是否方法
  *
  * @param {Object} obj 对象
  * @return {Boolean}
  */
var isFunction$1 = helperCreateInTypeof_1('function');
var isFunction_1 = isFunction$1;

function helperCreateGetObjects(name, getIndex) {
  var proMethod = Object[name];
  return function (obj) {
    var result = [];
    if (obj) {
      if (proMethod) {
        return proMethod(obj);
      }
      each_1(obj, getIndex > 1 ? function (key) {
        result.push(['' + key, obj[key]]);
      } : function () {
        result.push(arguments[getIndex]);
      });
    }
    return result;
  };
}
var helperCreateGetObjects_1 = helperCreateGetObjects;

/**
  * 获取对象所有属性
  *
  * @param {Object} obj 对象/数组
  * @return {Array}
  */
var keys = helperCreateGetObjects_1('keys', 1);
var keys_1 = keys;

function getCativeCtor(val, args) {
  var Ctor = val.__proto__.constructor;
  return args ? new Ctor(args) : new Ctor();
}
function handleValueClone(item, isDeep) {
  return isDeep ? copyValue(item, isDeep) : item;
}
function copyValue(val, isDeep) {
  if (val) {
    switch (staticObjectToString.call(val)) {
      case "[object Object]":
        {
          var restObj = Object.create(Object.getPrototypeOf(val));
          objectEach_1(val, function (item, key) {
            restObj[key] = handleValueClone(item, isDeep);
          });
          return restObj;
        }
      case "[object Date]":
      case "[object RegExp]":
        {
          return getCativeCtor(val, val.valueOf());
        }
      case "[object Array]":
      case "[object Arguments]":
        {
          var restArr = [];
          arrayEach_1(val, function (item) {
            restArr.push(handleValueClone(item, isDeep));
          });
          return restArr;
        }
      case "[object Set]":
        {
          var restSet = getCativeCtor(val);
          restSet.forEach(function (item) {
            restSet.add(handleValueClone(item, isDeep));
          });
          return restSet;
        }
      case "[object Map]":
        {
          var restMap = getCativeCtor(val);
          restMap.forEach(function (item, key) {
            restMap.set(key, handleValueClone(item, isDeep));
          });
          return restMap;
        }
    }
  }
  return val;
}

/**
  * 浅拷贝/深拷贝
  *
  * @param {Object} obj 对象/数组
  * @param {Boolean} deep 是否深拷贝
  * @return {Object}
  */
function clone(obj, deep) {
  if (obj) {
    return copyValue(obj, deep);
  }
  return obj;
}
var clone_1 = clone;

var objectAssignFns = Object.assign;
function handleAssign(destination, args, isClone) {
  var len = args.length;
  for (var source, index = 1; index < len; index++) {
    source = args[index];
    arrayEach_1(keys_1(args[index]), isClone ? function (key) {
      destination[key] = clone_1(source[key], isClone);
    } : function (key) {
      destination[key] = source[key];
    });
  }
  return destination;
}

/**
  * 将一个或多个源对象复制到目标对象中
  *
  * @param {Object} target 目标对象
  * @param {...Object}
  * @return {Boolean}
  */
var assign = function (target) {
  if (target) {
    var args = arguments;
    if (target === true) {
      if (args.length > 1) {
        target = isArray_1(target[1]) ? [] : {};
        return handleAssign(target, args, true);
      }
    } else {
      return objectAssignFns ? objectAssignFns.apply(Object, args) : handleAssign(target, args);
    }
  }
  return target;
};
var assign_1 = assign;

var XEUtils = function () {};
function mixin() {
  arrayEach_1(arguments, function (methods) {
    each_1(methods, function (fn, name) {
      XEUtils[name] = isFunction_1(fn) ? function () {
        var result = fn.apply(XEUtils.$context, arguments);
        XEUtils.$context = null;
        return result;
      } : fn;
    });
  });
}
function setup(options) {
  return assign_1(setupDefaults_1, options);
}
XEUtils.VERSION = '3.5.25';
XEUtils.mixin = mixin;
XEUtils.setup = setup;
var ctor = XEUtils;

function lastArrayEach(obj, iterate, context) {
  for (var len = obj.length - 1; len >= 0; len--) {
    iterate.call(context, obj[len], len, obj);
  }
}
var lastArrayEach_1 = lastArrayEach;

function lastObjectEach(obj, iterate, context) {
  lastArrayEach_1(keys_1(obj), function (key) {
    iterate.call(context, obj[key], key, obj);
  });
}
var lastObjectEach_1 = lastObjectEach;

/**
  * 判断是否为Null
  *
  * @param {Object} obj 对象
  * @return {Boolean}
  */
function isNull(obj) {
  return obj === null;
}
var isNull_1 = isNull;

/**
 * 返回一个获取对象属性的函数
 *
 * @param {String} name 属性名
 * @param {Object} defs 空值
 */
function property(name, defs) {
  return function (obj) {
    return isNull_1(obj) ? defs : obj[name];
  };
}
var property_1 = property;

/**
  * 指定方法后的返回值组成的新对象
  *
  * @param {Object} obj 对象/数组
  * @param {Function} iterate(item, index, obj) 回调
  * @param {Object} context 上下文
  * @return {Object}
  */
function objectMap(obj, iterate, context) {
  var result = {};
  if (obj) {
    if (iterate) {
      if (!isFunction_1(iterate)) {
        iterate = property_1(iterate);
      }
      each_1(obj, function (val, index) {
        result[index] = iterate.call(context, val, index, obj);
      });
    } else {
      return obj;
    }
  }
  return result;
}
var objectMap_1 = objectMap;

/**
  * 判断是否对象
  *
  * @param {Object} obj 对象
  * @return {Boolean}
  */
function isPlainObject(obj) {
  return obj ? obj.constructor === Object : false;
}
var isPlainObject_1 = isPlainObject;

function handleMerge(target, source) {
  if (isPlainObject_1(target) && isPlainObject_1(source) || isArray_1(target) && isArray_1(source)) {
    each_1(source, function (obj, key) {
      target[key] = handleMerge(target[key], obj);
    });
    return target;
  }
  return source;
}

/**
  * 将一个或多个源对象合并到目标对象中
  *
  * @param {Object} target 目标对象
  * @param {...Object}
  * @return {Boolean}
  */
var merge = function (target) {
  if (!target) {
    target = {};
  }
  var args = arguments;
  var len = args.length;
  for (var source, index = 1; index < len; index++) {
    source = args[index];
    if (source) {
      handleMerge(target, source);
    }
  }
  return target;
};
var merge_1 = merge;

/**
  * 指定方法后的返回值组成的新数组
  *
  * @param {Object} obj 对象/数组
  * @param {Function} iterate(item, index, obj) 回调
  * @param {Object} context 上下文
  * @return {Array}
  */
function map(obj, iterate, context) {
  var result = [];
  if (obj && arguments.length > 1) {
    if (obj.map) {
      return obj.map(iterate, context);
    } else {
      each_1(obj, function () {
        result.push(iterate.apply(context, arguments));
      });
    }
  }
  return result;
}
var map_1 = map;

function helperCreateIterateHandle(prop, useArray, restIndex, matchValue, defaultValue) {
  return function (obj, iterate, context) {
    if (obj && iterate) {
      if (prop && obj[prop]) {
        return obj[prop](iterate, context);
      } else {
        if (useArray && isArray_1(obj)) {
          for (var index = 0, len = obj.length; index < len; index++) {
            if (!!iterate.call(context, obj[index], index, obj) === matchValue) {
              return [true, false, index, obj[index]][restIndex];
            }
          }
        } else {
          for (var key in obj) {
            if (hasOwnProp_1(obj, key)) {
              if (!!iterate.call(context, obj[key], key, obj) === matchValue) {
                return [true, false, key, obj[key]][restIndex];
              }
            }
          }
        }
      }
    }
    return defaultValue;
  };
}
var helperCreateIterateHandle_1 = helperCreateIterateHandle;

/**
  * 对象中的值中的每一项运行给定函数,如果函数对任一项返回true,则返回true,否则返回false
  *
  * @param {Object} obj 对象/数组
  * @param {Function} iterate(item, index, obj) 回调
  * @param {Object} context 上下文
  * @return {Boolean}
  */
var some = helperCreateIterateHandle_1('some', 1, 0, true, false);
var some_1 = some;

/**
  * 对象中的值中的每一项运行给定函数,如果该函数对每一项都返回true,则返回true,否则返回false
  *
  * @param {Object} obj 对象/数组
  * @param {Function} iterate(item, index, obj) 回调
  * @param {Object} context 上下文
  * @return {Boolean}
  */
var every = helperCreateIterateHandle_1('every', 1, 1, false, true);
var every_1 = every;

/**
  * 判断对象是否包含该值,成功返回true否则false
  *
  * @param {Object} obj 对象
  * @param {Object} val 值
  * @return {Boolean}
  */
function includes(obj, val) {
  if (obj) {
    if (obj.includes) {
      return obj.includes(val);
    }
    for (var key in obj) {
      if (hasOwnProp_1(obj, key)) {
        if (val === obj[key]) {
          return true;
        }
      }
    }
  }
  return false;
}
var includes_1 = includes;

/**
  * 判断数组是否包含另一数组
  *
  * @param {Array} array1 数组
  * @param {Array} array2 被包含数组
  * @return {Boolean}
  */
function includeArrays(array1, array2) {
  var len;
  var index = 0;
  if (isArray_1(array1) && isArray_1(array2)) {
    for (len = array2.length; index < len; index++) {
      if (!includes_1(array1, array2[index])) {
        return false;
      }
    }
    return true;
  }
  return includes_1(array1, array2);
}
var includeArrays_1 = includeArrays;

/**
 * 数组去重
 * 
 * @param {*} array  数组
 * @param {*} iterate 字段或回调
 * @param {*} context 
 * @returns 
 */
function uniq(array, iterate, context) {
  var result = [];
  if (iterate) {
    if (!isFunction_1(iterate)) {
      iterate = property_1(iterate);
    }
    var val,
      valMap = {};
    each_1(array, function (item, key) {
      val = iterate.call(context, item, key, array);
      if (!valMap[val]) {
        valMap[val] = 1;
        result.push(item);
      }
    });
  } else {
    each_1(array, function (value) {
      if (!includes_1(result, value)) {
        result.push(value);
      }
    });
  }
  return result;
}
var uniq_1 = uniq;

/**
 * 将对象或者伪数组转为新数组
 *
 * @param {Array} list 数组
 * @return {Array}
 */
function toArray$1(list) {
  return map_1(list, function (item) {
    return item;
  });
}
var toArray_1 = toArray$1;

/**
  * 将多个数的值返回唯一的并集数组
  *
  * @param {...Array} 数组
  * @return {Array}
  */
function union() {
  var args = arguments;
  var result = [];
  var index = 0;
  var len = args.length;
  for (; index < len; index++) {
    result = result.concat(toArray_1(args[index]));
  }
  return uniq_1(result);
}
var union_1 = union;

var staticStrUndefined = 'undefined';
var staticStrUndefined_1 = staticStrUndefined;

/**
  * 判断是否Undefined
  *
  * @param {Object} obj 对象
  * @return {Boolean}
  */
var isUndefined = helperCreateInTypeof_1(staticStrUndefined_1);
var isUndefined_1 = isUndefined;

/**
 * 判断是否 undefined 和 null
 * @param {Object} obj 对象
 * @return {Boolean}
 */
function eqNull(obj) {
  return isNull_1(obj) || isUndefined_1(obj);
}
var eqNull_1 = eqNull;

var staticHGKeyRE = /(.+)?\[(\d+)\]$/;
var staticHGKeyRE_1 = staticHGKeyRE;

function helperGetHGSKeys(property) {
  // 以最快的方式判断数组，可忽略准确性
  return property ? property.splice && property.join ? property : ('' + property).replace(/(\[\d+\])\.?/g, '$1.').replace(/\.$/, '').split('.') : [];
}
var helperGetHGSKeys_1 = helperGetHGSKeys;

/**
 * 获取对象的属性的值，如果值为 undefined，则返回默认值
 * @param {Object/Array} obj 对象
 * @param {String/Function} property 键、路径
 * @param {Object} defaultValue 默认值
 * @return {Object}
 */
function get$1(obj, property, defaultValue) {
  if (eqNull_1(obj)) {
    return defaultValue;
  }
  var result = getValueByPath(obj, property);
  return isUndefined_1(result) ? defaultValue : result;
}
function getDeepProps(obj, key) {
  var matchs = key ? key.match(staticHGKeyRE_1) : '';
  return matchs ? matchs[1] ? obj[matchs[1]] ? obj[matchs[1]][matchs[2]] : undefined : obj[matchs[2]] : obj[key];
}
function getValueByPath(obj, property) {
  if (obj) {
    var rest, props, len;
    var index = 0;
    if (obj[property] || hasOwnProp_1(obj, property)) {
      return obj[property];
    } else {
      props = helperGetHGSKeys_1(property);
      len = props.length;
      if (len) {
        for (rest = obj; index < len; index++) {
          rest = getDeepProps(rest, props[index]);
          if (eqNull_1(rest)) {
            if (index === len - 1) {
              return rest;
            }
            return;
          }
        }
      }
      return rest;
    }
  }
}
var get_1 = get$1;

var ORDER_PROP_ASC = 'asc';
var ORDER_PROP_DESC = 'desc';

// function handleSort (v1, v2) {
//   return v1 > v2 ? 1 : -1
// }

// '' < 数字 < 字符 < null < undefined
function handleSort(v1, v2) {
  if (isUndefined_1(v1)) {
    return 1;
  }
  if (isNull_1(v1)) {
    return isUndefined_1(v2) ? -1 : 1;
  }
  return v1 && v1.localeCompare ? v1.localeCompare(v2) : v1 > v2 ? 1 : -1;
}
function buildMultiOrders(name, confs, compares) {
  return function (item1, item2) {
    var v1 = item1[name];
    var v2 = item2[name];
    if (v1 === v2) {
      return compares ? compares(item1, item2) : 0;
    }
    return confs.order === ORDER_PROP_DESC ? handleSort(v2, v1) : handleSort(v1, v2);
  };
}
function getSortConfs(arr, list, fieldConfs, context) {
  var sortConfs = [];
  fieldConfs = isArray_1(fieldConfs) ? fieldConfs : [fieldConfs];
  arrayEach_1(fieldConfs, function (handle, index) {
    if (handle) {
      var field = handle;
      var order;
      if (isArray_1(handle)) {
        field = handle[0];
        order = handle[1];
      } else if (isPlainObject_1(handle)) {
        field = handle.field;
        order = handle.order;
      }
      sortConfs.push({
        field: field,
        order: order || ORDER_PROP_ASC
      });
      arrayEach_1(list, isFunction_1(field) ? function (item, key) {
        item[index] = field.call(context, item.data, key, arr);
      } : function (item) {
        item[index] = field ? get_1(item.data, field) : item.data;
      });
    }
  });
  return sortConfs;
}

/**
  * 将数组进行排序
  *
  * @param {Array} arr 数组
  * @param {Function/String/Array} fieldConfs 方法或属性
  * @param {Object} context 上下文
  * @return {Array}
  */
function orderBy(arr, fieldConfs, context) {
  if (arr) {
    if (eqNull_1(fieldConfs)) {
      return toArray_1(arr).sort(handleSort);
    }
    var compares;
    var list = map_1(arr, function (item) {
      return {
        data: item
      };
    });
    var sortConfs = getSortConfs(arr, list, fieldConfs, context);
    var len = sortConfs.length - 1;
    while (len >= 0) {
      compares = buildMultiOrders(len, sortConfs[len], compares);
      len--;
    }
    if (compares) {
      list = list.sort(compares);
    }
    return map_1(list, property_1('data'));
  }
  return [];
}
var orderBy_1 = orderBy;

var sortBy = orderBy_1;
var sortBy_1 = sortBy;

/**
  * 获取一个指定范围内随机数
  *
  * @param {Number} minVal 最小值
  * @param {Number} maxVal 最大值
  * @return {Number}
  */
function random(minVal, maxVal) {
  return minVal >= maxVal ? minVal : (minVal = minVal >> 0) + Math.round(Math.random() * ((maxVal || 9) - minVal));
}
var random_1 = random;

/**
  * 获取对象所有值
  *
  * @param {Object} obj 对象/数组
  * @return {Array}
  */
var values = helperCreateGetObjects_1('values', 0);
var values_1 = values;

/**
  * 将一个数组随机打乱，返回一个新的数组
  *
  * @param {Array} array 数组
  * @return {Array}
  */
function shuffle(array) {
  var index;
  var result = [];
  var list = values_1(array);
  var len = list.length - 1;
  for (; len >= 0; len--) {
    index = len > 0 ? random_1(0, len) : 0;
    result.push(list[index]);
    list.splice(index, 1);
  }
  return result;
}
var shuffle_1 = shuffle;

/**
  * 从一个数组中随机返回几个元素
  *
  * @param {Array} array 数组
  * @param {Number} number 个数
  * @return {Array}
  */
function sample(array, number) {
  var result = shuffle_1(array);
  if (arguments.length <= 1) {
    return result[0];
  }
  if (number < result.length) {
    result.length = number || 0;
  }
  return result;
}
var sample_1 = sample;

function helperCreateToNumber(handle) {
  return function (str) {
    if (str) {
      var num = handle(str && str.replace ? str.replace(/,/g, '') : str);
      if (!isNaN(num)) {
        return num;
      }
    }
    return 0;
  };
}
var helperCreateToNumber_1 = helperCreateToNumber;

/**
 * 转数值
 * @param { String/Number } str 数值
 *
 * @return {Number}
 */
var toNumber = helperCreateToNumber_1(parseFloat);
var toNumber_1 = toNumber;

/**
 * 裁剪 Arguments 或数组 array，从 start 位置开始到 end 结束，但不包括 end 本身的位置
 * @param {Array/Arguments} array 数组或Arguments
 * @param {Number} startIndex 开始索引
 * @param {Number} endIndex 结束索引
 */
function slice(array, startIndex, endIndex) {
  var result = [];
  var argsSize = arguments.length;
  if (array) {
    startIndex = argsSize >= 2 ? toNumber_1(startIndex) : 0;
    endIndex = argsSize >= 3 ? toNumber_1(endIndex) : array.length;
    if (array.slice) {
      return array.slice(startIndex, endIndex);
    }
    for (; startIndex < endIndex; startIndex++) {
      result.push(array[startIndex]);
    }
  }
  return result;
}
var slice_1 = slice;

/**
  * 根据回调过滤数据
  *
  * @param {Object} obj 对象/数组
  * @param {Function} iterate(item, index, obj) 回调
  * @param {Object} context 上下文
  * @return {Object}
  */
function filter(obj, iterate, context) {
  var result = [];
  if (obj && iterate) {
    if (obj.filter) {
      return obj.filter(iterate, context);
    }
    each_1(obj, function (val, key) {
      if (iterate.call(context, val, key, obj)) {
        result.push(val);
      }
    });
  }
  return result;
}
var filter_1 = filter;

/**
  * 查找匹配第一条数据的键
  *
  * @param {Object} obj 对象/数组
  * @param {Function} iterate(item, index, obj) 回调
  * @param {Object} context 上下文
  * @return {Object}
  */
var findKey = helperCreateIterateHandle_1('', 0, 2, true);
var findKey_1 = findKey;

/**
  * 从左至右遍历，匹配最近的一条数据
  *
  * @param {Object} obj 对象/数组
  * @param {Function} iterate(item, index, obj) 回调
  * @param {Object} context 上下文
  * @return {Object}
  */
var find = helperCreateIterateHandle_1('find', 1, 3, true);
var find_1 = find;

/**
  * 从右至左遍历，匹配最近的一条数据
  *
  * @param {Object} obj 对象/数组
  * @param {Function} iterate(item, index, obj) 回调
  * @param {Object} context 上下文
  * @return {Object}
  */
function findLast(obj, iterate, context) {
  if (obj) {
    if (!isArray_1(obj)) {
      obj = values_1(obj);
    }
    for (var len = obj.length - 1; len >= 0; len--) {
      if (iterate.call(context, obj[len], len, obj)) {
        return obj[len];
      }
    }
  }
}
var findLast_1 = findLast;

/**
  * 接收一个函数作为累加器，数组中的每个值（从左到右）开始合并，最终为一个值。
  *
  * @param {Array} array 数组
  * @param {Function} callback 方法
  * @param {Object} initialValue 初始值
  * @return {Number}
  */
function reduce(array, callback, initialValue) {
  if (array) {
    var len, reduceMethod;
    var index = 0;
    var context = null;
    var previous = initialValue;
    var isInitialVal = arguments.length > 2;
    var keyList = keys_1(array);
    if (array.length && array.reduce) {
      reduceMethod = function () {
        return callback.apply(context, arguments);
      };
      if (isInitialVal) {
        return array.reduce(reduceMethod, previous);
      }
      return array.reduce(reduceMethod);
    }
    if (isInitialVal) {
      index = 1;
      previous = array[keyList[0]];
    }
    for (len = keyList.length; index < len; index++) {
      previous = callback.call(context, previous, array[keyList[index]], index, array);
    }
    return previous;
  }
}
var reduce_1 = reduce;

/**
  * 浅复制数组的一部分到同一数组中的另一个位置,数组大小不变
  *
  * @param {Array} array 数组
  * @param {Number} target 从该位置开始替换数据
  * @param {Number} start 从该位置开始读取数据，默认为 0 。如果为负值，表示倒数
  * @param {Number} end 到该位置前停止读取数据，默认等于数组长度。如果为负值，表示倒数
  * @return {Array}
  */
function copyWithin(array, target, start, end) {
  if (isArray_1(array) && array.copyWithin) {
    return array.copyWithin(target, start, end);
  }
  var replaceIndex, replaceArray;
  var targetIndex = target >> 0;
  var startIndex = start >> 0;
  var len = array.length;
  var endIndex = arguments.length > 3 ? end >> 0 : len;
  if (targetIndex < len) {
    targetIndex = targetIndex >= 0 ? targetIndex : len + targetIndex;
    if (targetIndex >= 0) {
      startIndex = startIndex >= 0 ? startIndex : len + startIndex;
      endIndex = endIndex >= 0 ? endIndex : len + endIndex;
      if (startIndex < endIndex) {
        for (replaceIndex = 0, replaceArray = array.slice(startIndex, endIndex); targetIndex < len; targetIndex++) {
          if (replaceArray.length <= replaceIndex) {
            break;
          }
          array[targetIndex] = replaceArray[replaceIndex++];
        }
      }
    }
  }
  return array;
}
var copyWithin_1 = copyWithin;

/**
  * 将一个数组分割成大小的组。如果数组不能被平均分配，那么最后一块将是剩下的元素
  *
  * @param {Array} array 数组
  * @param {Number} size 每组大小
  * @return {Array}
  */
function chunk(array, size) {
  var index;
  var result = [];
  var arrLen = size >> 0 || 1;
  if (isArray_1(array)) {
    if (arrLen >= 0 && array.length > arrLen) {
      index = 0;
      while (index < array.length) {
        result.push(array.slice(index, index + arrLen));
        index += arrLen;
      }
    } else {
      result = array.length ? [array] : array;
    }
  }
  return result;
}
var chunk_1 = chunk;

/**
  * 获取数组对象中某属性值，返回一个数组
  *
  * @param {Array} array 数组
  * @param {String} key 属性值
  * @return {Array}
  */
function pluck(obj, key) {
  return map_1(obj, property_1(key));
}
var pluck_1 = pluck;

function helperCreateMinMax(handle) {
  return function (arr, iterate) {
    if (arr && arr.length) {
      var rest, itemIndex;
      arrayEach_1(arr, function (itemVal, index) {
        if (iterate) {
          itemVal = isFunction_1(iterate) ? iterate(itemVal, index, arr) : get_1(itemVal, iterate);
        }
        if (!eqNull_1(itemVal) && (eqNull_1(rest) || handle(rest, itemVal))) {
          itemIndex = index;
          rest = itemVal;
        }
      });
      return arr[itemIndex];
    }
    return rest;
  };
}
var helperCreateMinMax_1 = helperCreateMinMax;

/**
  * 获取最大值
  *
  * @param {Array} arr 数组
  * @param {Function} iterate(item, index, obj) 回调
  * @return {Number}
  */
var max$1 = helperCreateMinMax_1(function (rest, itemVal) {
  return rest < itemVal;
});
var max_1 = max$1;

/**
 * 与 zip 相反
 *
 * @param {Array} arrays 数组集合
 */
function unzip(arrays) {
  var index, maxItem, len;
  var result = [];
  if (arrays && arrays.length) {
    index = 0;
    maxItem = max_1(arrays, function (item) {
      return item ? item.length : 0;
    });
    for (len = maxItem ? maxItem.length : 0; index < len; index++) {
      result.push(pluck_1(arrays, index));
    }
  }
  return result;
}
var unzip_1 = unzip;

/**
 * 将每个数组中相应位置的值合并在一起
 *
 * @param {Array*} array 数组
 */
function zip() {
  return unzip_1(arguments);
}
var zip_1 = zip;

/**
 * 根据键数组、值数组对转换为对象
 *
 * @param {Array} props 键数组
 * @param {Number} arr 值数组
 * @return {Object}
 */
function zipObject(props, arr) {
  var result = {};
  arr = arr || [];
  each_1(values_1(props), function (val, key) {
    result[val] = arr[key];
  });
  return result;
}
var zipObject_1 = zipObject;

function flattenDeep(array, deep) {
  var result = [];
  arrayEach_1(array, function (vals) {
    result = result.concat(isArray_1(vals) ? deep ? flattenDeep(vals, deep) : vals : [vals]);
  });
  return result;
}

/**
  * 将一个多维数组铺平
  * @param {Array} array 数组
  * @param {Boolean} deep 是否深层
  * @return {Array}
  */
function flatten(array, deep) {
  if (isArray_1(array)) {
    return flattenDeep(array, deep);
  }
  return [];
}
var flatten_1 = flatten;

function deepGetObj(obj, path) {
  var index = 0;
  var len = path.length;
  while (obj && index < len) {
    obj = obj[path[index++]];
  }
  return len && obj ? obj : 0;
}

/**
 * 在list的每个元素上执行方法,任何传递的额外参数都会在调用方法的时候传递给它
 *
 * @param {Array} list
 * @param {Array/String/Function} path
 * @param {...Object} arguments
 * @return {Array}
 */
function invoke(list, path) {
  var func;
  var args = arguments;
  var params = [];
  var paths = [];
  var index = 2;
  var len = args.length;
  for (; index < len; index++) {
    params.push(args[index]);
  }
  if (isArray_1(path)) {
    len = path.length - 1;
    for (index = 0; index < len; index++) {
      paths.push(path[index]);
    }
    path = path[len];
  }
  return map_1(list, function (context) {
    if (paths.length) {
      context = deepGetObj(context, paths);
    }
    func = context[path] || path;
    if (func && func.apply) {
      return func.apply(context, params);
    }
  });
}
var invoke_1 = invoke;

function helperDeleteProperty(obj, property) {
  try {
    delete obj[property];
  } catch (e) {
    obj[property] = undefined;
  }
}
var helperDeleteProperty_1 = helperDeleteProperty;

/**
  * 迭代器,从最后开始迭代
  *
  * @param {Object} obj 对象/数组
  * @param {Function} iterate(item, index, obj) 回调
  * @param {Object} context 上下文
  * @return {Object}
  */
function lastEach(obj, iterate, context) {
  if (obj) {
    return (isArray_1(obj) ? lastArrayEach_1 : lastObjectEach_1)(obj, iterate, context);
  }
  return obj;
}
var lastEach_1 = lastEach;

/**
  * 判断是否Object对象
  *
  * @param {Object} obj 对象
  * @return {Boolean}
  */
var isObject$1 = helperCreateInTypeof_1('object');
var isObject_1 = isObject$1;

/**
  * 清空对象
  *
  * @param {Object} obj 对象
  * @param {*} defs 默认值,如果不传（清空所有属性）、如果传对象（清空并继承)、如果传值(给所有赋值)
  * @param {Object/Array} assigns 默认值
  * @return {Object}
  */
function clear(obj, defs, assigns) {
  if (obj) {
    var len;
    var isDefs = arguments.length > 1 && (isNull_1(defs) || !isObject_1(defs));
    var extds = isDefs ? assigns : defs;
    if (isPlainObject_1(obj)) {
      objectEach_1(obj, isDefs ? function (val, key) {
        obj[key] = defs;
      } : function (val, key) {
        helperDeleteProperty_1(obj, key);
      });
      if (extds) {
        assign_1(obj, extds);
      }
    } else if (isArray_1(obj)) {
      if (isDefs) {
        len = obj.length;
        while (len > 0) {
          len--;
          obj[len] = defs;
        }
      } else {
        obj.length = 0;
      }
      if (extds) {
        obj.push.apply(obj, extds);
      }
    }
  }
  return obj;
}
var clear_1 = clear;

function pluckProperty(name) {
  return function (obj, key) {
    return key === name;
  };
}

/**
  * 移除对象属性
  *
  * @param {Object/Array} obj 对象/数组
  * @param {Function/String} iterate 方法或属性
  * @param {Object} context 上下文
  * @return {Object/Array}
  */
function remove(obj, iterate, context) {
  if (obj) {
    if (!eqNull_1(iterate)) {
      var removeKeys = [];
      var rest = [];
      if (!isFunction_1(iterate)) {
        iterate = pluckProperty(iterate);
      }
      each_1(obj, function (item, index, rest) {
        if (iterate.call(context, item, index, rest)) {
          removeKeys.push(index);
        }
      });
      if (isArray_1(obj)) {
        lastEach_1(removeKeys, function (item, key) {
          rest.push(obj[item]);
          obj.splice(item, 1);
        });
      } else {
        rest = {};
        arrayEach_1(removeKeys, function (key) {
          rest[key] = obj[key];
          helperDeleteProperty_1(obj, key);
        });
      }
      return rest;
    }
    return clear_1(obj);
  }
  return obj;
}
var remove_1 = remove;

function strictTree(array, optChildren) {
  each_1(array, function (item) {
    if (item[optChildren] && !item[optChildren].length) {
      remove_1(item, optChildren);
    }
  });
}

/**
  * 将一个带层级的数据列表转成树结构
  *
  * @param {Array} array 数组
  * @param {Object} options {strict: false, parentKey: 'parentId', key: 'id', children: 'children', mapChildren: 'children', data: 'data'}
  * @return {Array}
  */
function toArrayTree(array, options) {
  var opts = assign_1({}, setupDefaults_1.treeOptions, options);
  var optStrict = opts.strict;
  var optKey = opts.key;
  var optParentKey = opts.parentKey;
  var optChildren = opts.children;
  var optMapChildren = opts.mapChildren;
  var optSortKey = opts.sortKey;
  var optReverse = opts.reverse;
  var optData = opts.data;
  var result = [];
  var treeMap = {};
  var idsMap = {};
  var id, treeData, parentId;
  if (optSortKey) {
    array = orderBy_1(clone_1(array), optSortKey);
    if (optReverse) {
      array = array.reverse();
    }
  }
  each_1(array, function (item) {
    id = item[optKey];
    idsMap[id] = true;
  });
  each_1(array, function (item) {
    id = item[optKey];
    if (optData) {
      treeData = {};
      treeData[optData] = item;
    } else {
      treeData = item;
    }
    parentId = item[optParentKey];
    treeMap[id] = treeMap[id] || [];
    treeMap[parentId] = treeMap[parentId] || [];
    treeMap[parentId].push(treeData);
    treeData[optKey] = id;
    treeData[optParentKey] = parentId;
    treeData[optChildren] = treeMap[id];
    if (optMapChildren) {
      treeData[optMapChildren] = treeMap[id];
    }
    if (!optStrict || optStrict && eqNull_1(parentId)) {
      if (!idsMap[parentId]) {
        result.push(treeData);
      }
    }
  });
  if (optStrict) {
    strictTree(array, optChildren);
  }
  return result;
}
var toArrayTree_1 = toArrayTree;

function unTreeList(result, array, opts) {
  var optChildren = opts.children;
  var optData = opts.data;
  var optClear = opts.clear;
  each_1(array, function (item) {
    var children = item[optChildren];
    if (optData) {
      item = item[optData];
    }
    result.push(item);
    if (children && children.length) {
      unTreeList(result, children, opts);
    }
    if (optClear) {
      delete item[optChildren];
    }
  });
  return result;
}

/**
  * 将一个树结构转成数组列表
  *
  * @param {Array} array 数组
  * @param {Object} options { children: 'children', data: 'data', clear: false }
  * @return {Array}
  */
function toTreeArray(array, options) {
  return unTreeList([], array, assign_1({}, setupDefaults_1.treeOptions, options));
}
var toTreeArray_1 = toTreeArray;

function helperCreateTreeFunc(handle) {
  return function (obj, iterate, options, context) {
    var opts = options || {};
    var optChildren = opts.children || 'children';
    return handle(null, obj, iterate, context, [], [], optChildren, opts);
  };
}
var helperCreateTreeFunc_1 = helperCreateTreeFunc;

function findTreeItem(parent, obj, iterate, context, path, node, parseChildren, opts) {
  if (obj) {
    var item, index, len, paths, nodes, match;
    for (index = 0, len = obj.length; index < len; index++) {
      item = obj[index];
      paths = path.concat(['' + index]);
      nodes = node.concat([item]);
      if (iterate.call(context, item, index, obj, paths, parent, nodes)) {
        return {
          index: index,
          item: item,
          path: paths,
          items: obj,
          parent: parent,
          nodes: nodes
        };
      }
      if (parseChildren && item) {
        match = findTreeItem(item, item[parseChildren], iterate, context, paths.concat([parseChildren]), nodes, parseChildren);
        if (match) {
          return match;
        }
      }
    }
  }
}

/**
  * 从树结构中查找匹配第一条数据的键、值、路径
  *
  * @param {Object} obj 对象/数组
  * @param {Function} iterate(item, index, items, path, parent, nodes) 回调
  * @param {Object} options {children: 'children'}
  * @param {Object} context 上下文
  * @return {Object} { item, index, items, path, parent, nodes }
  */
var findTree = helperCreateTreeFunc_1(findTreeItem);
var findTree_1 = findTree;

function eachTreeItem(parent, obj, iterate, context, path, node, parseChildren, opts) {
  var paths, nodes;
  each_1(obj, function (item, index) {
    paths = path.concat(['' + index]);
    nodes = node.concat([item]);
    iterate.call(context, item, index, obj, paths, parent, nodes);
    if (item && parseChildren) {
      paths.push(parseChildren);
      eachTreeItem(item, item[parseChildren], iterate, context, paths, nodes, parseChildren);
    }
  });
}

/**
  * 从树结构中遍历数据的键、值、路径
  *
  * @param {Object} obj 对象/数组
  * @param {Function} iterate(item, index, items, path, parent, nodes) 回调
  * @param {Object} options {children: 'children', mapChildren: 'children}
  * @param {Object} context 上下文
  */
var eachTree = helperCreateTreeFunc_1(eachTreeItem);
var eachTree_1 = eachTree;

function mapTreeItem(parent, obj, iterate, context, path, node, parseChildren, opts) {
  var paths, nodes, rest;
  var mapChildren = opts.mapChildren || parseChildren;
  return map_1(obj, function (item, index) {
    paths = path.concat(['' + index]);
    nodes = node.concat([item]);
    rest = iterate.call(context, item, index, obj, paths, parent, nodes);
    if (rest && item && parseChildren && item[parseChildren]) {
      rest[mapChildren] = mapTreeItem(item, item[parseChildren], iterate, context, paths, nodes, parseChildren, opts);
    }
    return rest;
  });
}

/**
  * 从树结构中指定方法后的返回值组成的新数组
  *
  * @param {Object} obj 对象/数组
  * @param {Function} iterate(item, index, items, path, parent, nodes) 回调
  * @param {Object} options {children: 'children'}
  * @param {Object} context 上下文
  * @return {Object/Array}
  */
var mapTree = helperCreateTreeFunc_1(mapTreeItem);
var mapTree_1 = mapTree;

/**
  * 从树结构中根据回调过滤数据
  *
  * @param {Object} obj 对象/数组
  * @param {Function} iterate(item, index, items, path, parent) 回调
  * @param {Object} options {children: 'children'}
  * @param {Object} context 上下文
  * @return {Array}
  */
function filterTree(obj, iterate, options, context) {
  var result = [];
  if (obj && iterate) {
    eachTree_1(obj, function (item, index, items, path, parent, nodes) {
      if (iterate.call(context, item, index, items, path, parent, nodes)) {
        result.push(item);
      }
    }, options);
  }
  return result;
}
var filterTree_1 = filterTree;

function searchTreeItem(matchParent, parent, obj, iterate, context, path, node, parseChildren, opts) {
  var paths, nodes, rest, isMatch, hasChild;
  var rests = [];
  var hasOriginal = opts.original;
  var sourceData = opts.data;
  var mapChildren = opts.mapChildren || parseChildren;
  var isEvery = opts.isEvery;
  arrayEach_1(obj, function (item, index) {
    paths = path.concat(['' + index]);
    nodes = node.concat([item]);
    isMatch = matchParent && !isEvery || iterate.call(context, item, index, obj, paths, parent, nodes);
    hasChild = parseChildren && item[parseChildren];
    if (isMatch || hasChild) {
      if (hasOriginal) {
        rest = item;
      } else {
        rest = assign_1({}, item);
        if (sourceData) {
          rest[sourceData] = item;
        }
      }
      rest[mapChildren] = searchTreeItem(isMatch, item, item[parseChildren], iterate, context, paths, nodes, parseChildren, opts);
      if (isMatch || rest[mapChildren].length) {
        rests.push(rest);
      }
    } else if (isMatch) {
      rests.push(rest);
    }
  });
  return rests;
}

/**
  * 从树结构中根据回调查找数据
  *
  * @param {Object} obj 对象/数组
  * @param {Function} iterate(item, index, items, path, parent, nodes) 回调
  * @param {Object} options {children: 'children'}
  * @param {Object} context 上下文
  * @return {Array}
  */
var searchTree = helperCreateTreeFunc_1(function (parent, obj, iterate, context, path, nodes, parseChildren, opts) {
  return searchTreeItem(0, parent, obj, iterate, context, path, nodes, parseChildren, opts);
});
var searchTree_1 = searchTree;

function arrayIndexOf(list, val) {
  if (list.indexOf) {
    return list.indexOf(val);
  }
  for (var index = 0, len = list.length; index < len; index++) {
    if (val === list[index]) {
      return index;
    }
  }
}
var arrayIndexOf_1 = arrayIndexOf;

function arrayLastIndexOf(list, val) {
  if (list.lastIndexOf) {
    return list.lastIndexOf(val);
  }
  for (var len = list.length - 1; len >= 0; len--) {
    if (val === list[len]) {
      return len;
    }
  }
  return -1;
}
var arrayLastIndexOf_1 = arrayLastIndexOf;

/**
  * 判断是否Number对象
  *
  * @param {Object} obj 对象
  * @return {Boolean}
  */
var isNumber = helperCreateInTypeof_1('number');
var isNumber_1 = isNumber;

/* eslint-disable eqeqeq */
function isNumberNaN(obj) {
  return isNumber_1(obj) && isNaN(obj);
}
var _isNaN = isNumberNaN;

/**
  * 判断是否String对象
  *
  * @param {Object} obj 对象
  * @return {Boolean}
  */
var isString = helperCreateInTypeof_1('string');
var isString_1 = isString;

/**
  * 判断是否Date对象
  *
  * @param {Object} obj 对象
  * @return {Boolean}
  */
var isDate$1 = helperCreateInInObjectString_1('Date');
var isDate_1 = isDate$1;

var staticParseInt = parseInt;
var staticParseInt_1 = staticParseInt;

function helperGetUTCDateTime(resMaps) {
  return Date.UTC(resMaps.y, resMaps.M || 0, resMaps.d || 1, resMaps.H || 0, resMaps.m || 0, resMaps.s || 0, resMaps.S || 0);
}
var helperGetUTCDateTime_1 = helperGetUTCDateTime;

function helperGetDateTime(date) {
  return date.getTime();
}
var helperGetDateTime_1 = helperGetDateTime;

function getParseRule(txt) {
  return '(\\d{' + txt + '})';
}
function toParseMs(num) {
  if (num < 10) {
    return num * 100;
  } else if (num < 100) {
    return num * 10;
  }
  return num;
}
function toParseNum(num) {
  return isNaN(num) ? num : staticParseInt_1(num);
}
var d2 = getParseRule(2);
var d1or2 = getParseRule('1,2');
var d1or7 = getParseRule('1,7');
var d3or4 = getParseRule('3,4');
var place = '.{1}';
var d1Or2RE = place + d1or2;
var dzZ = '(([zZ])|([-+]\\d{2}:?\\d{2}))';
var defaulParseStrs = [d3or4, d1Or2RE, d1Or2RE, d1Or2RE, d1Or2RE, d1Or2RE, place + d1or7, dzZ];
var defaulParseREs = [];
for (var len = defaulParseStrs.length - 1; len >= 0; len--) {
  var rule = '';
  for (var i = 0; i < len + 1; i++) {
    rule += defaulParseStrs[i];
  }
  defaulParseREs.push(new RegExp('^' + rule + '$'));
}

/**
 * 解析默认格式
 */
function parseDefaultRules(str) {
  var matchRest,
    resMaps = {};
  for (var i = 0, dfrLen = defaulParseREs.length; i < dfrLen; i++) {
    matchRest = str.match(defaulParseREs[i]);
    if (matchRest) {
      resMaps.y = matchRest[1];
      resMaps.M = matchRest[2];
      resMaps.d = matchRest[3];
      resMaps.H = matchRest[4];
      resMaps.m = matchRest[5];
      resMaps.s = matchRest[6];
      resMaps.S = matchRest[7];
      resMaps.Z = matchRest[8];
      break;
    }
  }
  return resMaps;
}
var customParseStrs = [['yyyy', d3or4], ['yy', d2], ['MM', d2], ['M', d1or2], ['dd', d2], ['d', d1or2], ['HH', d2], ['H', d1or2], ['mm', d2], ['m', d1or2], ['ss', d2], ['s', d1or2], ['SSS', getParseRule(3)], ['S', d1or7], ['Z', dzZ]];
var parseRuleMaps = {};
var parseRuleKeys = ['\\[([^\\]]+)\\]'];
for (var i = 0; i < customParseStrs.length; i++) {
  var itemRule = customParseStrs[i];
  parseRuleMaps[itemRule[0]] = itemRule[1] + '?';
  parseRuleKeys.push(itemRule[0]);
}
var customParseRes = new RegExp(parseRuleKeys.join('|'), 'g');
var cacheFormatMaps = {};

/**
 * 解析自定义格式
 */
function parseCustomRules(str, format) {
  var cacheItem = cacheFormatMaps[format];
  if (!cacheItem) {
    var posIndexs = [];
    var re = format.replace(/([$(){}*+.?\\^|])/g, "\\$1").replace(customParseRes, function (text, val) {
      var firstChar = text.charAt(0);
      // 如果为转义符号:[关键字]
      if (firstChar === '[') {
        return val;
      }
      posIndexs.push(firstChar);
      return parseRuleMaps[text];
    });
    cacheItem = cacheFormatMaps[format] = {
      _i: posIndexs,
      _r: new RegExp(re)
    };
  }
  var resMaps = {};
  var matchRest = str.match(cacheItem._r);
  if (matchRest) {
    var _i = cacheItem._i;
    for (var i = 1, len = matchRest.length; i < len; i++) {
      resMaps[_i[i - 1]] = matchRest[i];
    }
    return resMaps;
  }
  return resMaps;
}

/**
 * 解析时区
 */
function parseTimeZone(resMaps) {
  // 如果为UTC 时间
  if (/^[zZ]/.test(resMaps.Z)) {
    return new Date(helperGetUTCDateTime_1(resMaps));
  } else {
    // 如果指定时区，时区转换
    var matchRest = resMaps.Z.match(/([-+])(\d{2}):?(\d{2})/);
    if (matchRest) {
      return new Date(helperGetUTCDateTime_1(resMaps) - (matchRest[1] === '-' ? -1 : 1) * staticParseInt_1(matchRest[2]) * 3600000 + staticParseInt_1(matchRest[3]) * 60000);
    }
  }
  return new Date('');
}

/**
  * 字符串转为日期
  *
  * @param {String/Number/Date} str 日期或数字
  * @param {String} format 解析日期格式(yyyy年份、MM月份、dd天、hh(12)HH(24)小时、mm分钟、ss秒、SSS毫秒、Z时区)
  * @return {Date}
  */
function toStringDate(str, format) {
  if (str) {
    var isDType = isDate_1(str);
    if (isDType || !format && /^[0-9]{11,15}$/.test(str)) {
      return new Date(isDType ? helperGetDateTime_1(str) : staticParseInt_1(str));
    }
    if (isString_1(str)) {
      var resMaps = format ? parseCustomRules(str, format) : parseDefaultRules(str);
      if (resMaps.y) {
        if (resMaps.M) {
          resMaps.M = toParseNum(resMaps.M) - 1;
        }
        if (resMaps.S) {
          // 如果7位则是微秒，只精确到3位毫秒
          resMaps.S = toParseMs(toParseNum(resMaps.S.substring(0, 3)));
        }
        if (resMaps.Z) {
          return parseTimeZone(resMaps);
        } else {
          return new Date(resMaps.y, resMaps.M || 0, resMaps.d || 1, resMaps.H || 0, resMaps.m || 0, resMaps.s || 0, resMaps.S || 0);
        }
      }
    }
  }
  return new Date('');
}
var toStringDate_1 = toStringDate;

function helperNewDate() {
  return new Date();
}
var helperNewDate_1 = helperNewDate;

/**
  * 判断是否闰年
  *
  * @param {Date} date 日期或数字
  * @return {Boolean}
  */
function isLeapYear(date) {
  var year;
  var currentDate = date ? toStringDate_1(date) : helperNewDate_1();
  if (isDate_1(currentDate)) {
    year = currentDate.getFullYear();
    return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
  }
  return false;
}
var isLeapYear_1 = isLeapYear;

/**
  * 已废弃，被 some, every 替换
  * @deprecated
  */
function forOf(obj, iterate, context) {
  if (obj) {
    if (isArray_1(obj)) {
      for (var index = 0, len = obj.length; index < len; index++) {
        if (iterate.call(context, obj[index], index, obj) === false) {
          break;
        }
      }
    } else {
      for (var key in obj) {
        if (hasOwnProp_1(obj, key)) {
          if (iterate.call(context, obj[key], key, obj) === false) {
            break;
          }
        }
      }
    }
  }
}
var forOf_1 = forOf;

/**
  * 已废弃
  * @deprecated
  */
function lastForOf(obj, iterate, context) {
  if (obj) {
    var len, list;
    if (isArray_1(obj)) {
      for (len = obj.length - 1; len >= 0; len--) {
        if (iterate.call(context, obj[len], len, obj) === false) {
          break;
        }
      }
    } else {
      list = hasOwnProp_1(obj);
      for (len = list.length - 1; len >= 0; len--) {
        if (iterate.call(context, obj[list[len]], list[len], obj) === false) {
          break;
        }
      }
    }
  }
}
var lastForOf_1 = lastForOf;

function helperCreateIndexOf(name, callback) {
  return function (obj, val) {
    if (obj) {
      if (obj[name]) {
        return obj[name](val);
      }
      if (isString_1(obj) || isArray_1(obj)) {
        return callback(obj, val);
      }
      for (var key in obj) {
        if (hasOwnProp_1(obj, key)) {
          if (val === obj[key]) {
            return key;
          }
        }
      }
    }
    return -1;
  };
}
var helperCreateIndexOf_1 = helperCreateIndexOf;

/**
  * 返回对象第一个索引值
  *
  * @param {Object} obj 对象
  * @param {Object} val 值
  * @return {Number}
  */
var indexOf = helperCreateIndexOf_1('indexOf', arrayIndexOf_1);
var indexOf_1 = indexOf;

/**
  * 从最后开始的索引值,返回对象第一个索引值
  *
  * @param {Object} array 对象
  * @param {Object} val 值
  * @return {Number}
  */
var lastIndexOf = helperCreateIndexOf_1('lastIndexOf', arrayLastIndexOf_1);
var lastIndexOf_1 = lastIndexOf;

/**
  * 返回对象的长度
  *
  * @param {Object} obj 对象
  * @return {Number}
  */
function getSize(obj) {
  var len = 0;
  if (isString_1(obj) || isArray_1(obj)) {
    return obj.length;
  }
  each_1(obj, function () {
    len++;
  });
  return len;
}
var getSize_1 = getSize;

function isNumberFinite(obj) {
  return isNumber_1(obj) && isFinite(obj);
}
var _isFinite = isNumberFinite;

/**
  * 判断是否整数
  *
  * @param {Number, String} number 数值
  * @return {Boolean}
  */
var isInteger = function (obj) {
  return !isNull_1(obj) && !isNaN(obj) && !isArray_1(obj) && obj % 1 === 0;
};
var isInteger_1 = isInteger;

/**
  * 判断是否小数
  *
  * @param {Number} obj 数值
  * @return {Boolean}
  */
function isFloat(obj) {
  return !isNull_1(obj) && !isNaN(obj) && !isArray_1(obj) && !isInteger_1(obj);
}
var isFloat_1 = isFloat;

/**
  * 判断是否Boolean对象
  *
  * @param {Object} obj 对象
  * @return {Boolean}
  */
var isBoolean = helperCreateInTypeof_1('boolean');
var isBoolean_1 = isBoolean;

/**
  * 判断是否RegExp对象
  *
  * @param {Object} obj 对象
  * @return {Boolean}
  */
var isRegExp = helperCreateInInObjectString_1('RegExp');
var isRegExp_1 = isRegExp;

/**
  * 判断是否Error对象
  *
  * @param {Object} obj 对象
  * @return {Boolean}
  */
var isError = helperCreateInInObjectString_1('Error');
var isError_1 = isError;

/**
  * 判断是否TypeError对象
  *
  * @param {Object} obj 对象
  * @return {Boolean}
  */
function isTypeError(obj) {
  return obj ? obj.constructor === TypeError : false;
}
var isTypeError_1 = isTypeError;

/**
  * 判断是否为空对象
  *
  * @param {Object} obj 对象
  * @return {Boolean}
  */
function isEmpty$1(obj) {
  for (var key in obj) {
    return false;
  }
  return true;
}
var isEmpty_1 = isEmpty$1;

/* eslint-disable valid-typeof */


/**
  * 判断是否Symbol对象
  *
  * @param {Object} obj 对象
  * @return {Boolean}
  */
var supportSymbol = typeof Symbol !== staticStrUndefined_1;
function isSymbol(obj) {
  return supportSymbol && Symbol.isSymbol ? Symbol.isSymbol(obj) : typeof obj === 'symbol';
}
var isSymbol_1 = isSymbol;

/**
  * 判断是否Arguments对象
  *
  * @param {Object} obj 对象
  * @return {Boolean}
  */
var isArguments = helperCreateInInObjectString_1('Arguments');
var isArguments_1 = isArguments;

/**
  * 判断是否Element对象
  *
  * @param {Object} obj 对象
  * @return {Boolean}
  */
function isElement$3(obj) {
  return !!(obj && isString_1(obj.nodeName) && isNumber_1(obj.nodeType));
}
var isElement_1 = isElement$3;

/* eslint-disable valid-typeof */
var staticDocument = typeof document === staticStrUndefined_1 ? 0 : document;
var staticDocument_1 = staticDocument;

/**
  * 判断是否Document对象
  *
  * @param {Object} obj 对象
  * @return {Boolean}
  */
function isDocument(obj) {
  return !!(obj && staticDocument_1 && obj.nodeType === 9);
}
var isDocument_1 = isDocument;

/* eslint-disable valid-typeof */
var staticWindow = typeof window === staticStrUndefined_1 ? 0 : window;
var staticWindow_1 = staticWindow;

/**
  * 判断是否Window对象
  *
  * @param {Object} obj 对象
  * @return {Boolean}
  */
function isWindow$1(obj) {
  return !!(staticWindow_1 && !!(obj && obj === obj.window));
}
var isWindow_1 = isWindow$1;

/* eslint-disable valid-typeof */


/**
  * 判断是否FormData对象
  *
  * @param {Object} obj 对象
  * @return {Boolean}
  */
var supportFormData = typeof FormData !== staticStrUndefined_1;
function isFormData(obj) {
  return supportFormData && obj instanceof FormData;
}
var isFormData_1 = isFormData;

/* eslint-disable valid-typeof */


/**
  * 判断是否Map对象
  *
  * @param {Object} obj 对象
  * @return {Boolean}
 */
var supportMap = typeof Map !== staticStrUndefined_1;
function isMap(obj) {
  return supportMap && obj instanceof Map;
}
var isMap_1 = isMap;

/* eslint-disable valid-typeof */


/**
  * 判断是否WeakMap对象
  *
  * @param {Object} obj 对象
  * @return {Boolean}
 */
var supportWeakMap = typeof WeakMap !== staticStrUndefined_1;
function isWeakMap(obj) {
  return supportWeakMap && obj instanceof WeakMap;
}
var isWeakMap_1 = isWeakMap;

/* eslint-disable valid-typeof */


/**
  * 判断是否Set对象
  *
  * @param {Object} obj 对象
  * @return {Boolean}
 */
var supportSet = typeof Set !== staticStrUndefined_1;
function isSet(obj) {
  return supportSet && obj instanceof Set;
}
var isSet_1 = isSet;

/* eslint-disable valid-typeof */


/**
  * 判断是否WeakSet对象
  *
  * @param {Object} obj 对象
  * @return {Boolean}
 */
var supportWeakSet = typeof WeakSet !== staticStrUndefined_1;
function isWeakSet(obj) {
  return supportWeakSet && obj instanceof WeakSet;
}
var isWeakSet_1 = isWeakSet;

function helperCreateiterateIndexOf(callback) {
  return function (obj, iterate, context) {
    if (obj && isFunction_1(iterate)) {
      if (isArray_1(obj) || isString_1(obj)) {
        return callback(obj, iterate, context);
      }
      for (var key in obj) {
        if (hasOwnProp_1(obj, key)) {
          if (iterate.call(context, obj[key], key, obj)) {
            return key;
          }
        }
      }
    }
    return -1;
  };
}
var helperCreateiterateIndexOf_1 = helperCreateiterateIndexOf;

/**
  * 返回对象第一个索引值
  *
  * @param {Object} obj 对象/数组
  * @param {Function} iterate(item, index, obj) 回调
  * @param {Object} context 上下文
  * @return {Object}
  */
var findIndexOf = helperCreateiterateIndexOf_1(function (obj, iterate, context) {
  for (var index = 0, len = obj.length; index < len; index++) {
    if (iterate.call(context, obj[index], index, obj)) {
      return index;
    }
  }
  return -1;
});
var findIndexOf_1 = findIndexOf;

function helperEqualCompare(val1, val2, compare, func, key, obj1, obj2) {
  if (val1 === val2) {
    return true;
  }
  if (val1 && val2 && !isNumber_1(val1) && !isNumber_1(val2) && !isString_1(val1) && !isString_1(val2)) {
    if (isRegExp_1(val1)) {
      return compare('' + val1, '' + val2, key, obj1, obj2);
    }
    if (isDate_1(val1) || isBoolean_1(val1)) {
      return compare(+val1, +val2, key, obj1, obj2);
    } else {
      var result, val1Keys, val2Keys;
      var isObj1Arr = isArray_1(val1);
      var isObj2Arr = isArray_1(val2);
      if (isObj1Arr || isObj2Arr ? isObj1Arr && isObj2Arr : val1.constructor === val2.constructor) {
        val1Keys = keys_1(val1);
        val2Keys = keys_1(val2);
        if (func) {
          result = func(val1, val2, key);
        }
        if (val1Keys.length === val2Keys.length) {
          return isUndefined_1(result) ? every_1(val1Keys, function (key, index) {
            return key === val2Keys[index] && helperEqualCompare(val1[key], val2[val2Keys[index]], compare, func, isObj1Arr || isObj2Arr ? index : key, val1, val2);
          }) : !!result;
        }
        return false;
      }
    }
  }
  return compare(val1, val2, key, obj1, obj2);
}
var helperEqualCompare_1 = helperEqualCompare;

function helperDefaultCompare(v1, v2) {
  return v1 === v2;
}
var helperDefaultCompare_1 = helperDefaultCompare;

/**
 * 深度比较两个对象之间的值是否相等
 *
 * @param {Object} obj1 值1
 * @param {Object} obj2 值2
 * @return {Boolean}
 */
function isEqual(obj1, obj2) {
  return helperEqualCompare_1(obj1, obj2, helperDefaultCompare_1);
}
var isEqual_1 = isEqual;

/**
 * 判断属性中的键和值是否包含在对象中
 *
 * @param {Object/Array} obj 对象
 * @param {Object} source 值
 * @return {Boolean}
 */
function isMatch(obj, source) {
  var objKeys = keys_1(obj);
  var sourceKeys = keys_1(source);
  if (sourceKeys.length) {
    if (includeArrays_1(objKeys, sourceKeys)) {
      return some_1(sourceKeys, function (key2) {
        return findIndexOf_1(objKeys, function (key1) {
          return key1 === key2 && isEqual_1(obj[key1], source[key2]);
        }) > -1;
      });
    }
  } else {
    return true;
  }
  return isEqual_1(obj, source);
}
var isMatch_1 = isMatch;

/**
 * 深度比较两个对象之间的值是否相等，使用自定义比较函数
 *
 * @param {Object} obj1 值1
 * @param {Object} obj2 值2
 * @param {Function} func 自定义函数
 * @return {Boolean}
 */
function isEqualWith(obj1, obj2, func) {
  if (isFunction_1(func)) {
    return helperEqualCompare_1(obj1, obj2, function (v1, v2, key, obj1, obj2) {
      var result = func(v1, v2, key, obj1, obj2);
      return isUndefined_1(result) ? helperDefaultCompare_1(v1, v2) : !!result;
    }, func);
  }
  return helperEqualCompare_1(obj1, obj2, helperDefaultCompare_1);
}
var isEqualWith_1 = isEqualWith;

/**
  * 获取对象类型
  *
  * @param {Object} obj 对象
  * @return {String}
  */
function getType(obj) {
  if (isNull_1(obj)) {
    return 'null';
  }
  if (isSymbol_1(obj)) {
    return 'symbol';
  }
  if (isDate_1(obj)) {
    return 'date';
  }
  if (isArray_1(obj)) {
    return 'array';
  }
  if (isRegExp_1(obj)) {
    return 'regexp';
  }
  if (isError_1(obj)) {
    return 'error';
  }
  return typeof obj;
}
var getType_1 = getType;

/**
  * 获取一个全局唯一标识
  *
  * @param {String} prefix 前缀
  * @return {Number}
  */
var __uniqueId = 0;
function uniqueId(prefix) {
  return [prefix, ++__uniqueId].join('');
}
var uniqueId_1 = uniqueId;

/**
  * 从最后开始的索引值,返回对象第一个索引值
  *
  * @param {Object} obj 对象/数组
  * @param {Function} iterate(item, index, obj) 回调
  * @param {Object} context 上下文
  * @return {Object}
  */
var findLastIndexOf = helperCreateiterateIndexOf_1(function (obj, iterate, context) {
  for (var len = obj.length - 1; len >= 0; len--) {
    if (iterate.call(context, obj[len], len, obj)) {
      return len;
    }
  }
  return -1;
});
var findLastIndexOf_1 = findLastIndexOf;

/**
  * 字符串转JSON
  *
  * @param {String} str 字符串
  * @return {Object} 返回转换后对象
  */
function toStringJSON(str) {
  if (isPlainObject_1(str)) {
    return str;
  } else if (isString_1(str)) {
    try {
      return JSON.parse(str);
    } catch (e) {}
  }
  return {};
}
var toStringJSON_1 = toStringJSON;

/**
  * JSON转字符串
  *
  * @param {Object} obj 对象
  * @return {String} 返回字符串
  */
function toJSONString(obj) {
  return eqNull_1(obj) ? '' : JSON.stringify(obj);
}
var toJSONString_1 = toJSONString;

/**
  * 获取对象所有属性、值
  *
  * @param {Object} obj 对象/数组
  * @return {Array}
  */
var entries = helperCreateGetObjects_1('entries', 2);
var entries_1 = entries;

function helperCreatePickOmit(case1, case2) {
  return function (obj, callback) {
    var item, index;
    var rest = {};
    var result = [];
    var context = this;
    var args = arguments;
    var len = args.length;
    if (!isFunction_1(callback)) {
      for (index = 1; index < len; index++) {
        item = args[index];
        result.push.apply(result, isArray_1(item) ? item : [item]);
      }
      callback = 0;
    }
    each_1(obj, function (val, key) {
      if ((callback ? callback.call(context, val, key, obj) : findIndexOf_1(result, function (name) {
        return name === key;
      }) > -1) ? case1 : case2) {
        rest[key] = val;
      }
    });
    return rest;
  };
}
var helperCreatePickOmit_1 = helperCreatePickOmit;

/**
 * 根据 key 过滤指定的属性值，返回一个新的对象
 *
 * @param {Object} obj 对象
 * @param {String/Array} key 键数组
 * @return {Object}
 */
var pick = helperCreatePickOmit_1(1, 0);
var pick_1 = pick;

/**
 * 根据 key 排除指定的属性值，返回一个新的对象
 *
 * @param {Object} obj 对象
 * @param {String/Array} key 键数组
 * @return {Object}
 */
var omit = helperCreatePickOmit_1(0, 1);
var omit_1 = omit;

/**
  * 获取对象第一个值
  *
  * @param {Object} obj 对象/数组
  * @return {Object}
  */
function first(obj) {
  return values_1(obj)[0];
}
var first_1 = first;

/**
  * 获取对象最后一个值
  *
  * @param {Object} obj 对象/数组
  * @return {Object}
  */
function last(obj) {
  var list = values_1(obj);
  return list[list.length - 1];
}
var last_1 = last;

/**
 * 检查键、路径是否是该对象的属性
 *
 * @param {Object/Array} data 对象
 * @param {String/Function} property 键、路径
 * @return {Boolean}
 */
function has(obj, property) {
  if (obj) {
    if (hasOwnProp_1(obj, property)) {
      return true;
    } else {
      var prop, arrIndex, objProp, matchs, rest, isHas;
      var props = helperGetHGSKeys_1(property);
      var index = 0;
      var len = props.length;
      for (rest = obj; index < len; index++) {
        isHas = false;
        prop = props[index];
        matchs = prop ? prop.match(staticHGKeyRE_1) : '';
        if (matchs) {
          arrIndex = matchs[1];
          objProp = matchs[2];
          if (arrIndex) {
            if (rest[arrIndex]) {
              if (hasOwnProp_1(rest[arrIndex], objProp)) {
                isHas = true;
                rest = rest[arrIndex][objProp];
              }
            }
          } else {
            if (hasOwnProp_1(rest, objProp)) {
              isHas = true;
              rest = rest[objProp];
            }
          }
        } else {
          if (hasOwnProp_1(rest, prop)) {
            isHas = true;
            rest = rest[prop];
          }
        }
        if (isHas) {
          if (index === len - 1) {
            return true;
          }
        } else {
          break;
        }
      }
    }
  }
  return false;
}
var has_1 = has;

var sKeyRE = /(.+)?\[(\d+)\]$/;
function setDeepProps(obj, key, isEnd, nextKey, value) {
  if (obj[key]) {
    if (isEnd) {
      obj[key] = value;
    }
  } else {
    var index;
    var rest;
    var currMatchs = key ? key.match(sKeyRE) : null;
    if (isEnd) {
      rest = value;
    } else {
      var nextMatchs = nextKey ? nextKey.match(sKeyRE) : null;
      if (nextMatchs && !nextMatchs[1]) {
        // 如果下一个属性为数组类型
        rest = new Array(staticParseInt_1(nextMatchs[2]) + 1);
      } else {
        rest = {};
      }
    }
    if (currMatchs) {
      if (currMatchs[1]) {
        // 如果为对象中数组
        index = staticParseInt_1(currMatchs[2]);
        if (obj[currMatchs[1]]) {
          if (isEnd) {
            obj[currMatchs[1]][index] = rest;
          } else {
            if (obj[currMatchs[1]][index]) {
              rest = obj[currMatchs[1]][index];
            } else {
              obj[currMatchs[1]][index] = rest;
            }
          }
        } else {
          obj[currMatchs[1]] = new Array(index + 1);
          obj[currMatchs[1]][index] = rest;
        }
      } else {
        // 如果为数组
        obj[currMatchs[2]] = rest;
      }
    } else {
      // 如果为对象
      obj[key] = rest;
    }
    return rest;
  }
  return obj[key];
}

/**
 * 设置对象属性上的值。如果属性不存在则创建它
 * @param {Object/Array} obj 对象
 * @param {String/Function} property 键、路径
 * @param {Object} value 值
 */
function set(obj, property, value) {
  if (obj) {
    if ((obj[property] || hasOwnProp_1(obj, property)) && !isPrototypePolluted(property)) {
      obj[property] = value;
    } else {
      var rest = obj;
      var props = helperGetHGSKeys_1(property);
      var len = props.length;
      for (var index = 0; index < len; index++) {
        if (isPrototypePolluted(props[index])) {
          continue;
        }
        var isEnd = index === len - 1;
        rest = setDeepProps(rest, props[index], isEnd, isEnd ? null : props[index + 1], value);
      }
    }
  }
  return obj;
}

/**
 * Blacklist certain keys to prevent Prototype Pollution
 * @param {string} key
 */
function isPrototypePolluted(key) {
  return key === '__proto__' || key === 'constructor' || key === 'prototype';
}
var set_1 = set;

function createiterateEmpty(iterate) {
  return function () {
    return isEmpty_1(iterate);
  };
}

/**
  * 集合分组,默认使用键值分组,如果有iterate则使用结果进行分组
  *
  * @param {Array} obj 对象
  * @param {Function} iterate 回调/对象属性
  * @param {Object} context 上下文
  * @return {Object}
  */
function groupBy(obj, iterate, context) {
  var groupKey;
  var result = {};
  if (obj) {
    if (iterate && isObject_1(iterate)) {
      iterate = createiterateEmpty(iterate);
    } else if (!isFunction_1(iterate)) {
      iterate = property_1(iterate);
    }
    each_1(obj, function (val, key) {
      groupKey = iterate ? iterate.call(context, val, key, obj) : val;
      if (result[groupKey]) {
        result[groupKey].push(val);
      } else {
        result[groupKey] = [val];
      }
    });
  }
  return result;
}
var groupBy_1 = groupBy;

/**
  * 集合分组统计,返回各组中对象的数量统计
  *
  * @param {Array} obj 对象
  * @param {Function} iterate 回调/对象属性
  * @param {Object} context 上下文
  * @return {Object}
  */
function countBy(obj, iterate, context) {
  var result = groupBy_1(obj, iterate, context || this);
  objectEach_1(result, function (item, key) {
    result[key] = item.length;
  });
  return result;
}
var countBy_1 = countBy;

/**
  * 序号列表生成函数
  *
  * @param {Number} start 起始值
  * @param {Number} stop 结束值
  * @param {Number} step 自增值
  * @return {Array}
  */
function range$1(start, stop, step) {
  var index, len;
  var result = [];
  var args = arguments;
  if (args.length < 2) {
    stop = args[0];
    start = 0;
  }
  index = start >> 0;
  len = stop >> 0;
  if (index < stop) {
    step = step >> 0 || 1;
    for (; index < len; index += step) {
      result.push(index);
    }
  }
  return result;
}
var range_1 = range$1;

/**
  * 将一个或者多个对象值解构到目标对象
  *
  * @param {Object} destination 目标对象
  * @param {...Object}
  * @return {Boolean}
  */
function destructuring(destination, sources) {
  if (destination && sources) {
    var rest = assign_1.apply(this, [{}].concat(slice_1(arguments, 1)));
    var restKeys = keys_1(rest);
    arrayEach_1(keys_1(destination), function (key) {
      if (includes_1(restKeys, key)) {
        destination[key] = rest[key];
      }
    });
  }
  return destination;
}
var destructuring_1 = destructuring;

/**
  * 获取最小值
  *
  * @param {Array} arr 数组
  * @param {Function} iterate(item, index, obj) 回调
  * @return {Number}
  */
var min$1 = helperCreateMinMax_1(function (rest, itemVal) {
  return rest > itemVal;
});
var min_1 = min$1;

function helperNumberDecimal(numStr) {
  return (numStr.split('.')[1] || '').length;
}
var helperNumberDecimal_1 = helperNumberDecimal;

function helperStringRepeat(str, count) {
  if (str.repeat) {
    return str.repeat(count);
  }
  var list = isNaN(count) ? [] : new Array(staticParseInt_1(count));
  return list.join(str) + (list.length > 0 ? str : '');
}
var helperStringRepeat_1 = helperStringRepeat;

function helperNumberOffsetPoint(str, offsetIndex) {
  return str.substring(0, offsetIndex) + '.' + str.substring(offsetIndex, str.length);
}
var helperNumberOffsetPoint_1 = helperNumberOffsetPoint;

/**
 * 数值转字符串，科学计数转字符串
 * @param { Number } num 数值
 *
 * @return {Number}
 */
function toNumberString(num) {
  var rest = '' + num;
  var scienceMatchs = rest.match(/^([-+]?)((\d+)|((\d+)?[.](\d+)?))e([-+]{1})([0-9]+)$/);
  if (scienceMatchs) {
    var isNegative = num < 0;
    var absFlag = isNegative ? '-' : '';
    var intNumStr = scienceMatchs[3] || '';
    var dIntNumStr = scienceMatchs[5] || '';
    var dFloatNumStr = scienceMatchs[6] || '';
    var sciencFlag = scienceMatchs[7];
    var scienceNumStr = scienceMatchs[8];
    var floatOffsetIndex = scienceNumStr - dFloatNumStr.length;
    var intOffsetIndex = scienceNumStr - intNumStr.length;
    var dIntOffsetIndex = scienceNumStr - dIntNumStr.length;
    if (sciencFlag === '+') {
      if (intNumStr) {
        return absFlag + intNumStr + helperStringRepeat_1('0', scienceNumStr);
      }
      if (floatOffsetIndex > 0) {
        return absFlag + dIntNumStr + dFloatNumStr + helperStringRepeat_1('0', floatOffsetIndex);
      }
      return absFlag + dIntNumStr + helperNumberOffsetPoint_1(dFloatNumStr, scienceNumStr);
    }
    if (intNumStr) {
      if (intOffsetIndex > 0) {
        return absFlag + '0.' + helperStringRepeat_1('0', Math.abs(intOffsetIndex)) + intNumStr;
      }
      return absFlag + helperNumberOffsetPoint_1(intNumStr, intOffsetIndex);
    }
    if (dIntOffsetIndex > 0) {
      return absFlag + '0.' + helperStringRepeat_1('0', Math.abs(dIntOffsetIndex)) + dIntNumStr + dFloatNumStr;
    }
    return absFlag + helperNumberOffsetPoint_1(dIntNumStr, dIntOffsetIndex) + dFloatNumStr;
  }
  return rest;
}
var toNumberString_1 = toNumberString;

function helperMultiply(multiplier, multiplicand) {
  var str1 = toNumberString_1(multiplier);
  var str2 = toNumberString_1(multiplicand);
  return parseInt(str1.replace('.', '')) * parseInt(str2.replace('.', '')) / Math.pow(10, helperNumberDecimal_1(str1) + helperNumberDecimal_1(str2));
}
var helperMultiply_1 = helperMultiply;

function helperCreateMathNumber(name) {
  return function (num, digits) {
    var numRest = toNumber_1(num);
    var rest = numRest;
    if (numRest) {
      digits = digits >> 0;
      var numStr = toNumberString_1(numRest);
      var nums = numStr.split('.');
      var intStr = nums[0];
      var floatStr = nums[1] || '';
      var fStr = floatStr.substring(0, digits + 1);
      var subRest = intStr + (fStr ? '.' + fStr : '');
      if (digits >= floatStr.length) {
        return toNumber_1(subRest);
      }
      subRest = numRest;
      if (digits > 0) {
        var ratio = Math.pow(10, digits);
        rest = Math[name](helperMultiply_1(subRest, ratio)) / ratio;
      } else {
        rest = Math[name](subRest);
      }
    }
    return rest;
  };
}
var helperCreateMathNumber_1 = helperCreateMathNumber;

/**
 * 将数值四舍五入
 *
 * @param {string|number} num 数值
 * @param {number} digits 小数保留位数
 * @return {number}
 */
var round$2 = helperCreateMathNumber_1('round');
var round_1 = round$2;

/**
 * 将数值向上舍入
 *
 * @param {string|number} num 数值
 * @param {number} digits 小数保留位数
 * @return {number}
 */
var ceil = helperCreateMathNumber_1('ceil');
var ceil_1 = ceil;

/**
 * 将数值向下舍入
 *
 * @param {string|number} num 数值
 * @param {number} digits 小数保留位数
 * @return {number}
 */
var floor = helperCreateMathNumber_1('floor');
var floor_1 = floor;

function toValueString(obj) {
  if (isNumber_1(obj)) {
    return toNumberString_1(obj);
  }
  return '' + (eqNull_1(obj) ? '' : obj);
}
var toValueString_1 = toValueString;

/**
  * 将数值四舍五入并格式化为固定小数位的字符串
  *
 * @param {string|number} num 数值
 * @param {number} digits 小数保留位数
  * @return {String}
  */
function toFixed(num, digits) {
  digits = digits >> 0;
  var str = toValueString_1(round_1(num, digits));
  var nums = str.split('.');
  var intStr = nums[0];
  var floatStr = nums[1] || '';
  var digitOffsetIndex = digits - floatStr.length;
  if (digits) {
    if (digitOffsetIndex > 0) {
      return intStr + '.' + floatStr + helperStringRepeat_1('0', digitOffsetIndex);
    }
    return intStr + helperNumberOffsetPoint_1(floatStr, Math.abs(digitOffsetIndex));
  }
  return intStr;
}
var toFixed_1 = toFixed;

/**
  * 千分位分隔符、小数点
  *
  * @param {String/Number} num 数值
  * @param {CommafyOptions} options 参数
  * @return {String}
 */
function commafy(num, options) {
  var opts = assign_1({}, setupDefaults_1.commafyOptions, options);
  var optDigits = opts.digits;
  var isNum = isNumber_1(num);
  var rest, result, isNegative, intStr, floatStr;
  if (isNum) {
    rest = (opts.ceil ? ceil_1 : opts.floor ? floor_1 : round_1)(num, optDigits);
    result = toNumberString_1(optDigits ? toFixed_1(rest, optDigits) : rest).split('.');
    intStr = result[0];
    floatStr = result[1];
    isNegative = intStr && rest < 0;
    if (isNegative) {
      intStr = intStr.substring(1, intStr.length);
    }
  } else {
    rest = toValueString_1(num).replace(/,/g, '');
    result = rest ? [rest] : [];
    intStr = result[0];
  }
  if (result.length) {
    return (isNegative ? '-' : '') + intStr.replace(new RegExp('(?=(?!(\\b))(.{' + (opts.spaceNumber || 3) + '})+$)', 'g'), opts.separator || ',') + (floatStr ? '.' + floatStr : '');
  }
  return rest;
}
var commafy_1 = commafy;

/**
 * 转整数
 * @param { String/Number } str 数值
 *
 * @return {Number}
 */
var toInteger = helperCreateToNumber_1(staticParseInt_1);
var toInteger_1 = toInteger;

/**
 * 乘法运算
 *
 * @param { Number } num1 数值1
 * @param { Number } num2 数值2
 * @return {Number}
 */
function multiply(num1, num2) {
  var multiplier = toNumber_1(num1);
  var multiplicand = toNumber_1(num2);
  return helperMultiply_1(multiplier, multiplicand);
}
var multiply_1 = multiply;

function helperNumberAdd(addend, augend) {
  var str1 = toNumberString_1(addend);
  var str2 = toNumberString_1(augend);
  var ratio = Math.pow(10, Math.max(helperNumberDecimal_1(str1), helperNumberDecimal_1(str2)));
  return (multiply_1(addend, ratio) + multiply_1(augend, ratio)) / ratio;
}
var helperNumberAdd_1 = helperNumberAdd;

/**
 * 加法运算
 *
 * @param { Number } num1 被加数
 * @param { Number } num2 加数
 * @return {Number}
 */
function add(num1, num2) {
  return helperNumberAdd_1(toNumber_1(num1), toNumber_1(num2));
}
var add_1 = add;

/**
 * 减法运算
 *
 * @param { Number } num1 被减数
 * @param { Number } num2 减数
 * @return {Number}
 */
function subtract(num1, num2) {
  var subtrahend = toNumber_1(num1);
  var minuend = toNumber_1(num2);
  var str1 = toNumberString_1(subtrahend);
  var str2 = toNumberString_1(minuend);
  var digit1 = helperNumberDecimal_1(str1);
  var digit2 = helperNumberDecimal_1(str2);
  var ratio = Math.pow(10, Math.max(digit1, digit2));
  var precision = digit1 >= digit2 ? digit1 : digit2;
  return parseFloat(toFixed_1((subtrahend * ratio - minuend * ratio) / ratio, precision));
}
var subtract_1 = subtract;

function helperNumberDivide(divisor, dividend) {
  var str1 = toNumberString_1(divisor);
  var str2 = toNumberString_1(dividend);
  var divisorDecimal = helperNumberDecimal_1(str1);
  var dividendDecimal = helperNumberDecimal_1(str2);
  var powY = dividendDecimal - divisorDecimal;
  var isMinus = powY < 0;
  var multiplicand = Math.pow(10, isMinus ? Math.abs(powY) : powY);
  return multiply_1(str1.replace('.', '') / str2.replace('.', ''), isMinus ? 1 / multiplicand : multiplicand);
}
var helperNumberDivide_1 = helperNumberDivide;

/**
 * 除法运算
 *
 * @param { Number } num1 数值1
 * @param { Number } num2 数值2
 * @return {Number}
 */
function divide(num1, num2) {
  return helperNumberDivide_1(toNumber_1(num1), toNumber_1(num2));
}
var divide_1 = divide;

/**
  * 求和函数，将数值相加
  *
  * @param {Array} array 数组
  * @param {Function/String} iterate 方法或属性
  * @param {Object} context 上下文
  * @return {Number}
  */
function sum(array, iterate, context) {
  var result = 0;
  each_1(array, iterate ? isFunction_1(iterate) ? function () {
    result = helperNumberAdd_1(result, iterate.apply(context, arguments));
  } : function (val) {
    result = helperNumberAdd_1(result, get_1(val, iterate));
  } : function (val) {
    result = helperNumberAdd_1(result, val);
  });
  return result;
}
var sum_1 = sum;

/**
  * 求平均值函数
  *
  * @param {Array} array 数组
  * @param {Function/String} iterate 方法或属性
  * @param {Object} context 上下文
  * @return {Number}
  */
function mean(array, iterate, context) {
  return helperNumberDivide_1(sum_1(array, iterate, context), getSize_1(array));
}
var mean_1 = mean;

var staticStrFirst = 'first';
var staticStrFirst_1 = staticStrFirst;

var staticStrLast = 'last';
var staticStrLast_1 = staticStrLast;

function helperGetDateFullYear(date) {
  return date.getFullYear();
}
var helperGetDateFullYear_1 = helperGetDateFullYear;

var staticDayTime = 86400000;
var staticDayTime_1 = staticDayTime;

function helperGetDateMonth(date) {
  return date.getMonth();
}
var helperGetDateMonth_1 = helperGetDateMonth;

/**
  * 判断是否有效的Date对象
  *
  * @param {any} val 对象
  * @return {boolean}
  */
function isValidDate(val) {
  return isDate_1(val) && !isNaN(helperGetDateTime_1(val));
}
var isValidDate_1 = isValidDate;

/**
  * 返回前几月或后几月的日期
  *
  * @param {Date} date 日期或数字
  * @param {Number} offsetMonth 月(默认当前月)、前几个月、后几个月
  * @param {Number/String} offsetDay 获取哪天：月初(first)、月末(last)、指定天数(数值)，如果为空，但超过指定月份的天数时，则默认单月最后一天
  * @return {Date}
  */
function getWhatMonth(date, offsetMonth, offsetDay) {
  var monthNum = offsetMonth && !isNaN(offsetMonth) ? offsetMonth : 0;
  date = toStringDate_1(date);
  if (isValidDate_1(date)) {
    if (offsetDay === staticStrFirst_1) {
      return new Date(helperGetDateFullYear_1(date), helperGetDateMonth_1(date) + monthNum, 1);
    } else if (offsetDay === staticStrLast_1) {
      return new Date(helperGetDateTime_1(getWhatMonth(date, monthNum + 1, staticStrFirst_1)) - 1);
    } else if (isNumber_1(offsetDay)) {
      date.setDate(offsetDay);
    }
    if (monthNum) {
      var currDate = date.getDate();
      date.setMonth(helperGetDateMonth_1(date) + monthNum);
      if (currDate !== date.getDate()) {
        // 当为指定天数，且被跨月了，则默认单月最后一天
        date.setDate(1);
        return new Date(helperGetDateTime_1(date) - staticDayTime_1);
      }
    }
  }
  return date;
}
var getWhatMonth_1 = getWhatMonth;

/**
  * 返回前几年或后几年的日期
  *
  * @param {Date} date 日期或数字
  * @param {Number} offset 年(默认当前年)、前几个年(数值)、后几个年(数值)
  * @param {Number/String} month 获取哪月(null默认当前年)、年初(first)、年末(last)、指定月份（0-11）
  * @return {Date}
  */
function getWhatYear(date, offset, month) {
  var number;
  date = toStringDate_1(date);
  if (isValidDate_1(date)) {
    if (offset) {
      number = offset && !isNaN(offset) ? offset : 0;
      date.setFullYear(helperGetDateFullYear_1(date) + number);
    }
    if (month || !isNaN(month)) {
      if (month === staticStrFirst_1) {
        return new Date(helperGetDateFullYear_1(date), 0, 1);
      } else if (month === staticStrLast_1) {
        date.setMonth(11);
        return getWhatMonth_1(date, 0, staticStrLast_1);
      } else {
        date.setMonth(month);
      }
    }
  }
  return date;
}
var getWhatYear_1 = getWhatYear;

function getQuarterNumber(date) {
  var month = date.getMonth();
  if (month < 3) {
    return 1;
  } else if (month < 6) {
    return 2;
  } else if (month < 9) {
    return 3;
  }
  return 4;
}

/**
  * 返回前几季度或后几季度的日期
  *
  * @param {Date} date 日期
  * @param {Number} offset 季度(默认当前季度)、前几季度、后几季度
  * @param {Number} day 获取哪天：月初(first)、月末(last)、指定天数(数值)，如果为空，但超过指定月份的天数时，则默认单月最后一天
  * @return {Date}
  */
function getWhatQuarter(date, offset, day) {
  var currMonth,
    monthOffset = offset && !isNaN(offset) ? offset * 3 : 0;
  date = toStringDate_1(date);
  if (isValidDate_1(date)) {
    currMonth = (getQuarterNumber(date) - 1) * 3;
    date.setMonth(currMonth);
    return getWhatMonth_1(date, monthOffset, day);
  }
  return date;
}
var getWhatQuarter_1 = getWhatQuarter;

/**
  * 返回前几天或后几天的日期
  *
  * @param {Date} date 日期或数字
  * @param {Number} offset 天(默认当天)、前几天、后几天
  * @param {String} mode 获取时分秒(null默认当前时分秒)、日初(first)、日末(last)
  * @return {Date}
  */
function getWhatDay(date, offset, mode) {
  date = toStringDate_1(date);
  if (isValidDate_1(date) && !isNaN(offset)) {
    date.setDate(date.getDate() + staticParseInt_1(offset));
    if (mode === staticStrFirst_1) {
      return new Date(helperGetDateFullYear_1(date), helperGetDateMonth_1(date), date.getDate());
    } else if (mode === staticStrLast_1) {
      return new Date(helperGetDateTime_1(getWhatDay(date, 1, staticStrFirst_1)) - 1);
    }
  }
  return date;
}
var getWhatDay_1 = getWhatDay;

function helperStringUpperCase(str) {
  return str.toUpperCase();
}
var helperStringUpperCase_1 = helperStringUpperCase;

var staticWeekTime = staticDayTime_1 * 7;
var staticWeekTime_1 = staticWeekTime;

/**
  * 返回前几周或后几周的星期几
  *
  * @param {Date} date 日期
  * @param {Number} offsetWeek 周(默认当前周)、前几周、后几周
  * @param {Number} offsetDay 星期天(默认0)、星期一(1)、星期二(2)、星期三(3)、星期四(4)、星期五(5)、星期六(6)
  * @param {Number} firstDay 周视图的起始天，默认星期一
  * @return {Date}
  */
function getWhatWeek(date, offsetWeek, offsetDay, firstDay) {
  date = toStringDate_1(date);
  if (isValidDate_1(date)) {
    var hasCustomDay = isNumber_1(offsetDay);
    var hasStartDay = isNumber_1(firstDay);
    var whatDayTime = helperGetDateTime_1(date);
    // 如果指定了天或周视图起始天
    if (hasCustomDay || hasStartDay) {
      var viewStartDay = hasStartDay ? firstDay : setupDefaults_1.firstDayOfWeek;
      var currentDay = date.getDay();
      var customDay = hasCustomDay ? offsetDay : currentDay;
      if (currentDay !== customDay) {
        var offsetNum = 0;
        if (viewStartDay > currentDay) {
          offsetNum = -(7 - viewStartDay + currentDay);
        } else if (viewStartDay < currentDay) {
          offsetNum = viewStartDay - currentDay;
        }
        if (customDay > viewStartDay) {
          whatDayTime += ((customDay === 0 ? 7 : customDay) - viewStartDay + offsetNum) * staticDayTime_1;
        } else if (customDay < viewStartDay) {
          whatDayTime += (7 - viewStartDay + customDay + offsetNum) * staticDayTime_1;
        } else {
          whatDayTime += offsetNum * staticDayTime_1;
        }
      }
    }
    if (offsetWeek && !isNaN(offsetWeek)) {
      whatDayTime += offsetWeek * staticWeekTime_1;
    }
    return new Date(whatDayTime);
  }
  return date;
}
var getWhatWeek_1 = getWhatWeek;

function helperCreateGetDateWeek(getStartDate) {
  return function (date, firstDay) {
    var viewStartDay = isNumber_1(firstDay) ? firstDay : setupDefaults_1.firstDayOfWeek;
    var targetDate = getWhatWeek_1(date, 0, viewStartDay, viewStartDay);
    if (isValidDate_1(targetDate)) {
      var targetOffsetDate = new Date(targetDate.getFullYear(), targetDate.getMonth(), targetDate.getDate());
      var targerStartDate = getStartDate(targetDate);
      var targetFirstDay = targerStartDate.getDay();
      if (targetFirstDay > viewStartDay) {
        targerStartDate.setDate(7 - targetFirstDay + viewStartDay + 1);
      }
      if (targetFirstDay < viewStartDay) {
        targerStartDate.setDate(viewStartDay - targetFirstDay + 1);
      }
      return Math.floor((helperGetDateTime_1(targetOffsetDate) - helperGetDateTime_1(targerStartDate)) / staticWeekTime_1 + 1);
    }
    return NaN;
  };
}
var helperCreateGetDateWeek_1 = helperCreateGetDateWeek;

/**
  * 返回某个年份的第几周
  *
  * @param {Date} date 日期或数字
  * @param {Number} firstDay 从年初的星期几为起始开始周开始算，默认星期一
  * @return {Number}
  */
var getYearWeek = helperCreateGetDateWeek_1(function (targetDate) {
  return new Date(targetDate.getFullYear(), 0, 1);
});
var getYearWeek_1 = getYearWeek;

function helperGetYMD(date) {
  return new Date(helperGetDateFullYear_1(date), helperGetDateMonth_1(date), date.getDate());
}
var helperGetYMD_1 = helperGetYMD;

function helperGetYMDTime(date) {
  return helperGetDateTime_1(helperGetYMD_1(date));
}
var helperGetYMDTime_1 = helperGetYMDTime;

/**
  * 返回某个年份的第几天
  *
  * @param {Date} date 日期或数字
  * @return {Number}
  */
function getYearDay(date) {
  date = toStringDate_1(date);
  if (isValidDate_1(date)) {
    return Math.floor((helperGetYMDTime_1(date) - helperGetYMDTime_1(getWhatYear_1(date, 0, staticStrFirst_1))) / staticDayTime_1) + 1;
  }
  return NaN;
}
var getYearDay_1 = getYearDay;

/**
  * 用指定字符从前面开始补全字符串
  *
  * @param {String} str 字符串
  * @param {Number} targetLength 结果长度
  * @param {Number} padString 补全字符
  * @return {String}
  */
function padStart(str, targetLength, padString) {
  var rest = toValueString_1(str);
  targetLength = targetLength >> 0;
  padString = isUndefined_1(padString) ? ' ' : '' + padString;
  if (rest.padStart) {
    return rest.padStart(targetLength, padString);
  }
  if (targetLength > rest.length) {
    targetLength -= rest.length;
    if (targetLength > padString.length) {
      padString += helperStringRepeat_1(padString, targetLength / padString.length);
    }
    return padString.slice(0, targetLength) + rest;
  }
  return rest;
}
var padStart_1 = padStart;

function handleCustomTemplate(date, formats, match, value) {
  var format = formats[match];
  if (format) {
    if (isFunction_1(format)) {
      return format(value, match, date);
    } else {
      return format[value];
    }
  }
  return value;
}
var dateFormatRE = /\[([^\]]+)]|y{2,4}|M{1,2}|d{1,2}|H{1,2}|h{1,2}|m{1,2}|s{1,2}|S{1,3}|Z{1,2}|W{1,2}|D{1,3}|[aAeEq]/g;

/**
  * 日期格式化为字符串，转义符号 []
  *
  * @param {Date} date 日期或数字
  * @param {String} format 输出日期格式(年份(yy|yyyy)、月份(M|MM自动补0)、天(d|dd自动补0)、12小时制(h|hh自动补0)、24小时制(H|HH自动补0)、分钟(m|mm自动补0)、秒(s|ss自动补0)、毫秒(S|SSS自动补0)、D当年的第几天、a/A上午下午、e/E星期几、w当年的第几周、W当月的第几周、q当年第几个季度、Z时区)
  * @param {Object} options {formats: {q: ['日', '一', '二', '三', '四', '五', '六'], E: function (value, match, date) {return '三'}, }} 自定义格式化模板
  * @return {String}
  */
function toDateString(date, format, options) {
  if (date) {
    date = toStringDate_1(date);
    if (isValidDate_1(date)) {
      var result = format || setupDefaults_1.parseDateFormat || setupDefaults_1.formatString;
      var hours = date.getHours();
      var apm = hours < 12 ? 'am' : 'pm';
      var formats = assign_1({}, setupDefaults_1.parseDateRules || setupDefaults_1.formatStringMatchs, options ? options.formats : null);
      var fy = function (match, length) {
        return ('' + helperGetDateFullYear_1(date)).substr(4 - length);
      };
      var fM = function (match, length) {
        return padStart_1(helperGetDateMonth_1(date) + 1, length, '0');
      };
      var fd = function (match, length) {
        return padStart_1(date.getDate(), length, '0');
      };
      var fH = function (match, length) {
        return padStart_1(hours, length, '0');
      };
      var fh = function (match, length) {
        return padStart_1(hours <= 12 ? hours : hours - 12, length, '0');
      };
      var fm = function (match, length) {
        return padStart_1(date.getMinutes(), length, '0');
      };
      var fs = function (match, length) {
        return padStart_1(date.getSeconds(), length, '0');
      };
      var fS = function (match, length) {
        return padStart_1(date.getMilliseconds(), length, '0');
      };
      var fZ = function (match, length) {
        var zoneHours = date.getTimezoneOffset() / 60 * -1;
        return handleCustomTemplate(date, formats, match, (zoneHours >= 0 ? '+' : '-') + padStart_1(zoneHours, 2, '0') + (length === 1 ? ':' : '') + '00');
      };
      var fW = function (match, length) {
        return padStart_1(handleCustomTemplate(date, formats, match, getYearWeek_1(date, (options ? options.firstDay : null) || setupDefaults_1.firstDayOfWeek)), length, '0');
      };
      var fD = function (match, length) {
        return padStart_1(handleCustomTemplate(date, formats, match, getYearDay_1(date)), length, '0');
      };
      var parseDates = {
        yyyy: fy,
        yy: fy,
        MM: fM,
        M: fM,
        dd: fd,
        d: fd,
        HH: fH,
        H: fH,
        hh: fh,
        h: fh,
        mm: fm,
        m: fm,
        ss: fs,
        s: fs,
        SSS: fS,
        S: fS,
        ZZ: fZ,
        Z: fZ,
        WW: fW,
        W: fW,
        DDD: fD,
        D: fD,
        a: function (match) {
          return handleCustomTemplate(date, formats, match, apm);
        },
        A: function (match) {
          return handleCustomTemplate(date, formats, match, helperStringUpperCase_1(apm));
        },
        e: function (match) {
          return handleCustomTemplate(date, formats, match, date.getDay());
        },
        E: function (match) {
          return handleCustomTemplate(date, formats, match, date.getDay());
        },
        q: function (match) {
          return handleCustomTemplate(date, formats, match, Math.floor((helperGetDateMonth_1(date) + 3) / 3));
        }
      };
      return result.replace(dateFormatRE, function (match, skip) {
        return skip || (parseDates[match] ? parseDates[match](match, match.length) : match);
      });
    }
    return 'Invalid Date';
  }
  return '';
}
var toDateString_1 = toDateString;

/**
 * 返回当前时间戳
 *
 * @returns Number
 */
var now = Date.now || function () {
  return helperGetDateTime_1(helperNewDate_1());
};
var now_1 = now;

/**
 * 将日期格式化为时间戳
 *
  * @param {String/Number/Date} str 日期或数字
  * @param {String} format 解析日期格式
 * @returns Number
 */
var timestamp = function (str, format) {
  if (str) {
    var date = toStringDate_1(str, format);
    return isDate_1(date) ? helperGetDateTime_1(date) : date;
  }
  return now_1();
};
var timestamp_1 = timestamp;

/**
 * 比较两个日期
 *
 * @param {Number/String/Date} date1 日期
 * @param {Number/String/Date} date2 日期
 * @param {String} format 对比格式
 */
function isDateSame(date1, date2, format) {
  if (date1 && date2) {
    date1 = toDateString_1(date1, format);
    return date1 !== 'Invalid Date' && date1 === toDateString_1(date2, format);
  }
  return false;
}
var isDateSame_1 = isDateSame;

/**
  * 返回某个月的第几周
  *
  * @param {Date} date 日期或数字
  * @param {Number} firstDay 周视图的起始天，默认星期一
  * @return {Number}
  */
var getMonthWeek = helperCreateGetDateWeek_1(function (targetDate) {
  return new Date(targetDate.getFullYear(), targetDate.getMonth(), 1);
});
var getMonthWeek_1 = getMonthWeek;

/**
  * 返回某个年份的天数
  *
  * @param {Date} date 日期或数字
  * @param {Number} offset 年(默认当年)、前几个年、后几个年
  * @return {Number}
  */
function getDayOfYear(date, year) {
  date = toStringDate_1(date);
  if (isValidDate_1(date)) {
    return isLeapYear_1(getWhatYear_1(date, year)) ? 366 : 365;
  }
  return NaN;
}
var getDayOfYear_1 = getDayOfYear;

/**
  * 返回某个月份的天数
  *
  * @param {Date} date 日期或数字
  * @param {Number} offset 月(默认当月)、前几个月、后几个月
  * @return {Number}
  */
function getDayOfMonth(date, month) {
  date = toStringDate_1(date);
  if (isValidDate_1(date)) {
    return Math.floor((helperGetDateTime_1(getWhatMonth_1(date, month, staticStrLast_1)) - helperGetDateTime_1(getWhatMonth_1(date, month, staticStrFirst_1))) / staticDayTime_1) + 1;
  }
  return NaN;
}
var getDayOfMonth_1 = getDayOfMonth;

var dateDiffRules = [['yyyy', 31536000000], ['MM', 2592000000], ['dd', 86400000], ['HH', 3600000], ['mm', 60000], ['ss', 1000], ['S', 0]];

/**
  * 返回两个日期之间差距,如果结束日期小于开始日期done为fasle
  *
  * @param {Date} startDate 开始日期
  * @param {Date} endDate 结束日期或当期日期
  * @return {Object}
  */
function getDateDiff(startDate, endDate) {
  var startTime, endTime, item, diffTime, len, index;
  var result = {
    done: false,
    time: 0
  };
  startDate = toStringDate_1(startDate);
  endDate = endDate ? toStringDate_1(endDate) : helperNewDate_1();
  if (isValidDate_1(startDate) && isValidDate_1(endDate)) {
    startTime = helperGetDateTime_1(startDate);
    endTime = helperGetDateTime_1(endDate);
    if (startTime < endTime) {
      diffTime = result.time = endTime - startTime;
      result.done = true;
      for (index = 0, len = dateDiffRules.length; index < len; index++) {
        item = dateDiffRules[index];
        if (diffTime >= item[1]) {
          if (index === len - 1) {
            result[item[0]] = diffTime || 0;
          } else {
            result[item[0]] = Math.floor(diffTime / item[1]);
            diffTime -= result[item[0]] * item[1];
          }
        } else {
          result[item[0]] = 0;
        }
      }
    }
  }
  return result;
}
var getDateDiff_1 = getDateDiff;

/**
  * 用指定字符从后面开始补全字符串
  *
  * @param {String} str 字符串
  * @param {Number} targetLength 结果长度
  * @param {Number} padString 补全字符
  * @return {String}
  */
function padEnd(str, targetLength, padString) {
  var rest = toValueString_1(str);
  targetLength = targetLength >> 0;
  padString = isUndefined_1(padString) ? ' ' : '' + padString;
  if (rest.padEnd) {
    return rest.padEnd(targetLength, padString);
  }
  if (targetLength > rest.length) {
    targetLength -= rest.length;
    if (targetLength > padString.length) {
      padString += helperStringRepeat_1(padString, targetLength / padString.length);
    }
    return rest + padString.slice(0, targetLength);
  }
  return rest;
}
var padEnd_1 = padEnd;

/**
  * 将字符串重复 n 次
  *
  * @param {String} str 字符串
  * @param {Number} count 次数
  * @return {String}
  */
function repeat(str, count) {
  return helperStringRepeat_1(toValueString_1(str), count);
}
var repeat_1 = repeat;

/**
  * 去除字符串右边的空格
  *
  * @param {String} str 字符串
  * @return {String}
  */
function trimRight(str) {
  return str && str.trimRight ? str.trimRight() : toValueString_1(str).replace(/[\s\uFEFF\xA0]+$/g, '');
}
var trimRight_1 = trimRight;

/**
  * 去除字符串左边的空格
  *
  * @param {String} str 字符串
  * @return {String}
  */
function trimLeft(str) {
  return str && str.trimLeft ? str.trimLeft() : toValueString_1(str).replace(/^[\s\uFEFF\xA0]+/g, '');
}
var trimLeft_1 = trimLeft;

/**
  * 去除字符串左右两边的空格
  *
  * @param {String} str 字符串
  * @return {String}
  */
function trim(str) {
  return str && str.trim ? str.trim() : trimRight_1(trimLeft_1(str));
}
var trim_1 = trim;

var staticEscapeMap = {
  '&': '&amp;',
  '<': '&lt;',
  '>': '&gt;',
  '"': '&quot;',
  "'": '&#x27;',
  '`': '&#x60;'
};
var staticEscapeMap_1 = staticEscapeMap;

function helperFormatEscaper(dataMap) {
  var replaceRegexp = new RegExp('(?:' + keys_1(dataMap).join('|') + ')', 'g');
  return function (str) {
    return toValueString_1(str).replace(replaceRegexp, function (match) {
      return dataMap[match];
    });
  };
}
var helperFormatEscaper_1 = helperFormatEscaper;

/**
  * 转义HTML字符串，替换&, <, >, ", ', `字符
  *
  * @param {String} str 字符串
  * @return {String}
  */
var escape = helperFormatEscaper_1(staticEscapeMap_1);
var _escape = escape;

var unescapeMap = {};
each_1(staticEscapeMap_1, function (item, key) {
  unescapeMap[staticEscapeMap_1[key]] = key;
});

/**
  * 反转escape
  *
  * @param {String} str 字符串
  * @return {String}
  */
var unescape$1 = helperFormatEscaper_1(unescapeMap);
var _unescape = unescape$1;

function helperStringSubstring(str, start, end) {
  return str.substring(start, end);
}
var helperStringSubstring_1 = helperStringSubstring;

function helperStringLowerCase(str) {
  return str.toLowerCase();
}
var helperStringLowerCase_1 = helperStringLowerCase;

var camelCacheMaps = {};

/**
  * 将带字符串转成驼峰字符串,例如： project-name 转为 projectName
  *
  * @param {String} str 字符串
  * @return {String}
  */
function camelCase(str) {
  str = toValueString_1(str);
  if (camelCacheMaps[str]) {
    return camelCacheMaps[str];
  }
  var strLen = str.length;
  var rest = str.replace(/([-]+)/g, function (text, flag, index) {
    return index && index + flag.length < strLen ? '-' : '';
  });
  strLen = rest.length;
  rest = rest.replace(/([A-Z]+)/g, function (text, upper, index) {
    var upperLen = upper.length;
    upper = helperStringLowerCase_1(upper);
    if (index) {
      if (upperLen > 2 && index + upperLen < strLen) {
        return helperStringUpperCase_1(helperStringSubstring_1(upper, 0, 1)) + helperStringSubstring_1(upper, 1, upperLen - 1) + helperStringUpperCase_1(helperStringSubstring_1(upper, upperLen - 1, upperLen));
      }
      return helperStringUpperCase_1(helperStringSubstring_1(upper, 0, 1)) + helperStringSubstring_1(upper, 1, upperLen);
    } else {
      if (upperLen > 1 && index + upperLen < strLen) {
        return helperStringSubstring_1(upper, 0, upperLen - 1) + helperStringUpperCase_1(helperStringSubstring_1(upper, upperLen - 1, upperLen));
      }
    }
    return upper;
  }).replace(/(-[a-zA-Z])/g, function (text, upper) {
    return helperStringUpperCase_1(helperStringSubstring_1(upper, 1, upper.length));
  });
  camelCacheMaps[str] = rest;
  return rest;
}
var camelCase_1 = camelCase;

var kebabCacheMaps = {};

/**
  * 将带驼峰字符串转成字符串,例如： projectName 转为 project-name
  *
  * @param {String} str 字符串
  * @return {String}
  */
function kebabCase(str) {
  str = toValueString_1(str);
  if (kebabCacheMaps[str]) {
    return kebabCacheMaps[str];
  }
  if (/^[A-Z]+$/.test(str)) {
    return helperStringLowerCase_1(str);
  }
  var rest = str.replace(/^([a-z])([A-Z]+)([a-z]+)$/, function (text, prevLower, upper, nextLower) {
    var upperLen = upper.length;
    if (upperLen > 1) {
      return prevLower + '-' + helperStringLowerCase_1(helperStringSubstring_1(upper, 0, upperLen - 1)) + '-' + helperStringLowerCase_1(helperStringSubstring_1(upper, upperLen - 1, upperLen)) + nextLower;
    }
    return helperStringLowerCase_1(prevLower + '-' + upper + nextLower);
  }).replace(/^([A-Z]+)([a-z]+)?$/, function (text, upper, nextLower) {
    var upperLen = upper.length;
    return helperStringLowerCase_1(helperStringSubstring_1(upper, 0, upperLen - 1) + '-' + helperStringSubstring_1(upper, upperLen - 1, upperLen) + (nextLower || ''));
  }).replace(/([a-z]?)([A-Z]+)([a-z]?)/g, function (text, prevLower, upper, nextLower, index) {
    var upperLen = upper.length;
    if (upperLen > 1) {
      if (prevLower) {
        prevLower += '-';
      }
      if (nextLower) {
        return (prevLower || '') + helperStringLowerCase_1(helperStringSubstring_1(upper, 0, upperLen - 1)) + '-' + helperStringLowerCase_1(helperStringSubstring_1(upper, upperLen - 1, upperLen)) + nextLower;
      }
    }
    return (prevLower || '') + (index ? '-' : '') + helperStringLowerCase_1(upper) + (nextLower || '');
  });
  rest = rest.replace(/([-]+)/g, function (text, flag, index) {
    return index && index + flag.length < rest.length ? '-' : '';
  });
  kebabCacheMaps[str] = rest;
  return rest;
}
var kebabCase_1 = kebabCase;

/**
  * 判断字符串是否在源字符串的头部
  *
  * @param {String} str 字符串
  * @param {String/Number} val 值
  * @param {Number} startIndex 开始索引
  * @return {String}
  */
function startsWith(str, val, startIndex) {
  var rest = toValueString_1(str);
  return (arguments.length === 1 ? rest : rest.substring(startIndex)).indexOf(val) === 0;
}
var startsWith_1 = startsWith;

/**
  * 判断字符串是否在源字符串的尾部
  *
  * @param {String} str 字符串
  * @param {String/Number} val 值
  * @param {Number} startIndex 开始索引
  * @return {String}
  */
function endsWith(str, val, startIndex) {
  var rest = toValueString_1(str);
  var argsLen = arguments.length;
  return argsLen > 1 && (argsLen > 2 ? rest.substring(0, startIndex).indexOf(val) === startIndex - 1 : rest.indexOf(val) === rest.length - 1);
}
var endsWith_1 = endsWith;

/**
 * 解析动态字符串模板
 * @param {atring} str 字符串模板
 * @param {any | any[]} args 对象
 * @param {any} options 
 */
function template(str, args, options) {
  return toValueString_1(str).replace((options || setupDefaults_1).tmplRE || /\{{2}([.\w[\]\s]+)\}{2}/g, function (match, key) {
    return get_1(args, trim_1(key));
  });
}
var template_1 = template;

/**
 * 字符串格式化占位符
 * @param { string } str 
 * @param { object | any[] } obj 
 */
function toFormatString(str, obj) {
  return template_1(str, obj, {
    tmplRE: /\{([.\w[\]\s]+)\}/g
  });
}
var toFormatString_1 = toFormatString;

/**
 * 一个空的方法，始终返回 undefined，可用于初始化值
 */
function noop$1() {}
var noop_1 = noop$1;

/**
  * 创建一个绑定上下文的函数
  *
  * @param {Function} callback 函数
  * @param {Object} context 上下文
  * @param {*} args 额外的参数
  * @return {Object}
  */
function bind(callback, context) {
  var args = slice_1(arguments, 2);
  return function () {
    return callback.apply(context, slice_1(arguments).concat(args));
  };
}
var bind_1 = bind;

/**
  * 创建一个只能调用一次的函数,只会返回第一次执行后的结果
  *
  * @param {Function} callback 函数
  * @param {Object} context 上下文
  * @param {*} args 额外的参数
  * @return {Object}
  */
function once(callback, context) {
  var done = false;
  var rest = null;
  var args = slice_1(arguments, 2);
  return function () {
    if (done) {
      return rest;
    }
    rest = callback.apply(context, slice_1(arguments).concat(args));
    done = true;
    return rest;
  };
}
var once_1 = once;

/**
  * 创建一个函数, 调用次数超过 count 次之后执行回调并将所有结果记住后返回
  *
  * @param {Number} count 调用次数
  * @param {Function} callback 完成回调
  * @return {Object}
  */
function after(count, callback, context) {
  var runCount = 0;
  var rests = [];
  return function () {
    var args = arguments;
    runCount++;
    if (runCount <= count) {
      rests.push(args[0]);
    }
    if (runCount >= count) {
      callback.apply(context, [rests].concat(slice_1(args)));
    }
  };
}
var after_1 = after;

/**
  * 创建一个函数, 调用次数不超过 count 次之前执行回调并将所有结果记住后返回
  *
  * @param {Number} count 调用次数
  * @param {Function} callback 完成回调
  * @return {Object}
  */
function before(count, callback, context) {
  var runCount = 0;
  var rests = [];
  context = context || this;
  return function () {
    var args = arguments;
    runCount++;
    if (runCount < count) {
      rests.push(args[0]);
      callback.apply(context, [rests].concat(slice_1(args)));
    }
  };
}
var before_1 = before;

/**
  * 节流函数；当被调用 n 毫秒后才会执行，如果在这时间内又被调用则至少每隔 n 秒毫秒调用一次该函数
  *
  * @param {Function} callback 回调
  * @param {Number} wait 多少秒毫
  * @param {Object} options 参数{leading: 是否在之前执行, trailing: 是否在之后执行}
  * @return {Function}
  */
function throttle(callback, wait, options) {
  var args = null;
  var context = null;
  var opts = options || {};
  var runFlag = false;
  var timeout = null;
  var optLeading = 'leading' in opts ? opts.leading : true;
  var optTrailing = 'trailing' in opts ? opts.trailing : false;
  var gcFn = function () {
    args = null;
    context = null;
  };
  var runFn = function () {
    runFlag = true;
    callback.apply(context, args);
    timeout = setTimeout(endFn, wait);
    gcFn();
  };
  var endFn = function () {
    timeout = null;
    if (!runFlag && optTrailing === true) {
      runFn();
    }
  };
  var cancelFn = function () {
    var rest = timeout !== null;
    if (rest) {
      clearTimeout(timeout);
    }
    gcFn();
    timeout = null;
    runFlag = false;
    return rest;
  };
  var throttled = function () {
    args = arguments;
    context = this;
    runFlag = false;
    if (timeout === null) {
      if (optLeading === true) {
        runFn();
      } else if (optTrailing === true) {
        timeout = setTimeout(endFn, wait);
      }
    }
  };
  throttled.cancel = cancelFn;
  return throttled;
}
var throttle_1 = throttle;

/**
  * 函数去抖；当被调用 n 毫秒后才会执行，如果在这时间内又被调用则将重新计算执行时间
  *
  * @param {Function} callback 回调
  * @param {Number} wait 多少秒毫
  * @param {Object} options 参数{leading: 是否在之前执行, trailing: 是否在之后执行}
  * @return {Function}
  */
function debounce$3(callback, wait, options) {
  var args = null;
  var context = null;
  var opts = options || {};
  var runFlag = false;
  var timeout = null;
  var isLeading = typeof options === 'boolean';
  var optLeading = 'leading' in opts ? opts.leading : isLeading;
  var optTrailing = 'trailing' in opts ? opts.trailing : !isLeading;
  var gcFn = function () {
    args = null;
    context = null;
  };
  var runFn = function () {
    runFlag = true;
    callback.apply(context, args);
    gcFn();
  };
  var endFn = function () {
    if (optLeading === true) {
      timeout = null;
    }
    if (!runFlag && optTrailing === true) {
      runFn();
    }
  };
  var cancelFn = function () {
    var rest = timeout !== null;
    if (rest) {
      clearTimeout(timeout);
    }
    gcFn();
    timeout = null;
    runFlag = false;
    return rest;
  };
  var debounced = function () {
    runFlag = false;
    args = arguments;
    context = this;
    if (timeout === null) {
      if (optLeading === true) {
        runFn();
      }
    } else {
      clearTimeout(timeout);
    }
    timeout = setTimeout(endFn, wait);
  };
  debounced.cancel = cancelFn;
  return debounced;
}
var debounce_1 = debounce$3;

/**
  * 该方法和 setTimeout 一样的效果，区别就是支持上下文和额外参数
  *
  * @param {Function} callback 函数
  * @param {Number} wait 延迟毫秒
  * @param {*} args 额外的参数
  * @return {Number}
 */
function delay(callback, wait) {
  var args = slice_1(arguments, 2);
  var context = this;
  return setTimeout(function () {
    callback.apply(context, args);
  }, wait);
}
var delay_1 = delay;

var staticDecodeURIComponent = decodeURIComponent;
var staticDecodeURIComponent_1 = staticDecodeURIComponent;

/**
 * 反序列化查询参数
 * @param {String} query 字符串
 */
function unserialize(str) {
  var items;
  var result = {};
  if (str && isString_1(str)) {
    arrayEach_1(str.split('&'), function (param) {
      items = param.split('=');
      result[staticDecodeURIComponent_1(items[0])] = staticDecodeURIComponent_1(items[1] || '');
    });
  }
  return result;
}
var unserialize_1 = unserialize;

var staticEncodeURIComponent = encodeURIComponent;
var staticEncodeURIComponent_1 = staticEncodeURIComponent;

function stringifyParams(resultVal, resultKey, isArr) {
  var _arr;
  var result = [];
  each_1(resultVal, function (item, key) {
    _arr = isArray_1(item);
    if (isPlainObject_1(item) || _arr) {
      result = result.concat(stringifyParams(item, resultKey + '[' + key + ']', _arr));
    } else {
      result.push(staticEncodeURIComponent_1(resultKey + '[' + (isArr ? '' : key) + ']') + '=' + staticEncodeURIComponent_1(isNull_1(item) ? '' : item));
    }
  });
  return result;
}

/**
 * 序列化查询参数
 *
 * @param {Object} query 查询参数
 */
function serialize(query) {
  var _arr;
  var params = [];
  each_1(query, function (item, key) {
    if (!isUndefined_1(item)) {
      _arr = isArray_1(item);
      if (isPlainObject_1(item) || _arr) {
        params = params.concat(stringifyParams(item, key, _arr));
      } else {
        params.push(staticEncodeURIComponent_1(key) + '=' + staticEncodeURIComponent_1(isNull_1(item) ? '' : item));
      }
    }
  });
  return params.join('&').replace(/%20/g, '+');
}
var serialize_1 = serialize;

/* eslint-disable valid-typeof */
var staticLocation = typeof location === staticStrUndefined_1 ? 0 : location;
var staticLocation_1 = staticLocation;

function helperGetLocatOrigin() {
  return staticLocation_1 ? staticLocation_1.origin || staticLocation_1.protocol + '//' + staticLocation_1.host : '';
}
var helperGetLocatOrigin_1 = helperGetLocatOrigin;

function parseURLQuery(uri) {
  return unserialize_1(uri.split('?')[1] || '');
}
function parseUrl(url) {
  var hashs, portText, searchs, parsed;
  var href = '' + url;
  if (href.indexOf('//') === 0) {
    href = (staticLocation_1 ? staticLocation_1.protocol : '') + href;
  } else if (href.indexOf('/') === 0) {
    href = helperGetLocatOrigin_1() + href;
  }
  searchs = href.replace(/#.*/, '').match(/(\?.*)/);
  parsed = {
    href: href,
    hash: '',
    host: '',
    hostname: '',
    protocol: '',
    port: '',
    search: searchs && searchs[1] && searchs[1].length > 1 ? searchs[1] : ''
  };
  parsed.path = href.replace(/^([a-z0-9.+-]*:)\/\//, function (text, protocol) {
    parsed.protocol = protocol;
    return '';
  }).replace(/^([a-z0-9.+-]*)(:\d+)?\/?/, function (text, hostname, port) {
    portText = port || '';
    parsed.port = portText.replace(':', '');
    parsed.hostname = hostname;
    parsed.host = hostname + portText;
    return '/';
  }).replace(/(#.*)/, function (text, hash) {
    parsed.hash = hash.length > 1 ? hash : '';
    return '';
  });
  hashs = parsed.hash.match(/#((.*)\?|(.*))/);
  parsed.pathname = parsed.path.replace(/(\?|#.*).*/, '');
  parsed.origin = parsed.protocol + '//' + parsed.host;
  parsed.hashKey = hashs ? hashs[2] || hashs[1] || '' : '';
  parsed.hashQuery = parseURLQuery(parsed.hash);
  parsed.searchQuery = parseURLQuery(parsed.search);
  return parsed;
}
var parseUrl_1 = parseUrl;

function getBaseURL() {
  if (staticLocation_1) {
    var pathname = staticLocation_1.pathname;
    var lastIndex = lastIndexOf_1(pathname, '/') + 1;
    return helperGetLocatOrigin_1() + (lastIndex === pathname.length ? pathname : pathname.substring(0, lastIndex));
  }
  return '';
}
var getBaseURL_1 = getBaseURL;

/**
  * 获取地址栏信息
  *
  * @return Object
  */
function locat() {
  return staticLocation_1 ? parseUrl_1(staticLocation_1.href) : {};
}
var locat_1 = locat;

function toCookieUnitTime(unit, expires) {
  var num = parseFloat(expires);
  var nowdate = helperNewDate_1();
  var time = helperGetDateTime_1(nowdate);
  switch (unit) {
    case 'y':
      return helperGetDateTime_1(getWhatYear_1(nowdate, num));
    case 'M':
      return helperGetDateTime_1(getWhatMonth_1(nowdate, num));
    case 'd':
      return helperGetDateTime_1(getWhatDay_1(nowdate, num));
    case 'h':
    case 'H':
      return time + num * 60 * 60 * 1000;
    case 'm':
      return time + num * 60 * 1000;
    case 's':
      return time + num * 1000;
  }
  return time;
}
function toCookieUTCString(date) {
  return (isDate_1(date) ? date : new Date(date)).toUTCString();
}

/**
  * cookie操作函数
  * @param {String/Array/Object} name 键/数组/对象
  * @param {String} value 值
  * @param {Object} options 参数
  *   @param {String} name: 键
  *   @param {Object} value: 值
  *   @param {String} path: 路径
  *   @param {String} domain: 作用域
  *   @param {Boolean} secure: 设置为安全的,只能用https协议
  *   @param {Number} expires: 过期时间,可以指定日期或者字符串，默认天
  */
function cookie(name, value, options) {
  if (staticDocument_1) {
    var opts, expires, values, result, cookies, keyIndex;
    var inserts = [];
    var args = arguments;
    if (isArray_1(name)) {
      inserts = name;
    } else if (args.length > 1) {
      inserts = [assign_1({
        name: name,
        value: value
      }, options)];
    } else if (isObject_1(name)) {
      inserts = [name];
    }
    if (inserts.length > 0) {
      arrayEach_1(inserts, function (obj) {
        opts = assign_1({}, setupDefaults_1.cookies, obj);
        values = [];
        if (opts.name) {
          expires = opts.expires;
          values.push(staticEncodeURIComponent_1(opts.name) + '=' + staticEncodeURIComponent_1(isObject_1(opts.value) ? JSON.stringify(opts.value) : opts.value));
          if (expires) {
            if (isNaN(expires)) {
              // UTCString || Unit
              expires = expires.replace(/^([0-9]+)(y|M|d|H|h|m|s)$/, function (text, num, unit) {
                return toCookieUTCString(toCookieUnitTime(unit, num));
              });
            } else if (/^[0-9]{11,13}$/.test(expires) || isDate_1(expires)) {
              // Date || now
              expires = toCookieUTCString(expires);
            } else {
              // day
              expires = toCookieUTCString(toCookieUnitTime('d', expires));
            }
            opts.expires = expires;
          }
          arrayEach_1(['expires', 'path', 'domain', 'secure'], function (key) {
            if (!isUndefined_1(opts[key])) {
              values.push(opts[key] && key === 'secure' ? key : key + '=' + opts[key]);
            }
          });
        }
        staticDocument_1.cookie = values.join('; ');
      });
      return true;
    } else {
      result = {};
      cookies = staticDocument_1.cookie;
      if (cookies) {
        arrayEach_1(cookies.split('; '), function (val) {
          keyIndex = val.indexOf('=');
          result[staticDecodeURIComponent_1(val.substring(0, keyIndex))] = staticDecodeURIComponent_1(val.substring(keyIndex + 1) || '');
        });
      }
      return args.length === 1 ? result[name] : result;
    }
  }
  return false;
}
function hasCookieItem(value) {
  return includes_1(cookieKeys(), value);
}
function getCookieItem(name) {
  return cookie(name);
}
function setCookieItem(name, value, options) {
  cookie(name, value, options);
  return cookie;
}
function removeCookieItem(name, options) {
  cookie(name, '', assign_1({
    expires: -1
  }, setupDefaults_1.cookies, options));
}
function cookieKeys() {
  return keys_1(cookie());
}
function cookieJson() {
  return cookie();
}
assign_1(cookie, {
  has: hasCookieItem,
  set: setCookieItem,
  setItem: setCookieItem,
  get: getCookieItem,
  getItem: getCookieItem,
  remove: removeCookieItem,
  removeItem: removeCookieItem,
  keys: cookieKeys,
  getJSON: cookieJson
});
var cookie_1 = cookie;

/* eslint-disable valid-typeof */
function isBrowseStorage(storage) {
  try {
    var testKey = '__xe_t';
    storage.setItem(testKey, 1);
    storage.removeItem(testKey);
    return true;
  } catch (e) {
    return false;
  }
}
function isBrowseType(type) {
  return navigator.userAgent.indexOf(type) > -1;
}

/**
  * 获取浏览器内核
  * @return Object
  */
function browse() {
  var $body, isChrome, isEdge;
  var isMobile = false;
  var isLocalStorage = false;
  var isSessionStorage = false;
  var result = {
    isNode: false,
    isMobile: isMobile,
    isPC: false,
    isDoc: !!staticDocument_1
  };
  if (!staticWindow_1 && typeof process !== staticStrUndefined_1) {
    result.isNode = true;
  } else {
    isEdge = isBrowseType('Edge');
    isChrome = isBrowseType('Chrome');
    isMobile = /(Android|webOS|iPhone|iPad|iPod|SymbianOS|BlackBerry|Windows Phone)/.test(navigator.userAgent);
    if (result.isDoc) {
      $body = staticDocument_1.body || staticDocument_1.documentElement;
      arrayEach_1(['webkit', 'khtml', 'moz', 'ms', 'o'], function (core) {
        result['-' + core] = !!$body[core + 'MatchesSelector'];
      });
    }
    try {
      isLocalStorage = isBrowseStorage(staticWindow_1.localStorage);
    } catch (e) {}
    try {
      isSessionStorage = isBrowseStorage(staticWindow_1.sessionStorage);
    } catch (e) {}
    assign_1(result, {
      edge: isEdge,
      firefox: isBrowseType('Firefox'),
      msie: !isEdge && result['-ms'],
      safari: !isChrome && !isEdge && isBrowseType('Safari'),
      isMobile: isMobile,
      isPC: !isMobile,
      isLocalStorage: isLocalStorage,
      isSessionStorage: isSessionStorage
    });
  }
  return result;
}
var browse_1 = browse;

// 核心


// 对象相关的方法






// 数组相关的方法






































// 基础方法

































































// 数值相关方法


















// 日期相关的方法


















// 字符串相关的方法
















// 函数相关的方法










// 地址相关的方法




// 浏览器相关的方法




assign_1(ctor, {
  // object
  assign: assign_1,
  objectEach: objectEach_1,
  lastObjectEach: lastObjectEach_1,
  objectMap: objectMap_1,
  merge: merge_1,
  // array
  uniq: uniq_1,
  union: union_1,
  sortBy: sortBy_1,
  orderBy: orderBy_1,
  shuffle: shuffle_1,
  sample: sample_1,
  some: some_1,
  every: every_1,
  slice: slice_1,
  filter: filter_1,
  find: find_1,
  findLast: findLast_1,
  findKey: findKey_1,
  includes: includes_1,
  arrayIndexOf: arrayIndexOf_1,
  arrayLastIndexOf: arrayLastIndexOf_1,
  map: map_1,
  reduce: reduce_1,
  copyWithin: copyWithin_1,
  chunk: chunk_1,
  zip: zip_1,
  unzip: unzip_1,
  zipObject: zipObject_1,
  flatten: flatten_1,
  toArray: toArray_1,
  includeArrays: includeArrays_1,
  pluck: pluck_1,
  invoke: invoke_1,
  arrayEach: arrayEach_1,
  lastArrayEach: lastArrayEach_1,
  toArrayTree: toArrayTree_1,
  toTreeArray: toTreeArray_1,
  findTree: findTree_1,
  eachTree: eachTree_1,
  mapTree: mapTree_1,
  filterTree: filterTree_1,
  searchTree: searchTree_1,
  // base
  hasOwnProp: hasOwnProp_1,
  eqNull: eqNull_1,
  isNaN: _isNaN,
  isFinite: _isFinite,
  isUndefined: isUndefined_1,
  isArray: isArray_1,
  isFloat: isFloat_1,
  isInteger: isInteger_1,
  isFunction: isFunction_1,
  isBoolean: isBoolean_1,
  isString: isString_1,
  isNumber: isNumber_1,
  isRegExp: isRegExp_1,
  isObject: isObject_1,
  isPlainObject: isPlainObject_1,
  isDate: isDate_1,
  isError: isError_1,
  isTypeError: isTypeError_1,
  isEmpty: isEmpty_1,
  isNull: isNull_1,
  isSymbol: isSymbol_1,
  isArguments: isArguments_1,
  isElement: isElement_1,
  isDocument: isDocument_1,
  isWindow: isWindow_1,
  isFormData: isFormData_1,
  isMap: isMap_1,
  isWeakMap: isWeakMap_1,
  isSet: isSet_1,
  isWeakSet: isWeakSet_1,
  isLeapYear: isLeapYear_1,
  isMatch: isMatch_1,
  isEqual: isEqual_1,
  isEqualWith: isEqualWith_1,
  getType: getType_1,
  uniqueId: uniqueId_1,
  getSize: getSize_1,
  indexOf: indexOf_1,
  lastIndexOf: lastIndexOf_1,
  findIndexOf: findIndexOf_1,
  findLastIndexOf: findLastIndexOf_1,
  toStringJSON: toStringJSON_1,
  toJSONString: toJSONString_1,
  keys: keys_1,
  values: values_1,
  entries: entries_1,
  pick: pick_1,
  omit: omit_1,
  first: first_1,
  last: last_1,
  each: each_1,
  forOf: forOf_1,
  lastForOf: lastForOf_1,
  lastEach: lastEach_1,
  has: has_1,
  get: get_1,
  set: set_1,
  groupBy: groupBy_1,
  countBy: countBy_1,
  clone: clone_1,
  clear: clear_1,
  remove: remove_1,
  range: range_1,
  destructuring: destructuring_1,
  // number
  random: random_1,
  min: min_1,
  max: max_1,
  commafy: commafy_1,
  round: round_1,
  ceil: ceil_1,
  floor: floor_1,
  toFixed: toFixed_1,
  toNumber: toNumber_1,
  toNumberString: toNumberString_1,
  toInteger: toInteger_1,
  add: add_1,
  subtract: subtract_1,
  multiply: multiply_1,
  divide: divide_1,
  sum: sum_1,
  mean: mean_1,
  // date
  now: now_1,
  timestamp: timestamp_1,
  isValidDate: isValidDate_1,
  isDateSame: isDateSame_1,
  toStringDate: toStringDate_1,
  toDateString: toDateString_1,
  getWhatYear: getWhatYear_1,
  getWhatQuarter: getWhatQuarter_1,
  getWhatMonth: getWhatMonth_1,
  getWhatWeek: getWhatWeek_1,
  getWhatDay: getWhatDay_1,
  getYearDay: getYearDay_1,
  getYearWeek: getYearWeek_1,
  getMonthWeek: getMonthWeek_1,
  getDayOfYear: getDayOfYear_1,
  getDayOfMonth: getDayOfMonth_1,
  getDateDiff: getDateDiff_1,
  // string
  trim: trim_1,
  trimLeft: trimLeft_1,
  trimRight: trimRight_1,
  escape: _escape,
  unescape: _unescape,
  camelCase: camelCase_1,
  kebabCase: kebabCase_1,
  repeat: repeat_1,
  padStart: padStart_1,
  padEnd: padEnd_1,
  startsWith: startsWith_1,
  endsWith: endsWith_1,
  template: template_1,
  toFormatString: toFormatString_1,
  toString: toValueString_1,
  toValueString: toValueString_1,
  // function
  noop: noop_1,
  property: property_1,
  bind: bind_1,
  once: once_1,
  after: after_1,
  before: before_1,
  throttle: throttle_1,
  debounce: debounce_1,
  delay: delay_1,
  // url
  unserialize: unserialize_1,
  serialize: serialize_1,
  parseUrl: parseUrl_1,
  // web
  getBaseURL: getBaseURL_1,
  locat: locat_1,
  browse: browse_1,
  cookie: cookie_1
});

var prism = createCommonjsModule(function (module) {
/* **********************************************
     Begin prism-core.js
********************************************** */

/// <reference lib="WebWorker"/>

var _self = typeof window !== 'undefined' ? window // if in browser
: typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope ? self // if in worker
: {} // if in node js
;

/**
 * Prism: Lightweight, robust, elegant syntax highlighting
 *
 * @license MIT <https://opensource.org/licenses/MIT>
 * @author Lea Verou <https://lea.verou.me>
 * @namespace
 * @public
 */
var Prism = function (_self) {
  // Private helper vars
  var lang = /(?:^|\s)lang(?:uage)?-([\w-]+)(?=\s|$)/i;
  var uniqueId = 0;

  // The grammar object for plaintext
  var plainTextGrammar = {};
  var _ = {
    /**
     * By default, Prism will attempt to highlight all code elements (by calling {@link Prism.highlightAll}) on the
     * current page after the page finished loading. This might be a problem if e.g. you wanted to asynchronously load
     * additional languages or plugins yourself.
     *
     * By setting this value to `true`, Prism will not automatically highlight all code elements on the page.
     *
     * You obviously have to change this value before the automatic highlighting started. To do this, you can add an
     * empty Prism object into the global scope before loading the Prism script like this:
     *
     * ```js
     * window.Prism = window.Prism || {};
     * Prism.manual = true;
     * // add a new <script> to load Prism's script
     * ```
     *
     * @default false
     * @type {boolean}
     * @memberof Prism
     * @public
     */
    manual: _self.Prism && _self.Prism.manual,
    /**
     * By default, if Prism is in a web worker, it assumes that it is in a worker it created itself, so it uses
     * `addEventListener` to communicate with its parent instance. However, if you're using Prism manually in your
     * own worker, you don't want it to do this.
     *
     * By setting this value to `true`, Prism will not add its own listeners to the worker.
     *
     * You obviously have to change this value before Prism executes. To do this, you can add an
     * empty Prism object into the global scope before loading the Prism script like this:
     *
     * ```js
     * window.Prism = window.Prism || {};
     * Prism.disableWorkerMessageHandler = true;
     * // Load Prism's script
     * ```
     *
     * @default false
     * @type {boolean}
     * @memberof Prism
     * @public
     */
    disableWorkerMessageHandler: _self.Prism && _self.Prism.disableWorkerMessageHandler,
    /**
     * A namespace for utility methods.
     *
     * All function in this namespace that are not explicitly marked as _public_ are for __internal use only__ and may
     * change or disappear at any time.
     *
     * @namespace
     * @memberof Prism
     */
    util: {
      encode: function encode(tokens) {
        if (tokens instanceof Token) {
          return new Token(tokens.type, encode(tokens.content), tokens.alias);
        } else if (Array.isArray(tokens)) {
          return tokens.map(encode);
        } else {
          return tokens.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/\u00a0/g, ' ');
        }
      },
      /**
       * Returns the name of the type of the given value.
       *
       * @param {any} o
       * @returns {string}
       * @example
       * type(null)      === 'Null'
       * type(undefined) === 'Undefined'
       * type(123)       === 'Number'
       * type('foo')     === 'String'
       * type(true)      === 'Boolean'
       * type([1, 2])    === 'Array'
       * type({})        === 'Object'
       * type(String)    === 'Function'
       * type(/abc+/)    === 'RegExp'
       */
      type: function (o) {
        return Object.prototype.toString.call(o).slice(8, -1);
      },
      /**
       * Returns a unique number for the given object. Later calls will still return the same number.
       *
       * @param {Object} obj
       * @returns {number}
       */
      objId: function (obj) {
        if (!obj['__id']) {
          Object.defineProperty(obj, '__id', {
            value: ++uniqueId
          });
        }
        return obj['__id'];
      },
      /**
       * Creates a deep clone of the given object.
       *
       * The main intended use of this function is to clone language definitions.
       *
       * @param {T} o
       * @param {Record<number, any>} [visited]
       * @returns {T}
       * @template T
       */
      clone: function deepClone(o, visited) {
        visited = visited || {};
        var clone;
        var id;
        switch (_.util.type(o)) {
          case 'Object':
            id = _.util.objId(o);
            if (visited[id]) {
              return visited[id];
            }
            clone = /** @type {Record<string, any>} */{};
            visited[id] = clone;
            for (var key in o) {
              if (o.hasOwnProperty(key)) {
                clone[key] = deepClone(o[key], visited);
              }
            }
            return /** @type {any} */clone;
          case 'Array':
            id = _.util.objId(o);
            if (visited[id]) {
              return visited[id];
            }
            clone = [];
            visited[id] = clone;
            ( /** @type {Array} */ /** @type {any} */o).forEach(function (v, i) {
              clone[i] = deepClone(v, visited);
            });
            return /** @type {any} */clone;
          default:
            return o;
        }
      },
      /**
       * Returns the Prism language of the given element set by a `language-xxxx` or `lang-xxxx` class.
       *
       * If no language is set for the element or the element is `null` or `undefined`, `none` will be returned.
       *
       * @param {Element} element
       * @returns {string}
       */
      getLanguage: function (element) {
        while (element) {
          var m = lang.exec(element.className);
          if (m) {
            return m[1].toLowerCase();
          }
          element = element.parentElement;
        }
        return 'none';
      },
      /**
       * Sets the Prism `language-xxxx` class of the given element.
       *
       * @param {Element} element
       * @param {string} language
       * @returns {void}
       */
      setLanguage: function (element, language) {
        // remove all `language-xxxx` classes
        // (this might leave behind a leading space)
        element.className = element.className.replace(RegExp(lang, 'gi'), '');

        // add the new `language-xxxx` class
        // (using `classList` will automatically clean up spaces for us)
        element.classList.add('language-' + language);
      },
      /**
       * Returns the script element that is currently executing.
       *
       * This does __not__ work for line script element.
       *
       * @returns {HTMLScriptElement | null}
       */
      currentScript: function () {
        if (typeof document === 'undefined') {
          return null;
        }
        if ('currentScript' in document && 1 < 2 /* hack to trip TS' flow analysis */) {
          return /** @type {any} */document.currentScript;
        }

        // IE11 workaround
        // we'll get the src of the current script by parsing IE11's error stack trace
        // this will not work for inline scripts

        try {
          throw new Error();
        } catch (err) {
          // Get file src url from stack. Specifically works with the format of stack traces in IE.
          // A stack will look like this:
          //
          // Error
          //    at _.util.currentScript (http://localhost/components/prism-core.js:119:5)
          //    at Global code (http://localhost/components/prism-core.js:606:1)

          var src = (/at [^(\r\n]*\((.*):[^:]+:[^:]+\)$/i.exec(err.stack) || [])[1];
          if (src) {
            var scripts = document.getElementsByTagName('script');
            for (var i in scripts) {
              if (scripts[i].src == src) {
                return scripts[i];
              }
            }
          }
          return null;
        }
      },
      /**
       * Returns whether a given class is active for `element`.
       *
       * The class can be activated if `element` or one of its ancestors has the given class and it can be deactivated
       * if `element` or one of its ancestors has the negated version of the given class. The _negated version_ of the
       * given class is just the given class with a `no-` prefix.
       *
       * Whether the class is active is determined by the closest ancestor of `element` (where `element` itself is
       * closest ancestor) that has the given class or the negated version of it. If neither `element` nor any of its
       * ancestors have the given class or the negated version of it, then the default activation will be returned.
       *
       * In the paradoxical situation where the closest ancestor contains __both__ the given class and the negated
       * version of it, the class is considered active.
       *
       * @param {Element} element
       * @param {string} className
       * @param {boolean} [defaultActivation=false]
       * @returns {boolean}
       */
      isActive: function (element, className, defaultActivation) {
        var no = 'no-' + className;
        while (element) {
          var classList = element.classList;
          if (classList.contains(className)) {
            return true;
          }
          if (classList.contains(no)) {
            return false;
          }
          element = element.parentElement;
        }
        return !!defaultActivation;
      }
    },
    /**
     * This namespace contains all currently loaded languages and the some helper functions to create and modify languages.
     *
     * @namespace
     * @memberof Prism
     * @public
     */
    languages: {
      /**
       * The grammar for plain, unformatted text.
       */
      plain: plainTextGrammar,
      plaintext: plainTextGrammar,
      text: plainTextGrammar,
      txt: plainTextGrammar,
      /**
       * Creates a deep copy of the language with the given id and appends the given tokens.
       *
       * If a token in `redef` also appears in the copied language, then the existing token in the copied language
       * will be overwritten at its original position.
       *
       * ## Best practices
       *
       * Since the position of overwriting tokens (token in `redef` that overwrite tokens in the copied language)
       * doesn't matter, they can technically be in any order. However, this can be confusing to others that trying to
       * understand the language definition because, normally, the order of tokens matters in Prism grammars.
       *
       * Therefore, it is encouraged to order overwriting tokens according to the positions of the overwritten tokens.
       * Furthermore, all non-overwriting tokens should be placed after the overwriting ones.
       *
       * @param {string} id The id of the language to extend. This has to be a key in `Prism.languages`.
       * @param {Grammar} redef The new tokens to append.
       * @returns {Grammar} The new language created.
       * @public
       * @example
       * Prism.languages['css-with-colors'] = Prism.languages.extend('css', {
       *     // Prism.languages.css already has a 'comment' token, so this token will overwrite CSS' 'comment' token
       *     // at its original position
       *     'comment': { ... },
       *     // CSS doesn't have a 'color' token, so this token will be appended
       *     'color': /\b(?:red|green|blue)\b/
       * });
       */
      extend: function (id, redef) {
        var lang = _.util.clone(_.languages[id]);
        for (var key in redef) {
          lang[key] = redef[key];
        }
        return lang;
      },
      /**
       * Inserts tokens _before_ another token in a language definition or any other grammar.
       *
       * ## Usage
       *
       * This helper method makes it easy to modify existing languages. For example, the CSS language definition
       * not only defines CSS highlighting for CSS documents, but also needs to define highlighting for CSS embedded
       * in HTML through `<style>` elements. To do this, it needs to modify `Prism.languages.markup` and add the
       * appropriate tokens. However, `Prism.languages.markup` is a regular JavaScript object literal, so if you do
       * this:
       *
       * ```js
       * Prism.languages.markup.style = {
       *     // token
       * };
       * ```
       *
       * then the `style` token will be added (and processed) at the end. `insertBefore` allows you to insert tokens
       * before existing tokens. For the CSS example above, you would use it like this:
       *
       * ```js
       * Prism.languages.insertBefore('markup', 'cdata', {
       *     'style': {
       *         // token
       *     }
       * });
       * ```
       *
       * ## Special cases
       *
       * If the grammars of `inside` and `insert` have tokens with the same name, the tokens in `inside`'s grammar
       * will be ignored.
       *
       * This behavior can be used to insert tokens after `before`:
       *
       * ```js
       * Prism.languages.insertBefore('markup', 'comment', {
       *     'comment': Prism.languages.markup.comment,
       *     // tokens after 'comment'
       * });
       * ```
       *
       * ## Limitations
       *
       * The main problem `insertBefore` has to solve is iteration order. Since ES2015, the iteration order for object
       * properties is guaranteed to be the insertion order (except for integer keys) but some browsers behave
       * differently when keys are deleted and re-inserted. So `insertBefore` can't be implemented by temporarily
       * deleting properties which is necessary to insert at arbitrary positions.
       *
       * To solve this problem, `insertBefore` doesn't actually insert the given tokens into the target object.
       * Instead, it will create a new object and replace all references to the target object with the new one. This
       * can be done without temporarily deleting properties, so the iteration order is well-defined.
       *
       * However, only references that can be reached from `Prism.languages` or `insert` will be replaced. I.e. if
       * you hold the target object in a variable, then the value of the variable will not change.
       *
       * ```js
       * var oldMarkup = Prism.languages.markup;
       * var newMarkup = Prism.languages.insertBefore('markup', 'comment', { ... });
       *
       * assert(oldMarkup !== Prism.languages.markup);
       * assert(newMarkup === Prism.languages.markup);
       * ```
       *
       * @param {string} inside The property of `root` (e.g. a language id in `Prism.languages`) that contains the
       * object to be modified.
       * @param {string} before The key to insert before.
       * @param {Grammar} insert An object containing the key-value pairs to be inserted.
       * @param {Object<string, any>} [root] The object containing `inside`, i.e. the object that contains the
       * object to be modified.
       *
       * Defaults to `Prism.languages`.
       * @returns {Grammar} The new grammar object.
       * @public
       */
      insertBefore: function (inside, before, insert, root) {
        root = root || ( /** @type {any} */_.languages);
        var grammar = root[inside];
        /** @type {Grammar} */
        var ret = {};
        for (var token in grammar) {
          if (grammar.hasOwnProperty(token)) {
            if (token == before) {
              for (var newToken in insert) {
                if (insert.hasOwnProperty(newToken)) {
                  ret[newToken] = insert[newToken];
                }
              }
            }

            // Do not insert token which also occur in insert. See #1525
            if (!insert.hasOwnProperty(token)) {
              ret[token] = grammar[token];
            }
          }
        }
        var old = root[inside];
        root[inside] = ret;

        // Update references in other language definitions
        _.languages.DFS(_.languages, function (key, value) {
          if (value === old && key != inside) {
            this[key] = ret;
          }
        });
        return ret;
      },
      // Traverse a language definition with Depth First Search
      DFS: function DFS(o, callback, type, visited) {
        visited = visited || {};
        var objId = _.util.objId;
        for (var i in o) {
          if (o.hasOwnProperty(i)) {
            callback.call(o, i, o[i], type || i);
            var property = o[i];
            var propertyType = _.util.type(property);
            if (propertyType === 'Object' && !visited[objId(property)]) {
              visited[objId(property)] = true;
              DFS(property, callback, null, visited);
            } else if (propertyType === 'Array' && !visited[objId(property)]) {
              visited[objId(property)] = true;
              DFS(property, callback, i, visited);
            }
          }
        }
      }
    },
    plugins: {},
    /**
     * This is the most high-level function in Prism’s API.
     * It fetches all the elements that have a `.language-xxxx` class and then calls {@link Prism.highlightElement} on
     * each one of them.
     *
     * This is equivalent to `Prism.highlightAllUnder(document, async, callback)`.
     *
     * @param {boolean} [async=false] Same as in {@link Prism.highlightAllUnder}.
     * @param {HighlightCallback} [callback] Same as in {@link Prism.highlightAllUnder}.
     * @memberof Prism
     * @public
     */
    highlightAll: function (async, callback) {
      _.highlightAllUnder(document, async, callback);
    },
    /**
     * Fetches all the descendants of `container` that have a `.language-xxxx` class and then calls
     * {@link Prism.highlightElement} on each one of them.
     *
     * The following hooks will be run:
     * 1. `before-highlightall`
     * 2. `before-all-elements-highlight`
     * 3. All hooks of {@link Prism.highlightElement} for each element.
     *
     * @param {ParentNode} container The root element, whose descendants that have a `.language-xxxx` class will be highlighted.
     * @param {boolean} [async=false] Whether each element is to be highlighted asynchronously using Web Workers.
     * @param {HighlightCallback} [callback] An optional callback to be invoked on each element after its highlighting is done.
     * @memberof Prism
     * @public
     */
    highlightAllUnder: function (container, async, callback) {
      var env = {
        callback: callback,
        container: container,
        selector: 'code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code'
      };
      _.hooks.run('before-highlightall', env);
      env.elements = Array.prototype.slice.apply(env.container.querySelectorAll(env.selector));
      _.hooks.run('before-all-elements-highlight', env);
      for (var i = 0, element; element = env.elements[i++];) {
        _.highlightElement(element, async === true, env.callback);
      }
    },
    /**
     * Highlights the code inside a single element.
     *
     * The following hooks will be run:
     * 1. `before-sanity-check`
     * 2. `before-highlight`
     * 3. All hooks of {@link Prism.highlight}. These hooks will be run by an asynchronous worker if `async` is `true`.
     * 4. `before-insert`
     * 5. `after-highlight`
     * 6. `complete`
     *
     * Some the above hooks will be skipped if the element doesn't contain any text or there is no grammar loaded for
     * the element's language.
     *
     * @param {Element} element The element containing the code.
     * It must have a class of `language-xxxx` to be processed, where `xxxx` is a valid language identifier.
     * @param {boolean} [async=false] Whether the element is to be highlighted asynchronously using Web Workers
     * to improve performance and avoid blocking the UI when highlighting very large chunks of code. This option is
     * [disabled by default](https://prismjs.com/faq.html#why-is-asynchronous-highlighting-disabled-by-default).
     *
     * Note: All language definitions required to highlight the code must be included in the main `prism.js` file for
     * asynchronous highlighting to work. You can build your own bundle on the
     * [Download page](https://prismjs.com/download.html).
     * @param {HighlightCallback} [callback] An optional callback to be invoked after the highlighting is done.
     * Mostly useful when `async` is `true`, since in that case, the highlighting is done asynchronously.
     * @memberof Prism
     * @public
     */
    highlightElement: function (element, async, callback) {
      // Find language
      var language = _.util.getLanguage(element);
      var grammar = _.languages[language];

      // Set language on the element, if not present
      _.util.setLanguage(element, language);

      // Set language on the parent, for styling
      var parent = element.parentElement;
      if (parent && parent.nodeName.toLowerCase() === 'pre') {
        _.util.setLanguage(parent, language);
      }
      var code = element.textContent;
      var env = {
        element: element,
        language: language,
        grammar: grammar,
        code: code
      };
      function insertHighlightedCode(highlightedCode) {
        env.highlightedCode = highlightedCode;
        _.hooks.run('before-insert', env);
        env.element.innerHTML = env.highlightedCode;
        _.hooks.run('after-highlight', env);
        _.hooks.run('complete', env);
        callback && callback.call(env.element);
      }
      _.hooks.run('before-sanity-check', env);

      // plugins may change/add the parent/element
      parent = env.element.parentElement;
      if (parent && parent.nodeName.toLowerCase() === 'pre' && !parent.hasAttribute('tabindex')) {
        parent.setAttribute('tabindex', '0');
      }
      if (!env.code) {
        _.hooks.run('complete', env);
        callback && callback.call(env.element);
        return;
      }
      _.hooks.run('before-highlight', env);
      if (!env.grammar) {
        insertHighlightedCode(_.util.encode(env.code));
        return;
      }
      if (async && _self.Worker) {
        var worker = new Worker(_.filename);
        worker.onmessage = function (evt) {
          insertHighlightedCode(evt.data);
        };
        worker.postMessage(JSON.stringify({
          language: env.language,
          code: env.code,
          immediateClose: true
        }));
      } else {
        insertHighlightedCode(_.highlight(env.code, env.grammar, env.language));
      }
    },
    /**
     * Low-level function, only use if you know what you’re doing. It accepts a string of text as input
     * and the language definitions to use, and returns a string with the HTML produced.
     *
     * The following hooks will be run:
     * 1. `before-tokenize`
     * 2. `after-tokenize`
     * 3. `wrap`: On each {@link Token}.
     *
     * @param {string} text A string with the code to be highlighted.
     * @param {Grammar} grammar An object containing the tokens to use.
     *
     * Usually a language definition like `Prism.languages.markup`.
     * @param {string} language The name of the language definition passed to `grammar`.
     * @returns {string} The highlighted HTML.
     * @memberof Prism
     * @public
     * @example
     * Prism.highlight('var foo = true;', Prism.languages.javascript, 'javascript');
     */
    highlight: function (text, grammar, language) {
      var env = {
        code: text,
        grammar: grammar,
        language: language
      };
      _.hooks.run('before-tokenize', env);
      if (!env.grammar) {
        throw new Error('The language "' + env.language + '" has no grammar.');
      }
      env.tokens = _.tokenize(env.code, env.grammar);
      _.hooks.run('after-tokenize', env);
      return Token.stringify(_.util.encode(env.tokens), env.language);
    },
    /**
     * This is the heart of Prism, and the most low-level function you can use. It accepts a string of text as input
     * and the language definitions to use, and returns an array with the tokenized code.
     *
     * When the language definition includes nested tokens, the function is called recursively on each of these tokens.
     *
     * This method could be useful in other contexts as well, as a very crude parser.
     *
     * @param {string} text A string with the code to be highlighted.
     * @param {Grammar} grammar An object containing the tokens to use.
     *
     * Usually a language definition like `Prism.languages.markup`.
     * @returns {TokenStream} An array of strings and tokens, a token stream.
     * @memberof Prism
     * @public
     * @example
     * let code = `var foo = 0;`;
     * let tokens = Prism.tokenize(code, Prism.languages.javascript);
     * tokens.forEach(token => {
     *     if (token instanceof Prism.Token && token.type === 'number') {
     *         console.log(`Found numeric literal: ${token.content}`);
     *     }
     * });
     */
    tokenize: function (text, grammar) {
      var rest = grammar.rest;
      if (rest) {
        for (var token in rest) {
          grammar[token] = rest[token];
        }
        delete grammar.rest;
      }
      var tokenList = new LinkedList();
      addAfter(tokenList, tokenList.head, text);
      matchGrammar(text, tokenList, grammar, tokenList.head, 0);
      return toArray(tokenList);
    },
    /**
     * @namespace
     * @memberof Prism
     * @public
     */
    hooks: {
      all: {},
      /**
       * Adds the given callback to the list of callbacks for the given hook.
       *
       * The callback will be invoked when the hook it is registered for is run.
       * Hooks are usually directly run by a highlight function but you can also run hooks yourself.
       *
       * One callback function can be registered to multiple hooks and the same hook multiple times.
       *
       * @param {string} name The name of the hook.
       * @param {HookCallback} callback The callback function which is given environment variables.
       * @public
       */
      add: function (name, callback) {
        var hooks = _.hooks.all;
        hooks[name] = hooks[name] || [];
        hooks[name].push(callback);
      },
      /**
       * Runs a hook invoking all registered callbacks with the given environment variables.
       *
       * Callbacks will be invoked synchronously and in the order in which they were registered.
       *
       * @param {string} name The name of the hook.
       * @param {Object<string, any>} env The environment variables of the hook passed to all callbacks registered.
       * @public
       */
      run: function (name, env) {
        var callbacks = _.hooks.all[name];
        if (!callbacks || !callbacks.length) {
          return;
        }
        for (var i = 0, callback; callback = callbacks[i++];) {
          callback(env);
        }
      }
    },
    Token: Token
  };
  _self.Prism = _;

  // Typescript note:
  // The following can be used to import the Token type in JSDoc:
  //
  //   @typedef {InstanceType<import("./prism-core")["Token"]>} Token

  /**
   * Creates a new token.
   *
   * @param {string} type See {@link Token#type type}
   * @param {string | TokenStream} content See {@link Token#content content}
   * @param {string|string[]} [alias] The alias(es) of the token.
   * @param {string} [matchedStr=""] A copy of the full string this token was created from.
   * @class
   * @global
   * @public
   */
  function Token(type, content, alias, matchedStr) {
    /**
     * The type of the token.
     *
     * This is usually the key of a pattern in a {@link Grammar}.
     *
     * @type {string}
     * @see GrammarToken
     * @public
     */
    this.type = type;
    /**
     * The strings or tokens contained by this token.
     *
     * This will be a token stream if the pattern matched also defined an `inside` grammar.
     *
     * @type {string | TokenStream}
     * @public
     */
    this.content = content;
    /**
     * The alias(es) of the token.
     *
     * @type {string|string[]}
     * @see GrammarToken
     * @public
     */
    this.alias = alias;
    // Copy of the full string this token was created from
    this.length = (matchedStr || '').length | 0;
  }

  /**
   * A token stream is an array of strings and {@link Token Token} objects.
   *
   * Token streams have to fulfill a few properties that are assumed by most functions (mostly internal ones) that process
   * them.
   *
   * 1. No adjacent strings.
   * 2. No empty strings.
   *
   *    The only exception here is the token stream that only contains the empty string and nothing else.
   *
   * @typedef {Array<string | Token>} TokenStream
   * @global
   * @public
   */

  /**
   * Converts the given token or token stream to an HTML representation.
   *
   * The following hooks will be run:
   * 1. `wrap`: On each {@link Token}.
   *
   * @param {string | Token | TokenStream} o The token or token stream to be converted.
   * @param {string} language The name of current language.
   * @returns {string} The HTML representation of the token or token stream.
   * @memberof Token
   * @static
   */
  Token.stringify = function stringify(o, language) {
    if (typeof o == 'string') {
      return o;
    }
    if (Array.isArray(o)) {
      var s = '';
      o.forEach(function (e) {
        s += stringify(e, language);
      });
      return s;
    }
    var env = {
      type: o.type,
      content: stringify(o.content, language),
      tag: 'span',
      classes: ['token', o.type],
      attributes: {},
      language: language
    };
    var aliases = o.alias;
    if (aliases) {
      if (Array.isArray(aliases)) {
        Array.prototype.push.apply(env.classes, aliases);
      } else {
        env.classes.push(aliases);
      }
    }
    _.hooks.run('wrap', env);
    var attributes = '';
    for (var name in env.attributes) {
      attributes += ' ' + name + '="' + (env.attributes[name] || '').replace(/"/g, '&quot;') + '"';
    }
    return '<' + env.tag + ' class="' + env.classes.join(' ') + '"' + attributes + '>' + env.content + '</' + env.tag + '>';
  };

  /**
   * @param {RegExp} pattern
   * @param {number} pos
   * @param {string} text
   * @param {boolean} lookbehind
   * @returns {RegExpExecArray | null}
   */
  function matchPattern(pattern, pos, text, lookbehind) {
    pattern.lastIndex = pos;
    var match = pattern.exec(text);
    if (match && lookbehind && match[1]) {
      // change the match to remove the text matched by the Prism lookbehind group
      var lookbehindLength = match[1].length;
      match.index += lookbehindLength;
      match[0] = match[0].slice(lookbehindLength);
    }
    return match;
  }

  /**
   * @param {string} text
   * @param {LinkedList<string | Token>} tokenList
   * @param {any} grammar
   * @param {LinkedListNode<string | Token>} startNode
   * @param {number} startPos
   * @param {RematchOptions} [rematch]
   * @returns {void}
   * @private
   *
   * @typedef RematchOptions
   * @property {string} cause
   * @property {number} reach
   */
  function matchGrammar(text, tokenList, grammar, startNode, startPos, rematch) {
    for (var token in grammar) {
      if (!grammar.hasOwnProperty(token) || !grammar[token]) {
        continue;
      }
      var patterns = grammar[token];
      patterns = Array.isArray(patterns) ? patterns : [patterns];
      for (var j = 0; j < patterns.length; ++j) {
        if (rematch && rematch.cause == token + ',' + j) {
          return;
        }
        var patternObj = patterns[j];
        var inside = patternObj.inside;
        var lookbehind = !!patternObj.lookbehind;
        var greedy = !!patternObj.greedy;
        var alias = patternObj.alias;
        if (greedy && !patternObj.pattern.global) {
          // Without the global flag, lastIndex won't work
          var flags = patternObj.pattern.toString().match(/[imsuy]*$/)[0];
          patternObj.pattern = RegExp(patternObj.pattern.source, flags + 'g');
        }

        /** @type {RegExp} */
        var pattern = patternObj.pattern || patternObj;
        for (
        // iterate the token list and keep track of the current token/string position
        var currentNode = startNode.next, pos = startPos; currentNode !== tokenList.tail; pos += currentNode.value.length, currentNode = currentNode.next) {
          if (rematch && pos >= rematch.reach) {
            break;
          }
          var str = currentNode.value;
          if (tokenList.length > text.length) {
            // Something went terribly wrong, ABORT, ABORT!
            return;
          }
          if (str instanceof Token) {
            continue;
          }
          var removeCount = 1; // this is the to parameter of removeBetween
          var match;
          if (greedy) {
            match = matchPattern(pattern, pos, text, lookbehind);
            if (!match || match.index >= text.length) {
              break;
            }
            var from = match.index;
            var to = match.index + match[0].length;
            var p = pos;

            // find the node that contains the match
            p += currentNode.value.length;
            while (from >= p) {
              currentNode = currentNode.next;
              p += currentNode.value.length;
            }
            // adjust pos (and p)
            p -= currentNode.value.length;
            pos = p;

            // the current node is a Token, then the match starts inside another Token, which is invalid
            if (currentNode.value instanceof Token) {
              continue;
            }

            // find the last node which is affected by this match
            for (var k = currentNode; k !== tokenList.tail && (p < to || typeof k.value === 'string'); k = k.next) {
              removeCount++;
              p += k.value.length;
            }
            removeCount--;

            // replace with the new match
            str = text.slice(pos, p);
            match.index -= pos;
          } else {
            match = matchPattern(pattern, 0, str, lookbehind);
            if (!match) {
              continue;
            }
          }

          // eslint-disable-next-line no-redeclare
          var from = match.index;
          var matchStr = match[0];
          var before = str.slice(0, from);
          var after = str.slice(from + matchStr.length);
          var reach = pos + str.length;
          if (rematch && reach > rematch.reach) {
            rematch.reach = reach;
          }
          var removeFrom = currentNode.prev;
          if (before) {
            removeFrom = addAfter(tokenList, removeFrom, before);
            pos += before.length;
          }
          removeRange(tokenList, removeFrom, removeCount);
          var wrapped = new Token(token, inside ? _.tokenize(matchStr, inside) : matchStr, alias, matchStr);
          currentNode = addAfter(tokenList, removeFrom, wrapped);
          if (after) {
            addAfter(tokenList, currentNode, after);
          }
          if (removeCount > 1) {
            // at least one Token object was removed, so we have to do some rematching
            // this can only happen if the current pattern is greedy

            /** @type {RematchOptions} */
            var nestedRematch = {
              cause: token + ',' + j,
              reach: reach
            };
            matchGrammar(text, tokenList, grammar, currentNode.prev, pos, nestedRematch);

            // the reach might have been extended because of the rematching
            if (rematch && nestedRematch.reach > rematch.reach) {
              rematch.reach = nestedRematch.reach;
            }
          }
        }
      }
    }
  }

  /**
   * @typedef LinkedListNode
   * @property {T} value
   * @property {LinkedListNode<T> | null} prev The previous node.
   * @property {LinkedListNode<T> | null} next The next node.
   * @template T
   * @private
   */

  /**
   * @template T
   * @private
   */
  function LinkedList() {
    /** @type {LinkedListNode<T>} */
    var head = {
      value: null,
      prev: null,
      next: null
    };
    /** @type {LinkedListNode<T>} */
    var tail = {
      value: null,
      prev: head,
      next: null
    };
    head.next = tail;

    /** @type {LinkedListNode<T>} */
    this.head = head;
    /** @type {LinkedListNode<T>} */
    this.tail = tail;
    this.length = 0;
  }

  /**
   * Adds a new node with the given value to the list.
   *
   * @param {LinkedList<T>} list
   * @param {LinkedListNode<T>} node
   * @param {T} value
   * @returns {LinkedListNode<T>} The added node.
   * @template T
   */
  function addAfter(list, node, value) {
    // assumes that node != list.tail && values.length >= 0
    var next = node.next;
    var newNode = {
      value: value,
      prev: node,
      next: next
    };
    node.next = newNode;
    next.prev = newNode;
    list.length++;
    return newNode;
  }
  /**
   * Removes `count` nodes after the given node. The given node will not be removed.
   *
   * @param {LinkedList<T>} list
   * @param {LinkedListNode<T>} node
   * @param {number} count
   * @template T
   */
  function removeRange(list, node, count) {
    var next = node.next;
    for (var i = 0; i < count && next !== list.tail; i++) {
      next = next.next;
    }
    node.next = next;
    next.prev = node;
    list.length -= i;
  }
  /**
   * @param {LinkedList<T>} list
   * @returns {T[]}
   * @template T
   */
  function toArray(list) {
    var array = [];
    var node = list.head.next;
    while (node !== list.tail) {
      array.push(node.value);
      node = node.next;
    }
    return array;
  }
  if (!_self.document) {
    if (!_self.addEventListener) {
      // in Node.js
      return _;
    }
    if (!_.disableWorkerMessageHandler) {
      // In worker
      _self.addEventListener('message', function (evt) {
        var message = JSON.parse(evt.data);
        var lang = message.language;
        var code = message.code;
        var immediateClose = message.immediateClose;
        _self.postMessage(_.highlight(code, _.languages[lang], lang));
        if (immediateClose) {
          _self.close();
        }
      }, false);
    }
    return _;
  }

  // Get current script and highlight
  var script = _.util.currentScript();
  if (script) {
    _.filename = script.src;
    if (script.hasAttribute('data-manual')) {
      _.manual = true;
    }
  }
  function highlightAutomaticallyCallback() {
    if (!_.manual) {
      _.highlightAll();
    }
  }
  if (!_.manual) {
    // If the document state is "loading", then we'll use DOMContentLoaded.
    // If the document state is "interactive" and the prism.js script is deferred, then we'll also use the
    // DOMContentLoaded event because there might be some plugins or languages which have also been deferred and they
    // might take longer one animation frame to execute which can create a race condition where only some plugins have
    // been loaded when Prism.highlightAll() is executed, depending on how fast resources are loaded.
    // See https://github.com/PrismJS/prism/issues/2102
    var readyState = document.readyState;
    if (readyState === 'loading' || readyState === 'interactive' && script && script.defer) {
      document.addEventListener('DOMContentLoaded', highlightAutomaticallyCallback);
    } else {
      if (window.requestAnimationFrame) {
        window.requestAnimationFrame(highlightAutomaticallyCallback);
      } else {
        window.setTimeout(highlightAutomaticallyCallback, 16);
      }
    }
  }
  return _;
}(_self);
if (module.exports) {
  module.exports = Prism;
}

// hack for components to work correctly in node.js
if (typeof commonjsGlobal !== 'undefined') {
  commonjsGlobal.Prism = Prism;
}

// some additional documentation/types

/**
 * The expansion of a simple `RegExp` literal to support additional properties.
 *
 * @typedef GrammarToken
 * @property {RegExp} pattern The regular expression of the token.
 * @property {boolean} [lookbehind=false] If `true`, then the first capturing group of `pattern` will (effectively)
 * behave as a lookbehind group meaning that the captured text will not be part of the matched text of the new token.
 * @property {boolean} [greedy=false] Whether the token is greedy.
 * @property {string|string[]} [alias] An optional alias or list of aliases.
 * @property {Grammar} [inside] The nested grammar of this token.
 *
 * The `inside` grammar will be used to tokenize the text value of each token of this kind.
 *
 * This can be used to make nested and even recursive language definitions.
 *
 * Note: This can cause infinite recursion. Be careful when you embed different languages or even the same language into
 * each another.
 * @global
 * @public
 */

/**
 * @typedef Grammar
 * @type {Object<string, RegExp | GrammarToken | Array<RegExp | GrammarToken>>}
 * @property {Grammar} [rest] An optional grammar object that will be appended to this grammar.
 * @global
 * @public
 */

/**
 * A function which will invoked after an element was successfully highlighted.
 *
 * @callback HighlightCallback
 * @param {Element} element The element successfully highlighted.
 * @returns {void}
 * @global
 * @public
 */

/**
 * @callback HookCallback
 * @param {Object<string, any>} env The environment variables of the hook.
 * @returns {void}
 * @global
 * @public
 */

/* **********************************************
     Begin prism-markup.js
********************************************** */

Prism.languages.markup = {
  'comment': {
    pattern: /<!--(?:(?!<!--)[\s\S])*?-->/,
    greedy: true
  },
  'prolog': {
    pattern: /<\?[\s\S]+?\?>/,
    greedy: true
  },
  'doctype': {
    // https://www.w3.org/TR/xml/#NT-doctypedecl
    pattern: /<!DOCTYPE(?:[^>"'[\]]|"[^"]*"|'[^']*')+(?:\[(?:[^<"'\]]|"[^"]*"|'[^']*'|<(?!!--)|<!--(?:[^-]|-(?!->))*-->)*\]\s*)?>/i,
    greedy: true,
    inside: {
      'internal-subset': {
        pattern: /(^[^\[]*\[)[\s\S]+(?=\]>$)/,
        lookbehind: true,
        greedy: true,
        inside: null // see below
      },
      'string': {
        pattern: /"[^"]*"|'[^']*'/,
        greedy: true
      },
      'punctuation': /^<!|>$|[[\]]/,
      'doctype-tag': /^DOCTYPE/i,
      'name': /[^\s<>'"]+/
    }
  },
  'cdata': {
    pattern: /<!\[CDATA\[[\s\S]*?\]\]>/i,
    greedy: true
  },
  'tag': {
    pattern: /<\/?(?!\d)[^\s>\/=$<%]+(?:\s(?:\s*[^\s>\/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+(?=[\s>]))|(?=[\s/>])))+)?\s*\/?>/,
    greedy: true,
    inside: {
      'tag': {
        pattern: /^<\/?[^\s>\/]+/,
        inside: {
          'punctuation': /^<\/?/,
          'namespace': /^[^\s>\/:]+:/
        }
      },
      'special-attr': [],
      'attr-value': {
        pattern: /=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+)/,
        inside: {
          'punctuation': [{
            pattern: /^=/,
            alias: 'attr-equals'
          }, {
            pattern: /^(\s*)["']|["']$/,
            lookbehind: true
          }]
        }
      },
      'punctuation': /\/?>/,
      'attr-name': {
        pattern: /[^\s>\/]+/,
        inside: {
          'namespace': /^[^\s>\/:]+:/
        }
      }
    }
  },
  'entity': [{
    pattern: /&[\da-z]{1,8};/i,
    alias: 'named-entity'
  }, /&#x?[\da-f]{1,8};/i]
};
Prism.languages.markup['tag'].inside['attr-value'].inside['entity'] = Prism.languages.markup['entity'];
Prism.languages.markup['doctype'].inside['internal-subset'].inside = Prism.languages.markup;

// Plugin to make entity title show the real entity, idea by Roman Komarov
Prism.hooks.add('wrap', function (env) {
  if (env.type === 'entity') {
    env.attributes['title'] = env.content.replace(/&amp;/, '&');
  }
});
Object.defineProperty(Prism.languages.markup.tag, 'addInlined', {
  /**
   * Adds an inlined language to markup.
   *
   * An example of an inlined language is CSS with `<style>` tags.
   *
   * @param {string} tagName The name of the tag that contains the inlined language. This name will be treated as
   * case insensitive.
   * @param {string} lang The language key.
   * @example
   * addInlined('style', 'css');
   */
  value: function addInlined(tagName, lang) {
    var includedCdataInside = {};
    includedCdataInside['language-' + lang] = {
      pattern: /(^<!\[CDATA\[)[\s\S]+?(?=\]\]>$)/i,
      lookbehind: true,
      inside: Prism.languages[lang]
    };
    includedCdataInside['cdata'] = /^<!\[CDATA\[|\]\]>$/i;
    var inside = {
      'included-cdata': {
        pattern: /<!\[CDATA\[[\s\S]*?\]\]>/i,
        inside: includedCdataInside
      }
    };
    inside['language-' + lang] = {
      pattern: /[\s\S]+/,
      inside: Prism.languages[lang]
    };
    var def = {};
    def[tagName] = {
      pattern: RegExp(/(<__[^>]*>)(?:<!\[CDATA\[(?:[^\]]|\](?!\]>))*\]\]>|(?!<!\[CDATA\[)[\s\S])*?(?=<\/__>)/.source.replace(/__/g, function () {
        return tagName;
      }), 'i'),
      lookbehind: true,
      greedy: true,
      inside: inside
    };
    Prism.languages.insertBefore('markup', 'cdata', def);
  }
});
Object.defineProperty(Prism.languages.markup.tag, 'addAttribute', {
  /**
   * Adds an pattern to highlight languages embedded in HTML attributes.
   *
   * An example of an inlined language is CSS with `style` attributes.
   *
   * @param {string} attrName The name of the tag that contains the inlined language. This name will be treated as
   * case insensitive.
   * @param {string} lang The language key.
   * @example
   * addAttribute('style', 'css');
   */
  value: function (attrName, lang) {
    Prism.languages.markup.tag.inside['special-attr'].push({
      pattern: RegExp(/(^|["'\s])/.source + '(?:' + attrName + ')' + /\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+(?=[\s>]))/.source, 'i'),
      lookbehind: true,
      inside: {
        'attr-name': /^[^\s=]+/,
        'attr-value': {
          pattern: /=[\s\S]+/,
          inside: {
            'value': {
              pattern: /(^=\s*(["']|(?!["'])))\S[\s\S]*(?=\2$)/,
              lookbehind: true,
              alias: [lang, 'language-' + lang],
              inside: Prism.languages[lang]
            },
            'punctuation': [{
              pattern: /^=/,
              alias: 'attr-equals'
            }, /"|'/]
          }
        }
      }
    });
  }
});
Prism.languages.html = Prism.languages.markup;
Prism.languages.mathml = Prism.languages.markup;
Prism.languages.svg = Prism.languages.markup;
Prism.languages.xml = Prism.languages.extend('markup', {});
Prism.languages.ssml = Prism.languages.xml;
Prism.languages.atom = Prism.languages.xml;
Prism.languages.rss = Prism.languages.xml;

/* **********************************************
     Begin prism-css.js
********************************************** */

(function (Prism) {
  var string = /(?:"(?:\\(?:\r\n|[\s\S])|[^"\\\r\n])*"|'(?:\\(?:\r\n|[\s\S])|[^'\\\r\n])*')/;
  Prism.languages.css = {
    'comment': /\/\*[\s\S]*?\*\//,
    'atrule': {
      pattern: RegExp('@[\\w-](?:' + /[^;{\s"']|\s+(?!\s)/.source + '|' + string.source + ')*?' + /(?:;|(?=\s*\{))/.source),
      inside: {
        'rule': /^@[\w-]+/,
        'selector-function-argument': {
          pattern: /(\bselector\s*\(\s*(?![\s)]))(?:[^()\s]|\s+(?![\s)])|\((?:[^()]|\([^()]*\))*\))+(?=\s*\))/,
          lookbehind: true,
          alias: 'selector'
        },
        'keyword': {
          pattern: /(^|[^\w-])(?:and|not|only|or)(?![\w-])/,
          lookbehind: true
        }
        // See rest below
      }
    },
    'url': {
      // https://drafts.csswg.org/css-values-3/#urls
      pattern: RegExp('\\burl\\((?:' + string.source + '|' + /(?:[^\\\r\n()"']|\\[\s\S])*/.source + ')\\)', 'i'),
      greedy: true,
      inside: {
        'function': /^url/i,
        'punctuation': /^\(|\)$/,
        'string': {
          pattern: RegExp('^' + string.source + '$'),
          alias: 'url'
        }
      }
    },
    'selector': {
      pattern: RegExp('(^|[{}\\s])[^{}\\s](?:[^{};"\'\\s]|\\s+(?![\\s{])|' + string.source + ')*(?=\\s*\\{)'),
      lookbehind: true
    },
    'string': {
      pattern: string,
      greedy: true
    },
    'property': {
      pattern: /(^|[^-\w\xA0-\uFFFF])(?!\s)[-_a-z\xA0-\uFFFF](?:(?!\s)[-\w\xA0-\uFFFF])*(?=\s*:)/i,
      lookbehind: true
    },
    'important': /!important\b/i,
    'function': {
      pattern: /(^|[^-a-z0-9])[-a-z0-9]+(?=\()/i,
      lookbehind: true
    },
    'punctuation': /[(){};:,]/
  };
  Prism.languages.css['atrule'].inside.rest = Prism.languages.css;
  var markup = Prism.languages.markup;
  if (markup) {
    markup.tag.addInlined('style', 'css');
    markup.tag.addAttribute('style', 'css');
  }
})(Prism);

/* **********************************************
     Begin prism-clike.js
********************************************** */

Prism.languages.clike = {
  'comment': [{
    pattern: /(^|[^\\])\/\*[\s\S]*?(?:\*\/|$)/,
    lookbehind: true,
    greedy: true
  }, {
    pattern: /(^|[^\\:])\/\/.*/,
    lookbehind: true,
    greedy: true
  }],
  'string': {
    pattern: /(["'])(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/,
    greedy: true
  },
  'class-name': {
    pattern: /(\b(?:class|extends|implements|instanceof|interface|new|trait)\s+|\bcatch\s+\()[\w.\\]+/i,
    lookbehind: true,
    inside: {
      'punctuation': /[.\\]/
    }
  },
  'keyword': /\b(?:break|catch|continue|do|else|finally|for|function|if|in|instanceof|new|null|return|throw|try|while)\b/,
  'boolean': /\b(?:false|true)\b/,
  'function': /\b\w+(?=\()/,
  'number': /\b0x[\da-f]+\b|(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:e[+-]?\d+)?/i,
  'operator': /[<>]=?|[!=]=?=?|--?|\+\+?|&&?|\|\|?|[?*/~^%]/,
  'punctuation': /[{}[\];(),.:]/
};

/* **********************************************
     Begin prism-javascript.js
********************************************** */

Prism.languages.javascript = Prism.languages.extend('clike', {
  'class-name': [Prism.languages.clike['class-name'], {
    pattern: /(^|[^$\w\xA0-\uFFFF])(?!\s)[_$A-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\.(?:constructor|prototype))/,
    lookbehind: true
  }],
  'keyword': [{
    pattern: /((?:^|\})\s*)catch\b/,
    lookbehind: true
  }, {
    pattern: /(^|[^.]|\.\.\.\s*)\b(?:as|assert(?=\s*\{)|async(?=\s*(?:function\b|\(|[$\w\xA0-\uFFFF]|$))|await|break|case|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally(?=\s*(?:\{|$))|for|from(?=\s*(?:['"]|$))|function|(?:get|set)(?=\s*(?:[#\[$\w\xA0-\uFFFF]|$))|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)\b/,
    lookbehind: true
  }],
  // Allow for all non-ASCII characters (See http://stackoverflow.com/a/2008444)
  'function': /#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*(?:\.\s*(?:apply|bind|call)\s*)?\()/,
  'number': {
    pattern: RegExp(/(^|[^\w$])/.source + '(?:' + (
    // constant
    /NaN|Infinity/.source + '|' +
    // binary integer
    /0[bB][01]+(?:_[01]+)*n?/.source + '|' +
    // octal integer
    /0[oO][0-7]+(?:_[0-7]+)*n?/.source + '|' +
    // hexadecimal integer
    /0[xX][\dA-Fa-f]+(?:_[\dA-Fa-f]+)*n?/.source + '|' +
    // decimal bigint
    /\d+(?:_\d+)*n/.source + '|' +
    // decimal number (integer or float) but no bigint
    /(?:\d+(?:_\d+)*(?:\.(?:\d+(?:_\d+)*)?)?|\.\d+(?:_\d+)*)(?:[Ee][+-]?\d+(?:_\d+)*)?/.source) + ')' + /(?![\w$])/.source),
    lookbehind: true
  },
  'operator': /--|\+\+|\*\*=?|=>|&&=?|\|\|=?|[!=]==|<<=?|>>>?=?|[-+*/%&|^!=<>]=?|\.{3}|\?\?=?|\?\.?|[~:]/
});
Prism.languages.javascript['class-name'][0].pattern = /(\b(?:class|extends|implements|instanceof|interface|new)\s+)[\w.\\]+/;
Prism.languages.insertBefore('javascript', 'keyword', {
  'regex': {
    pattern: RegExp(
    // lookbehind
    // eslint-disable-next-line regexp/no-dupe-characters-character-class
    /((?:^|[^$\w\xA0-\uFFFF."'\])\s]|\b(?:return|yield))\s*)/.source +
    // Regex pattern:
    // There are 2 regex patterns here. The RegExp set notation proposal added support for nested character
    // classes if the `v` flag is present. Unfortunately, nested CCs are both context-free and incompatible
    // with the only syntax, so we have to define 2 different regex patterns.
    /\//.source + '(?:' + /(?:\[(?:[^\]\\\r\n]|\\.)*\]|\\.|[^/\\\[\r\n])+\/[dgimyus]{0,7}/.source + '|' +
    // `v` flag syntax. This supports 3 levels of nested character classes.
    /(?:\[(?:[^[\]\\\r\n]|\\.|\[(?:[^[\]\\\r\n]|\\.|\[(?:[^[\]\\\r\n]|\\.)*\])*\])*\]|\\.|[^/\\\[\r\n])+\/[dgimyus]{0,7}v[dgimyus]{0,7}/.source + ')' +
    // lookahead
    /(?=(?:\s|\/\*(?:[^*]|\*(?!\/))*\*\/)*(?:$|[\r\n,.;:})\]]|\/\/))/.source),
    lookbehind: true,
    greedy: true,
    inside: {
      'regex-source': {
        pattern: /^(\/)[\s\S]+(?=\/[a-z]*$)/,
        lookbehind: true,
        alias: 'language-regex',
        inside: Prism.languages.regex
      },
      'regex-delimiter': /^\/|\/$/,
      'regex-flags': /^[a-z]+$/
    }
  },
  // This must be declared before keyword because we use "function" inside the look-forward
  'function-variable': {
    pattern: /#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*[=:]\s*(?:async\s*)?(?:\bfunction\b|(?:\((?:[^()]|\([^()]*\))*\)|(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*)\s*=>))/,
    alias: 'function'
  },
  'parameter': [{
    pattern: /(function(?:\s+(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*)?\s*\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\))/,
    lookbehind: true,
    inside: Prism.languages.javascript
  }, {
    pattern: /(^|[^$\w\xA0-\uFFFF])(?!\s)[_$a-z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*=>)/i,
    lookbehind: true,
    inside: Prism.languages.javascript
  }, {
    pattern: /(\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\)\s*=>)/,
    lookbehind: true,
    inside: Prism.languages.javascript
  }, {
    pattern: /((?:\b|\s|^)(?!(?:as|async|await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)(?![$\w\xA0-\uFFFF]))(?:(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*\s*)\(\s*|\]\s*\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\)\s*\{)/,
    lookbehind: true,
    inside: Prism.languages.javascript
  }],
  'constant': /\b[A-Z](?:[A-Z_]|\dx?)*\b/
});
Prism.languages.insertBefore('javascript', 'string', {
  'hashbang': {
    pattern: /^#!.*/,
    greedy: true,
    alias: 'comment'
  },
  'template-string': {
    pattern: /`(?:\\[\s\S]|\$\{(?:[^{}]|\{(?:[^{}]|\{[^}]*\})*\})+\}|(?!\$\{)[^\\`])*`/,
    greedy: true,
    inside: {
      'template-punctuation': {
        pattern: /^`|`$/,
        alias: 'string'
      },
      'interpolation': {
        pattern: /((?:^|[^\\])(?:\\{2})*)\$\{(?:[^{}]|\{(?:[^{}]|\{[^}]*\})*\})+\}/,
        lookbehind: true,
        inside: {
          'interpolation-punctuation': {
            pattern: /^\$\{|\}$/,
            alias: 'punctuation'
          },
          rest: Prism.languages.javascript
        }
      },
      'string': /[\s\S]+/
    }
  },
  'string-property': {
    pattern: /((?:^|[,{])[ \t]*)(["'])(?:\\(?:\r\n|[\s\S])|(?!\2)[^\\\r\n])*\2(?=\s*:)/m,
    lookbehind: true,
    greedy: true,
    alias: 'property'
  }
});
Prism.languages.insertBefore('javascript', 'operator', {
  'literal-property': {
    pattern: /((?:^|[,{])[ \t]*)(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*:)/m,
    lookbehind: true,
    alias: 'property'
  }
});
if (Prism.languages.markup) {
  Prism.languages.markup.tag.addInlined('script', 'javascript');

  // add attribute support for all DOM events.
  // https://developer.mozilla.org/en-US/docs/Web/Events#Standard_events
  Prism.languages.markup.tag.addAttribute(/on(?:abort|blur|change|click|composition(?:end|start|update)|dblclick|error|focus(?:in|out)?|key(?:down|up)|load|mouse(?:down|enter|leave|move|out|over|up)|reset|resize|scroll|select|slotchange|submit|unload|wheel)/.source, 'javascript');
}
Prism.languages.js = Prism.languages.javascript;

/* **********************************************
     Begin prism-file-highlight.js
********************************************** */

(function () {
  if (typeof Prism === 'undefined' || typeof document === 'undefined') {
    return;
  }

  // https://developer.mozilla.org/en-US/docs/Web/API/Element/matches#Polyfill
  if (!Element.prototype.matches) {
    Element.prototype.matches = Element.prototype.msMatchesSelector || Element.prototype.webkitMatchesSelector;
  }
  var LOADING_MESSAGE = 'Loading…';
  var FAILURE_MESSAGE = function (status, message) {
    return '✖ Error ' + status + ' while fetching file: ' + message;
  };
  var FAILURE_EMPTY_MESSAGE = '✖ Error: File does not exist or is empty';
  var EXTENSIONS = {
    'js': 'javascript',
    'py': 'python',
    'rb': 'ruby',
    'ps1': 'powershell',
    'psm1': 'powershell',
    'sh': 'bash',
    'bat': 'batch',
    'h': 'c',
    'tex': 'latex'
  };
  var STATUS_ATTR = 'data-src-status';
  var STATUS_LOADING = 'loading';
  var STATUS_LOADED = 'loaded';
  var STATUS_FAILED = 'failed';
  var SELECTOR = 'pre[data-src]:not([' + STATUS_ATTR + '="' + STATUS_LOADED + '"])' + ':not([' + STATUS_ATTR + '="' + STATUS_LOADING + '"])';

  /**
   * Loads the given file.
   *
   * @param {string} src The URL or path of the source file to load.
   * @param {(result: string) => void} success
   * @param {(reason: string) => void} error
   */
  function loadFile(src, success, error) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', src, true);
    xhr.onreadystatechange = function () {
      if (xhr.readyState == 4) {
        if (xhr.status < 400 && xhr.responseText) {
          success(xhr.responseText);
        } else {
          if (xhr.status >= 400) {
            error(FAILURE_MESSAGE(xhr.status, xhr.statusText));
          } else {
            error(FAILURE_EMPTY_MESSAGE);
          }
        }
      }
    };
    xhr.send(null);
  }

  /**
   * Parses the given range.
   *
   * This returns a range with inclusive ends.
   *
   * @param {string | null | undefined} range
   * @returns {[number, number | undefined] | undefined}
   */
  function parseRange(range) {
    var m = /^\s*(\d+)\s*(?:(,)\s*(?:(\d+)\s*)?)?$/.exec(range || '');
    if (m) {
      var start = Number(m[1]);
      var comma = m[2];
      var end = m[3];
      if (!comma) {
        return [start, start];
      }
      if (!end) {
        return [start, undefined];
      }
      return [start, Number(end)];
    }
    return undefined;
  }
  Prism.hooks.add('before-highlightall', function (env) {
    env.selector += ', ' + SELECTOR;
  });
  Prism.hooks.add('before-sanity-check', function (env) {
    var pre = /** @type {HTMLPreElement} */env.element;
    if (pre.matches(SELECTOR)) {
      env.code = ''; // fast-path the whole thing and go to complete

      pre.setAttribute(STATUS_ATTR, STATUS_LOADING); // mark as loading

      // add code element with loading message
      var code = pre.appendChild(document.createElement('CODE'));
      code.textContent = LOADING_MESSAGE;
      var src = pre.getAttribute('data-src');
      var language = env.language;
      if (language === 'none') {
        // the language might be 'none' because there is no language set;
        // in this case, we want to use the extension as the language
        var extension = (/\.(\w+)$/.exec(src) || [, 'none'])[1];
        language = EXTENSIONS[extension] || extension;
      }

      // set language classes
      Prism.util.setLanguage(code, language);
      Prism.util.setLanguage(pre, language);

      // preload the language
      var autoloader = Prism.plugins.autoloader;
      if (autoloader) {
        autoloader.loadLanguages(language);
      }

      // load file
      loadFile(src, function (text) {
        // mark as loaded
        pre.setAttribute(STATUS_ATTR, STATUS_LOADED);

        // handle data-range
        var range = parseRange(pre.getAttribute('data-range'));
        if (range) {
          var lines = text.split(/\r\n?|\n/g);

          // the range is one-based and inclusive on both ends
          var start = range[0];
          var end = range[1] == null ? lines.length : range[1];
          if (start < 0) {
            start += lines.length;
          }
          start = Math.max(0, Math.min(start - 1, lines.length));
          if (end < 0) {
            end += lines.length;
          }
          end = Math.max(0, Math.min(end, lines.length));
          text = lines.slice(start, end).join('\n');

          // add data-start for line numbers
          if (!pre.hasAttribute('data-start')) {
            pre.setAttribute('data-start', String(start + 1));
          }
        }

        // highlight code
        code.textContent = text;
        Prism.highlightElement(code);
      }, function (error) {
        // mark as failed
        pre.setAttribute(STATUS_ATTR, STATUS_FAILED);
        code.textContent = error;
      });
    }
  });
  Prism.plugins.fileHighlight = {
    /**
     * Executes the File Highlight plugin for all matching `pre` elements under the given container.
     *
     * Note: Elements which are already loaded or currently loading will not be touched by this method.
     *
     * @param {ParentNode} [container=document]
     */
    highlight: function highlight(container) {
      var elements = (container || document).querySelectorAll(SELECTOR);
      for (var i = 0, element; element = elements[i++];) {
        Prism.highlightElement(element);
      }
    }
  };
  var logged = false;
  /** @deprecated Use `Prism.plugins.fileHighlight.highlight` instead. */
  Prism.fileHighlight = function () {
    if (!logged) {
      console.warn('Prism.fileHighlight is deprecated. Use `Prism.plugins.fileHighlight.highlight` instead.');
      logged = true;
    }
    Prism.plugins.fileHighlight.highlight.apply(this, arguments);
  };
})();
});

Prism.languages.clike = {
  'comment': [{
    pattern: /(^|[^\\])\/\*[\s\S]*?(?:\*\/|$)/,
    lookbehind: true,
    greedy: true
  }, {
    pattern: /(^|[^\\:])\/\/.*/,
    lookbehind: true,
    greedy: true
  }],
  'string': {
    pattern: /(["'])(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/,
    greedy: true
  },
  'class-name': {
    pattern: /(\b(?:class|extends|implements|instanceof|interface|new|trait)\s+|\bcatch\s+\()[\w.\\]+/i,
    lookbehind: true,
    inside: {
      'punctuation': /[.\\]/
    }
  },
  'keyword': /\b(?:break|catch|continue|do|else|finally|for|function|if|in|instanceof|new|null|return|throw|try|while)\b/,
  'boolean': /\b(?:false|true)\b/,
  'function': /\b\w+(?=\()/,
  'number': /\b0x[\da-f]+\b|(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:e[+-]?\d+)?/i,
  'operator': /[<>]=?|[!=]=?=?|--?|\+\+?|&&?|\|\|?|[?*/~^%]/,
  'punctuation': /[{}[\];(),.:]/
};

Prism.languages.markup = {
  'comment': {
    pattern: /<!--(?:(?!<!--)[\s\S])*?-->/,
    greedy: true
  },
  'prolog': {
    pattern: /<\?[\s\S]+?\?>/,
    greedy: true
  },
  'doctype': {
    // https://www.w3.org/TR/xml/#NT-doctypedecl
    pattern: /<!DOCTYPE(?:[^>"'[\]]|"[^"]*"|'[^']*')+(?:\[(?:[^<"'\]]|"[^"]*"|'[^']*'|<(?!!--)|<!--(?:[^-]|-(?!->))*-->)*\]\s*)?>/i,
    greedy: true,
    inside: {
      'internal-subset': {
        pattern: /(^[^\[]*\[)[\s\S]+(?=\]>$)/,
        lookbehind: true,
        greedy: true,
        inside: null // see below
      },
      'string': {
        pattern: /"[^"]*"|'[^']*'/,
        greedy: true
      },
      'punctuation': /^<!|>$|[[\]]/,
      'doctype-tag': /^DOCTYPE/i,
      'name': /[^\s<>'"]+/
    }
  },
  'cdata': {
    pattern: /<!\[CDATA\[[\s\S]*?\]\]>/i,
    greedy: true
  },
  'tag': {
    pattern: /<\/?(?!\d)[^\s>\/=$<%]+(?:\s(?:\s*[^\s>\/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+(?=[\s>]))|(?=[\s/>])))+)?\s*\/?>/,
    greedy: true,
    inside: {
      'tag': {
        pattern: /^<\/?[^\s>\/]+/,
        inside: {
          'punctuation': /^<\/?/,
          'namespace': /^[^\s>\/:]+:/
        }
      },
      'special-attr': [],
      'attr-value': {
        pattern: /=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+)/,
        inside: {
          'punctuation': [{
            pattern: /^=/,
            alias: 'attr-equals'
          }, {
            pattern: /^(\s*)["']|["']$/,
            lookbehind: true
          }]
        }
      },
      'punctuation': /\/?>/,
      'attr-name': {
        pattern: /[^\s>\/]+/,
        inside: {
          'namespace': /^[^\s>\/:]+:/
        }
      }
    }
  },
  'entity': [{
    pattern: /&[\da-z]{1,8};/i,
    alias: 'named-entity'
  }, /&#x?[\da-f]{1,8};/i]
};
Prism.languages.markup['tag'].inside['attr-value'].inside['entity'] = Prism.languages.markup['entity'];
Prism.languages.markup['doctype'].inside['internal-subset'].inside = Prism.languages.markup;

// Plugin to make entity title show the real entity, idea by Roman Komarov
Prism.hooks.add('wrap', function (env) {
  if (env.type === 'entity') {
    env.attributes['title'] = env.content.replace(/&amp;/, '&');
  }
});
Object.defineProperty(Prism.languages.markup.tag, 'addInlined', {
  /**
   * Adds an inlined language to markup.
   *
   * An example of an inlined language is CSS with `<style>` tags.
   *
   * @param {string} tagName The name of the tag that contains the inlined language. This name will be treated as
   * case insensitive.
   * @param {string} lang The language key.
   * @example
   * addInlined('style', 'css');
   */
  value: function addInlined(tagName, lang) {
    var includedCdataInside = {};
    includedCdataInside['language-' + lang] = {
      pattern: /(^<!\[CDATA\[)[\s\S]+?(?=\]\]>$)/i,
      lookbehind: true,
      inside: Prism.languages[lang]
    };
    includedCdataInside['cdata'] = /^<!\[CDATA\[|\]\]>$/i;
    var inside = {
      'included-cdata': {
        pattern: /<!\[CDATA\[[\s\S]*?\]\]>/i,
        inside: includedCdataInside
      }
    };
    inside['language-' + lang] = {
      pattern: /[\s\S]+/,
      inside: Prism.languages[lang]
    };
    var def = {};
    def[tagName] = {
      pattern: RegExp(/(<__[^>]*>)(?:<!\[CDATA\[(?:[^\]]|\](?!\]>))*\]\]>|(?!<!\[CDATA\[)[\s\S])*?(?=<\/__>)/.source.replace(/__/g, function () {
        return tagName;
      }), 'i'),
      lookbehind: true,
      greedy: true,
      inside: inside
    };
    Prism.languages.insertBefore('markup', 'cdata', def);
  }
});
Object.defineProperty(Prism.languages.markup.tag, 'addAttribute', {
  /**
   * Adds an pattern to highlight languages embedded in HTML attributes.
   *
   * An example of an inlined language is CSS with `style` attributes.
   *
   * @param {string} attrName The name of the tag that contains the inlined language. This name will be treated as
   * case insensitive.
   * @param {string} lang The language key.
   * @example
   * addAttribute('style', 'css');
   */
  value: function (attrName, lang) {
    Prism.languages.markup.tag.inside['special-attr'].push({
      pattern: RegExp(/(^|["'\s])/.source + '(?:' + attrName + ')' + /\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+(?=[\s>]))/.source, 'i'),
      lookbehind: true,
      inside: {
        'attr-name': /^[^\s=]+/,
        'attr-value': {
          pattern: /=[\s\S]+/,
          inside: {
            'value': {
              pattern: /(^=\s*(["']|(?!["'])))\S[\s\S]*(?=\2$)/,
              lookbehind: true,
              alias: [lang, 'language-' + lang],
              inside: Prism.languages[lang]
            },
            'punctuation': [{
              pattern: /^=/,
              alias: 'attr-equals'
            }, /"|'/]
          }
        }
      }
    });
  }
});
Prism.languages.html = Prism.languages.markup;
Prism.languages.mathml = Prism.languages.markup;
Prism.languages.svg = Prism.languages.markup;
Prism.languages.xml = Prism.languages.extend('markup', {});
Prism.languages.ssml = Prism.languages.xml;
Prism.languages.atom = Prism.languages.xml;
Prism.languages.rss = Prism.languages.xml;

Prism.languages.javascript = Prism.languages.extend('clike', {
  'class-name': [Prism.languages.clike['class-name'], {
    pattern: /(^|[^$\w\xA0-\uFFFF])(?!\s)[_$A-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\.(?:constructor|prototype))/,
    lookbehind: true
  }],
  'keyword': [{
    pattern: /((?:^|\})\s*)catch\b/,
    lookbehind: true
  }, {
    pattern: /(^|[^.]|\.\.\.\s*)\b(?:as|assert(?=\s*\{)|async(?=\s*(?:function\b|\(|[$\w\xA0-\uFFFF]|$))|await|break|case|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally(?=\s*(?:\{|$))|for|from(?=\s*(?:['"]|$))|function|(?:get|set)(?=\s*(?:[#\[$\w\xA0-\uFFFF]|$))|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)\b/,
    lookbehind: true
  }],
  // Allow for all non-ASCII characters (See http://stackoverflow.com/a/2008444)
  'function': /#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*(?:\.\s*(?:apply|bind|call)\s*)?\()/,
  'number': {
    pattern: RegExp(/(^|[^\w$])/.source + '(?:' + (
    // constant
    /NaN|Infinity/.source + '|' +
    // binary integer
    /0[bB][01]+(?:_[01]+)*n?/.source + '|' +
    // octal integer
    /0[oO][0-7]+(?:_[0-7]+)*n?/.source + '|' +
    // hexadecimal integer
    /0[xX][\dA-Fa-f]+(?:_[\dA-Fa-f]+)*n?/.source + '|' +
    // decimal bigint
    /\d+(?:_\d+)*n/.source + '|' +
    // decimal number (integer or float) but no bigint
    /(?:\d+(?:_\d+)*(?:\.(?:\d+(?:_\d+)*)?)?|\.\d+(?:_\d+)*)(?:[Ee][+-]?\d+(?:_\d+)*)?/.source) + ')' + /(?![\w$])/.source),
    lookbehind: true
  },
  'operator': /--|\+\+|\*\*=?|=>|&&=?|\|\|=?|[!=]==|<<=?|>>>?=?|[-+*/%&|^!=<>]=?|\.{3}|\?\?=?|\?\.?|[~:]/
});
Prism.languages.javascript['class-name'][0].pattern = /(\b(?:class|extends|implements|instanceof|interface|new)\s+)[\w.\\]+/;
Prism.languages.insertBefore('javascript', 'keyword', {
  'regex': {
    pattern: RegExp(
    // lookbehind
    // eslint-disable-next-line regexp/no-dupe-characters-character-class
    /((?:^|[^$\w\xA0-\uFFFF."'\])\s]|\b(?:return|yield))\s*)/.source +
    // Regex pattern:
    // There are 2 regex patterns here. The RegExp set notation proposal added support for nested character
    // classes if the `v` flag is present. Unfortunately, nested CCs are both context-free and incompatible
    // with the only syntax, so we have to define 2 different regex patterns.
    /\//.source + '(?:' + /(?:\[(?:[^\]\\\r\n]|\\.)*\]|\\.|[^/\\\[\r\n])+\/[dgimyus]{0,7}/.source + '|' +
    // `v` flag syntax. This supports 3 levels of nested character classes.
    /(?:\[(?:[^[\]\\\r\n]|\\.|\[(?:[^[\]\\\r\n]|\\.|\[(?:[^[\]\\\r\n]|\\.)*\])*\])*\]|\\.|[^/\\\[\r\n])+\/[dgimyus]{0,7}v[dgimyus]{0,7}/.source + ')' +
    // lookahead
    /(?=(?:\s|\/\*(?:[^*]|\*(?!\/))*\*\/)*(?:$|[\r\n,.;:})\]]|\/\/))/.source),
    lookbehind: true,
    greedy: true,
    inside: {
      'regex-source': {
        pattern: /^(\/)[\s\S]+(?=\/[a-z]*$)/,
        lookbehind: true,
        alias: 'language-regex',
        inside: Prism.languages.regex
      },
      'regex-delimiter': /^\/|\/$/,
      'regex-flags': /^[a-z]+$/
    }
  },
  // This must be declared before keyword because we use "function" inside the look-forward
  'function-variable': {
    pattern: /#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*[=:]\s*(?:async\s*)?(?:\bfunction\b|(?:\((?:[^()]|\([^()]*\))*\)|(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*)\s*=>))/,
    alias: 'function'
  },
  'parameter': [{
    pattern: /(function(?:\s+(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*)?\s*\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\))/,
    lookbehind: true,
    inside: Prism.languages.javascript
  }, {
    pattern: /(^|[^$\w\xA0-\uFFFF])(?!\s)[_$a-z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*=>)/i,
    lookbehind: true,
    inside: Prism.languages.javascript
  }, {
    pattern: /(\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\)\s*=>)/,
    lookbehind: true,
    inside: Prism.languages.javascript
  }, {
    pattern: /((?:\b|\s|^)(?!(?:as|async|await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)(?![$\w\xA0-\uFFFF]))(?:(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*\s*)\(\s*|\]\s*\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\)\s*\{)/,
    lookbehind: true,
    inside: Prism.languages.javascript
  }],
  'constant': /\b[A-Z](?:[A-Z_]|\dx?)*\b/
});
Prism.languages.insertBefore('javascript', 'string', {
  'hashbang': {
    pattern: /^#!.*/,
    greedy: true,
    alias: 'comment'
  },
  'template-string': {
    pattern: /`(?:\\[\s\S]|\$\{(?:[^{}]|\{(?:[^{}]|\{[^}]*\})*\})+\}|(?!\$\{)[^\\`])*`/,
    greedy: true,
    inside: {
      'template-punctuation': {
        pattern: /^`|`$/,
        alias: 'string'
      },
      'interpolation': {
        pattern: /((?:^|[^\\])(?:\\{2})*)\$\{(?:[^{}]|\{(?:[^{}]|\{[^}]*\})*\})+\}/,
        lookbehind: true,
        inside: {
          'interpolation-punctuation': {
            pattern: /^\$\{|\}$/,
            alias: 'punctuation'
          },
          rest: Prism.languages.javascript
        }
      },
      'string': /[\s\S]+/
    }
  },
  'string-property': {
    pattern: /((?:^|[,{])[ \t]*)(["'])(?:\\(?:\r\n|[\s\S])|(?!\2)[^\\\r\n])*\2(?=\s*:)/m,
    lookbehind: true,
    greedy: true,
    alias: 'property'
  }
});
Prism.languages.insertBefore('javascript', 'operator', {
  'literal-property': {
    pattern: /((?:^|[,{])[ \t]*)(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*:)/m,
    lookbehind: true,
    alias: 'property'
  }
});
if (Prism.languages.markup) {
  Prism.languages.markup.tag.addInlined('script', 'javascript');

  // add attribute support for all DOM events.
  // https://developer.mozilla.org/en-US/docs/Web/Events#Standard_events
  Prism.languages.markup.tag.addAttribute(/on(?:abort|blur|change|click|composition(?:end|start|update)|dblclick|error|focus(?:in|out)?|key(?:down|up)|load|mouse(?:down|enter|leave|move|out|over|up)|reset|resize|scroll|select|slotchange|submit|unload|wheel)/.source, 'javascript');
}
Prism.languages.js = Prism.languages.javascript;

(function (Prism) {
  var string = /(?:"(?:\\(?:\r\n|[\s\S])|[^"\\\r\n])*"|'(?:\\(?:\r\n|[\s\S])|[^'\\\r\n])*')/;
  Prism.languages.css = {
    'comment': /\/\*[\s\S]*?\*\//,
    'atrule': {
      pattern: RegExp('@[\\w-](?:' + /[^;{\s"']|\s+(?!\s)/.source + '|' + string.source + ')*?' + /(?:;|(?=\s*\{))/.source),
      inside: {
        'rule': /^@[\w-]+/,
        'selector-function-argument': {
          pattern: /(\bselector\s*\(\s*(?![\s)]))(?:[^()\s]|\s+(?![\s)])|\((?:[^()]|\([^()]*\))*\))+(?=\s*\))/,
          lookbehind: true,
          alias: 'selector'
        },
        'keyword': {
          pattern: /(^|[^\w-])(?:and|not|only|or)(?![\w-])/,
          lookbehind: true
        }
        // See rest below
      }
    },
    'url': {
      // https://drafts.csswg.org/css-values-3/#urls
      pattern: RegExp('\\burl\\((?:' + string.source + '|' + /(?:[^\\\r\n()"']|\\[\s\S])*/.source + ')\\)', 'i'),
      greedy: true,
      inside: {
        'function': /^url/i,
        'punctuation': /^\(|\)$/,
        'string': {
          pattern: RegExp('^' + string.source + '$'),
          alias: 'url'
        }
      }
    },
    'selector': {
      pattern: RegExp('(^|[{}\\s])[^{}\\s](?:[^{};"\'\\s]|\\s+(?![\\s{])|' + string.source + ')*(?=\\s*\\{)'),
      lookbehind: true
    },
    'string': {
      pattern: string,
      greedy: true
    },
    'property': {
      pattern: /(^|[^-\w\xA0-\uFFFF])(?!\s)[-_a-z\xA0-\uFFFF](?:(?!\s)[-\w\xA0-\uFFFF])*(?=\s*:)/i,
      lookbehind: true
    },
    'important': /!important\b/i,
    'function': {
      pattern: /(^|[^-a-z0-9])[-a-z0-9]+(?=\()/i,
      lookbehind: true
    },
    'punctuation': /[(){};:,]/
  };
  Prism.languages.css['atrule'].inside.rest = Prism.languages.css;
  var markup = Prism.languages.markup;
  if (markup) {
    markup.tag.addInlined('style', 'css');
    markup.tag.addAttribute('style', 'css');
  }
})(Prism);

(function (Prism) {
  // $ set | grep '^[A-Z][^[:space:]]*=' | cut -d= -f1 | tr '\n' '|'
  // + LC_ALL, RANDOM, REPLY, SECONDS.
  // + make sure PS1..4 are here as they are not always set,
  // - some useless things.
  var envVars = '\\b(?:BASH|BASHOPTS|BASH_ALIASES|BASH_ARGC|BASH_ARGV|BASH_CMDS|BASH_COMPLETION_COMPAT_DIR|BASH_LINENO|BASH_REMATCH|BASH_SOURCE|BASH_VERSINFO|BASH_VERSION|COLORTERM|COLUMNS|COMP_WORDBREAKS|DBUS_SESSION_BUS_ADDRESS|DEFAULTS_PATH|DESKTOP_SESSION|DIRSTACK|DISPLAY|EUID|GDMSESSION|GDM_LANG|GNOME_KEYRING_CONTROL|GNOME_KEYRING_PID|GPG_AGENT_INFO|GROUPS|HISTCONTROL|HISTFILE|HISTFILESIZE|HISTSIZE|HOME|HOSTNAME|HOSTTYPE|IFS|INSTANCE|JOB|LANG|LANGUAGE|LC_ADDRESS|LC_ALL|LC_IDENTIFICATION|LC_MEASUREMENT|LC_MONETARY|LC_NAME|LC_NUMERIC|LC_PAPER|LC_TELEPHONE|LC_TIME|LESSCLOSE|LESSOPEN|LINES|LOGNAME|LS_COLORS|MACHTYPE|MAILCHECK|MANDATORY_PATH|NO_AT_BRIDGE|OLDPWD|OPTERR|OPTIND|ORBIT_SOCKETDIR|OSTYPE|PAPERSIZE|PATH|PIPESTATUS|PPID|PS1|PS2|PS3|PS4|PWD|RANDOM|REPLY|SECONDS|SELINUX_INIT|SESSION|SESSIONTYPE|SESSION_MANAGER|SHELL|SHELLOPTS|SHLVL|SSH_AUTH_SOCK|TERM|UID|UPSTART_EVENTS|UPSTART_INSTANCE|UPSTART_JOB|UPSTART_SESSION|USER|WINDOWID|XAUTHORITY|XDG_CONFIG_DIRS|XDG_CURRENT_DESKTOP|XDG_DATA_DIRS|XDG_GREETER_DATA_DIR|XDG_MENU_PREFIX|XDG_RUNTIME_DIR|XDG_SEAT|XDG_SEAT_PATH|XDG_SESSION_DESKTOP|XDG_SESSION_ID|XDG_SESSION_PATH|XDG_SESSION_TYPE|XDG_VTNR|XMODIFIERS)\\b';
  var commandAfterHeredoc = {
    pattern: /(^(["']?)\w+\2)[ \t]+\S.*/,
    lookbehind: true,
    alias: 'punctuation',
    // this looks reasonably well in all themes
    inside: null // see below
  };
  var insideString = {
    'bash': commandAfterHeredoc,
    'environment': {
      pattern: RegExp('\\$' + envVars),
      alias: 'constant'
    },
    'variable': [
    // [0]: Arithmetic Environment
    {
      pattern: /\$?\(\([\s\S]+?\)\)/,
      greedy: true,
      inside: {
        // If there is a $ sign at the beginning highlight $(( and )) as variable
        'variable': [{
          pattern: /(^\$\(\([\s\S]+)\)\)/,
          lookbehind: true
        }, /^\$\(\(/],
        'number': /\b0x[\dA-Fa-f]+\b|(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:[Ee]-?\d+)?/,
        // Operators according to https://www.gnu.org/software/bash/manual/bashref.html#Shell-Arithmetic
        'operator': /--|\+\+|\*\*=?|<<=?|>>=?|&&|\|\||[=!+\-*/%<>^&|]=?|[?~:]/,
        // If there is no $ sign at the beginning highlight (( and )) as punctuation
        'punctuation': /\(\(?|\)\)?|,|;/
      }
    },
    // [1]: Command Substitution
    {
      pattern: /\$\((?:\([^)]+\)|[^()])+\)|`[^`]+`/,
      greedy: true,
      inside: {
        'variable': /^\$\(|^`|\)$|`$/
      }
    },
    // [2]: Brace expansion
    {
      pattern: /\$\{[^}]+\}/,
      greedy: true,
      inside: {
        'operator': /:[-=?+]?|[!\/]|##?|%%?|\^\^?|,,?/,
        'punctuation': /[\[\]]/,
        'environment': {
          pattern: RegExp('(\\{)' + envVars),
          lookbehind: true,
          alias: 'constant'
        }
      }
    }, /\$(?:\w+|[#?*!@$])/],
    // Escape sequences from echo and printf's manuals, and escaped quotes.
    'entity': /\\(?:[abceEfnrtv\\"]|O?[0-7]{1,3}|U[0-9a-fA-F]{8}|u[0-9a-fA-F]{4}|x[0-9a-fA-F]{1,2})/
  };
  Prism.languages.bash = {
    'shebang': {
      pattern: /^#!\s*\/.*/,
      alias: 'important'
    },
    'comment': {
      pattern: /(^|[^"{\\$])#.*/,
      lookbehind: true
    },
    'function-name': [
    // a) function foo {
    // b) foo() {
    // c) function foo() {
    // but not “foo {”
    {
      // a) and c)
      pattern: /(\bfunction\s+)[\w-]+(?=(?:\s*\(?:\s*\))?\s*\{)/,
      lookbehind: true,
      alias: 'function'
    }, {
      // b)
      pattern: /\b[\w-]+(?=\s*\(\s*\)\s*\{)/,
      alias: 'function'
    }],
    // Highlight variable names as variables in for and select beginnings.
    'for-or-select': {
      pattern: /(\b(?:for|select)\s+)\w+(?=\s+in\s)/,
      alias: 'variable',
      lookbehind: true
    },
    // Highlight variable names as variables in the left-hand part
    // of assignments (“=” and “+=”).
    'assign-left': {
      pattern: /(^|[\s;|&]|[<>]\()\w+(?:\.\w+)*(?=\+?=)/,
      inside: {
        'environment': {
          pattern: RegExp('(^|[\\s;|&]|[<>]\\()' + envVars),
          lookbehind: true,
          alias: 'constant'
        }
      },
      alias: 'variable',
      lookbehind: true
    },
    // Highlight parameter names as variables
    'parameter': {
      pattern: /(^|\s)-{1,2}(?:\w+:[+-]?)?\w+(?:\.\w+)*(?=[=\s]|$)/,
      alias: 'variable',
      lookbehind: true
    },
    'string': [
    // Support for Here-documents https://en.wikipedia.org/wiki/Here_document
    {
      pattern: /((?:^|[^<])<<-?\s*)(\w+)\s[\s\S]*?(?:\r?\n|\r)\2/,
      lookbehind: true,
      greedy: true,
      inside: insideString
    },
    // Here-document with quotes around the tag
    // → No expansion (so no “inside”).
    {
      pattern: /((?:^|[^<])<<-?\s*)(["'])(\w+)\2\s[\s\S]*?(?:\r?\n|\r)\3/,
      lookbehind: true,
      greedy: true,
      inside: {
        'bash': commandAfterHeredoc
      }
    },
    // “Normal” string
    {
      // https://www.gnu.org/software/bash/manual/html_node/Double-Quotes.html
      pattern: /(^|[^\\](?:\\\\)*)"(?:\\[\s\S]|\$\([^)]+\)|\$(?!\()|`[^`]+`|[^"\\`$])*"/,
      lookbehind: true,
      greedy: true,
      inside: insideString
    }, {
      // https://www.gnu.org/software/bash/manual/html_node/Single-Quotes.html
      pattern: /(^|[^$\\])'[^']*'/,
      lookbehind: true,
      greedy: true
    }, {
      // https://www.gnu.org/software/bash/manual/html_node/ANSI_002dC-Quoting.html
      pattern: /\$'(?:[^'\\]|\\[\s\S])*'/,
      greedy: true,
      inside: {
        'entity': insideString.entity
      }
    }],
    'environment': {
      pattern: RegExp('\\$?' + envVars),
      alias: 'constant'
    },
    'variable': insideString.variable,
    'function': {
      pattern: /(^|[\s;|&]|[<>]\()(?:add|apropos|apt|apt-cache|apt-get|aptitude|aspell|automysqlbackup|awk|basename|bash|bc|bconsole|bg|bzip2|cal|cargo|cat|cfdisk|chgrp|chkconfig|chmod|chown|chroot|cksum|clear|cmp|column|comm|composer|cp|cron|crontab|csplit|curl|cut|date|dc|dd|ddrescue|debootstrap|df|diff|diff3|dig|dir|dircolors|dirname|dirs|dmesg|docker|docker-compose|du|egrep|eject|env|ethtool|expand|expect|expr|fdformat|fdisk|fg|fgrep|file|find|fmt|fold|format|free|fsck|ftp|fuser|gawk|git|gparted|grep|groupadd|groupdel|groupmod|groups|grub-mkconfig|gzip|halt|head|hg|history|host|hostname|htop|iconv|id|ifconfig|ifdown|ifup|import|install|ip|java|jobs|join|kill|killall|less|link|ln|locate|logname|logrotate|look|lpc|lpr|lprint|lprintd|lprintq|lprm|ls|lsof|lynx|make|man|mc|mdadm|mkconfig|mkdir|mke2fs|mkfifo|mkfs|mkisofs|mknod|mkswap|mmv|more|most|mount|mtools|mtr|mutt|mv|nano|nc|netstat|nice|nl|node|nohup|notify-send|npm|nslookup|op|open|parted|passwd|paste|pathchk|ping|pkill|pnpm|podman|podman-compose|popd|pr|printcap|printenv|ps|pushd|pv|quota|quotacheck|quotactl|ram|rar|rcp|reboot|remsync|rename|renice|rev|rm|rmdir|rpm|rsync|scp|screen|sdiff|sed|sendmail|seq|service|sftp|sh|shellcheck|shuf|shutdown|sleep|slocate|sort|split|ssh|stat|strace|su|sudo|sum|suspend|swapon|sync|sysctl|tac|tail|tar|tee|time|timeout|top|touch|tr|traceroute|tsort|tty|umount|uname|unexpand|uniq|units|unrar|unshar|unzip|update-grub|uptime|useradd|userdel|usermod|users|uudecode|uuencode|v|vcpkg|vdir|vi|vim|virsh|vmstat|wait|watch|wc|wget|whereis|which|who|whoami|write|xargs|xdg-open|yarn|yes|zenity|zip|zsh|zypper)(?=$|[)\s;|&])/,
      lookbehind: true
    },
    'keyword': {
      pattern: /(^|[\s;|&]|[<>]\()(?:case|do|done|elif|else|esac|fi|for|function|if|in|select|then|until|while)(?=$|[)\s;|&])/,
      lookbehind: true
    },
    // https://www.gnu.org/software/bash/manual/html_node/Shell-Builtin-Commands.html
    'builtin': {
      pattern: /(^|[\s;|&]|[<>]\()(?:\.|:|alias|bind|break|builtin|caller|cd|command|continue|declare|echo|enable|eval|exec|exit|export|getopts|hash|help|let|local|logout|mapfile|printf|pwd|read|readarray|readonly|return|set|shift|shopt|source|test|times|trap|type|typeset|ulimit|umask|unalias|unset)(?=$|[)\s;|&])/,
      lookbehind: true,
      // Alias added to make those easier to distinguish from strings.
      alias: 'class-name'
    },
    'boolean': {
      pattern: /(^|[\s;|&]|[<>]\()(?:false|true)(?=$|[)\s;|&])/,
      lookbehind: true
    },
    'file-descriptor': {
      pattern: /\B&\d\b/,
      alias: 'important'
    },
    'operator': {
      // Lots of redirections here, but not just that.
      pattern: /\d?<>|>\||\+=|=[=~]?|!=?|<<[<-]?|[&\d]?>>|\d[<>]&?|[<>][&=]?|&[>&]?|\|[&|]?/,
      inside: {
        'file-descriptor': {
          pattern: /^\d/,
          alias: 'important'
        }
      }
    },
    'punctuation': /\$?\(\(?|\)\)?|\.\.|[{}[\];\\]/,
    'number': {
      pattern: /(^|\s)(?:[1-9]\d*|0)(?:[.,]\d+)?\b/,
      lookbehind: true
    }
  };
  commandAfterHeredoc.inside = Prism.languages.bash;

  /* Patterns in command substitution. */
  var toBeCopied = ['comment', 'function-name', 'for-or-select', 'assign-left', 'parameter', 'string', 'environment', 'function', 'keyword', 'builtin', 'boolean', 'file-descriptor', 'operator', 'punctuation', 'number'];
  var inside = insideString.variable[1].inside;
  for (var i = 0; i < toBeCopied.length; i++) {
    inside[toBeCopied[i]] = Prism.languages.bash[toBeCopied[i]];
  }
  Prism.languages.sh = Prism.languages.bash;
  Prism.languages.shell = Prism.languages.bash;
})(Prism);

(function (Prism) {
  var keywords = [/\b(?:async|sync|yield)\*/, /\b(?:abstract|assert|async|await|break|case|catch|class|const|continue|covariant|default|deferred|do|dynamic|else|enum|export|extends|extension|external|factory|final|finally|for|get|hide|if|implements|import|in|interface|library|mixin|new|null|on|operator|part|rethrow|return|set|show|static|super|switch|sync|this|throw|try|typedef|var|void|while|with|yield)\b/];

  // Handles named imports, such as http.Client
  var packagePrefix = /(^|[^\w.])(?:[a-z]\w*\s*\.\s*)*(?:[A-Z]\w*\s*\.\s*)*/.source;

  // based on the dart naming conventions
  var className = {
    pattern: RegExp(packagePrefix + /[A-Z](?:[\d_A-Z]*[a-z]\w*)?\b/.source),
    lookbehind: true,
    inside: {
      'namespace': {
        pattern: /^[a-z]\w*(?:\s*\.\s*[a-z]\w*)*(?:\s*\.)?/,
        inside: {
          'punctuation': /\./
        }
      }
    }
  };
  Prism.languages.dart = Prism.languages.extend('clike', {
    'class-name': [className, {
      // variables and parameters
      // this to support class names (or generic parameters) which do not contain a lower case letter (also works for methods)
      pattern: RegExp(packagePrefix + /[A-Z]\w*(?=\s+\w+\s*[;,=()])/.source),
      lookbehind: true,
      inside: className.inside
    }],
    'keyword': keywords,
    'operator': /\bis!|\b(?:as|is)\b|\+\+|--|&&|\|\||<<=?|>>=?|~(?:\/=?)?|[+\-*\/%&^|=!<>]=?|\?/
  });
  Prism.languages.insertBefore('dart', 'string', {
    'string-literal': {
      pattern: /r?(?:("""|''')[\s\S]*?\1|(["'])(?:\\.|(?!\2)[^\\\r\n])*\2(?!\2))/,
      greedy: true,
      inside: {
        'interpolation': {
          pattern: /((?:^|[^\\])(?:\\{2})*)\$(?:\w+|\{(?:[^{}]|\{[^{}]*\})*\})/,
          lookbehind: true,
          inside: {
            'punctuation': /^\$\{?|\}$/,
            'expression': {
              pattern: /[\s\S]+/,
              inside: Prism.languages.dart
            }
          }
        },
        'string': /[\s\S]+/
      }
    },
    'string': undefined
  });
  Prism.languages.insertBefore('dart', 'class-name', {
    'metadata': {
      pattern: /@\w+/,
      alias: 'function'
    }
  });
  Prism.languages.insertBefore('dart', 'class-name', {
    'generics': {
      pattern: /<(?:[\w\s,.&?]|<(?:[\w\s,.&?]|<(?:[\w\s,.&?]|<[\w\s,.&?]*>)*>)*>)*>/,
      inside: {
        'class-name': className,
        'keyword': keywords,
        'punctuation': /[<>(),.:]/,
        'operator': /[?&|]/
      }
    }
  });
})(Prism);

(function (Prism) {
  Prism.languages.diff = {
    'coord': [
    // Match all kinds of coord lines (prefixed by "+++", "---" or "***").
    /^(?:\*{3}|-{3}|\+{3}).*$/m,
    // Match "@@ ... @@" coord lines in unified diff.
    /^@@.*@@$/m,
    // Match coord lines in normal diff (starts with a number).
    /^\d.*$/m]

    // deleted, inserted, unchanged, diff
  };

  /**
   * A map from the name of a block to its line prefix.
   *
   * @type {Object<string, string>}
   */
  var PREFIXES = {
    'deleted-sign': '-',
    'deleted-arrow': '<',
    'inserted-sign': '+',
    'inserted-arrow': '>',
    'unchanged': ' ',
    'diff': '!'
  };

  // add a token for each prefix
  Object.keys(PREFIXES).forEach(function (name) {
    var prefix = PREFIXES[name];
    var alias = [];
    if (!/^\w+$/.test(name)) {
      // "deleted-sign" -> "deleted"
      alias.push(/\w+/.exec(name)[0]);
    }
    if (name === 'diff') {
      alias.push('bold');
    }
    Prism.languages.diff[name] = {
      pattern: RegExp('^(?:[' + prefix + '].*(?:\r\n?|\n|(?![\\s\\S])))+', 'm'),
      alias: alias,
      inside: {
        'line': {
          pattern: /(.)(?=[\s\S]).*(?:\r\n?|\n)?/,
          lookbehind: true
        },
        'prefix': {
          pattern: /[\s\S]/,
          alias: /\w+/.exec(name)[0]
        }
      }
    };
  });

  // make prefixes available to Diff plugin
  Object.defineProperty(Prism.languages.diff, 'PREFIXES', {
    value: PREFIXES
  });
})(Prism);

Prism.languages.erlang = {
  'comment': /%.+/,
  'string': {
    pattern: /"(?:\\.|[^\\"\r\n])*"/,
    greedy: true
  },
  'quoted-function': {
    pattern: /'(?:\\.|[^\\'\r\n])+'(?=\()/,
    alias: 'function'
  },
  'quoted-atom': {
    pattern: /'(?:\\.|[^\\'\r\n])+'/,
    alias: 'atom'
  },
  'boolean': /\b(?:false|true)\b/,
  'keyword': /\b(?:after|begin|case|catch|end|fun|if|of|receive|try|when)\b/,
  'number': [/\$\\?./, /\b\d+#[a-z0-9]+/i, /(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:e[+-]?\d+)?/i],
  'function': /\b[a-z][\w@]*(?=\()/,
  'variable': {
    // Look-behind is used to prevent wrong highlighting of atoms containing "@"
    pattern: /(^|[^@])(?:\b|\?)[A-Z_][\w@]*/,
    lookbehind: true
  },
  'operator': [/[=\/<>:]=|=[:\/]=|\+\+?|--?|[=*\/!]|\b(?:and|andalso|band|bnot|bor|bsl|bsr|bxor|div|not|or|orelse|rem|xor)\b/, {
    // We don't want to match <<
    pattern: /(^|[^<])<(?!<)/,
    lookbehind: true
  }, {
    // We don't want to match >>
    pattern: /(^|[^>])>(?!>)/,
    lookbehind: true
  }],
  'atom': /\b[a-z][\w@]*/,
  'punctuation': /[()[\]{}:;,.#|]|<<|>>/
};

Prism.languages.go = Prism.languages.extend('clike', {
  'string': {
    pattern: /(^|[^\\])"(?:\\.|[^"\\\r\n])*"|`[^`]*`/,
    lookbehind: true,
    greedy: true
  },
  'keyword': /\b(?:break|case|chan|const|continue|default|defer|else|fallthrough|for|func|go(?:to)?|if|import|interface|map|package|range|return|select|struct|switch|type|var)\b/,
  'boolean': /\b(?:_|false|iota|nil|true)\b/,
  'number': [
  // binary and octal integers
  /\b0(?:b[01_]+|o[0-7_]+)i?\b/i,
  // hexadecimal integers and floats
  /\b0x(?:[a-f\d_]+(?:\.[a-f\d_]*)?|\.[a-f\d_]+)(?:p[+-]?\d+(?:_\d+)*)?i?(?!\w)/i,
  // decimal integers and floats
  /(?:\b\d[\d_]*(?:\.[\d_]*)?|\B\.\d[\d_]*)(?:e[+-]?[\d_]+)?i?(?!\w)/i],
  'operator': /[*\/%^!=]=?|\+[=+]?|-[=-]?|\|[=|]?|&(?:=|&|\^=?)?|>(?:>=?|=)?|<(?:<=?|=|-)?|:=|\.\.\./,
  'builtin': /\b(?:append|bool|byte|cap|close|complex|complex(?:64|128)|copy|delete|error|float(?:32|64)|u?int(?:8|16|32|64)?|imag|len|make|new|panic|print(?:ln)?|real|recover|rune|string|uintptr)\b/
});
Prism.languages.insertBefore('go', 'string', {
  'char': {
    pattern: /'(?:\\.|[^'\\\r\n]){0,10}'/,
    greedy: true
  }
});
delete Prism.languages.go['class-name'];

(function (Prism) {
  var interpolation = {
    pattern: /((?:^|[^\\$])(?:\\{2})*)\$(?:\w+|\{[^{}]*\})/,
    lookbehind: true,
    inside: {
      'interpolation-punctuation': {
        pattern: /^\$\{?|\}$/,
        alias: 'punctuation'
      },
      'expression': {
        pattern: /[\s\S]+/,
        inside: null // see below
      }
    }
  };
  Prism.languages.groovy = Prism.languages.extend('clike', {
    'string': {
      // https://groovy-lang.org/syntax.html#_dollar_slashy_string
      pattern: /'''(?:[^\\]|\\[\s\S])*?'''|'(?:\\.|[^\\'\r\n])*'/,
      greedy: true
    },
    'keyword': /\b(?:abstract|as|assert|boolean|break|byte|case|catch|char|class|const|continue|def|default|do|double|else|enum|extends|final|finally|float|for|goto|if|implements|import|in|instanceof|int|interface|long|native|new|package|private|protected|public|return|short|static|strictfp|super|switch|synchronized|this|throw|throws|trait|transient|try|void|volatile|while)\b/,
    'number': /\b(?:0b[01_]+|0x[\da-f_]+(?:\.[\da-f_p\-]+)?|[\d_]+(?:\.[\d_]+)?(?:e[+-]?\d+)?)[glidf]?\b/i,
    'operator': {
      pattern: /(^|[^.])(?:~|==?~?|\?[.:]?|\*(?:[.=]|\*=?)?|\.[@&]|\.\.<|\.\.(?!\.)|-[-=>]?|\+[+=]?|!=?|<(?:<=?|=>?)?|>(?:>>?=?|=)?|&[&=]?|\|[|=]?|\/=?|\^=?|%=?)/,
      lookbehind: true
    },
    'punctuation': /\.+|[{}[\];(),:$]/
  });
  Prism.languages.insertBefore('groovy', 'string', {
    'shebang': {
      pattern: /#!.+/,
      alias: 'comment',
      greedy: true
    },
    'interpolation-string': {
      // TODO: Slash strings (e.g. /foo/) can contain line breaks but this will cause a lot of trouble with
      // simple division (see JS regex), so find a fix maybe?
      pattern: /"""(?:[^\\]|\\[\s\S])*?"""|(["/])(?:\\.|(?!\1)[^\\\r\n])*\1|\$\/(?:[^/$]|\$(?:[/$]|(?![/$]))|\/(?!\$))*\/\$/,
      greedy: true,
      inside: {
        'interpolation': interpolation,
        'string': /[\s\S]+/
      }
    }
  });
  Prism.languages.insertBefore('groovy', 'punctuation', {
    'spock-block': /\b(?:and|cleanup|expect|given|setup|then|when|where):/
  });
  Prism.languages.insertBefore('groovy', 'function', {
    'annotation': {
      pattern: /(^|[^.])@\w+/,
      lookbehind: true,
      alias: 'punctuation'
    }
  });
  interpolation.inside.expression.inside = Prism.languages.groovy;
})(Prism);

(function (Prism) {
  var keywords = /\b(?:abstract|assert|boolean|break|byte|case|catch|char|class|const|continue|default|do|double|else|enum|exports|extends|final|finally|float|for|goto|if|implements|import|instanceof|int|interface|long|module|native|new|non-sealed|null|open|opens|package|permits|private|protected|provides|public|record(?!\s*[(){}[\]<>=%~.:,;?+\-*/&|^])|requires|return|sealed|short|static|strictfp|super|switch|synchronized|this|throw|throws|to|transient|transitive|try|uses|var|void|volatile|while|with|yield)\b/;

  // full package (optional) + parent classes (optional)
  var classNamePrefix = /(?:[a-z]\w*\s*\.\s*)*(?:[A-Z]\w*\s*\.\s*)*/.source;

  // based on the java naming conventions
  var className = {
    pattern: RegExp(/(^|[^\w.])/.source + classNamePrefix + /[A-Z](?:[\d_A-Z]*[a-z]\w*)?\b/.source),
    lookbehind: true,
    inside: {
      'namespace': {
        pattern: /^[a-z]\w*(?:\s*\.\s*[a-z]\w*)*(?:\s*\.)?/,
        inside: {
          'punctuation': /\./
        }
      },
      'punctuation': /\./
    }
  };
  Prism.languages.java = Prism.languages.extend('clike', {
    'string': {
      pattern: /(^|[^\\])"(?:\\.|[^"\\\r\n])*"/,
      lookbehind: true,
      greedy: true
    },
    'class-name': [className, {
      // variables, parameters, and constructor references
      // this to support class names (or generic parameters) which do not contain a lower case letter (also works for methods)
      pattern: RegExp(/(^|[^\w.])/.source + classNamePrefix + /[A-Z]\w*(?=\s+\w+\s*[;,=()]|\s*(?:\[[\s,]*\]\s*)?::\s*new\b)/.source),
      lookbehind: true,
      inside: className.inside
    }, {
      // class names based on keyword
      // this to support class names (or generic parameters) which do not contain a lower case letter (also works for methods)
      pattern: RegExp(/(\b(?:class|enum|extends|implements|instanceof|interface|new|record|throws)\s+)/.source + classNamePrefix + /[A-Z]\w*\b/.source),
      lookbehind: true,
      inside: className.inside
    }],
    'keyword': keywords,
    'function': [Prism.languages.clike.function, {
      pattern: /(::\s*)[a-z_]\w*/,
      lookbehind: true
    }],
    'number': /\b0b[01][01_]*L?\b|\b0x(?:\.[\da-f_p+-]+|[\da-f_]+(?:\.[\da-f_p+-]+)?)\b|(?:\b\d[\d_]*(?:\.[\d_]*)?|\B\.\d[\d_]*)(?:e[+-]?\d[\d_]*)?[dfl]?/i,
    'operator': {
      pattern: /(^|[^.])(?:<<=?|>>>?=?|->|--|\+\+|&&|\|\||::|[?:~]|[-+*/%&|^!=<>]=?)/m,
      lookbehind: true
    },
    'constant': /\b[A-Z][A-Z_\d]+\b/
  });
  Prism.languages.insertBefore('java', 'string', {
    'triple-quoted-string': {
      // http://openjdk.java.net/jeps/355#Description
      pattern: /"""[ \t]*[\r\n](?:(?:"|"")?(?:\\.|[^"\\]))*"""/,
      greedy: true,
      alias: 'string'
    },
    'char': {
      pattern: /'(?:\\.|[^'\\\r\n]){1,6}'/,
      greedy: true
    }
  });
  Prism.languages.insertBefore('java', 'class-name', {
    'annotation': {
      pattern: /(^|[^.])@\w+(?:\s*\.\s*\w+)*/,
      lookbehind: true,
      alias: 'punctuation'
    },
    'generics': {
      pattern: /<(?:[\w\s,.?]|&(?!&)|<(?:[\w\s,.?]|&(?!&)|<(?:[\w\s,.?]|&(?!&)|<(?:[\w\s,.?]|&(?!&))*>)*>)*>)*>/,
      inside: {
        'class-name': className,
        'keyword': keywords,
        'punctuation': /[<>(),.:]/,
        'operator': /[?&|]/
      }
    },
    'import': [{
      pattern: RegExp(/(\bimport\s+)/.source + classNamePrefix + /(?:[A-Z]\w*|\*)(?=\s*;)/.source),
      lookbehind: true,
      inside: {
        'namespace': className.inside.namespace,
        'punctuation': /\./,
        'operator': /\*/,
        'class-name': /\w+/
      }
    }, {
      pattern: RegExp(/(\bimport\s+static\s+)/.source + classNamePrefix + /(?:\w+|\*)(?=\s*;)/.source),
      lookbehind: true,
      alias: 'static',
      inside: {
        'namespace': className.inside.namespace,
        'static': /\b\w+$/,
        'punctuation': /\./,
        'operator': /\*/,
        'class-name': /\w+/
      }
    }],
    'namespace': {
      pattern: RegExp(/(\b(?:exports|import(?:\s+static)?|module|open|opens|package|provides|requires|to|transitive|uses|with)\s+)(?!<keyword>)[a-z]\w*(?:\.[a-z]\w*)*\.?/.source.replace(/<keyword>/g, function () {
        return keywords.source;
      })),
      lookbehind: true,
      inside: {
        'punctuation': /\./
      }
    }
  });
})(Prism);

// https://www.json.org/json-en.html
Prism.languages.json = {
  'property': {
    pattern: /(^|[^\\])"(?:\\.|[^\\"\r\n])*"(?=\s*:)/,
    lookbehind: true,
    greedy: true
  },
  'string': {
    pattern: /(^|[^\\])"(?:\\.|[^\\"\r\n])*"(?!\s*:)/,
    lookbehind: true,
    greedy: true
  },
  'comment': {
    pattern: /\/\/.*|\/\*[\s\S]*?(?:\*\/|$)/,
    greedy: true
  },
  'number': /-?\b\d+(?:\.\d+)?(?:e[+-]?\d+)?\b/i,
  'punctuation': /[{}[\],]/,
  'operator': /:/,
  'boolean': /\b(?:false|true)\b/,
  'null': {
    pattern: /\bnull\b/,
    alias: 'keyword'
  }
};
Prism.languages.webmanifest = Prism.languages.json;

(function (Prism) {
  Prism.languages.kotlin = Prism.languages.extend('clike', {
    'keyword': {
      // The lookbehind prevents wrong highlighting of e.g. kotlin.properties.get
      pattern: /(^|[^.])\b(?:abstract|actual|annotation|as|break|by|catch|class|companion|const|constructor|continue|crossinline|data|do|dynamic|else|enum|expect|external|final|finally|for|fun|get|if|import|in|infix|init|inline|inner|interface|internal|is|lateinit|noinline|null|object|open|operator|out|override|package|private|protected|public|reified|return|sealed|set|super|suspend|tailrec|this|throw|to|try|typealias|val|var|vararg|when|where|while)\b/,
      lookbehind: true
    },
    'function': [{
      pattern: /(?:`[^\r\n`]+`|\b\w+)(?=\s*\()/,
      greedy: true
    }, {
      pattern: /(\.)(?:`[^\r\n`]+`|\w+)(?=\s*\{)/,
      lookbehind: true,
      greedy: true
    }],
    'number': /\b(?:0[xX][\da-fA-F]+(?:_[\da-fA-F]+)*|0[bB][01]+(?:_[01]+)*|\d+(?:_\d+)*(?:\.\d+(?:_\d+)*)?(?:[eE][+-]?\d+(?:_\d+)*)?[fFL]?)\b/,
    'operator': /\+[+=]?|-[-=>]?|==?=?|!(?:!|==?)?|[\/*%<>]=?|[?:]:?|\.\.|&&|\|\||\b(?:and|inv|or|shl|shr|ushr|xor)\b/
  });
  delete Prism.languages.kotlin['class-name'];
  var interpolationInside = {
    'interpolation-punctuation': {
      pattern: /^\$\{?|\}$/,
      alias: 'punctuation'
    },
    'expression': {
      pattern: /[\s\S]+/,
      inside: Prism.languages.kotlin
    }
  };
  Prism.languages.insertBefore('kotlin', 'string', {
    // https://kotlinlang.org/spec/expressions.html#string-interpolation-expressions
    'string-literal': [{
      pattern: /"""(?:[^$]|\$(?:(?!\{)|\{[^{}]*\}))*?"""/,
      alias: 'multiline',
      inside: {
        'interpolation': {
          pattern: /\$(?:[a-z_]\w*|\{[^{}]*\})/i,
          inside: interpolationInside
        },
        'string': /[\s\S]+/
      }
    }, {
      pattern: /"(?:[^"\\\r\n$]|\\.|\$(?:(?!\{)|\{[^{}]*\}))*"/,
      alias: 'singleline',
      inside: {
        'interpolation': {
          pattern: /((?:^|[^\\])(?:\\{2})*)\$(?:[a-z_]\w*|\{[^{}]*\})/i,
          lookbehind: true,
          inside: interpolationInside
        },
        'string': /[\s\S]+/
      }
    }],
    'char': {
      // https://kotlinlang.org/spec/expressions.html#character-literals
      pattern: /'(?:[^'\\\r\n]|\\(?:.|u[a-fA-F0-9]{0,4}))'/,
      greedy: true
    }
  });
  delete Prism.languages.kotlin['string'];
  Prism.languages.insertBefore('kotlin', 'keyword', {
    'annotation': {
      pattern: /\B@(?:\w+:)?(?:[A-Z]\w*|\[[^\]]+\])/,
      alias: 'builtin'
    }
  });
  Prism.languages.insertBefore('kotlin', 'function', {
    'label': {
      pattern: /\b\w+@|@\w+\b/,
      alias: 'symbol'
    }
  });
  Prism.languages.kt = Prism.languages.kotlin;
  Prism.languages.kts = Prism.languages.kotlin;
})(Prism);

(function (Prism) {
  var brackets = /(?:\((?:[^()\\]|\\[\s\S])*\)|\{(?:[^{}\\]|\\[\s\S])*\}|\[(?:[^[\]\\]|\\[\s\S])*\]|<(?:[^<>\\]|\\[\s\S])*>)/.source;
  Prism.languages.perl = {
    'comment': [{
      // POD
      pattern: /(^\s*)=\w[\s\S]*?=cut.*/m,
      lookbehind: true,
      greedy: true
    }, {
      pattern: /(^|[^\\$])#.*/,
      lookbehind: true,
      greedy: true
    }],
    // TODO Could be nice to handle Heredoc too.
    'string': [{
      pattern: RegExp(/\b(?:q|qq|qw|qx)(?![a-zA-Z0-9])\s*/.source + '(?:' + [
      // q/.../
      /([^a-zA-Z0-9\s{(\[<])(?:(?!\1)[^\\]|\\[\s\S])*\1/.source,
      // q a...a
      // eslint-disable-next-line regexp/strict
      /([a-zA-Z0-9])(?:(?!\2)[^\\]|\\[\s\S])*\2/.source,
      // q(...)
      // q{...}
      // q[...]
      // q<...>
      brackets].join('|') + ')'),
      greedy: true
    },
    // "...", `...`
    {
      pattern: /("|`)(?:(?!\1)[^\\]|\\[\s\S])*\1/,
      greedy: true
    },
    // '...'
    // FIXME Multi-line single-quoted strings are not supported as they would break variables containing '
    {
      pattern: /'(?:[^'\\\r\n]|\\.)*'/,
      greedy: true
    }],
    'regex': [{
      pattern: RegExp(/\b(?:m|qr)(?![a-zA-Z0-9])\s*/.source + '(?:' + [
      // m/.../
      /([^a-zA-Z0-9\s{(\[<])(?:(?!\1)[^\\]|\\[\s\S])*\1/.source,
      // m a...a
      // eslint-disable-next-line regexp/strict
      /([a-zA-Z0-9])(?:(?!\2)[^\\]|\\[\s\S])*\2/.source,
      // m(...)
      // m{...}
      // m[...]
      // m<...>
      brackets].join('|') + ')' + /[msixpodualngc]*/.source),
      greedy: true
    },
    // The lookbehinds prevent -s from breaking
    {
      pattern: RegExp(/(^|[^-])\b(?:s|tr|y)(?![a-zA-Z0-9])\s*/.source + '(?:' + [
      // s/.../.../
      // eslint-disable-next-line regexp/strict
      /([^a-zA-Z0-9\s{(\[<])(?:(?!\2)[^\\]|\\[\s\S])*\2(?:(?!\2)[^\\]|\\[\s\S])*\2/.source,
      // s a...a...a
      // eslint-disable-next-line regexp/strict
      /([a-zA-Z0-9])(?:(?!\3)[^\\]|\\[\s\S])*\3(?:(?!\3)[^\\]|\\[\s\S])*\3/.source,
      // s(...)(...)
      // s{...}{...}
      // s[...][...]
      // s<...><...>
      // s(...)[...]
      brackets + /\s*/.source + brackets].join('|') + ')' + /[msixpodualngcer]*/.source),
      lookbehind: true,
      greedy: true
    },
    // /.../
    // The look-ahead tries to prevent two divisions on
    // the same line from being highlighted as regex.
    // This does not support multi-line regex.
    {
      pattern: /\/(?:[^\/\\\r\n]|\\.)*\/[msixpodualngc]*(?=\s*(?:$|[\r\n,.;})&|\-+*~<>!?^]|(?:and|cmp|eq|ge|gt|le|lt|ne|not|or|x|xor)\b))/,
      greedy: true
    }],
    // FIXME Not sure about the handling of ::, ', and #
    'variable': [
    // ${^POSTMATCH}
    /[&*$@%]\{\^[A-Z]+\}/,
    // $^V
    /[&*$@%]\^[A-Z_]/,
    // ${...}
    /[&*$@%]#?(?=\{)/,
    // $foo
    /[&*$@%]#?(?:(?:::)*'?(?!\d)[\w$]+(?![\w$]))+(?:::)*/,
    // $1
    /[&*$@%]\d+/,
    // $_, @_, %!
    // The negative lookahead prevents from breaking the %= operator
    /(?!%=)[$@%][!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~]/],
    'filehandle': {
      // <>, <FOO>, _
      pattern: /<(?![<=])\S*?>|\b_\b/,
      alias: 'symbol'
    },
    'v-string': {
      // v1.2, 1.2.3
      pattern: /v\d+(?:\.\d+)*|\d+(?:\.\d+){2,}/,
      alias: 'string'
    },
    'function': {
      pattern: /(\bsub[ \t]+)\w+/,
      lookbehind: true
    },
    'keyword': /\b(?:any|break|continue|default|delete|die|do|else|elsif|eval|for|foreach|given|goto|if|last|local|my|next|our|package|print|redo|require|return|say|state|sub|switch|undef|unless|until|use|when|while)\b/,
    'number': /\b(?:0x[\dA-Fa-f](?:_?[\dA-Fa-f])*|0b[01](?:_?[01])*|(?:(?:\d(?:_?\d)*)?\.)?\d(?:_?\d)*(?:[Ee][+-]?\d+)?)\b/,
    'operator': /-[rwxoRWXOezsfdlpSbctugkTBMAC]\b|\+[+=]?|-[-=>]?|\*\*?=?|\/\/?=?|=[=~>]?|~[~=]?|\|\|?=?|&&?=?|<(?:=>?|<=?)?|>>?=?|![~=]?|[%^]=?|\.(?:=|\.\.?)?|[\\?]|\bx(?:=|\b)|\b(?:and|cmp|eq|ge|gt|le|lt|ne|not|or|xor)\b/,
    'punctuation': /[{}[\];(),:]/
  };
})(Prism);

(function (Prism) {
  /**
   * Returns the placeholder for the given language id and index.
   *
   * @param {string} language
   * @param {string|number} index
   * @returns {string}
   */
  function getPlaceholder(language, index) {
    return '___' + language.toUpperCase() + index + '___';
  }
  Object.defineProperties(Prism.languages['markup-templating'] = {}, {
    buildPlaceholders: {
      /**
       * Tokenize all inline templating expressions matching `placeholderPattern`.
       *
       * If `replaceFilter` is provided, only matches of `placeholderPattern` for which `replaceFilter` returns
       * `true` will be replaced.
       *
       * @param {object} env The environment of the `before-tokenize` hook.
       * @param {string} language The language id.
       * @param {RegExp} placeholderPattern The matches of this pattern will be replaced by placeholders.
       * @param {(match: string) => boolean} [replaceFilter]
       */
      value: function (env, language, placeholderPattern, replaceFilter) {
        if (env.language !== language) {
          return;
        }
        var tokenStack = env.tokenStack = [];
        env.code = env.code.replace(placeholderPattern, function (match) {
          if (typeof replaceFilter === 'function' && !replaceFilter(match)) {
            return match;
          }
          var i = tokenStack.length;
          var placeholder;

          // Check for existing strings
          while (env.code.indexOf(placeholder = getPlaceholder(language, i)) !== -1) {
            ++i;
          }

          // Create a sparse array
          tokenStack[i] = match;
          return placeholder;
        });

        // Switch the grammar to markup
        env.grammar = Prism.languages.markup;
      }
    },
    tokenizePlaceholders: {
      /**
       * Replace placeholders with proper tokens after tokenizing.
       *
       * @param {object} env The environment of the `after-tokenize` hook.
       * @param {string} language The language id.
       */
      value: function (env, language) {
        if (env.language !== language || !env.tokenStack) {
          return;
        }

        // Switch the grammar back
        env.grammar = Prism.languages[language];
        var j = 0;
        var keys = Object.keys(env.tokenStack);
        function walkTokens(tokens) {
          for (var i = 0; i < tokens.length; i++) {
            // all placeholders are replaced already
            if (j >= keys.length) {
              break;
            }
            var token = tokens[i];
            if (typeof token === 'string' || token.content && typeof token.content === 'string') {
              var k = keys[j];
              var t = env.tokenStack[k];
              var s = typeof token === 'string' ? token : token.content;
              var placeholder = getPlaceholder(language, k);
              var index = s.indexOf(placeholder);
              if (index > -1) {
                ++j;
                var before = s.substring(0, index);
                var middle = new Prism.Token(language, Prism.tokenize(t, env.grammar), 'language-' + language, t);
                var after = s.substring(index + placeholder.length);
                var replacement = [];
                if (before) {
                  replacement.push.apply(replacement, walkTokens([before]));
                }
                replacement.push(middle);
                if (after) {
                  replacement.push.apply(replacement, walkTokens([after]));
                }
                if (typeof token === 'string') {
                  tokens.splice.apply(tokens, [i, 1].concat(replacement));
                } else {
                  token.content = replacement;
                }
              }
            } else if (token.content /* && typeof token.content !== 'string' */) {
              walkTokens(token.content);
            }
          }
          return tokens;
        }
        walkTokens(env.tokens);
      }
    }
  });
})(Prism);

/**
 * Original by Aaron Harun: http://aahacreative.com/2012/07/31/php-syntax-highlighting-prism/
 * Modified by Miles Johnson: http://milesj.me
 * Rewritten by Tom Pavelec
 *
 * Supports PHP 5.3 - 8.0
 */
(function (Prism) {
  var comment = /\/\*[\s\S]*?\*\/|\/\/.*|#(?!\[).*/;
  var constant = [{
    pattern: /\b(?:false|true)\b/i,
    alias: 'boolean'
  }, {
    pattern: /(::\s*)\b[a-z_]\w*\b(?!\s*\()/i,
    greedy: true,
    lookbehind: true
  }, {
    pattern: /(\b(?:case|const)\s+)\b[a-z_]\w*(?=\s*[;=])/i,
    greedy: true,
    lookbehind: true
  }, /\b(?:null)\b/i, /\b[A-Z_][A-Z0-9_]*\b(?!\s*\()/];
  var number = /\b0b[01]+(?:_[01]+)*\b|\b0o[0-7]+(?:_[0-7]+)*\b|\b0x[\da-f]+(?:_[\da-f]+)*\b|(?:\b\d+(?:_\d+)*\.?(?:\d+(?:_\d+)*)?|\B\.\d+)(?:e[+-]?\d+)?/i;
  var operator = /<?=>|\?\?=?|\.{3}|\??->|[!=]=?=?|::|\*\*=?|--|\+\+|&&|\|\||<<|>>|[?~]|[/^|%*&<>.+-]=?/;
  var punctuation = /[{}\[\](),:;]/;
  Prism.languages.php = {
    'delimiter': {
      pattern: /\?>$|^<\?(?:php(?=\s)|=)?/i,
      alias: 'important'
    },
    'comment': comment,
    'variable': /\$+(?:\w+\b|(?=\{))/,
    'package': {
      pattern: /(namespace\s+|use\s+(?:function\s+)?)(?:\\?\b[a-z_]\w*)+\b(?!\\)/i,
      lookbehind: true,
      inside: {
        'punctuation': /\\/
      }
    },
    'class-name-definition': {
      pattern: /(\b(?:class|enum|interface|trait)\s+)\b[a-z_]\w*(?!\\)\b/i,
      lookbehind: true,
      alias: 'class-name'
    },
    'function-definition': {
      pattern: /(\bfunction\s+)[a-z_]\w*(?=\s*\()/i,
      lookbehind: true,
      alias: 'function'
    },
    'keyword': [{
      pattern: /(\(\s*)\b(?:array|bool|boolean|float|int|integer|object|string)\b(?=\s*\))/i,
      alias: 'type-casting',
      greedy: true,
      lookbehind: true
    }, {
      pattern: /([(,?]\s*)\b(?:array(?!\s*\()|bool|callable|(?:false|null)(?=\s*\|)|float|int|iterable|mixed|object|self|static|string)\b(?=\s*\$)/i,
      alias: 'type-hint',
      greedy: true,
      lookbehind: true
    }, {
      pattern: /(\)\s*:\s*(?:\?\s*)?)\b(?:array(?!\s*\()|bool|callable|(?:false|null)(?=\s*\|)|float|int|iterable|mixed|never|object|self|static|string|void)\b/i,
      alias: 'return-type',
      greedy: true,
      lookbehind: true
    }, {
      pattern: /\b(?:array(?!\s*\()|bool|float|int|iterable|mixed|object|string|void)\b/i,
      alias: 'type-declaration',
      greedy: true
    }, {
      pattern: /(\|\s*)(?:false|null)\b|\b(?:false|null)(?=\s*\|)/i,
      alias: 'type-declaration',
      greedy: true,
      lookbehind: true
    }, {
      pattern: /\b(?:parent|self|static)(?=\s*::)/i,
      alias: 'static-context',
      greedy: true
    }, {
      // yield from
      pattern: /(\byield\s+)from\b/i,
      lookbehind: true
    },
    // `class` is always a keyword unlike other keywords
    /\bclass\b/i, {
      // https://www.php.net/manual/en/reserved.keywords.php
      //
      // keywords cannot be preceded by "->"
      // the complex lookbehind means `(?<!(?:->|::)\s*)`
      pattern: /((?:^|[^\s>:]|(?:^|[^-])>|(?:^|[^:]):)\s*)\b(?:abstract|and|array|as|break|callable|case|catch|clone|const|continue|declare|default|die|do|echo|else|elseif|empty|enddeclare|endfor|endforeach|endif|endswitch|endwhile|enum|eval|exit|extends|final|finally|fn|for|foreach|function|global|goto|if|implements|include|include_once|instanceof|insteadof|interface|isset|list|match|namespace|never|new|or|parent|print|private|protected|public|readonly|require|require_once|return|self|static|switch|throw|trait|try|unset|use|var|while|xor|yield|__halt_compiler)\b/i,
      lookbehind: true
    }],
    'argument-name': {
      pattern: /([(,]\s*)\b[a-z_]\w*(?=\s*:(?!:))/i,
      lookbehind: true
    },
    'class-name': [{
      pattern: /(\b(?:extends|implements|instanceof|new(?!\s+self|\s+static))\s+|\bcatch\s*\()\b[a-z_]\w*(?!\\)\b/i,
      greedy: true,
      lookbehind: true
    }, {
      pattern: /(\|\s*)\b[a-z_]\w*(?!\\)\b/i,
      greedy: true,
      lookbehind: true
    }, {
      pattern: /\b[a-z_]\w*(?!\\)\b(?=\s*\|)/i,
      greedy: true
    }, {
      pattern: /(\|\s*)(?:\\?\b[a-z_]\w*)+\b/i,
      alias: 'class-name-fully-qualified',
      greedy: true,
      lookbehind: true,
      inside: {
        'punctuation': /\\/
      }
    }, {
      pattern: /(?:\\?\b[a-z_]\w*)+\b(?=\s*\|)/i,
      alias: 'class-name-fully-qualified',
      greedy: true,
      inside: {
        'punctuation': /\\/
      }
    }, {
      pattern: /(\b(?:extends|implements|instanceof|new(?!\s+self\b|\s+static\b))\s+|\bcatch\s*\()(?:\\?\b[a-z_]\w*)+\b(?!\\)/i,
      alias: 'class-name-fully-qualified',
      greedy: true,
      lookbehind: true,
      inside: {
        'punctuation': /\\/
      }
    }, {
      pattern: /\b[a-z_]\w*(?=\s*\$)/i,
      alias: 'type-declaration',
      greedy: true
    }, {
      pattern: /(?:\\?\b[a-z_]\w*)+(?=\s*\$)/i,
      alias: ['class-name-fully-qualified', 'type-declaration'],
      greedy: true,
      inside: {
        'punctuation': /\\/
      }
    }, {
      pattern: /\b[a-z_]\w*(?=\s*::)/i,
      alias: 'static-context',
      greedy: true
    }, {
      pattern: /(?:\\?\b[a-z_]\w*)+(?=\s*::)/i,
      alias: ['class-name-fully-qualified', 'static-context'],
      greedy: true,
      inside: {
        'punctuation': /\\/
      }
    }, {
      pattern: /([(,?]\s*)[a-z_]\w*(?=\s*\$)/i,
      alias: 'type-hint',
      greedy: true,
      lookbehind: true
    }, {
      pattern: /([(,?]\s*)(?:\\?\b[a-z_]\w*)+(?=\s*\$)/i,
      alias: ['class-name-fully-qualified', 'type-hint'],
      greedy: true,
      lookbehind: true,
      inside: {
        'punctuation': /\\/
      }
    }, {
      pattern: /(\)\s*:\s*(?:\?\s*)?)\b[a-z_]\w*(?!\\)\b/i,
      alias: 'return-type',
      greedy: true,
      lookbehind: true
    }, {
      pattern: /(\)\s*:\s*(?:\?\s*)?)(?:\\?\b[a-z_]\w*)+\b(?!\\)/i,
      alias: ['class-name-fully-qualified', 'return-type'],
      greedy: true,
      lookbehind: true,
      inside: {
        'punctuation': /\\/
      }
    }],
    'constant': constant,
    'function': {
      pattern: /(^|[^\\\w])\\?[a-z_](?:[\w\\]*\w)?(?=\s*\()/i,
      lookbehind: true,
      inside: {
        'punctuation': /\\/
      }
    },
    'property': {
      pattern: /(->\s*)\w+/,
      lookbehind: true
    },
    'number': number,
    'operator': operator,
    'punctuation': punctuation
  };
  var string_interpolation = {
    pattern: /\{\$(?:\{(?:\{[^{}]+\}|[^{}]+)\}|[^{}])+\}|(^|[^\\{])\$+(?:\w+(?:\[[^\r\n\[\]]+\]|->\w+)?)/,
    lookbehind: true,
    inside: Prism.languages.php
  };
  var string = [{
    pattern: /<<<'([^']+)'[\r\n](?:.*[\r\n])*?\1;/,
    alias: 'nowdoc-string',
    greedy: true,
    inside: {
      'delimiter': {
        pattern: /^<<<'[^']+'|[a-z_]\w*;$/i,
        alias: 'symbol',
        inside: {
          'punctuation': /^<<<'?|[';]$/
        }
      }
    }
  }, {
    pattern: /<<<(?:"([^"]+)"[\r\n](?:.*[\r\n])*?\1;|([a-z_]\w*)[\r\n](?:.*[\r\n])*?\2;)/i,
    alias: 'heredoc-string',
    greedy: true,
    inside: {
      'delimiter': {
        pattern: /^<<<(?:"[^"]+"|[a-z_]\w*)|[a-z_]\w*;$/i,
        alias: 'symbol',
        inside: {
          'punctuation': /^<<<"?|[";]$/
        }
      },
      'interpolation': string_interpolation
    }
  }, {
    pattern: /`(?:\\[\s\S]|[^\\`])*`/,
    alias: 'backtick-quoted-string',
    greedy: true
  }, {
    pattern: /'(?:\\[\s\S]|[^\\'])*'/,
    alias: 'single-quoted-string',
    greedy: true
  }, {
    pattern: /"(?:\\[\s\S]|[^\\"])*"/,
    alias: 'double-quoted-string',
    greedy: true,
    inside: {
      'interpolation': string_interpolation
    }
  }];
  Prism.languages.insertBefore('php', 'variable', {
    'string': string,
    'attribute': {
      pattern: /#\[(?:[^"'\/#]|\/(?![*/])|\/\/.*$|#(?!\[).*$|\/\*(?:[^*]|\*(?!\/))*\*\/|"(?:\\[\s\S]|[^\\"])*"|'(?:\\[\s\S]|[^\\'])*')+\](?=\s*[a-z$#])/im,
      greedy: true,
      inside: {
        'attribute-content': {
          pattern: /^(#\[)[\s\S]+(?=\]$)/,
          lookbehind: true,
          // inside can appear subset of php
          inside: {
            'comment': comment,
            'string': string,
            'attribute-class-name': [{
              pattern: /([^:]|^)\b[a-z_]\w*(?!\\)\b/i,
              alias: 'class-name',
              greedy: true,
              lookbehind: true
            }, {
              pattern: /([^:]|^)(?:\\?\b[a-z_]\w*)+/i,
              alias: ['class-name', 'class-name-fully-qualified'],
              greedy: true,
              lookbehind: true,
              inside: {
                'punctuation': /\\/
              }
            }],
            'constant': constant,
            'number': number,
            'operator': operator,
            'punctuation': punctuation
          }
        },
        'delimiter': {
          pattern: /^#\[|\]$/,
          alias: 'punctuation'
        }
      }
    }
  });
  Prism.hooks.add('before-tokenize', function (env) {
    if (!/<\?/.test(env.code)) {
      return;
    }
    var phpPattern = /<\?(?:[^"'/#]|\/(?![*/])|("|')(?:\\[\s\S]|(?!\1)[^\\])*\1|(?:\/\/|#(?!\[))(?:[^?\n\r]|\?(?!>))*(?=$|\?>|[\r\n])|#\[|\/\*(?:[^*]|\*(?!\/))*(?:\*\/|$))*?(?:\?>|$)/g;
    Prism.languages['markup-templating'].buildPlaceholders(env, 'php', phpPattern);
  });
  Prism.hooks.add('after-tokenize', function (env) {
    Prism.languages['markup-templating'].tokenizePlaceholders(env, 'php');
  });
})(Prism);

(function (Prism) {
  var powershell = Prism.languages.powershell = {
    'comment': [{
      pattern: /(^|[^`])<#[\s\S]*?#>/,
      lookbehind: true
    }, {
      pattern: /(^|[^`])#.*/,
      lookbehind: true
    }],
    'string': [{
      pattern: /"(?:`[\s\S]|[^`"])*"/,
      greedy: true,
      inside: null // see below
    }, {
      pattern: /'(?:[^']|'')*'/,
      greedy: true
    }],
    // Matches name spaces as well as casts, attribute decorators. Force starting with letter to avoid matching array indices
    // Supports two levels of nested brackets (e.g. `[OutputType([System.Collections.Generic.List[int]])]`)
    'namespace': /\[[a-z](?:\[(?:\[[^\]]*\]|[^\[\]])*\]|[^\[\]])*\]/i,
    'boolean': /\$(?:false|true)\b/i,
    'variable': /\$\w+\b/,
    // Cmdlets and aliases. Aliases should come last, otherwise "write" gets preferred over "write-host" for example
    // Get-Command | ?{ $_.ModuleName -match "Microsoft.PowerShell.(Util|Core|Management)" }
    // Get-Alias | ?{ $_.ReferencedCommand.Module.Name -match "Microsoft.PowerShell.(Util|Core|Management)" }
    'function': [/\b(?:Add|Approve|Assert|Backup|Block|Checkpoint|Clear|Close|Compare|Complete|Compress|Confirm|Connect|Convert|ConvertFrom|ConvertTo|Copy|Debug|Deny|Disable|Disconnect|Dismount|Edit|Enable|Enter|Exit|Expand|Export|Find|ForEach|Format|Get|Grant|Group|Hide|Import|Initialize|Install|Invoke|Join|Limit|Lock|Measure|Merge|Move|New|Open|Optimize|Out|Ping|Pop|Protect|Publish|Push|Read|Receive|Redo|Register|Remove|Rename|Repair|Request|Reset|Resize|Resolve|Restart|Restore|Resume|Revoke|Save|Search|Select|Send|Set|Show|Skip|Sort|Split|Start|Step|Stop|Submit|Suspend|Switch|Sync|Tee|Test|Trace|Unblock|Undo|Uninstall|Unlock|Unprotect|Unpublish|Unregister|Update|Use|Wait|Watch|Where|Write)-[a-z]+\b/i, /\b(?:ac|cat|chdir|clc|cli|clp|clv|compare|copy|cp|cpi|cpp|cvpa|dbp|del|diff|dir|ebp|echo|epal|epcsv|epsn|erase|fc|fl|ft|fw|gal|gbp|gc|gci|gcs|gdr|gi|gl|gm|gp|gps|group|gsv|gu|gv|gwmi|iex|ii|ipal|ipcsv|ipsn|irm|iwmi|iwr|kill|lp|ls|measure|mi|mount|move|mp|mv|nal|ndr|ni|nv|ogv|popd|ps|pushd|pwd|rbp|rd|rdr|ren|ri|rm|rmdir|rni|rnp|rp|rv|rvpa|rwmi|sal|saps|sasv|sbp|sc|select|set|shcm|si|sl|sleep|sls|sort|sp|spps|spsv|start|sv|swmi|tee|trcm|type|write)\b/i],
    // per http://technet.microsoft.com/en-us/library/hh847744.aspx
    'keyword': /\b(?:Begin|Break|Catch|Class|Continue|Data|Define|Do|DynamicParam|Else|ElseIf|End|Exit|Filter|Finally|For|ForEach|From|Function|If|InlineScript|Parallel|Param|Process|Return|Sequence|Switch|Throw|Trap|Try|Until|Using|Var|While|Workflow)\b/i,
    'operator': {
      pattern: /(^|\W)(?:!|-(?:b?(?:and|x?or)|as|(?:Not)?(?:Contains|In|Like|Match)|eq|ge|gt|is(?:Not)?|Join|le|lt|ne|not|Replace|sh[lr])\b|-[-=]?|\+[+=]?|[*\/%]=?)/i,
      lookbehind: true
    },
    'punctuation': /[|{}[\];(),.]/
  };

  // Variable interpolation inside strings, and nested expressions
  powershell.string[0].inside = {
    'function': {
      // Allow for one level of nesting
      pattern: /(^|[^`])\$\((?:\$\([^\r\n()]*\)|(?!\$\()[^\r\n)])*\)/,
      lookbehind: true,
      inside: powershell
    },
    'boolean': powershell.boolean,
    'variable': powershell.variable
  };
})(Prism);

Prism.languages.python = {
  'comment': {
    pattern: /(^|[^\\])#.*/,
    lookbehind: true,
    greedy: true
  },
  'string-interpolation': {
    pattern: /(?:f|fr|rf)(?:("""|''')[\s\S]*?\1|("|')(?:\\.|(?!\2)[^\\\r\n])*\2)/i,
    greedy: true,
    inside: {
      'interpolation': {
        // "{" <expression> <optional "!s", "!r", or "!a"> <optional ":" format specifier> "}"
        pattern: /((?:^|[^{])(?:\{\{)*)\{(?!\{)(?:[^{}]|\{(?!\{)(?:[^{}]|\{(?!\{)(?:[^{}])+\})+\})+\}/,
        lookbehind: true,
        inside: {
          'format-spec': {
            pattern: /(:)[^:(){}]+(?=\}$)/,
            lookbehind: true
          },
          'conversion-option': {
            pattern: /![sra](?=[:}]$)/,
            alias: 'punctuation'
          },
          rest: null
        }
      },
      'string': /[\s\S]+/
    }
  },
  'triple-quoted-string': {
    pattern: /(?:[rub]|br|rb)?("""|''')[\s\S]*?\1/i,
    greedy: true,
    alias: 'string'
  },
  'string': {
    pattern: /(?:[rub]|br|rb)?("|')(?:\\.|(?!\1)[^\\\r\n])*\1/i,
    greedy: true
  },
  'function': {
    pattern: /((?:^|\s)def[ \t]+)[a-zA-Z_]\w*(?=\s*\()/g,
    lookbehind: true
  },
  'class-name': {
    pattern: /(\bclass\s+)\w+/i,
    lookbehind: true
  },
  'decorator': {
    pattern: /(^[\t ]*)@\w+(?:\.\w+)*/m,
    lookbehind: true,
    alias: ['annotation', 'punctuation'],
    inside: {
      'punctuation': /\./
    }
  },
  'keyword': /\b(?:_(?=\s*:)|and|as|assert|async|await|break|case|class|continue|def|del|elif|else|except|exec|finally|for|from|global|if|import|in|is|lambda|match|nonlocal|not|or|pass|print|raise|return|try|while|with|yield)\b/,
  'builtin': /\b(?:__import__|abs|all|any|apply|ascii|basestring|bin|bool|buffer|bytearray|bytes|callable|chr|classmethod|cmp|coerce|compile|complex|delattr|dict|dir|divmod|enumerate|eval|execfile|file|filter|float|format|frozenset|getattr|globals|hasattr|hash|help|hex|id|input|int|intern|isinstance|issubclass|iter|len|list|locals|long|map|max|memoryview|min|next|object|oct|open|ord|pow|property|range|raw_input|reduce|reload|repr|reversed|round|set|setattr|slice|sorted|staticmethod|str|sum|super|tuple|type|unichr|unicode|vars|xrange|zip)\b/,
  'boolean': /\b(?:False|None|True)\b/,
  'number': /\b0(?:b(?:_?[01])+|o(?:_?[0-7])+|x(?:_?[a-f0-9])+)\b|(?:\b\d+(?:_\d+)*(?:\.(?:\d+(?:_\d+)*)?)?|\B\.\d+(?:_\d+)*)(?:e[+-]?\d+(?:_\d+)*)?j?(?!\w)/i,
  'operator': /[-+%=]=?|!=|:=|\*\*?=?|\/\/?=?|<[<=>]?|>[=>]?|[&|^~]/,
  'punctuation': /[{}[\];(),.:]/
};
Prism.languages.python['string-interpolation'].inside['interpolation'].inside.rest = Prism.languages.python;
Prism.languages.py = Prism.languages.python;

/**
 * Original by Samuel Flores
 *
 * Adds the following new token classes:
 *     constant, builtin, variable, symbol, regex
 */
(function (Prism) {
  Prism.languages.ruby = Prism.languages.extend('clike', {
    'comment': {
      pattern: /#.*|^=begin\s[\s\S]*?^=end/m,
      greedy: true
    },
    'class-name': {
      pattern: /(\b(?:class|module)\s+|\bcatch\s+\()[\w.\\]+|\b[A-Z_]\w*(?=\s*\.\s*new\b)/,
      lookbehind: true,
      inside: {
        'punctuation': /[.\\]/
      }
    },
    'keyword': /\b(?:BEGIN|END|alias|and|begin|break|case|class|def|define_method|defined|do|each|else|elsif|end|ensure|extend|for|if|in|include|module|new|next|nil|not|or|prepend|private|protected|public|raise|redo|require|rescue|retry|return|self|super|then|throw|undef|unless|until|when|while|yield)\b/,
    'operator': /\.{2,3}|&\.|===|<?=>|[!=]?~|(?:&&|\|\||<<|>>|\*\*|[+\-*/%<>!^&|=])=?|[?:]/,
    'punctuation': /[(){}[\].,;]/
  });
  Prism.languages.insertBefore('ruby', 'operator', {
    'double-colon': {
      pattern: /::/,
      alias: 'punctuation'
    }
  });
  var interpolation = {
    pattern: /((?:^|[^\\])(?:\\{2})*)#\{(?:[^{}]|\{[^{}]*\})*\}/,
    lookbehind: true,
    inside: {
      'content': {
        pattern: /^(#\{)[\s\S]+(?=\}$)/,
        lookbehind: true,
        inside: Prism.languages.ruby
      },
      'delimiter': {
        pattern: /^#\{|\}$/,
        alias: 'punctuation'
      }
    }
  };
  delete Prism.languages.ruby.function;
  var percentExpression = '(?:' + [/([^a-zA-Z0-9\s{(\[<=])(?:(?!\1)[^\\]|\\[\s\S])*\1/.source, /\((?:[^()\\]|\\[\s\S]|\((?:[^()\\]|\\[\s\S])*\))*\)/.source, /\{(?:[^{}\\]|\\[\s\S]|\{(?:[^{}\\]|\\[\s\S])*\})*\}/.source, /\[(?:[^\[\]\\]|\\[\s\S]|\[(?:[^\[\]\\]|\\[\s\S])*\])*\]/.source, /<(?:[^<>\\]|\\[\s\S]|<(?:[^<>\\]|\\[\s\S])*>)*>/.source].join('|') + ')';
  var symbolName = /(?:"(?:\\.|[^"\\\r\n])*"|(?:\b[a-zA-Z_]\w*|[^\s\0-\x7F]+)[?!]?|\$.)/.source;
  Prism.languages.insertBefore('ruby', 'keyword', {
    'regex-literal': [{
      pattern: RegExp(/%r/.source + percentExpression + /[egimnosux]{0,6}/.source),
      greedy: true,
      inside: {
        'interpolation': interpolation,
        'regex': /[\s\S]+/
      }
    }, {
      pattern: /(^|[^/])\/(?!\/)(?:\[[^\r\n\]]+\]|\\.|[^[/\\\r\n])+\/[egimnosux]{0,6}(?=\s*(?:$|[\r\n,.;})#]))/,
      lookbehind: true,
      greedy: true,
      inside: {
        'interpolation': interpolation,
        'regex': /[\s\S]+/
      }
    }],
    'variable': /[@$]+[a-zA-Z_]\w*(?:[?!]|\b)/,
    'symbol': [{
      pattern: RegExp(/(^|[^:]):/.source + symbolName),
      lookbehind: true,
      greedy: true
    }, {
      pattern: RegExp(/([\r\n{(,][ \t]*)/.source + symbolName + /(?=:(?!:))/.source),
      lookbehind: true,
      greedy: true
    }],
    'method-definition': {
      pattern: /(\bdef\s+)\w+(?:\s*\.\s*\w+)?/,
      lookbehind: true,
      inside: {
        'function': /\b\w+$/,
        'keyword': /^self\b/,
        'class-name': /^\w+/,
        'punctuation': /\./
      }
    }
  });
  Prism.languages.insertBefore('ruby', 'string', {
    'string-literal': [{
      pattern: RegExp(/%[qQiIwWs]?/.source + percentExpression),
      greedy: true,
      inside: {
        'interpolation': interpolation,
        'string': /[\s\S]+/
      }
    }, {
      pattern: /("|')(?:#\{[^}]+\}|#(?!\{)|\\(?:\r\n|[\s\S])|(?!\1)[^\\#\r\n])*\1/,
      greedy: true,
      inside: {
        'interpolation': interpolation,
        'string': /[\s\S]+/
      }
    }, {
      pattern: /<<[-~]?([a-z_]\w*)[\r\n](?:.*[\r\n])*?[\t ]*\1/i,
      alias: 'heredoc-string',
      greedy: true,
      inside: {
        'delimiter': {
          pattern: /^<<[-~]?[a-z_]\w*|\b[a-z_]\w*$/i,
          inside: {
            'symbol': /\b\w+/,
            'punctuation': /^<<[-~]?/
          }
        },
        'interpolation': interpolation,
        'string': /[\s\S]+/
      }
    }, {
      pattern: /<<[-~]?'([a-z_]\w*)'[\r\n](?:.*[\r\n])*?[\t ]*\1/i,
      alias: 'heredoc-string',
      greedy: true,
      inside: {
        'delimiter': {
          pattern: /^<<[-~]?'[a-z_]\w*'|\b[a-z_]\w*$/i,
          inside: {
            'symbol': /\b\w+/,
            'punctuation': /^<<[-~]?'|'$/
          }
        },
        'string': /[\s\S]+/
      }
    }],
    'command-literal': [{
      pattern: RegExp(/%x/.source + percentExpression),
      greedy: true,
      inside: {
        'interpolation': interpolation,
        'command': {
          pattern: /[\s\S]+/,
          alias: 'string'
        }
      }
    }, {
      pattern: /`(?:#\{[^}]+\}|#(?!\{)|\\(?:\r\n|[\s\S])|[^\\`#\r\n])*`/,
      greedy: true,
      inside: {
        'interpolation': interpolation,
        'command': {
          pattern: /[\s\S]+/,
          alias: 'string'
        }
      }
    }]
  });
  delete Prism.languages.ruby.string;
  Prism.languages.insertBefore('ruby', 'number', {
    'builtin': /\b(?:Array|Bignum|Binding|Class|Continuation|Dir|Exception|FalseClass|File|Fixnum|Float|Hash|IO|Integer|MatchData|Method|Module|NilClass|Numeric|Object|Proc|Range|Regexp|Stat|String|Struct|Symbol|TMS|Thread|ThreadGroup|Time|TrueClass)\b/,
    'constant': /\b[A-Z][A-Z0-9_]*(?:[?!]|\b)/
  });
  Prism.languages.rb = Prism.languages.ruby;
})(Prism);

Prism.languages.scala = Prism.languages.extend('java', {
  'triple-quoted-string': {
    pattern: /"""[\s\S]*?"""/,
    greedy: true,
    alias: 'string'
  },
  'string': {
    pattern: /("|')(?:\\.|(?!\1)[^\\\r\n])*\1/,
    greedy: true
  },
  'keyword': /<-|=>|\b(?:abstract|case|catch|class|def|derives|do|else|enum|extends|extension|final|finally|for|forSome|given|if|implicit|import|infix|inline|lazy|match|new|null|object|opaque|open|override|package|private|protected|return|sealed|self|super|this|throw|trait|transparent|try|type|using|val|var|while|with|yield)\b/,
  'number': /\b0x(?:[\da-f]*\.)?[\da-f]+|(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:e\d+)?[dfl]?/i,
  'builtin': /\b(?:Any|AnyRef|AnyVal|Boolean|Byte|Char|Double|Float|Int|Long|Nothing|Short|String|Unit)\b/,
  'symbol': /'[^\d\s\\]\w*/
});
Prism.languages.insertBefore('scala', 'triple-quoted-string', {
  'string-interpolation': {
    pattern: /\b[a-z]\w*(?:"""(?:[^$]|\$(?:[^{]|\{(?:[^{}]|\{[^{}]*\})*\}))*?"""|"(?:[^$"\r\n]|\$(?:[^{]|\{(?:[^{}]|\{[^{}]*\})*\}))*")/i,
    greedy: true,
    inside: {
      'id': {
        pattern: /^\w+/,
        greedy: true,
        alias: 'function'
      },
      'escape': {
        pattern: /\\\$"|\$[$"]/,
        greedy: true,
        alias: 'symbol'
      },
      'interpolation': {
        pattern: /\$(?:\w+|\{(?:[^{}]|\{[^{}]*\})*\})/,
        greedy: true,
        inside: {
          'punctuation': /^\$\{?|\}$/,
          'expression': {
            pattern: /[\s\S]+/,
            inside: Prism.languages.scala
          }
        }
      },
      'string': /[\s\S]+/
    }
  }
});
delete Prism.languages.scala['class-name'];
delete Prism.languages.scala['function'];
delete Prism.languages.scala['constant'];

Prism.languages.sql = {
  'comment': {
    pattern: /(^|[^\\])(?:\/\*[\s\S]*?\*\/|(?:--|\/\/|#).*)/,
    lookbehind: true
  },
  'variable': [{
    pattern: /@(["'`])(?:\\[\s\S]|(?!\1)[^\\])+\1/,
    greedy: true
  }, /@[\w.$]+/],
  'string': {
    pattern: /(^|[^@\\])("|')(?:\\[\s\S]|(?!\2)[^\\]|\2\2)*\2/,
    greedy: true,
    lookbehind: true
  },
  'identifier': {
    pattern: /(^|[^@\\])`(?:\\[\s\S]|[^`\\]|``)*`/,
    greedy: true,
    lookbehind: true,
    inside: {
      'punctuation': /^`|`$/
    }
  },
  'function': /\b(?:AVG|COUNT|FIRST|FORMAT|LAST|LCASE|LEN|MAX|MID|MIN|MOD|NOW|ROUND|SUM|UCASE)(?=\s*\()/i,
  // Should we highlight user defined functions too?
  'keyword': /\b(?:ACTION|ADD|AFTER|ALGORITHM|ALL|ALTER|ANALYZE|ANY|APPLY|AS|ASC|AUTHORIZATION|AUTO_INCREMENT|BACKUP|BDB|BEGIN|BERKELEYDB|BIGINT|BINARY|BIT|BLOB|BOOL|BOOLEAN|BREAK|BROWSE|BTREE|BULK|BY|CALL|CASCADED?|CASE|CHAIN|CHAR(?:ACTER|SET)?|CHECK(?:POINT)?|CLOSE|CLUSTERED|COALESCE|COLLATE|COLUMNS?|COMMENT|COMMIT(?:TED)?|COMPUTE|CONNECT|CONSISTENT|CONSTRAINT|CONTAINS(?:TABLE)?|CONTINUE|CONVERT|CREATE|CROSS|CURRENT(?:_DATE|_TIME|_TIMESTAMP|_USER)?|CURSOR|CYCLE|DATA(?:BASES?)?|DATE(?:TIME)?|DAY|DBCC|DEALLOCATE|DEC|DECIMAL|DECLARE|DEFAULT|DEFINER|DELAYED|DELETE|DELIMITERS?|DENY|DESC|DESCRIBE|DETERMINISTIC|DISABLE|DISCARD|DISK|DISTINCT|DISTINCTROW|DISTRIBUTED|DO|DOUBLE|DROP|DUMMY|DUMP(?:FILE)?|DUPLICATE|ELSE(?:IF)?|ENABLE|ENCLOSED|END|ENGINE|ENUM|ERRLVL|ERRORS|ESCAPED?|EXCEPT|EXEC(?:UTE)?|EXISTS|EXIT|EXPLAIN|EXTENDED|FETCH|FIELDS|FILE|FILLFACTOR|FIRST|FIXED|FLOAT|FOLLOWING|FOR(?: EACH ROW)?|FORCE|FOREIGN|FREETEXT(?:TABLE)?|FROM|FULL|FUNCTION|GEOMETRY(?:COLLECTION)?|GLOBAL|GOTO|GRANT|GROUP|HANDLER|HASH|HAVING|HOLDLOCK|HOUR|IDENTITY(?:COL|_INSERT)?|IF|IGNORE|IMPORT|INDEX|INFILE|INNER|INNODB|INOUT|INSERT|INT|INTEGER|INTERSECT|INTERVAL|INTO|INVOKER|ISOLATION|ITERATE|JOIN|KEYS?|KILL|LANGUAGE|LAST|LEAVE|LEFT|LEVEL|LIMIT|LINENO|LINES|LINESTRING|LOAD|LOCAL|LOCK|LONG(?:BLOB|TEXT)|LOOP|MATCH(?:ED)?|MEDIUM(?:BLOB|INT|TEXT)|MERGE|MIDDLEINT|MINUTE|MODE|MODIFIES|MODIFY|MONTH|MULTI(?:LINESTRING|POINT|POLYGON)|NATIONAL|NATURAL|NCHAR|NEXT|NO|NONCLUSTERED|NULLIF|NUMERIC|OFF?|OFFSETS?|ON|OPEN(?:DATASOURCE|QUERY|ROWSET)?|OPTIMIZE|OPTION(?:ALLY)?|ORDER|OUT(?:ER|FILE)?|OVER|PARTIAL|PARTITION|PERCENT|PIVOT|PLAN|POINT|POLYGON|PRECEDING|PRECISION|PREPARE|PREV|PRIMARY|PRINT|PRIVILEGES|PROC(?:EDURE)?|PUBLIC|PURGE|QUICK|RAISERROR|READS?|REAL|RECONFIGURE|REFERENCES|RELEASE|RENAME|REPEAT(?:ABLE)?|REPLACE|REPLICATION|REQUIRE|RESIGNAL|RESTORE|RESTRICT|RETURN(?:ING|S)?|REVOKE|RIGHT|ROLLBACK|ROUTINE|ROW(?:COUNT|GUIDCOL|S)?|RTREE|RULE|SAVE(?:POINT)?|SCHEMA|SECOND|SELECT|SERIAL(?:IZABLE)?|SESSION(?:_USER)?|SET(?:USER)?|SHARE|SHOW|SHUTDOWN|SIMPLE|SMALLINT|SNAPSHOT|SOME|SONAME|SQL|START(?:ING)?|STATISTICS|STATUS|STRIPED|SYSTEM_USER|TABLES?|TABLESPACE|TEMP(?:ORARY|TABLE)?|TERMINATED|TEXT(?:SIZE)?|THEN|TIME(?:STAMP)?|TINY(?:BLOB|INT|TEXT)|TOP?|TRAN(?:SACTIONS?)?|TRIGGER|TRUNCATE|TSEQUAL|TYPES?|UNBOUNDED|UNCOMMITTED|UNDEFINED|UNION|UNIQUE|UNLOCK|UNPIVOT|UNSIGNED|UPDATE(?:TEXT)?|USAGE|USE|USER|USING|VALUES?|VAR(?:BINARY|CHAR|CHARACTER|YING)|VIEW|WAITFOR|WARNINGS|WHEN|WHERE|WHILE|WITH(?: ROLLUP|IN)?|WORK|WRITE(?:TEXT)?|YEAR)\b/i,
  'boolean': /\b(?:FALSE|NULL|TRUE)\b/i,
  'number': /\b0x[\da-f]+\b|\b\d+(?:\.\d*)?|\B\.\d+\b/i,
  'operator': /[-+*\/=%^~]|&&?|\|\|?|!=?|<(?:=>?|<|>)?|>[>=]?|\b(?:AND|BETWEEN|DIV|ILIKE|IN|IS|LIKE|NOT|OR|REGEXP|RLIKE|SOUNDS LIKE|XOR)\b/i,
  'punctuation': /[;[\]()`,.]/
};

Prism.languages['visual-basic'] = {
  'comment': {
    pattern: /(?:['‘’]|REM\b)(?:[^\r\n_]|_(?:\r\n?|\n)?)*/i,
    inside: {
      'keyword': /^REM/i
    }
  },
  'directive': {
    pattern: /#(?:Const|Else|ElseIf|End|ExternalChecksum|ExternalSource|If|Region)(?:\b_[ \t]*(?:\r\n?|\n)|.)+/i,
    alias: 'property',
    greedy: true
  },
  'string': {
    pattern: /\$?["“”](?:["“”]{2}|[^"“”])*["“”]C?/i,
    greedy: true
  },
  'date': {
    pattern: /#[ \t]*(?:\d+([/-])\d+\1\d+(?:[ \t]+(?:\d+[ \t]*(?:AM|PM)|\d+:\d+(?::\d+)?(?:[ \t]*(?:AM|PM))?))?|\d+[ \t]*(?:AM|PM)|\d+:\d+(?::\d+)?(?:[ \t]*(?:AM|PM))?)[ \t]*#/i,
    alias: 'number'
  },
  'number': /(?:(?:\b\d+(?:\.\d+)?|\.\d+)(?:E[+-]?\d+)?|&[HO][\dA-F]+)(?:[FRD]|U?[ILS])?/i,
  'boolean': /\b(?:False|Nothing|True)\b/i,
  'keyword': /\b(?:AddHandler|AddressOf|Alias|And(?:Also)?|As|Boolean|ByRef|Byte|ByVal|Call|Case|Catch|C(?:Bool|Byte|Char|Date|Dbl|Dec|Int|Lng|Obj|SByte|Short|Sng|Str|Type|UInt|ULng|UShort)|Char|Class|Const|Continue|Currency|Date|Decimal|Declare|Default|Delegate|Dim|DirectCast|Do|Double|Each|Else(?:If)?|End(?:If)?|Enum|Erase|Error|Event|Exit|Finally|For|Friend|Function|Get(?:Type|XMLNamespace)?|Global|GoSub|GoTo|Handles|If|Implements|Imports|In|Inherits|Integer|Interface|Is|IsNot|Let|Lib|Like|Long|Loop|Me|Mod|Module|Must(?:Inherit|Override)|My(?:Base|Class)|Namespace|Narrowing|New|Next|Not(?:Inheritable|Overridable)?|Object|Of|On|Operator|Option(?:al)?|Or(?:Else)?|Out|Overloads|Overridable|Overrides|ParamArray|Partial|Private|Property|Protected|Public|RaiseEvent|ReadOnly|ReDim|RemoveHandler|Resume|Return|SByte|Select|Set|Shadows|Shared|short|Single|Static|Step|Stop|String|Structure|Sub|SyncLock|Then|Throw|To|Try|TryCast|Type|TypeOf|U(?:Integer|Long|Short)|Until|Using|Variant|Wend|When|While|Widening|With(?:Events)?|WriteOnly|Xor)\b/i,
  'operator': /[+\-*/\\^<=>&#@$%!]|\b_(?=[ \t]*[\r\n])/,
  'punctuation': /[{}().,:?]/
};
Prism.languages.vb = Prism.languages['visual-basic'];
Prism.languages.vba = Prism.languages['visual-basic'];

(function (Prism) {
  /**
   * If the given language is present, it will insert the given doc comment grammar token into it.
   *
   * @param {string} lang
   * @param {any} docComment
   */
  function insertDocComment(lang, docComment) {
    if (Prism.languages[lang]) {
      Prism.languages.insertBefore(lang, 'comment', {
        'doc-comment': docComment
      });
    }
  }
  var tag = Prism.languages.markup.tag;
  var slashDocComment = {
    pattern: /\/\/\/.*/,
    greedy: true,
    alias: 'comment',
    inside: {
      'tag': tag
    }
  };
  var tickDocComment = {
    pattern: /'''.*/,
    greedy: true,
    alias: 'comment',
    inside: {
      'tag': tag
    }
  };
  insertDocComment('csharp', slashDocComment);
  insertDocComment('fsharp', slashDocComment);
  insertDocComment('vbnet', tickDocComment);
})(Prism);

(function (Prism) {
  // https://yaml.org/spec/1.2/spec.html#c-ns-anchor-property
  // https://yaml.org/spec/1.2/spec.html#c-ns-alias-node
  var anchorOrAlias = /[*&][^\s[\]{},]+/;
  // https://yaml.org/spec/1.2/spec.html#c-ns-tag-property
  var tag = /!(?:<[\w\-%#;/?:@&=+$,.!~*'()[\]]+>|(?:[a-zA-Z\d-]*!)?[\w\-%#;/?:@&=+$.~*'()]+)?/;
  // https://yaml.org/spec/1.2/spec.html#c-ns-properties(n,c)
  var properties = '(?:' + tag.source + '(?:[ \t]+' + anchorOrAlias.source + ')?|' + anchorOrAlias.source + '(?:[ \t]+' + tag.source + ')?)';
  // https://yaml.org/spec/1.2/spec.html#ns-plain(n,c)
  // This is a simplified version that doesn't support "#" and multiline keys
  // All these long scarry character classes are simplified versions of YAML's characters
  var plainKey = /(?:[^\s\x00-\x08\x0e-\x1f!"#%&'*,\-:>?@[\]`{|}\x7f-\x84\x86-\x9f\ud800-\udfff\ufffe\uffff]|[?:-]<PLAIN>)(?:[ \t]*(?:(?![#:])<PLAIN>|:<PLAIN>))*/.source.replace(/<PLAIN>/g, function () {
    return /[^\s\x00-\x08\x0e-\x1f,[\]{}\x7f-\x84\x86-\x9f\ud800-\udfff\ufffe\uffff]/.source;
  });
  var string = /"(?:[^"\\\r\n]|\\.)*"|'(?:[^'\\\r\n]|\\.)*'/.source;

  /**
   *
   * @param {string} value
   * @param {string} [flags]
   * @returns {RegExp}
   */
  function createValuePattern(value, flags) {
    flags = (flags || '').replace(/m/g, '') + 'm'; // add m flag
    var pattern = /([:\-,[{]\s*(?:\s<<prop>>[ \t]+)?)(?:<<value>>)(?=[ \t]*(?:$|,|\]|\}|(?:[\r\n]\s*)?#))/.source.replace(/<<prop>>/g, function () {
      return properties;
    }).replace(/<<value>>/g, function () {
      return value;
    });
    return RegExp(pattern, flags);
  }
  Prism.languages.yaml = {
    'scalar': {
      pattern: RegExp(/([\-:]\s*(?:\s<<prop>>[ \t]+)?[|>])[ \t]*(?:((?:\r?\n|\r)[ \t]+)\S[^\r\n]*(?:\2[^\r\n]+)*)/.source.replace(/<<prop>>/g, function () {
        return properties;
      })),
      lookbehind: true,
      alias: 'string'
    },
    'comment': /#.*/,
    'key': {
      pattern: RegExp(/((?:^|[:\-,[{\r\n?])[ \t]*(?:<<prop>>[ \t]+)?)<<key>>(?=\s*:\s)/.source.replace(/<<prop>>/g, function () {
        return properties;
      }).replace(/<<key>>/g, function () {
        return '(?:' + plainKey + '|' + string + ')';
      })),
      lookbehind: true,
      greedy: true,
      alias: 'atrule'
    },
    'directive': {
      pattern: /(^[ \t]*)%.+/m,
      lookbehind: true,
      alias: 'important'
    },
    'datetime': {
      pattern: createValuePattern(/\d{4}-\d\d?-\d\d?(?:[tT]|[ \t]+)\d\d?:\d{2}:\d{2}(?:\.\d*)?(?:[ \t]*(?:Z|[-+]\d\d?(?::\d{2})?))?|\d{4}-\d{2}-\d{2}|\d\d?:\d{2}(?::\d{2}(?:\.\d*)?)?/.source),
      lookbehind: true,
      alias: 'number'
    },
    'boolean': {
      pattern: createValuePattern(/false|true/.source, 'i'),
      lookbehind: true,
      alias: 'important'
    },
    'null': {
      pattern: createValuePattern(/null|~/.source, 'i'),
      lookbehind: true,
      alias: 'important'
    },
    'string': {
      pattern: createValuePattern(string),
      lookbehind: true,
      greedy: true
    },
    'number': {
      pattern: createValuePattern(/[+-]?(?:0x[\da-f]+|0o[0-7]+|(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?|\.inf|\.nan)/.source, 'i'),
      lookbehind: true
    },
    'tag': tag,
    'important': anchorOrAlias,
    'punctuation': /---|[:[\]{}\-,|>?]|\.\.\./
  };
  Prism.languages.yml = Prism.languages.yaml;
})(Prism);

(function () {
  if (typeof Prism === 'undefined' || typeof document === 'undefined') {
    return;
  }

  /**
   * Plugin name which is used as a class name for <pre> which is activating the plugin
   *
   * @type {string}
   */
  var PLUGIN_NAME = 'line-numbers';

  /**
   * Regular expression used for determining line breaks
   *
   * @type {RegExp}
   */
  var NEW_LINE_EXP = /\n(?!$)/g;

  /**
   * Global exports
   */
  var config = Prism.plugins.lineNumbers = {
    /**
     * Get node for provided line number
     *
     * @param {Element} element pre element
     * @param {number} number line number
     * @returns {Element|undefined}
     */
    getLine: function (element, number) {
      if (element.tagName !== 'PRE' || !element.classList.contains(PLUGIN_NAME)) {
        return;
      }
      var lineNumberRows = element.querySelector('.line-numbers-rows');
      if (!lineNumberRows) {
        return;
      }
      var lineNumberStart = parseInt(element.getAttribute('data-start'), 10) || 1;
      var lineNumberEnd = lineNumberStart + (lineNumberRows.children.length - 1);
      if (number < lineNumberStart) {
        number = lineNumberStart;
      }
      if (number > lineNumberEnd) {
        number = lineNumberEnd;
      }
      var lineIndex = number - lineNumberStart;
      return lineNumberRows.children[lineIndex];
    },
    /**
     * Resizes the line numbers of the given element.
     *
     * This function will not add line numbers. It will only resize existing ones.
     *
     * @param {HTMLElement} element A `<pre>` element with line numbers.
     * @returns {void}
     */
    resize: function (element) {
      resizeElements([element]);
    },
    /**
     * Whether the plugin can assume that the units font sizes and margins are not depended on the size of
     * the current viewport.
     *
     * Setting this to `true` will allow the plugin to do certain optimizations for better performance.
     *
     * Set this to `false` if you use any of the following CSS units: `vh`, `vw`, `vmin`, `vmax`.
     *
     * @type {boolean}
     */
    assumeViewportIndependence: true
  };

  /**
   * Resizes the given elements.
   *
   * @param {HTMLElement[]} elements
   */
  function resizeElements(elements) {
    elements = elements.filter(function (e) {
      var codeStyles = getStyles(e);
      var whiteSpace = codeStyles['white-space'];
      return whiteSpace === 'pre-wrap' || whiteSpace === 'pre-line';
    });
    if (elements.length == 0) {
      return;
    }
    var infos = elements.map(function (element) {
      var codeElement = element.querySelector('code');
      var lineNumbersWrapper = element.querySelector('.line-numbers-rows');
      if (!codeElement || !lineNumbersWrapper) {
        return undefined;
      }

      /** @type {HTMLElement} */
      var lineNumberSizer = element.querySelector('.line-numbers-sizer');
      var codeLines = codeElement.textContent.split(NEW_LINE_EXP);
      if (!lineNumberSizer) {
        lineNumberSizer = document.createElement('span');
        lineNumberSizer.className = 'line-numbers-sizer';
        codeElement.appendChild(lineNumberSizer);
      }
      lineNumberSizer.innerHTML = '0';
      lineNumberSizer.style.display = 'block';
      var oneLinerHeight = lineNumberSizer.getBoundingClientRect().height;
      lineNumberSizer.innerHTML = '';
      return {
        element: element,
        lines: codeLines,
        lineHeights: [],
        oneLinerHeight: oneLinerHeight,
        sizer: lineNumberSizer
      };
    }).filter(Boolean);
    infos.forEach(function (info) {
      var lineNumberSizer = info.sizer;
      var lines = info.lines;
      var lineHeights = info.lineHeights;
      var oneLinerHeight = info.oneLinerHeight;
      lineHeights[lines.length - 1] = undefined;
      lines.forEach(function (line, index) {
        if (line && line.length > 1) {
          var e = lineNumberSizer.appendChild(document.createElement('span'));
          e.style.display = 'block';
          e.textContent = line;
        } else {
          lineHeights[index] = oneLinerHeight;
        }
      });
    });
    infos.forEach(function (info) {
      var lineNumberSizer = info.sizer;
      var lineHeights = info.lineHeights;
      var childIndex = 0;
      for (var i = 0; i < lineHeights.length; i++) {
        if (lineHeights[i] === undefined) {
          lineHeights[i] = lineNumberSizer.children[childIndex++].getBoundingClientRect().height;
        }
      }
    });
    infos.forEach(function (info) {
      var lineNumberSizer = info.sizer;
      var wrapper = info.element.querySelector('.line-numbers-rows');
      lineNumberSizer.style.display = 'none';
      lineNumberSizer.innerHTML = '';
      info.lineHeights.forEach(function (height, lineNumber) {
        wrapper.children[lineNumber].style.height = height + 'px';
      });
    });
  }

  /**
   * Returns style declarations for the element
   *
   * @param {Element} element
   */
  function getStyles(element) {
    if (!element) {
      return null;
    }
    return window.getComputedStyle ? getComputedStyle(element) : element.currentStyle || null;
  }
  var lastWidth = undefined;
  window.addEventListener('resize', function () {
    if (config.assumeViewportIndependence && lastWidth === window.innerWidth) {
      return;
    }
    lastWidth = window.innerWidth;
    resizeElements(Array.prototype.slice.call(document.querySelectorAll('pre.' + PLUGIN_NAME)));
  });
  Prism.hooks.add('complete', function (env) {
    if (!env.code) {
      return;
    }
    var code = /** @type {Element} */env.element;
    var pre = /** @type {HTMLElement} */code.parentNode;

    // works only for <code> wrapped inside <pre> (not inline)
    if (!pre || !/pre/i.test(pre.nodeName)) {
      return;
    }

    // Abort if line numbers already exists
    if (code.querySelector('.line-numbers-rows')) {
      return;
    }

    // only add line numbers if <code> or one of its ancestors has the `line-numbers` class
    if (!Prism.util.isActive(code, PLUGIN_NAME)) {
      return;
    }

    // Remove the class 'line-numbers' from the <code>
    code.classList.remove(PLUGIN_NAME);
    // Add the class 'line-numbers' to the <pre>
    pre.classList.add(PLUGIN_NAME);
    var match = env.code.match(NEW_LINE_EXP);
    var linesNum = match ? match.length + 1 : 1;
    var lineNumbersWrapper;
    var lines = new Array(linesNum + 1).join('<span></span>');
    lineNumbersWrapper = document.createElement('span');
    lineNumbersWrapper.setAttribute('aria-hidden', 'true');
    lineNumbersWrapper.className = 'line-numbers-rows';
    lineNumbersWrapper.innerHTML = lines;
    if (pre.hasAttribute('data-start')) {
      pre.style.counterReset = 'linenumber ' + (parseInt(pre.getAttribute('data-start'), 10) - 1);
    }
    env.element.appendChild(lineNumbersWrapper);
    resizeElements([pre]);
    Prism.hooks.run('line-numbers', env);
  });
  Prism.hooks.add('line-numbers', function (env) {
    env.plugins = env.plugins || {};
    env.plugins.lineNumbers = true;
  });
})();

(function () {
  if (typeof Prism === 'undefined' || typeof document === 'undefined') {
    return;
  }
  var callbacks = [];
  var map = {};
  var noop = function () {};
  Prism.plugins.toolbar = {};

  /**
   * @typedef ButtonOptions
   * @property {string} text The text displayed.
   * @property {string} [url] The URL of the link which will be created.
   * @property {Function} [onClick] The event listener for the `click` event of the created button.
   * @property {string} [className] The class attribute to include with element.
   */

  /**
   * Register a button callback with the toolbar.
   *
   * @param {string} key
   * @param {ButtonOptions|Function} opts
   */
  var registerButton = Prism.plugins.toolbar.registerButton = function (key, opts) {
    var callback;
    if (typeof opts === 'function') {
      callback = opts;
    } else {
      callback = function (env) {
        var element;
        if (typeof opts.onClick === 'function') {
          element = document.createElement('button');
          element.type = 'button';
          element.addEventListener('click', function () {
            opts.onClick.call(this, env);
          });
        } else if (typeof opts.url === 'string') {
          element = document.createElement('a');
          element.href = opts.url;
        } else {
          element = document.createElement('span');
        }
        if (opts.className) {
          element.classList.add(opts.className);
        }
        element.textContent = opts.text;
        return element;
      };
    }
    if (key in map) {
      console.warn('There is a button with the key "' + key + '" registered already.');
      return;
    }
    callbacks.push(map[key] = callback);
  };

  /**
   * Returns the callback order of the given element.
   *
   * @param {HTMLElement} element
   * @returns {string[] | undefined}
   */
  function getOrder(element) {
    while (element) {
      var order = element.getAttribute('data-toolbar-order');
      if (order != null) {
        order = order.trim();
        if (order.length) {
          return order.split(/\s*,\s*/g);
        } else {
          return [];
        }
      }
      element = element.parentElement;
    }
  }

  /**
   * Post-highlight Prism hook callback.
   *
   * @param env
   */
  var hook = Prism.plugins.toolbar.hook = function (env) {
    // Check if inline or actual code block (credit to line-numbers plugin)
    var pre = env.element.parentNode;
    if (!pre || !/pre/i.test(pre.nodeName)) {
      return;
    }

    // Autoloader rehighlights, so only do this once.
    if (pre.parentNode.classList.contains('code-toolbar')) {
      return;
    }

    // Create wrapper for <pre> to prevent scrolling toolbar with content
    var wrapper = document.createElement('div');
    wrapper.classList.add('code-toolbar');
    pre.parentNode.insertBefore(wrapper, pre);
    wrapper.appendChild(pre);

    // Setup the toolbar
    var toolbar = document.createElement('div');
    toolbar.classList.add('toolbar');

    // order callbacks
    var elementCallbacks = callbacks;
    var order = getOrder(env.element);
    if (order) {
      elementCallbacks = order.map(function (key) {
        return map[key] || noop;
      });
    }
    elementCallbacks.forEach(function (callback) {
      var element = callback(env);
      if (!element) {
        return;
      }
      var item = document.createElement('div');
      item.classList.add('toolbar-item');
      item.appendChild(element);
      toolbar.appendChild(item);
    });

    // Add our toolbar to the currently created wrapper of <pre> tag
    wrapper.appendChild(toolbar);
  };
  registerButton('label', function (env) {
    var pre = env.element.parentNode;
    if (!pre || !/pre/i.test(pre.nodeName)) {
      return;
    }
    if (!pre.hasAttribute('data-label')) {
      return;
    }
    var element;
    var template;
    var text = pre.getAttribute('data-label');
    try {
      // Any normal text will blow up this selector.
      template = document.querySelector('template#' + text);
    } catch (e) {/* noop */}
    if (template) {
      element = template.content;
    } else {
      if (pre.hasAttribute('data-url')) {
        element = document.createElement('a');
        element.href = pre.getAttribute('data-url');
      } else {
        element = document.createElement('span');
      }
      element.textContent = text;
    }
    return element;
  });

  /**
   * Register the toolbar with Prism.
   */
  Prism.hooks.add('complete', hook);
})();

(function () {
  if (typeof Prism === 'undefined' || typeof document === 'undefined') {
    return;
  }
  if (!Prism.plugins.toolbar) {
    console.warn('Show Languages plugin loaded before Toolbar plugin.');
    return;
  }

  /* eslint-disable */

  // The languages map is built automatically with gulp
  var Languages = /*languages_placeholder[*/{
    "none": "Plain text",
    "plain": "Plain text",
    "plaintext": "Plain text",
    "text": "Plain text",
    "txt": "Plain text",
    "html": "HTML",
    "xml": "XML",
    "svg": "SVG",
    "mathml": "MathML",
    "ssml": "SSML",
    "rss": "RSS",
    "css": "CSS",
    "clike": "C-like",
    "js": "JavaScript",
    "abap": "ABAP",
    "abnf": "ABNF",
    "al": "AL",
    "antlr4": "ANTLR4",
    "g4": "ANTLR4",
    "apacheconf": "Apache Configuration",
    "apl": "APL",
    "aql": "AQL",
    "ino": "Arduino",
    "arff": "ARFF",
    "armasm": "ARM Assembly",
    "arm-asm": "ARM Assembly",
    "art": "Arturo",
    "asciidoc": "AsciiDoc",
    "adoc": "AsciiDoc",
    "aspnet": "ASP.NET (C#)",
    "asm6502": "6502 Assembly",
    "asmatmel": "Atmel AVR Assembly",
    "autohotkey": "AutoHotkey",
    "autoit": "AutoIt",
    "avisynth": "AviSynth",
    "avs": "AviSynth",
    "avro-idl": "Avro IDL",
    "avdl": "Avro IDL",
    "awk": "AWK",
    "gawk": "GAWK",
    "sh": "Shell",
    "basic": "BASIC",
    "bbcode": "BBcode",
    "bbj": "BBj",
    "bnf": "BNF",
    "rbnf": "RBNF",
    "bqn": "BQN",
    "bsl": "BSL (1C:Enterprise)",
    "oscript": "OneScript",
    "csharp": "C#",
    "cs": "C#",
    "dotnet": "C#",
    "cpp": "C++",
    "cfscript": "CFScript",
    "cfc": "CFScript",
    "cil": "CIL",
    "cilkc": "Cilk/C",
    "cilk-c": "Cilk/C",
    "cilkcpp": "Cilk/C++",
    "cilk-cpp": "Cilk/C++",
    "cilk": "Cilk/C++",
    "cmake": "CMake",
    "cobol": "COBOL",
    "coffee": "CoffeeScript",
    "conc": "Concurnas",
    "csp": "Content-Security-Policy",
    "css-extras": "CSS Extras",
    "csv": "CSV",
    "cue": "CUE",
    "dataweave": "DataWeave",
    "dax": "DAX",
    "django": "Django/Jinja2",
    "jinja2": "Django/Jinja2",
    "dns-zone-file": "DNS zone file",
    "dns-zone": "DNS zone file",
    "dockerfile": "Docker",
    "dot": "DOT (Graphviz)",
    "gv": "DOT (Graphviz)",
    "ebnf": "EBNF",
    "editorconfig": "EditorConfig",
    "ejs": "EJS",
    "etlua": "Embedded Lua templating",
    "erb": "ERB",
    "excel-formula": "Excel Formula",
    "xlsx": "Excel Formula",
    "xls": "Excel Formula",
    "fsharp": "F#",
    "firestore-security-rules": "Firestore security rules",
    "ftl": "FreeMarker Template Language",
    "gml": "GameMaker Language",
    "gamemakerlanguage": "GameMaker Language",
    "gap": "GAP (CAS)",
    "gcode": "G-code",
    "gdscript": "GDScript",
    "gedcom": "GEDCOM",
    "gettext": "gettext",
    "po": "gettext",
    "glsl": "GLSL",
    "gn": "GN",
    "gni": "GN",
    "linker-script": "GNU Linker Script",
    "ld": "GNU Linker Script",
    "go-module": "Go module",
    "go-mod": "Go module",
    "graphql": "GraphQL",
    "hbs": "Handlebars",
    "hs": "Haskell",
    "hcl": "HCL",
    "hlsl": "HLSL",
    "http": "HTTP",
    "hpkp": "HTTP Public-Key-Pins",
    "hsts": "HTTP Strict-Transport-Security",
    "ichigojam": "IchigoJam",
    "icu-message-format": "ICU Message Format",
    "idr": "Idris",
    "ignore": ".ignore",
    "gitignore": ".gitignore",
    "hgignore": ".hgignore",
    "npmignore": ".npmignore",
    "inform7": "Inform 7",
    "javadoc": "JavaDoc",
    "javadoclike": "JavaDoc-like",
    "javastacktrace": "Java stack trace",
    "jq": "JQ",
    "jsdoc": "JSDoc",
    "js-extras": "JS Extras",
    "json": "JSON",
    "webmanifest": "Web App Manifest",
    "json5": "JSON5",
    "jsonp": "JSONP",
    "jsstacktrace": "JS stack trace",
    "js-templates": "JS Templates",
    "keepalived": "Keepalived Configure",
    "kts": "Kotlin Script",
    "kt": "Kotlin",
    "kumir": "KuMir (КуМир)",
    "kum": "KuMir (КуМир)",
    "latex": "LaTeX",
    "tex": "TeX",
    "context": "ConTeXt",
    "lilypond": "LilyPond",
    "ly": "LilyPond",
    "emacs": "Lisp",
    "elisp": "Lisp",
    "emacs-lisp": "Lisp",
    "llvm": "LLVM IR",
    "log": "Log file",
    "lolcode": "LOLCODE",
    "magma": "Magma (CAS)",
    "md": "Markdown",
    "markup-templating": "Markup templating",
    "matlab": "MATLAB",
    "maxscript": "MAXScript",
    "mel": "MEL",
    "metafont": "METAFONT",
    "mongodb": "MongoDB",
    "moon": "MoonScript",
    "n1ql": "N1QL",
    "n4js": "N4JS",
    "n4jsd": "N4JS",
    "nand2tetris-hdl": "Nand To Tetris HDL",
    "naniscript": "Naninovel Script",
    "nani": "Naninovel Script",
    "nasm": "NASM",
    "neon": "NEON",
    "nginx": "nginx",
    "nsis": "NSIS",
    "objectivec": "Objective-C",
    "objc": "Objective-C",
    "ocaml": "OCaml",
    "opencl": "OpenCL",
    "openqasm": "OpenQasm",
    "qasm": "OpenQasm",
    "parigp": "PARI/GP",
    "objectpascal": "Object Pascal",
    "psl": "PATROL Scripting Language",
    "pcaxis": "PC-Axis",
    "px": "PC-Axis",
    "peoplecode": "PeopleCode",
    "pcode": "PeopleCode",
    "php": "PHP",
    "phpdoc": "PHPDoc",
    "php-extras": "PHP Extras",
    "plant-uml": "PlantUML",
    "plantuml": "PlantUML",
    "plsql": "PL/SQL",
    "powerquery": "PowerQuery",
    "pq": "PowerQuery",
    "mscript": "PowerQuery",
    "powershell": "PowerShell",
    "promql": "PromQL",
    "properties": ".properties",
    "protobuf": "Protocol Buffers",
    "purebasic": "PureBasic",
    "pbfasm": "PureBasic",
    "purs": "PureScript",
    "py": "Python",
    "qsharp": "Q#",
    "qs": "Q#",
    "q": "Q (kdb+ database)",
    "qml": "QML",
    "rkt": "Racket",
    "cshtml": "Razor C#",
    "razor": "Razor C#",
    "jsx": "React JSX",
    "tsx": "React TSX",
    "renpy": "Ren'py",
    "rpy": "Ren'py",
    "res": "ReScript",
    "rest": "reST (reStructuredText)",
    "robotframework": "Robot Framework",
    "robot": "Robot Framework",
    "rb": "Ruby",
    "sas": "SAS",
    "sass": "Sass (Sass)",
    "scss": "Sass (SCSS)",
    "shell-session": "Shell session",
    "sh-session": "Shell session",
    "shellsession": "Shell session",
    "sml": "SML",
    "smlnj": "SML/NJ",
    "solidity": "Solidity (Ethereum)",
    "sol": "Solidity (Ethereum)",
    "solution-file": "Solution file",
    "sln": "Solution file",
    "soy": "Soy (Closure Template)",
    "sparql": "SPARQL",
    "rq": "SPARQL",
    "splunk-spl": "Splunk SPL",
    "sqf": "SQF: Status Quo Function (Arma 3)",
    "sql": "SQL",
    "stata": "Stata Ado",
    "iecst": "Structured Text (IEC 61131-3)",
    "supercollider": "SuperCollider",
    "sclang": "SuperCollider",
    "systemd": "Systemd configuration file",
    "t4-templating": "T4 templating",
    "t4-cs": "T4 Text Templates (C#)",
    "t4": "T4 Text Templates (C#)",
    "t4-vb": "T4 Text Templates (VB)",
    "tap": "TAP",
    "tt2": "Template Toolkit 2",
    "toml": "TOML",
    "trickle": "trickle",
    "troy": "troy",
    "trig": "TriG",
    "ts": "TypeScript",
    "tsconfig": "TSConfig",
    "uscript": "UnrealScript",
    "uc": "UnrealScript",
    "uorazor": "UO Razor Script",
    "uri": "URI",
    "url": "URL",
    "vbnet": "VB.Net",
    "vhdl": "VHDL",
    "vim": "vim",
    "visual-basic": "Visual Basic",
    "vba": "VBA",
    "vb": "Visual Basic",
    "wasm": "WebAssembly",
    "web-idl": "Web IDL",
    "webidl": "Web IDL",
    "wgsl": "WGSL",
    "wiki": "Wiki markup",
    "wolfram": "Wolfram language",
    "nb": "Mathematica Notebook",
    "wl": "Wolfram language",
    "xeoracube": "XeoraCube",
    "xml-doc": "XML doc (.net)",
    "xojo": "Xojo (REALbasic)",
    "xquery": "XQuery",
    "yaml": "YAML",
    "yml": "YAML",
    "yang": "YANG"
  } /*]*/;

  /* eslint-enable */

  Prism.plugins.toolbar.registerButton('show-language', function (env) {
    var pre = env.element.parentNode;
    if (!pre || !/pre/i.test(pre.nodeName)) {
      return;
    }

    /**
     * Tries to guess the name of a language given its id.
     *
     * @param {string} id The language id.
     * @returns {string}
     */
    function guessTitle(id) {
      if (!id) {
        return id;
      }
      return (id.substring(0, 1).toUpperCase() + id.substring(1)).replace(/s(?=cript)/, 'S');
    }
    var language = pre.getAttribute('data-language') || Languages[env.language] || guessTitle(env.language);
    if (!language) {
      return;
    }
    var element = document.createElement('span');
    element.textContent = language;
    return element;
  });
})();

(function () {
  if (typeof Prism === 'undefined' || typeof document === 'undefined') {
    return;
  }
  if (!Prism.plugins.toolbar) {
    console.warn('Copy to Clipboard plugin loaded before Toolbar plugin.');
    return;
  }

  /**
   * When the given elements is clicked by the user, the given text will be copied to clipboard.
   *
   * @param {HTMLElement} element
   * @param {CopyInfo} copyInfo
   *
   * @typedef CopyInfo
   * @property {() => string} getText
   * @property {() => void} success
   * @property {(reason: unknown) => void} error
   */
  function registerClipboard(element, copyInfo) {
    element.addEventListener('click', function () {
      copyTextToClipboard(copyInfo);
    });
  }

  // https://stackoverflow.com/a/30810322/7595472

  /** @param {CopyInfo} copyInfo */
  function fallbackCopyTextToClipboard(copyInfo) {
    var textArea = document.createElement('textarea');
    textArea.value = copyInfo.getText();

    // Avoid scrolling to bottom
    textArea.style.top = '0';
    textArea.style.left = '0';
    textArea.style.position = 'fixed';
    document.body.appendChild(textArea);
    textArea.focus();
    textArea.select();
    try {
      var successful = document.execCommand('copy');
      setTimeout(function () {
        if (successful) {
          copyInfo.success();
        } else {
          copyInfo.error();
        }
      }, 1);
    } catch (err) {
      setTimeout(function () {
        copyInfo.error(err);
      }, 1);
    }
    document.body.removeChild(textArea);
  }
  /** @param {CopyInfo} copyInfo */
  function copyTextToClipboard(copyInfo) {
    if (navigator.clipboard) {
      navigator.clipboard.writeText(copyInfo.getText()).then(copyInfo.success, function () {
        // try the fallback in case `writeText` didn't work
        fallbackCopyTextToClipboard(copyInfo);
      });
    } else {
      fallbackCopyTextToClipboard(copyInfo);
    }
  }

  /**
   * Selects the text content of the given element.
   *
   * @param {Element} element
   */
  function selectElementText(element) {
    // https://stackoverflow.com/a/20079910/7595472
    window.getSelection().selectAllChildren(element);
  }

  /**
   * Traverses up the DOM tree to find data attributes that override the default plugin settings.
   *
   * @param {Element} startElement An element to start from.
   * @returns {Settings} The plugin settings.
   * @typedef {Record<"copy" | "copy-error" | "copy-success" | "copy-timeout", string | number>} Settings
   */
  function getSettings(startElement) {
    /** @type {Settings} */
    var settings = {
      'copy': 'Copy',
      'copy-error': 'Press Ctrl+C to copy',
      'copy-success': 'Copied!',
      'copy-timeout': 5000
    };
    var prefix = 'data-prismjs-';
    for (var key in settings) {
      var attr = prefix + key;
      var element = startElement;
      while (element && !element.hasAttribute(attr)) {
        element = element.parentElement;
      }
      if (element) {
        settings[key] = element.getAttribute(attr);
      }
    }
    return settings;
  }
  Prism.plugins.toolbar.registerButton('copy-to-clipboard', function (env) {
    var element = env.element;
    var settings = getSettings(element);
    var linkCopy = document.createElement('button');
    linkCopy.className = 'copy-to-clipboard-button';
    linkCopy.setAttribute('type', 'button');
    var linkSpan = document.createElement('span');
    linkCopy.appendChild(linkSpan);
    setState('copy');
    registerClipboard(linkCopy, {
      getText: function () {
        return element.textContent;
      },
      success: function () {
        setState('copy-success');
        resetText();
      },
      error: function () {
        setState('copy-error');
        setTimeout(function () {
          selectElementText(element);
        }, 1);
        resetText();
      }
    });
    return linkCopy;
    function resetText() {
      setTimeout(function () {
        setState('copy');
      }, settings['copy-timeout']);
    }

    /** @param {"copy" | "copy-error" | "copy-success"} state */
    function setState(state) {
      linkSpan.textContent = settings[state];
      linkCopy.setAttribute('data-copy-state', state);
    }
  });
})();

function _extends$1() {
  return _extends$1 = Object.assign ? Object.assign.bind() : function (n) {
    for (var e = 1; e < arguments.length; e++) {
      var t = arguments[e];
      for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
    }
    return n;
  }, _extends$1.apply(null, arguments);
}

function _extends() {
  return _extends = Object.assign ? Object.assign.bind() : function (a) {
    for (var b, c = 1; c < arguments.length; c++) for (var d in b = arguments[c], b) Object.prototype.hasOwnProperty.call(b, d) && (a[d] = b[d]);
    return a;
  }, _extends.apply(this, arguments);
}
var normalMerge = ["attrs", "props", "domProps"],
  toArrayMerge = ["class", "style", "directives"],
  functionalMerge = ["on", "nativeOn"],
  mergeJsxProps = function (a) {
    return a.reduce(function (c, a) {
      for (var b in a) if (!c[b]) c[b] = a[b];else if (-1 !== normalMerge.indexOf(b)) c[b] = _extends({}, c[b], a[b]);else if (-1 !== toArrayMerge.indexOf(b)) {
        var d = c[b] instanceof Array ? c[b] : [c[b]],
          e = a[b] instanceof Array ? a[b] : [a[b]];
        c[b] = [].concat(d, e);
      } else if (-1 !== functionalMerge.indexOf(b)) {
        for (var f in a[b]) if (c[b][f]) {
          var g = c[b][f] instanceof Array ? c[b][f] : [c[b][f]],
            h = a[b][f] instanceof Array ? a[b][f] : [a[b][f]];
          c[b][f] = [].concat(g, h);
        } else c[b][f] = a[b][f];
      } else if ("hook" === b) for (var i in a[b]) c[b][i] = c[b][i] ? mergeFn(c[b][i], a[b][i]) : a[b][i];else c[b] = a[b];
      return c;
    }, {});
  },
  mergeFn = function (a, b) {
    return function () {
      a && a.apply(this, arguments), b && b.apply(this, arguments);
    };
  };
var helper = mergeJsxProps;

var _mergeJSXProps = helper;

/**
 * bem helper
 * b() // 'button'
 * b('text') // 'button__text'
 * b({ disabled }) // 'button button--disabled'
 * b('text', { disabled }) // 'button__text button__text--disabled'
 * b(['disabled', 'primary']) // 'button button--disabled button--primary'
 */
function gen(name, mods) {
  if (!mods) {
    return '';
  }
  if (typeof mods === 'string') {
    return " " + name + "--" + mods;
  }
  if (Array.isArray(mods)) {
    return mods.reduce(function (ret, item) {
      return ret + gen(name, item);
    }, '');
  }
  return Object.keys(mods).reduce(function (ret, key) {
    return ret + (mods[key] ? gen(name, key) : '');
  }, '');
}
function createBEM(name) {
  return function (el, mods) {
    if (el && typeof el !== 'string') {
      mods = el;
      el = '';
    }
    el = el ? name + "__" + el : name;
    return "" + el + gen(el, mods);
  };
}

var hasOwnProperty$1 = Object.prototype.hasOwnProperty;
function assignKey(to, from, key) {
  var val = from[key];
  if (!isDef(val)) {
    return;
  }
  if (!hasOwnProperty$1.call(to, key) || !isObject(val)) {
    to[key] = val;
  } else {
    // eslint-disable-next-line @typescript-eslint/no-use-before-define
    to[key] = deepAssign(Object(to[key]), from[key]);
  }
}
function deepAssign(to, from) {
  Object.keys(from).forEach(function (key) {
    assignKey(to, from, key);
  });
  return to;
}

var defaultMessages = {
  name: '姓名',
  tel: '电话',
  save: '保存',
  confirm: '确认',
  cancel: '取消',
  delete: '删除',
  complete: '完成',
  loading: '加载中...',
  telEmpty: '请填写电话',
  nameEmpty: '请填写姓名',
  nameInvalid: '请输入正确的姓名',
  confirmDelete: '确定要删除吗',
  telInvalid: '请输入正确的手机号',
  vanCalendar: {
    end: '结束',
    start: '开始',
    title: '日期选择',
    confirm: '确定',
    startEnd: '开始/结束',
    weekdays: ['日', '一', '二', '三', '四', '五', '六'],
    monthTitle: function monthTitle(year, month) {
      return year + "\u5E74" + month + "\u6708";
    },
    rangePrompt: function rangePrompt(maxRange) {
      return "\u9009\u62E9\u5929\u6570\u4E0D\u80FD\u8D85\u8FC7 " + maxRange + " \u5929";
    }
  },
  vanCascader: {
    select: '请选择'
  },
  vanContactCard: {
    addText: '添加联系人'
  },
  vanContactList: {
    addText: '新建联系人'
  },
  vanPagination: {
    prev: '上一页',
    next: '下一页'
  },
  vanPullRefresh: {
    pulling: '下拉即可刷新...',
    loosing: '释放即可刷新...'
  },
  vanSubmitBar: {
    label: '合计：'
  },
  vanCoupon: {
    unlimited: '无使用门槛',
    discount: function discount(_discount) {
      return _discount + "\u6298";
    },
    condition: function condition(_condition) {
      return "\u6EE1" + _condition + "\u5143\u53EF\u7528";
    }
  },
  vanCouponCell: {
    title: '优惠券',
    tips: '暂无可用',
    count: function count(_count) {
      return _count + "\u5F20\u53EF\u7528";
    }
  },
  vanCouponList: {
    empty: '暂无优惠券',
    exchange: '兑换',
    close: '不使用优惠券',
    enable: '可用',
    disabled: '不可用',
    placeholder: '请输入优惠码'
  },
  vanAddressEdit: {
    area: '地区',
    postal: '邮政编码',
    areaEmpty: '请选择地区',
    addressEmpty: '请填写详细地址',
    postalEmpty: '邮政编码格式不正确',
    defaultAddress: '设为默认收货地址',
    telPlaceholder: '收货人手机号',
    namePlaceholder: '收货人姓名',
    areaPlaceholder: '选择省 / 市 / 区'
  },
  vanAddressEditDetail: {
    label: '详细地址',
    placeholder: '街道门牌、楼层房间号等信息'
  },
  vanAddressList: {
    add: '新增地址'
  }
};

var proto = Vue.prototype;
var defineReactive = Vue.util.defineReactive;
defineReactive(proto, '$vantLang', 'zh-CN');
defineReactive(proto, '$vantMessages', {
  'zh-CN': defaultMessages
});
var Locale = {
  messages: function messages() {
    return proto.$vantMessages[proto.$vantLang];
  },
  use: function use(lang, messages) {
    var _this$add;
    proto.$vantLang = lang;
    this.add((_this$add = {}, _this$add[lang] = messages, _this$add));
  },
  add: function add(messages) {
    if (messages === void 0) {
      messages = {};
    }
    deepAssign(proto.$vantMessages, messages);
  }
};

var camelizeRE = /-(\w)/g;
function camelize(str) {
  return str.replace(camelizeRE, function (_, c) {
    return c.toUpperCase();
  });
}
function padZero(num, targetLength) {
  if (targetLength === void 0) {
    targetLength = 2;
  }
  var str = num + '';
  while (str.length < targetLength) {
    str = '0' + str;
  }
  return str;
}

/**
 * Use scopedSlots in Vue 2.6+
 * downgrade to slots in lower version
 */
var SlotsMixin = {
  methods: {
    slots: function slots(name, props) {
      if (name === void 0) {
        name = 'default';
      }
      var $slots = this.$slots,
        $scopedSlots = this.$scopedSlots;
      var scopedSlot = $scopedSlots[name];
      if (scopedSlot) {
        return scopedSlot(props);
      }
      return $slots[name];
    }
  }
};

/**
 * Create a basic component with common options
 */
function install$1(Vue) {
  var name = this.name;
  Vue.component(name, this);
  Vue.component(camelize("-" + name), this);
} // unify slots & scopedSlots

function unifySlots(context) {
  // use data.scopedSlots in lower Vue version
  var scopedSlots = context.scopedSlots || context.data.scopedSlots || {};
  var slots = context.slots();
  Object.keys(slots).forEach(function (key) {
    if (!scopedSlots[key]) {
      scopedSlots[key] = function () {
        return slots[key];
      };
    }
  });
  return scopedSlots;
} // should be removed after Vue 3

function transformFunctionComponent(pure) {
  return {
    functional: true,
    props: pure.props,
    model: pure.model,
    render: function render(h, context) {
      return pure(h, context.props, unifySlots(context), context);
    }
  };
}
function createComponent$1H(name) {
  return function (sfc) {
    if (isFunction(sfc)) {
      sfc = transformFunctionComponent(sfc);
    }
    if (!sfc.functional) {
      sfc.mixins = sfc.mixins || [];
      sfc.mixins.push(SlotsMixin);
    }
    sfc.name = name;
    sfc.install = install$1;
    return sfc;
  };
}

function createI18N(name) {
  var prefix = camelize(name) + '.';
  return function (path) {
    var messages = Locale.messages();
    var message = get(messages, prefix + path) || get(messages, path);
    for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
      args[_key - 1] = arguments[_key];
    }
    return isFunction(message) ? message.apply(void 0, args) : message;
  };
}

function createNamespace(name) {
  name = 'van-' + name;
  return [createComponent$1H(name), createBEM(name), createI18N(name)];
}

function isNumeric(val) {
  return /^\d+(\.\d+)?$/.test(val);
}
function isNaN$1(val) {
  if (Number.isNaN) {
    return Number.isNaN(val);
  } // eslint-disable-next-line no-self-compare

  return val !== val;
}

function addUnit(value) {
  if (!isDef(value)) {
    return undefined;
  }
  value = String(value);
  return isNumeric(value) ? value + "px" : value;
} // cache

var rootFontSize;
function getRootFontSize() {
  if (!rootFontSize) {
    var doc = document.documentElement;
    var fontSize = doc.style.fontSize || window.getComputedStyle(doc).fontSize;
    rootFontSize = parseFloat(fontSize);
  }
  return rootFontSize;
}
function convertRem(value) {
  value = value.replace(/rem/g, '');
  return +value * getRootFontSize();
}
function convertVw(value) {
  value = value.replace(/vw/g, '');
  return +value * window.innerWidth / 100;
}
function convertVh(value) {
  value = value.replace(/vh/g, '');
  return +value * window.innerHeight / 100;
}
function unitToPx(value) {
  if (typeof value === 'number') {
    return value;
  }
  if (inBrowser) {
    if (value.indexOf('rem') !== -1) {
      return convertRem(value);
    }
    if (value.indexOf('vw') !== -1) {
      return convertVw(value);
    }
    if (value.indexOf('vh') !== -1) {
      return convertVh(value);
    }
  }
  return parseFloat(value);
}

var inBrowser = typeof window !== 'undefined';
var isServer = Vue.prototype.$isServer; // eslint-disable-next-line @typescript-eslint/no-empty-function

function noop() {}
function isDef(val) {
  return val !== undefined && val !== null;
}
function isFunction(val) {
  return typeof val === 'function';
}
function isObject(val) {
  return val !== null && typeof val === 'object';
}
function isPromise(val) {
  return isObject(val) && isFunction(val.then) && isFunction(val.catch);
}
function get(object, path) {
  var keys = path.split('.');
  var result = object;
  keys.forEach(function (key) {
    var _result$key;
    result = isObject(result) ? (_result$key = result[key]) != null ? _result$key : '' : '';
  });
  return result;
}
/**
 * Checks if `value` is an empty object, collection, map, or set.
 *
 * Objects are considered empty if they have no own enumerable string keyed
 * properties.
 *
 * Array-like values such as `arguments` objects, arrays, buffers, strings, or
 * jQuery-like collections are considered empty if they have a `length` of `0`.
 * Similarly, maps and sets are considered empty if they have a `size` of `0`.
 *
 * @function isEmpty
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is empty, else `false`.
 * @example
 *
 * _.isEmpty(null);
 * // => true
 *
 * _.isEmpty(true);
 * // => true
 *
 * _.isEmpty(1);
 * // => true
 *
 * _.isEmpty([1, 2, 3]);
 * // => false
 *
 * _.isEmpty({ 'a': 1 });
 * // => false
 */

function isEmpty(value) {
  if (value == null) {
    return true;
  }
  if (typeof value !== 'object') {
    return true;
  }
  return Object.keys(value).length === 0;
}

var inheritKey = ['ref', 'key', 'style', 'class', 'attrs', 'refInFor', 'nativeOn', 'directives', 'staticClass', 'staticStyle'];
var mapInheritKey = {
  nativeOn: 'on'
}; // inherit partial context, map nativeOn to on

function inherit(context, inheritListeners) {
  var result = inheritKey.reduce(function (obj, key) {
    if (context.data[key]) {
      obj[mapInheritKey[key] || key] = context.data[key];
    }
    return obj;
  }, {});
  if (inheritListeners) {
    result.on = result.on || {};
    _extends$1(result.on, context.data.on);
  }
  return result;
} // emit event

function emit(context, eventName) {
  for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
    args[_key - 2] = arguments[_key];
  }
  var listeners = context.listeners[eventName];
  if (listeners) {
    if (Array.isArray(listeners)) {
      listeners.forEach(function (listener) {
        listener.apply(void 0, args);
      });
    } else {
      listeners.apply(void 0, args);
    }
  }
} // mount functional component

function mount(Component, data) {
  var instance = new Vue({
    el: document.createElement('div'),
    props: Component.props,
    render: function render(h) {
      return h(Component, _extends$1({
        props: this.$props
      }, data));
    }
  });
  document.body.appendChild(instance.$el);
  return instance;
}

var context = {
  zIndex: 2000,
  lockCount: 0,
  stack: [],
  find: function find(vm) {
    return this.stack.filter(function (item) {
      return item.vm === vm;
    })[0];
  },
  remove: function remove(vm) {
    var item = this.find(vm);
    if (!item) return;
    item.vm = null;
    item.overlay = null;
    var index = this.stack.indexOf(item);
    this.stack.splice(index, 1);
  }
};

// eslint-disable-next-line import/no-mutable-exports
var supportsPassive = false;
if (!isServer) {
  try {
    var opts = {};
    Object.defineProperty(opts, 'passive', {
      // eslint-disable-next-line getter-return
      get: function get() {
        /* istanbul ignore next */
        supportsPassive = true;
      }
    });
    window.addEventListener('test-passive', null, opts); // eslint-disable-next-line no-empty
  } catch (e) {}
}
function on(target, event, handler, passive) {
  if (passive === void 0) {
    passive = false;
  }
  if (!isServer) {
    target.addEventListener(event, handler, supportsPassive ? {
      capture: false,
      passive: passive
    } : false);
  }
}
function off(target, event, handler) {
  if (!isServer) {
    target.removeEventListener(event, handler);
  }
}
function stopPropagation(event) {
  event.stopPropagation();
}
function preventDefault(event, isStopPropagation) {
  /* istanbul ignore else */
  if (typeof event.cancelable !== 'boolean' || event.cancelable) {
    event.preventDefault();
  }
  if (isStopPropagation) {
    stopPropagation(event);
  }
}

var _createNamespace$1C = createNamespace('overlay'),
  createComponent$1G = _createNamespace$1C[0],
  bem$1x = _createNamespace$1C[1];
function preventTouchMove(event) {
  preventDefault(event, true);
}
function Overlay(h, props, slots, ctx) {
  var style = _extends$1({
    zIndex: props.zIndex
  }, props.customStyle);
  if (isDef(props.duration)) {
    style.animationDuration = props.duration + "s";
  }
  return h("transition", {
    "attrs": {
      "name": "van-fade"
    }
  }, [h("div", _mergeJSXProps([{
    "directives": [{
      name: "show",
      value: props.show
    }],
    "style": style,
    "class": [bem$1x(), props.className],
    "on": {
      "touchmove": props.lockScroll ? preventTouchMove : noop
    }
  }, inherit(ctx, true)]), [slots.default == null ? void 0 : slots.default()])]);
}
Overlay.props = {
  show: Boolean,
  zIndex: [Number, String],
  duration: [Number, String],
  className: null,
  customStyle: Object,
  lockScroll: {
    type: Boolean,
    default: true
  }
};
var Overlay$1 = createComponent$1G(Overlay);

function removeNode(el) {
  var parent = el.parentNode;
  if (parent) {
    parent.removeChild(el);
  }
}

var defaultConfig$1 = {
  className: '',
  customStyle: {}
};
function mountOverlay(vm) {
  return mount(Overlay$1, {
    on: {
      // close popup when overlay clicked & closeOnClickOverlay is true
      click: function click() {
        vm.$emit('click-overlay');
        if (vm.closeOnClickOverlay) {
          if (vm.onClickOverlay) {
            vm.onClickOverlay();
          } else {
            vm.close();
          }
        }
      }
    }
  });
}
function updateOverlay(vm) {
  var item = context.find(vm);
  if (item) {
    var el = vm.$el;
    var config = item.config,
      overlay = item.overlay;
    if (el && el.parentNode) {
      el.parentNode.insertBefore(overlay.$el, el);
    }
    _extends$1(overlay, defaultConfig$1, config, {
      show: true
    });
  }
}
function openOverlay(vm, config) {
  var item = context.find(vm);
  if (item) {
    item.config = config;
  } else {
    var overlay = mountOverlay(vm);
    context.stack.push({
      vm: vm,
      config: config,
      overlay: overlay
    });
  }
  updateOverlay(vm);
}
function closeOverlay(vm) {
  var item = context.find(vm);
  if (item) {
    item.overlay.show = false;
  }
}
function removeOverlay(vm) {
  var item = context.find(vm);
  if (item) {
    removeNode(item.overlay.$el);
    context.remove(vm);
  }
}

function isWindow(val) {
  return val === window;
} // get nearest scroll element
// https://github.com/vant-ui/vant/issues/3823

var overflowScrollReg = /scroll|auto|overlay/i;
function getScroller(el, root) {
  if (root === void 0) {
    root = window;
  }
  var node = el;
  while (node && node.tagName !== 'HTML' && node.tagName !== 'BODY' && node.nodeType === 1 && node !== root) {
    var _window$getComputedSt = window.getComputedStyle(node),
      overflowY = _window$getComputedSt.overflowY;
    if (overflowScrollReg.test(overflowY)) {
      return node;
    }
    node = node.parentNode;
  }
  return root;
}
function getScrollTop(el) {
  var top = 'scrollTop' in el ? el.scrollTop : el.pageYOffset; // iOS scroll bounce cause minus scrollTop

  return Math.max(top, 0);
}
function setScrollTop(el, value) {
  if ('scrollTop' in el) {
    el.scrollTop = value;
  } else {
    el.scrollTo(el.scrollX, value);
  }
}
function getRootScrollTop() {
  return window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;
}
function setRootScrollTop(value) {
  setScrollTop(window, value);
  setScrollTop(document.body, value);
} // get distance from element top to page top or scroller top

function getElementTop(el, scroller) {
  if (isWindow(el)) {
    return 0;
  }
  var scrollTop = scroller ? getScrollTop(scroller) : getRootScrollTop();
  return el.getBoundingClientRect().top + scrollTop;
}
function getVisibleHeight(el) {
  if (isWindow(el)) {
    return el.innerHeight;
  }
  return el.getBoundingClientRect().height;
}
function getVisibleTop(el) {
  if (isWindow(el)) {
    return 0;
  }
  return el.getBoundingClientRect().top;
}

function getDirection(x, y) {
  if (x > y) {
    return 'horizontal';
  }
  if (y > x) {
    return 'vertical';
  }
  return '';
}
var TouchMixin = {
  data: function data() {
    return {
      direction: ''
    };
  },
  methods: {
    touchStart: function touchStart(event) {
      this.resetTouchStatus();
      this.startX = event.touches[0].clientX;
      this.startY = event.touches[0].clientY;
    },
    touchMove: function touchMove(event) {
      var touch = event.touches[0]; // safari back will set clientX to negative number

      this.deltaX = touch.clientX < 0 ? 0 : touch.clientX - this.startX;
      this.deltaY = touch.clientY - this.startY;
      this.offsetX = Math.abs(this.deltaX);
      this.offsetY = Math.abs(this.deltaY); // lock direction when distance is greater than a certain value

      var LOCK_DIRECTION_DISTANCE = 10;
      if (!this.direction || this.offsetX < LOCK_DIRECTION_DISTANCE && this.offsetY < LOCK_DIRECTION_DISTANCE) {
        this.direction = getDirection(this.offsetX, this.offsetY);
      }
    },
    resetTouchStatus: function resetTouchStatus() {
      this.direction = '';
      this.deltaX = 0;
      this.deltaY = 0;
      this.offsetX = 0;
      this.offsetY = 0;
    },
    // avoid Vue 2.6 event bubble issues by manually binding events
    // https://github.com/vant-ui/vant/issues/3015
    bindTouchEvent: function bindTouchEvent(el) {
      var onTouchStart = this.onTouchStart,
        onTouchMove = this.onTouchMove,
        onTouchEnd = this.onTouchEnd;
      on(el, 'touchstart', onTouchStart);
      on(el, 'touchmove', onTouchMove);
      if (onTouchEnd) {
        on(el, 'touchend', onTouchEnd);
        on(el, 'touchcancel', onTouchEnd);
      }
    }
  }
};

function getElement(selector) {
  if (typeof selector === 'string') {
    return document.querySelector(selector);
  }
  return selector();
}
function PortalMixin(_temp) {
  var _ref = _temp === void 0 ? {} : _temp,
    ref = _ref.ref,
    afterPortal = _ref.afterPortal;
  return {
    props: {
      getContainer: [String, Function]
    },
    watch: {
      getContainer: 'portal'
    },
    mounted: function mounted() {
      if (this.getContainer) {
        this.portal();
      }
    },
    methods: {
      portal: function portal() {
        var getContainer = this.getContainer;
        var el = ref ? this.$refs[ref] : this.$el;
        var container;
        if (getContainer) {
          container = getElement(getContainer);
        } else if (this.$parent) {
          container = this.$parent.$el;
        }
        if (container && container !== el.parentNode) {
          container.appendChild(el);
        }
        if (afterPortal) {
          afterPortal.call(this);
        }
      }
    }
  };
}

/**
 * Bind event when mounted or activated
 */
var uid$1 = 0;
function BindEventMixin(handler) {
  var key = "binded_" + uid$1++;
  function bind() {
    if (!this[key]) {
      handler.call(this, on, true);
      this[key] = true;
    }
  }
  function unbind() {
    if (this[key]) {
      handler.call(this, off, false);
      this[key] = false;
    }
  }
  return {
    mounted: bind,
    activated: bind,
    deactivated: unbind,
    beforeDestroy: unbind
  };
}

var CloseOnPopstateMixin = {
  mixins: [BindEventMixin(function (bind, isBind) {
    this.handlePopstate(isBind && this.closeOnPopstate);
  })],
  props: {
    closeOnPopstate: Boolean
  },
  data: function data() {
    return {
      bindStatus: false
    };
  },
  watch: {
    closeOnPopstate: function closeOnPopstate(val) {
      this.handlePopstate(val);
    }
  },
  methods: {
    onPopstate: function onPopstate() {
      this.close();
      this.shouldReopen = false;
    },
    handlePopstate: function handlePopstate(bind) {
      /* istanbul ignore if */
      if (this.$isServer) {
        return;
      }
      if (this.bindStatus !== bind) {
        this.bindStatus = bind;
        var action = bind ? on : off;
        action(window, 'popstate', this.onPopstate);
      }
    }
  }
};

// Context
var popupMixinProps = {
  // Initial rendering animation
  transitionAppear: Boolean,
  // whether to show popup
  value: Boolean,
  // whether to show overlay
  overlay: Boolean,
  // overlay custom style
  overlayStyle: Object,
  // overlay custom class name
  overlayClass: String,
  // whether to close popup when overlay is clicked
  closeOnClickOverlay: Boolean,
  // z-index
  zIndex: [Number, String],
  // prevent body scroll
  lockScroll: {
    type: Boolean,
    default: true
  },
  // whether to lazy render
  lazyRender: {
    type: Boolean,
    default: true
  }
};
function PopupMixin(options) {
  if (options === void 0) {
    options = {};
  }
  return {
    mixins: [TouchMixin, CloseOnPopstateMixin, PortalMixin({
      afterPortal: function afterPortal() {
        if (this.overlay) {
          updateOverlay();
        }
      }
    })],
    provide: function provide() {
      return {
        vanPopup: this
      };
    },
    props: popupMixinProps,
    data: function data() {
      this.onReopenCallback = [];
      return {
        inited: this.value
      };
    },
    computed: {
      shouldRender: function shouldRender() {
        return this.inited || !this.lazyRender;
      }
    },
    watch: {
      value: function value(val) {
        var type = val ? 'open' : 'close';
        this.inited = this.inited || this.value;
        this[type]();
        if (!options.skipToggleEvent) {
          this.$emit(type);
        }
      },
      overlay: 'renderOverlay'
    },
    mounted: function mounted() {
      if (this.value) {
        this.open();
      }
    },
    /* istanbul ignore next */
    activated: function activated() {
      if (this.shouldReopen) {
        this.$emit('input', true);
        this.shouldReopen = false;
      }
    },
    beforeDestroy: function beforeDestroy() {
      removeOverlay(this);
      if (this.opened) {
        this.removeLock();
      }
      if (this.getContainer) {
        removeNode(this.$el);
      }
    },
    /* istanbul ignore next */
    deactivated: function deactivated() {
      if (this.value) {
        this.close();
        this.shouldReopen = true;
      }
    },
    methods: {
      open: function open() {
        /* istanbul ignore next */
        if (this.$isServer || this.opened) {
          return;
        } // cover default zIndex

        if (this.zIndex !== undefined) {
          context.zIndex = this.zIndex;
        }
        this.opened = true;
        this.renderOverlay();
        this.addLock();
        this.onReopenCallback.forEach(function (callback) {
          callback();
        });
      },
      addLock: function addLock() {
        if (this.lockScroll) {
          on(document, 'touchstart', this.touchStart);
          on(document, 'touchmove', this.onTouchMove);
          if (!context.lockCount) {
            document.body.classList.add('van-overflow-hidden');
          }
          context.lockCount++;
        }
      },
      removeLock: function removeLock() {
        if (this.lockScroll && context.lockCount) {
          context.lockCount--;
          off(document, 'touchstart', this.touchStart);
          off(document, 'touchmove', this.onTouchMove);
          if (!context.lockCount) {
            document.body.classList.remove('van-overflow-hidden');
          }
        }
      },
      close: function close() {
        if (!this.opened) {
          return;
        }
        closeOverlay(this);
        this.opened = false;
        this.removeLock();
        this.$emit('input', false);
      },
      onTouchMove: function onTouchMove(event) {
        this.touchMove(event);
        var direction = this.deltaY > 0 ? '10' : '01';
        var el = getScroller(event.target, this.$el);
        var scrollHeight = el.scrollHeight,
          offsetHeight = el.offsetHeight,
          scrollTop = el.scrollTop;
        var status = '11';
        /* istanbul ignore next */

        if (scrollTop === 0) {
          status = offsetHeight >= scrollHeight ? '00' : '01';
        } else if (scrollTop + offsetHeight >= scrollHeight) {
          status = '10';
        }
        /* istanbul ignore next */

        if (status !== '11' && this.direction === 'vertical' && !(parseInt(status, 2) & parseInt(direction, 2))) {
          preventDefault(event, true);
        }
      },
      renderOverlay: function renderOverlay() {
        var _this = this;
        if (this.$isServer || !this.value) {
          return;
        }
        this.$nextTick(function () {
          _this.updateZIndex(_this.overlay ? 1 : 0);
          if (_this.overlay) {
            openOverlay(_this, {
              zIndex: context.zIndex++,
              duration: _this.duration,
              className: _this.overlayClass,
              customStyle: _this.overlayStyle
            });
          } else {
            closeOverlay(_this);
          }
        });
      },
      updateZIndex: function updateZIndex(value) {
        if (value === void 0) {
          value = 0;
        }
        this.$el.style.zIndex = ++context.zIndex + value;
      },
      onReopen: function onReopen(callback) {
        this.onReopenCallback.push(callback);
      }
    }
  };
}

var _createNamespace$1B = createNamespace('info'),
  createComponent$1F = _createNamespace$1B[0],
  bem$1w = _createNamespace$1B[1];
function Info(h, props, slots, ctx) {
  var dot = props.dot,
    info = props.info;
  var showInfo = isDef(info) && info !== '';
  if (!dot && !showInfo) {
    return;
  }
  return h("div", _mergeJSXProps([{
    "class": bem$1w({
      dot: dot
    })
  }, inherit(ctx, true)]), [dot ? '' : props.info]);
}
Info.props = {
  dot: Boolean,
  info: [Number, String]
};
var Info$1 = createComponent$1F(Info);

var _createNamespace$1A = createNamespace('icon'),
  createComponent$1E = _createNamespace$1A[0],
  bem$1v = _createNamespace$1A[1];
function isImage(name) {
  return name ? name.indexOf('/') !== -1 : false;
} // compatible with legacy usage, should be removed in next major version

var LEGACY_MAP = {
  medel: 'medal',
  'medel-o': 'medal-o',
  'calender-o': 'calendar-o'
};
function correctName(name) {
  return name && LEGACY_MAP[name] || name;
}
function Icon(h, props, slots, ctx) {
  var _props$badge;
  var name = correctName(props.name);
  var imageIcon = isImage(name);
  return h(props.tag, _mergeJSXProps([{
    "class": [props.classPrefix, imageIcon ? '' : props.classPrefix + "-" + name],
    "style": {
      color: props.color,
      fontSize: addUnit(props.size)
    }
  }, inherit(ctx, true)]), [slots.default && slots.default(), imageIcon && h("img", {
    "class": bem$1v('image'),
    "attrs": {
      "src": name
    }
  }), h(Info$1, {
    "attrs": {
      "dot": props.dot,
      "info": (_props$badge = props.badge) != null ? _props$badge : props.info
    }
  })]);
}
Icon.props = {
  dot: Boolean,
  name: String,
  size: [Number, String],
  // @deprecated
  // should be removed in next major version
  info: [Number, String],
  badge: [Number, String],
  color: String,
  tag: {
    type: String,
    default: 'i'
  },
  classPrefix: {
    type: String,
    default: bem$1v()
  }
};
var Icon$1 = createComponent$1E(Icon);

var _createNamespace$1z = createNamespace('popup'),
  createComponent$1D = _createNamespace$1z[0],
  bem$1u = _createNamespace$1z[1];
var Popup = createComponent$1D({
  mixins: [PopupMixin()],
  props: {
    round: Boolean,
    duration: [Number, String],
    closeable: Boolean,
    transition: String,
    safeAreaInsetBottom: Boolean,
    closeIcon: {
      type: String,
      default: 'cross'
    },
    closeIconPosition: {
      type: String,
      default: 'top-right'
    },
    position: {
      type: String,
      default: 'center'
    },
    overlay: {
      type: Boolean,
      default: true
    },
    closeOnClickOverlay: {
      type: Boolean,
      default: true
    }
  },
  beforeCreate: function beforeCreate() {
    var _this = this;
    var createEmitter = function createEmitter(eventName) {
      return function (event) {
        return _this.$emit(eventName, event);
      };
    };
    this.onClick = createEmitter('click');
    this.onOpened = createEmitter('opened');
    this.onClosed = createEmitter('closed');
  },
  methods: {
    onClickCloseIcon: function onClickCloseIcon(event) {
      this.$emit('click-close-icon', event);
      this.close();
    }
  },
  render: function render() {
    var _bem;
    var h = arguments[0];
    if (!this.shouldRender) {
      return;
    }
    var round = this.round,
      position = this.position,
      duration = this.duration;
    var isCenter = position === 'center';
    var transitionName = this.transition || (isCenter ? 'van-fade' : "van-popup-slide-" + position);
    var style = {};
    if (isDef(duration)) {
      var key = isCenter ? 'animationDuration' : 'transitionDuration';
      style[key] = duration + "s";
    }
    return h("transition", {
      "attrs": {
        "appear": this.transitionAppear,
        "name": transitionName
      },
      "on": {
        "afterEnter": this.onOpened,
        "afterLeave": this.onClosed
      }
    }, [h("div", {
      "directives": [{
        name: "show",
        value: this.value
      }],
      "style": style,
      "class": bem$1u((_bem = {
        round: round
      }, _bem[position] = position, _bem['safe-area-inset-bottom'] = this.safeAreaInsetBottom, _bem)),
      "on": {
        "click": this.onClick
      }
    }, [this.slots(), this.closeable && h(Icon$1, {
      "attrs": {
        "role": "button",
        "tabindex": "0",
        "name": this.closeIcon
      },
      "class": bem$1u('close-icon', this.closeIconPosition),
      "on": {
        "click": this.onClickCloseIcon
      }
    })])]);
  }
});

var _createNamespace$1y = createNamespace('loading'),
  createComponent$1C = _createNamespace$1y[0],
  bem$1t = _createNamespace$1y[1];
function LoadingIcon(h, props) {
  if (props.type === 'spinner') {
    var Spin = [];
    for (var i = 0; i < 12; i++) {
      Spin.push(h("i"));
    }
    return Spin;
  }
  return h("svg", {
    "class": bem$1t('circular'),
    "attrs": {
      "viewBox": "25 25 50 50"
    }
  }, [h("circle", {
    "attrs": {
      "cx": "50",
      "cy": "50",
      "r": "20",
      "fill": "none"
    }
  })]);
}
function LoadingText(h, props, slots) {
  if (slots.default) {
    var _props$textColor;
    var style = {
      fontSize: addUnit(props.textSize),
      color: (_props$textColor = props.textColor) != null ? _props$textColor : props.color
    };
    return h("span", {
      "class": bem$1t('text'),
      "style": style
    }, [slots.default()]);
  }
}
function Loading(h, props, slots, ctx) {
  var color = props.color,
    size = props.size,
    type = props.type;
  var style = {
    color: color
  };
  if (size) {
    var iconSize = addUnit(size);
    style.width = iconSize;
    style.height = iconSize;
  }
  return h("div", _mergeJSXProps([{
    "class": bem$1t([type, {
      vertical: props.vertical
    }])
  }, inherit(ctx, true)]), [h("span", {
    "class": bem$1t('spinner', type),
    "style": style
  }, [LoadingIcon(h, props)]), LoadingText(h, props, slots)]);
}
Loading.props = {
  color: String,
  size: [Number, String],
  vertical: Boolean,
  textSize: [Number, String],
  textColor: String,
  type: {
    type: String,
    default: 'circular'
  }
};
var Loading$1 = createComponent$1C(Loading);

var _createNamespace$1x = createNamespace('action-sheet'),
  createComponent$1B = _createNamespace$1x[0],
  bem$1s = _createNamespace$1x[1];
function ActionSheet(h, props, slots, ctx) {
  var title = props.title,
    cancelText = props.cancelText,
    closeable = props.closeable;
  function onCancel() {
    emit(ctx, 'input', false);
    emit(ctx, 'cancel');
  }
  function Header() {
    if (title) {
      return h("div", {
        "class": bem$1s('header')
      }, [title, closeable && h(Icon$1, {
        "attrs": {
          "name": props.closeIcon
        },
        "class": bem$1s('close'),
        "on": {
          "click": onCancel
        }
      })]);
    }
  }
  function Option(item, index) {
    var disabled = item.disabled,
      loading = item.loading,
      callback = item.callback;
    function onClickOption(event) {
      event.stopPropagation();
      if (disabled || loading) {
        return;
      }
      if (callback) {
        callback(item);
      }
      if (props.closeOnClickAction) {
        emit(ctx, 'input', false);
      }
      Vue.nextTick(function () {
        emit(ctx, 'select', item, index);
      });
    }
    function OptionContent() {
      if (loading) {
        return h(Loading$1, {
          "class": bem$1s('loading-icon')
        });
      }
      return [h("span", {
        "class": bem$1s('name')
      }, [item.name]), item.subname && h("div", {
        "class": bem$1s('subname')
      }, [item.subname])];
    }
    return h("button", {
      "attrs": {
        "type": "button"
      },
      "class": [bem$1s('item', {
        disabled: disabled,
        loading: loading
      }), item.className],
      "style": {
        color: item.color
      },
      "on": {
        "click": onClickOption
      }
    }, [OptionContent()]);
  }
  function CancelText() {
    if (cancelText) {
      return [h("div", {
        "class": bem$1s('gap')
      }), h("button", {
        "attrs": {
          "type": "button"
        },
        "class": bem$1s('cancel'),
        "on": {
          "click": onCancel
        }
      }, [cancelText])];
    }
  }
  function Description() {
    var description = (slots.description == null ? void 0 : slots.description()) || props.description;
    if (description) {
      return h("div", {
        "class": bem$1s('description')
      }, [description]);
    }
  }
  return h(Popup, _mergeJSXProps([{
    "class": bem$1s(),
    "attrs": {
      "position": "bottom",
      "round": props.round,
      "value": props.value,
      "overlay": props.overlay,
      "duration": props.duration,
      "lazyRender": props.lazyRender,
      "lockScroll": props.lockScroll,
      "getContainer": props.getContainer,
      "closeOnPopstate": props.closeOnPopstate,
      "closeOnClickOverlay": props.closeOnClickOverlay,
      "safeAreaInsetBottom": props.safeAreaInsetBottom
    }
  }, inherit(ctx, true)]), [Header(), Description(), h("div", {
    "class": bem$1s('content')
  }, [props.actions && props.actions.map(Option), slots.default == null ? void 0 : slots.default()]), CancelText()]);
}
ActionSheet.props = _extends$1({}, popupMixinProps, {
  title: String,
  actions: Array,
  duration: [Number, String],
  cancelText: String,
  description: String,
  getContainer: [String, Function],
  closeOnPopstate: Boolean,
  closeOnClickAction: Boolean,
  round: {
    type: Boolean,
    default: true
  },
  closeable: {
    type: Boolean,
    default: true
  },
  closeIcon: {
    type: String,
    default: 'cross'
  },
  safeAreaInsetBottom: {
    type: Boolean,
    default: true
  },
  overlay: {
    type: Boolean,
    default: true
  },
  closeOnClickOverlay: {
    type: Boolean,
    default: true
  }
});
var ActionSheet$1 = createComponent$1B(ActionSheet);

function isMobile(value) {
  value = value.replace(/[^-|\d]/g, '');
  return /^((\+86)|(86))?(1)\d{10}$/.test(value) || /^0[0-9-]{10,13}$/.test(value);
}

var DEFAULT_ITEM_HEIGHT = 44;
var pickerProps = {
  title: String,
  loading: Boolean,
  readonly: Boolean,
  itemHeight: [Number, String],
  showToolbar: Boolean,
  cancelButtonText: String,
  confirmButtonText: String,
  allowHtml: {
    type: Boolean,
    default: true
  },
  visibleItemCount: {
    type: [Number, String],
    default: 6
  },
  swipeDuration: {
    type: [Number, String],
    default: 1000
  }
};

// color
var RED = '#ee0a24'; // border

var BORDER = 'van-hairline';
var BORDER_TOP = BORDER + "--top";
var BORDER_LEFT = BORDER + "--left";
var BORDER_BOTTOM = BORDER + "--bottom";
var BORDER_SURROUND = BORDER + "--surround";
var BORDER_TOP_BOTTOM = BORDER + "--top-bottom";
var BORDER_UNSET_TOP_BOTTOM = BORDER + "-unset--top-bottom";

function deepClone(obj) {
  if (!isDef(obj)) {
    return obj;
  }
  if (Array.isArray(obj)) {
    return obj.map(function (item) {
      return deepClone(item);
    });
  }
  if (typeof obj === 'object') {
    var to = {};
    Object.keys(obj).forEach(function (key) {
      to[key] = deepClone(obj[key]);
    });
    return to;
  }
  return obj;
}

function range(num, min, max) {
  return Math.min(Math.max(num, min), max);
}
function trimExtraChar(value, _char, regExp) {
  var index = value.indexOf(_char);
  var prefix = '';
  if (index === -1) {
    return value;
  }
  if (_char === '-' && index !== 0) {
    return value.slice(0, index);
  }
  if (_char === '.' && value.match(/^(\.|-\.)/)) {
    prefix = index ? '-0' : '0';
  }
  return prefix + value.slice(0, index + 1) + value.slice(index).replace(regExp, '');
}
function formatNumber(value, allowDot, allowMinus) {
  if (allowDot === void 0) {
    allowDot = true;
  }
  if (allowMinus === void 0) {
    allowMinus = true;
  }
  if (allowDot) {
    value = trimExtraChar(value, '.', /\./g);
  } else {
    value = value.split('.')[0];
  }
  if (allowMinus) {
    value = trimExtraChar(value, '-', /-/g);
  } else {
    value = value.replace(/-/, '');
  }
  var regExp = allowDot ? /[^-0-9.]/g : /[^-0-9]/g;
  return value.replace(regExp, '');
} // add num and avoid float number

function addNumber(num1, num2) {
  var cardinal = Math.pow(10, 10);
  return Math.round((num1 + num2) * cardinal) / cardinal;
}

var DEFAULT_DURATION = 200; // 惯性滑动思路:
// 在手指离开屏幕时，如果和上一次 move 时的间隔小于 `MOMENTUM_LIMIT_TIME` 且 move
// 距离大于 `MOMENTUM_LIMIT_DISTANCE` 时，执行惯性滑动

var MOMENTUM_LIMIT_TIME = 300;
var MOMENTUM_LIMIT_DISTANCE = 15;
var _createNamespace$1w = createNamespace('picker-column'),
  createComponent$1A = _createNamespace$1w[0],
  bem$1r = _createNamespace$1w[1];
function getElementTranslateY(element) {
  var style = window.getComputedStyle(element);
  var transform = style.transform || style.webkitTransform;
  var translateY = transform.slice(7, transform.length - 1).split(', ')[5];
  return Number(translateY);
}
function isOptionDisabled(option) {
  return isObject(option) && option.disabled;
} // use standard WheelEvent:
// https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent

var supportMousewheel = inBrowser && 'onwheel' in window;
var mousewheelTimer = null;
var PickerColumn = createComponent$1A({
  mixins: [TouchMixin],
  props: {
    valueKey: String,
    readonly: Boolean,
    allowHtml: Boolean,
    className: String,
    itemHeight: Number,
    defaultIndex: Number,
    swipeDuration: [Number, String],
    visibleItemCount: [Number, String],
    initialOptions: {
      type: Array,
      default: function _default() {
        return [];
      }
    }
  },
  data: function data() {
    return {
      offset: 0,
      duration: 0,
      options: deepClone(this.initialOptions),
      currentIndex: this.defaultIndex
    };
  },
  created: function created() {
    if (this.$parent.children) {
      this.$parent.children.push(this);
    }
    this.setIndex(this.currentIndex);
  },
  mounted: function mounted() {
    this.bindTouchEvent(this.$el);
    if (supportMousewheel) {
      on(this.$el, 'wheel', this.onMouseWheel, false);
    }
  },
  destroyed: function destroyed() {
    var children = this.$parent.children;
    if (children) {
      children.splice(children.indexOf(this), 1);
    }
    if (supportMousewheel) {
      off(this.$el, 'wheel');
    }
  },
  watch: {
    initialOptions: 'setOptions',
    defaultIndex: function defaultIndex(val) {
      this.setIndex(val);
    }
  },
  computed: {
    count: function count() {
      return this.options.length;
    },
    baseOffset: function baseOffset() {
      return this.itemHeight * (this.visibleItemCount - 1) / 2;
    }
  },
  methods: {
    setOptions: function setOptions(options) {
      if (JSON.stringify(options) !== JSON.stringify(this.options)) {
        this.options = deepClone(options);
        this.setIndex(this.defaultIndex);
      }
    },
    onTouchStart: function onTouchStart(event) {
      if (this.readonly) {
        return;
      }
      this.touchStart(event);
      if (this.moving) {
        var translateY = getElementTranslateY(this.$refs.wrapper);
        this.offset = Math.min(0, translateY - this.baseOffset);
        this.startOffset = this.offset;
      } else {
        this.startOffset = this.offset;
      }
      this.duration = 0;
      this.transitionEndTrigger = null;
      this.touchStartTime = Date.now();
      this.momentumOffset = this.startOffset;
    },
    onTouchMove: function onTouchMove(event) {
      if (this.readonly) {
        return;
      }
      this.touchMove(event);
      if (this.direction === 'vertical') {
        this.moving = true;
        preventDefault(event, true);
      }
      this.offset = range(this.startOffset + this.deltaY, -(this.count * this.itemHeight), this.itemHeight);
      var now = Date.now();
      if (now - this.touchStartTime > MOMENTUM_LIMIT_TIME) {
        this.touchStartTime = now;
        this.momentumOffset = this.offset;
      }
    },
    onTouchEnd: function onTouchEnd() {
      var _this = this;
      if (this.readonly) {
        return;
      }
      var distance = this.offset - this.momentumOffset;
      var duration = Date.now() - this.touchStartTime;
      var allowMomentum = duration < MOMENTUM_LIMIT_TIME && Math.abs(distance) > MOMENTUM_LIMIT_DISTANCE;
      if (allowMomentum) {
        this.momentum(distance, duration);
        return;
      }
      var index = this.getIndexByOffset(this.offset);
      this.duration = DEFAULT_DURATION;
      this.setIndex(index, true); // compatible with desktop scenario
      // use setTimeout to skip the click event Emitted after touchstart

      setTimeout(function () {
        _this.moving = false;
      }, 0);
    },
    onMouseWheel: function onMouseWheel(event) {
      var _this2 = this;
      if (this.readonly) {
        return;
      }
      preventDefault(event, true); // simply combine touchstart and touchmove

      var translateY = getElementTranslateY(this.$refs.wrapper);
      this.startOffset = Math.min(0, translateY - this.baseOffset);
      this.momentumOffset = this.startOffset;
      this.transitionEndTrigger = null; // directly use deltaY, see https://caniuse.com/?search=deltaY
      // use deltaY to detect direction for not special setting device
      // https://developer.mozilla.org/en-US/docs/Web/API/Element/wheel_event

      var deltaY = event.deltaY;
      if (this.startOffset === 0 && deltaY < 0) {
        return;
      } // Calculate the offset based on itemHeight

      var itemOffset = this.itemHeight * (deltaY > 0 ? -1 : 1);
      this.offset = range(this.startOffset + itemOffset, -(this.count * this.itemHeight), this.itemHeight);
      if (mousewheelTimer) {
        clearTimeout(mousewheelTimer);
      }
      mousewheelTimer = setTimeout(function () {
        _this2.onTouchEnd();
        _this2.touchStartTime = 0;
      }, MOMENTUM_LIMIT_TIME);
    },
    onTransitionEnd: function onTransitionEnd() {
      this.stopMomentum();
    },
    onClickItem: function onClickItem(index) {
      if (this.moving || this.readonly) {
        return;
      }
      this.transitionEndTrigger = null;
      this.duration = DEFAULT_DURATION;
      this.setIndex(index, true);
    },
    adjustIndex: function adjustIndex(index) {
      index = range(index, 0, this.count);
      for (var i = index; i < this.count; i++) {
        if (!isOptionDisabled(this.options[i])) return i;
      }
      for (var _i = index - 1; _i >= 0; _i--) {
        if (!isOptionDisabled(this.options[_i])) return _i;
      }
    },
    getOptionText: function getOptionText(option) {
      if (isObject(option) && this.valueKey in option) {
        return option[this.valueKey];
      }
      return option;
    },
    setIndex: function setIndex(index, emitChange) {
      var _this3 = this;
      index = this.adjustIndex(index) || 0;
      var offset = -index * this.itemHeight;
      var trigger = function trigger() {
        if (index !== _this3.currentIndex) {
          _this3.currentIndex = index;
          if (emitChange) {
            _this3.$emit('change', index);
          }
        }
      }; // trigger the change event after transitionend when moving

      if (this.moving && offset !== this.offset) {
        this.transitionEndTrigger = trigger;
      } else {
        trigger();
      }
      this.offset = offset;
    },
    setValue: function setValue(value) {
      var options = this.options;
      for (var i = 0; i < options.length; i++) {
        if (this.getOptionText(options[i]) === value) {
          return this.setIndex(i);
        }
      }
    },
    getValue: function getValue() {
      return this.options[this.currentIndex];
    },
    getIndexByOffset: function getIndexByOffset(offset) {
      return range(Math.round(-offset / this.itemHeight), 0, this.count - 1);
    },
    momentum: function momentum(distance, duration) {
      var speed = Math.abs(distance / duration);
      distance = this.offset + speed / 0.003 * (distance < 0 ? -1 : 1);
      var index = this.getIndexByOffset(distance);
      this.duration = +this.swipeDuration;
      this.setIndex(index, true);
    },
    stopMomentum: function stopMomentum() {
      this.moving = false;
      this.duration = 0;
      if (this.transitionEndTrigger) {
        this.transitionEndTrigger();
        this.transitionEndTrigger = null;
      }
    },
    genOptions: function genOptions() {
      var _this4 = this;
      var h = this.$createElement;
      var optionStyle = {
        height: this.itemHeight + "px"
      };
      return this.options.map(function (option, index) {
        var _domProps;
        var text = _this4.getOptionText(option);
        var disabled = isOptionDisabled(option);
        var data = {
          style: optionStyle,
          attrs: {
            role: 'button',
            tabindex: disabled ? -1 : 0
          },
          class: [bem$1r('item', {
            disabled: disabled,
            selected: index === _this4.currentIndex
          })],
          on: {
            click: function click() {
              _this4.onClickItem(index);
            }
          }
        };
        var childData = {
          class: 'van-ellipsis',
          domProps: (_domProps = {}, _domProps[_this4.allowHtml ? 'innerHTML' : 'textContent'] = text, _domProps)
        };
        return h("li", _mergeJSXProps([{}, data]), [_this4.slots('option', option) || h("div", _mergeJSXProps([{}, childData]))]);
      });
    }
  },
  render: function render() {
    var h = arguments[0];
    var wrapperStyle = {
      transform: "translate3d(0, " + (this.offset + this.baseOffset) + "px, 0)",
      transitionDuration: this.duration + "ms",
      transitionProperty: this.duration ? 'all' : 'none'
    };
    return h("div", {
      "class": [bem$1r(), this.className]
    }, [h("ul", {
      "ref": "wrapper",
      "style": wrapperStyle,
      "class": bem$1r('wrapper'),
      "on": {
        "transitionend": this.onTransitionEnd
      }
    }, [this.genOptions()])]);
  }
});

var _createNamespace$1v = createNamespace('picker'),
  createComponent$1z = _createNamespace$1v[0],
  bem$1q = _createNamespace$1v[1],
  t$q = _createNamespace$1v[2];
var Picker = createComponent$1z({
  props: _extends$1({}, pickerProps, {
    defaultIndex: {
      type: [Number, String],
      default: 0
    },
    columns: {
      type: Array,
      default: function _default() {
        return [];
      }
    },
    toolbarPosition: {
      type: String,
      default: 'top'
    },
    valueKey: {
      type: String,
      default: 'text'
    }
  }),
  data: function data() {
    return {
      children: [],
      formattedColumns: []
    };
  },
  computed: {
    itemPxHeight: function itemPxHeight() {
      return this.itemHeight ? unitToPx(this.itemHeight) : DEFAULT_ITEM_HEIGHT;
    },
    dataType: function dataType() {
      var columns = this.columns;
      var firstColumn = columns[0] || {};
      if (firstColumn.children) {
        return 'cascade';
      }
      if (firstColumn.values) {
        return 'object';
      }
      return 'text';
    }
  },
  watch: {
    columns: {
      handler: 'format',
      immediate: true
    }
  },
  methods: {
    format: function format() {
      var columns = this.columns,
        dataType = this.dataType;
      if (dataType === 'text') {
        this.formattedColumns = [{
          values: columns
        }];
      } else if (dataType === 'cascade') {
        this.formatCascade();
      } else {
        this.formattedColumns = columns;
      }
    },
    formatCascade: function formatCascade() {
      var formatted = [];
      var cursor = {
        children: this.columns
      };
      while (cursor && cursor.children) {
        var _cursor$defaultIndex;
        var _cursor = cursor,
          children = _cursor.children;
        var defaultIndex = (_cursor$defaultIndex = cursor.defaultIndex) != null ? _cursor$defaultIndex : +this.defaultIndex;
        while (children[defaultIndex] && children[defaultIndex].disabled) {
          if (defaultIndex < children.length - 1) {
            defaultIndex++;
          } else {
            defaultIndex = 0;
            break;
          }
        }
        formatted.push({
          values: cursor.children,
          className: cursor.className,
          defaultIndex: defaultIndex
        });
        cursor = children[defaultIndex];
      }
      this.formattedColumns = formatted;
    },
    emit: function emit(event) {
      var _this = this;
      if (this.dataType === 'text') {
        this.$emit(event, this.getColumnValue(0), this.getColumnIndex(0));
      } else {
        var values = this.getValues(); // compatible with old version of wrong parameters
        // should be removed in next major version
        // see: https://github.com/vant-ui/vant/issues/5905

        if (this.dataType === 'cascade') {
          values = values.map(function (item) {
            return item[_this.valueKey];
          });
        }
        this.$emit(event, values, this.getIndexes());
      }
    },
    onCascadeChange: function onCascadeChange(columnIndex) {
      var cursor = {
        children: this.columns
      };
      var indexes = this.getIndexes();
      for (var i = 0; i <= columnIndex; i++) {
        cursor = cursor.children[indexes[i]];
      }
      while (cursor && cursor.children) {
        columnIndex++;
        this.setColumnValues(columnIndex, cursor.children);
        cursor = cursor.children[cursor.defaultIndex || 0];
      }
    },
    onChange: function onChange(columnIndex) {
      var _this2 = this;
      if (this.dataType === 'cascade') {
        this.onCascadeChange(columnIndex);
      }
      if (this.dataType === 'text') {
        this.$emit('change', this, this.getColumnValue(0), this.getColumnIndex(0));
      } else {
        var values = this.getValues(); // compatible with old version of wrong parameters
        // should be removed in next major version
        // see: https://github.com/vant-ui/vant/issues/5905

        if (this.dataType === 'cascade') {
          values = values.map(function (item) {
            return item[_this2.valueKey];
          });
        }
        this.$emit('change', this, values, columnIndex);
      }
    },
    // get column instance by index
    getColumn: function getColumn(index) {
      return this.children[index];
    },
    // @exposed-api
    // get column value by index
    getColumnValue: function getColumnValue(index) {
      var column = this.getColumn(index);
      return column && column.getValue();
    },
    // @exposed-api
    // set column value by index
    setColumnValue: function setColumnValue(index, value) {
      var column = this.getColumn(index);
      if (column) {
        column.setValue(value);
        if (this.dataType === 'cascade') {
          this.onCascadeChange(index);
        }
      }
    },
    // @exposed-api
    // get column option index by column index
    getColumnIndex: function getColumnIndex(columnIndex) {
      return (this.getColumn(columnIndex) || {}).currentIndex;
    },
    // @exposed-api
    // set column option index by column index
    setColumnIndex: function setColumnIndex(columnIndex, optionIndex) {
      var column = this.getColumn(columnIndex);
      if (column) {
        column.setIndex(optionIndex);
        if (this.dataType === 'cascade') {
          this.onCascadeChange(columnIndex);
        }
      }
    },
    // @exposed-api
    // get options of column by index
    getColumnValues: function getColumnValues(index) {
      return (this.children[index] || {}).options;
    },
    // @exposed-api
    // set options of column by index
    setColumnValues: function setColumnValues(index, options) {
      var column = this.children[index];
      if (column) {
        column.setOptions(options);
      }
    },
    // @exposed-api
    // get values of all columns
    getValues: function getValues() {
      return this.children.map(function (child) {
        return child.getValue();
      });
    },
    // @exposed-api
    // set values of all columns
    setValues: function setValues(values) {
      var _this3 = this;
      values.forEach(function (value, index) {
        _this3.setColumnValue(index, value);
      });
    },
    // @exposed-api
    // get indexes of all columns
    getIndexes: function getIndexes() {
      return this.children.map(function (child) {
        return child.currentIndex;
      });
    },
    // @exposed-api
    // set indexes of all columns
    setIndexes: function setIndexes(indexes) {
      var _this4 = this;
      indexes.forEach(function (optionIndex, columnIndex) {
        _this4.setColumnIndex(columnIndex, optionIndex);
      });
    },
    // @exposed-api
    confirm: function confirm() {
      this.children.forEach(function (child) {
        return child.stopMomentum();
      });
      this.emit('confirm');
    },
    cancel: function cancel() {
      this.emit('cancel');
    },
    genTitle: function genTitle() {
      var h = this.$createElement;
      var titleSlot = this.slots('title');
      if (titleSlot) {
        return titleSlot;
      }
      if (this.title) {
        return h("div", {
          "class": ['van-ellipsis', bem$1q('title')]
        }, [this.title]);
      }
    },
    genCancel: function genCancel() {
      var h = this.$createElement;
      return h("button", {
        "attrs": {
          "type": "button"
        },
        "class": bem$1q('cancel'),
        "on": {
          "click": this.cancel
        }
      }, [this.slots('cancel') || this.cancelButtonText || t$q('cancel')]);
    },
    genConfirm: function genConfirm() {
      var h = this.$createElement;
      return h("button", {
        "attrs": {
          "type": "button"
        },
        "class": bem$1q('confirm'),
        "on": {
          "click": this.confirm
        }
      }, [this.slots('confirm') || this.confirmButtonText || t$q('confirm')]);
    },
    genToolbar: function genToolbar() {
      var h = this.$createElement;
      if (this.showToolbar) {
        return h("div", {
          "class": bem$1q('toolbar')
        }, [this.slots() || [this.genCancel(), this.genTitle(), this.genConfirm()]]);
      }
    },
    genColumns: function genColumns() {
      var h = this.$createElement;
      var itemPxHeight = this.itemPxHeight;
      var wrapHeight = itemPxHeight * this.visibleItemCount;
      var frameStyle = {
        height: itemPxHeight + "px"
      };
      var columnsStyle = {
        height: wrapHeight + "px"
      };
      var maskStyle = {
        backgroundSize: "100% " + (wrapHeight - itemPxHeight) / 2 + "px"
      };
      return h("div", {
        "class": bem$1q('columns'),
        "style": columnsStyle,
        "on": {
          "touchmove": preventDefault
        }
      }, [this.genColumnItems(), h("div", {
        "class": bem$1q('mask'),
        "style": maskStyle
      }), h("div", {
        "class": [BORDER_UNSET_TOP_BOTTOM, bem$1q('frame')],
        "style": frameStyle
      })]);
    },
    genColumnItems: function genColumnItems() {
      var _this5 = this;
      var h = this.$createElement;
      return this.formattedColumns.map(function (item, columnIndex) {
        var _item$defaultIndex;
        return h(PickerColumn, {
          "attrs": {
            "readonly": _this5.readonly,
            "valueKey": _this5.valueKey,
            "allowHtml": _this5.allowHtml,
            "className": item.className,
            "itemHeight": _this5.itemPxHeight,
            "defaultIndex": (_item$defaultIndex = item.defaultIndex) != null ? _item$defaultIndex : +_this5.defaultIndex,
            "swipeDuration": _this5.swipeDuration,
            "visibleItemCount": _this5.visibleItemCount,
            "initialOptions": item.values
          },
          "scopedSlots": {
            option: _this5.$scopedSlots.option
          },
          "on": {
            "change": function change() {
              _this5.onChange(columnIndex);
            }
          }
        });
      });
    }
  },
  render: function render(h) {
    return h("div", {
      "class": bem$1q()
    }, [this.toolbarPosition === 'top' ? this.genToolbar() : h(), this.loading ? h(Loading$1, {
      "class": bem$1q('loading')
    }) : h(), this.slots('columns-top'), this.genColumns(), this.slots('columns-bottom'), this.toolbarPosition === 'bottom' ? this.genToolbar() : h()]);
  }
});

var _createNamespace$1u = createNamespace('area'),
  createComponent$1y = _createNamespace$1u[0],
  bem$1p = _createNamespace$1u[1];
var PLACEHOLDER_CODE = '000000';
function isOverseaCode(code) {
  return code[0] === '9';
}
function pickSlots(instance, keys) {
  var $slots = instance.$slots,
    $scopedSlots = instance.$scopedSlots;
  var scopedSlots = {};
  keys.forEach(function (key) {
    if ($scopedSlots[key]) {
      scopedSlots[key] = $scopedSlots[key];
    } else if ($slots[key]) {
      scopedSlots[key] = function () {
        return $slots[key];
      };
    }
  });
  return scopedSlots;
}
var Area = createComponent$1y({
  props: _extends$1({}, pickerProps, {
    value: String,
    areaList: {
      type: Object,
      default: function _default() {
        return {};
      }
    },
    columnsNum: {
      type: [Number, String],
      default: 3
    },
    isOverseaCode: {
      type: Function,
      default: isOverseaCode
    },
    columnsPlaceholder: {
      type: Array,
      default: function _default() {
        return [];
      }
    }
  }),
  data: function data() {
    return {
      code: this.value,
      columns: [{
        values: []
      }, {
        values: []
      }, {
        values: []
      }]
    };
  },
  computed: {
    province: function province() {
      return this.areaList.province_list || {};
    },
    city: function city() {
      return this.areaList.city_list || {};
    },
    county: function county() {
      return this.areaList.county_list || {};
    },
    displayColumns: function displayColumns() {
      return this.columns.slice(0, +this.columnsNum);
    },
    placeholderMap: function placeholderMap() {
      return {
        province: this.columnsPlaceholder[0] || '',
        city: this.columnsPlaceholder[1] || '',
        county: this.columnsPlaceholder[2] || ''
      };
    }
  },
  watch: {
    value: function value(val) {
      this.code = val;
      this.setValues();
    },
    areaList: {
      deep: true,
      handler: 'setValues'
    },
    columnsNum: function columnsNum() {
      var _this = this;
      this.$nextTick(function () {
        _this.setValues();
      });
    }
  },
  mounted: function mounted() {
    this.setValues();
  },
  methods: {
    // get list by code
    getList: function getList(type, code) {
      var result = [];
      if (type !== 'province' && !code) {
        return result;
      }
      var list = this[type];
      result = Object.keys(list).map(function (listCode) {
        return {
          code: listCode,
          name: list[listCode]
        };
      });
      if (code) {
        // oversea code
        if (this.isOverseaCode(code) && type === 'city') {
          code = '9';
        }
        result = result.filter(function (item) {
          return item.code.indexOf(code) === 0;
        });
      }
      if (this.placeholderMap[type] && result.length) {
        // set columns placeholder
        var codeFill = '';
        if (type === 'city') {
          codeFill = PLACEHOLDER_CODE.slice(2, 4);
        } else if (type === 'county') {
          codeFill = PLACEHOLDER_CODE.slice(4, 6);
        }
        result.unshift({
          code: "" + code + codeFill,
          name: this.placeholderMap[type]
        });
      }
      return result;
    },
    // get index by code
    getIndex: function getIndex(type, code) {
      var compareNum = type === 'province' ? 2 : type === 'city' ? 4 : 6;
      var list = this.getList(type, code.slice(0, compareNum - 2)); // oversea code

      if (this.isOverseaCode(code) && type === 'province') {
        compareNum = 1;
      }
      code = code.slice(0, compareNum);
      for (var i = 0; i < list.length; i++) {
        if (list[i].code.slice(0, compareNum) === code) {
          return i;
        }
      }
      return 0;
    },
    // parse output columns data
    parseOutputValues: function parseOutputValues(values) {
      var _this2 = this;
      return values.map(function (value, index) {
        // save undefined value
        if (!value) return value;
        value = JSON.parse(JSON.stringify(value));
        if (!value.code || value.name === _this2.columnsPlaceholder[index]) {
          value.code = '';
          value.name = '';
        }
        return value;
      });
    },
    onChange: function onChange(picker, values, index) {
      this.code = values[index].code;
      this.setValues();
      var parsedValues = this.parseOutputValues(picker.getValues());
      this.$emit('change', picker, parsedValues, index);
    },
    onConfirm: function onConfirm(values, index) {
      values = this.parseOutputValues(values);
      this.setValues();
      this.$emit('confirm', values, index);
    },
    getDefaultCode: function getDefaultCode() {
      if (this.columnsPlaceholder.length) {
        return PLACEHOLDER_CODE;
      }
      var countyCodes = Object.keys(this.county);
      if (countyCodes[0]) {
        return countyCodes[0];
      }
      var cityCodes = Object.keys(this.city);
      if (cityCodes[0]) {
        return cityCodes[0];
      }
      return '';
    },
    setValues: function setValues() {
      var code = this.code;
      if (!code) {
        code = this.getDefaultCode();
      }
      var picker = this.$refs.picker;
      var province = this.getList('province');
      var city = this.getList('city', code.slice(0, 2));
      if (!picker) {
        return;
      }
      picker.setColumnValues(0, province);
      picker.setColumnValues(1, city);
      if (city.length && code.slice(2, 4) === '00' && !this.isOverseaCode(code)) {
        code = city[0].code;
      }
      picker.setColumnValues(2, this.getList('county', code.slice(0, 4)));
      picker.setIndexes([this.getIndex('province', code), this.getIndex('city', code), this.getIndex('county', code)]);
    },
    getValues: function getValues() {
      var picker = this.$refs.picker;
      var getValues = picker ? picker.getValues().filter(function (value) {
        return !!value;
      }) : [];
      getValues = this.parseOutputValues(getValues);
      return getValues;
    },
    getArea: function getArea() {
      var values = this.getValues();
      var area = {
        code: '',
        country: '',
        province: '',
        city: '',
        county: ''
      };
      if (!values.length) {
        return area;
      }
      var names = values.map(function (item) {
        return item.name;
      });
      var validValues = values.filter(function (value) {
        return !!value.code;
      });
      area.code = validValues.length ? validValues[validValues.length - 1].code : '';
      if (this.isOverseaCode(area.code)) {
        area.country = names[1] || '';
        area.province = names[2] || '';
      } else {
        area.province = names[0] || '';
        area.city = names[1] || '';
        area.county = names[2] || '';
      }
      return area;
    },
    // @exposed-api
    reset: function reset(code) {
      this.code = code || '';
      this.setValues();
    }
  },
  render: function render() {
    var h = arguments[0];
    var on = _extends$1({}, this.$listeners, {
      change: this.onChange,
      confirm: this.onConfirm
    });
    return h(Picker, {
      "ref": "picker",
      "class": bem$1p(),
      "attrs": {
        "showToolbar": true,
        "valueKey": "name",
        "title": this.title,
        "columns": this.displayColumns,
        "loading": this.loading,
        "readonly": this.readonly,
        "itemHeight": this.itemHeight,
        "swipeDuration": this.swipeDuration,
        "visibleItemCount": this.visibleItemCount,
        "cancelButtonText": this.cancelButtonText,
        "confirmButtonText": this.confirmButtonText
      },
      "scopedSlots": pickSlots(this, ['title', 'columns-top', 'columns-bottom']),
      "on": _extends$1({}, on)
    });
  }
});

/**
 * Vue Router support
 */
function isRedundantNavigation(err) {
  return err.name === 'NavigationDuplicated' ||
  // compatible with vue-router@3.3
  err.message && err.message.indexOf('redundant navigation') !== -1;
}
function route(router, config) {
  var to = config.to,
    url = config.url,
    replace = config.replace;
  if (to && router) {
    var promise = router[replace ? 'replace' : 'push'](to);
    /* istanbul ignore else */

    if (promise && promise.catch) {
      promise.catch(function (err) {
        if (err && !isRedundantNavigation(err)) {
          throw err;
        }
      });
    }
  } else if (url) {
    replace ? location.replace(url) : location.href = url;
  }
}
function functionalRoute(context) {
  route(context.parent && context.parent.$router, context.props);
}
var routeProps = {
  url: String,
  replace: Boolean,
  to: [String, Object]
};

var cellProps = {
  icon: String,
  size: String,
  center: Boolean,
  isLink: Boolean,
  required: Boolean,
  iconPrefix: String,
  titleStyle: null,
  titleClass: null,
  valueClass: null,
  labelClass: null,
  title: [Number, String],
  value: [Number, String],
  label: [Number, String],
  arrowDirection: String,
  border: {
    type: Boolean,
    default: true
  },
  clickable: {
    type: Boolean,
    default: null
  }
};

var _createNamespace$1t = createNamespace('cell'),
  createComponent$1x = _createNamespace$1t[0],
  bem$1o = _createNamespace$1t[1];
function Cell(h, props, slots, ctx) {
  var _props$clickable;
  var icon = props.icon,
    size = props.size,
    title = props.title,
    label = props.label,
    value = props.value,
    isLink = props.isLink;
  var showTitle = slots.title || isDef(title);
  function Label() {
    var showLabel = slots.label || isDef(label);
    if (showLabel) {
      return h("div", {
        "class": [bem$1o('label'), props.labelClass]
      }, [slots.label ? slots.label() : label]);
    }
  }
  function Title() {
    if (showTitle) {
      return h("div", {
        "class": [bem$1o('title'), props.titleClass],
        "style": props.titleStyle
      }, [slots.title ? slots.title() : h("span", [title]), Label()]);
    }
  }
  function Value() {
    var showValue = slots.default || isDef(value);
    if (showValue) {
      return h("div", {
        "class": [bem$1o('value', {
          alone: !showTitle
        }), props.valueClass]
      }, [slots.default ? slots.default() : h("span", [value])]);
    }
  }
  function LeftIcon() {
    if (slots.icon) {
      return slots.icon();
    }
    if (icon) {
      return h(Icon$1, {
        "class": bem$1o('left-icon'),
        "attrs": {
          "name": icon,
          "classPrefix": props.iconPrefix
        }
      });
    }
  }
  function RightIcon() {
    var rightIconSlot = slots['right-icon'];
    if (rightIconSlot) {
      return rightIconSlot();
    }
    if (isLink) {
      var arrowDirection = props.arrowDirection;
      return h(Icon$1, {
        "class": bem$1o('right-icon'),
        "attrs": {
          "name": arrowDirection ? "arrow-" + arrowDirection : 'arrow'
        }
      });
    }
  }
  function onClick(event) {
    emit(ctx, 'click', event);
    functionalRoute(ctx);
  }
  var clickable = (_props$clickable = props.clickable) != null ? _props$clickable : isLink;
  var classes = {
    clickable: clickable,
    center: props.center,
    required: props.required,
    borderless: !props.border
  };
  if (size) {
    classes[size] = size;
  }
  return h("div", _mergeJSXProps([{
    "class": bem$1o(classes),
    "attrs": {
      "role": clickable ? 'button' : null,
      "tabindex": clickable ? 0 : null
    },
    "on": {
      "click": onClick
    }
  }, inherit(ctx)]), [LeftIcon(), Title(), Value(), RightIcon(), slots.extra == null ? void 0 : slots.extra()]);
}
Cell.props = _extends$1({}, cellProps, routeProps);
var Cell$1 = createComponent$1x(Cell);

function isAndroid() {
  /* istanbul ignore next */
  return isServer ? false : /android/.test(navigator.userAgent.toLowerCase());
}
function isIOS$1() {
  /* istanbul ignore next */
  return isServer ? false : /ios|iphone|ipad|ipod/.test(navigator.userAgent.toLowerCase());
}

/**
 * Hack for iOS12 page scroll
 * https://developers.weixin.qq.com/community/develop/doc/00044ae90742f8c82fb78fcae56800
 */
var isIOS = isIOS$1();
/* istanbul ignore next */

function resetScroll() {
  if (isIOS) {
    setRootScrollTop(getRootScrollTop());
  }
}

var _createNamespace$1s = createNamespace('field'),
  createComponent$1w = _createNamespace$1s[0],
  bem$1n = _createNamespace$1s[1];
var Field = createComponent$1w({
  inheritAttrs: false,
  provide: function provide() {
    return {
      vanField: this
    };
  },
  inject: {
    vanForm: {
      default: null
    }
  },
  props: _extends$1({}, cellProps, {
    name: String,
    rules: Array,
    disabled: {
      type: Boolean,
      default: null
    },
    readonly: {
      type: Boolean,
      default: null
    },
    autosize: [Boolean, Object],
    leftIcon: String,
    rightIcon: String,
    clearable: Boolean,
    formatter: Function,
    maxlength: [Number, String],
    labelWidth: [Number, String],
    labelClass: null,
    labelAlign: String,
    inputAlign: String,
    placeholder: String,
    errorMessage: String,
    errorMessageAlign: String,
    showWordLimit: Boolean,
    value: {
      type: [Number, String],
      default: ''
    },
    type: {
      type: String,
      default: 'text'
    },
    error: {
      type: Boolean,
      default: null
    },
    colon: {
      type: Boolean,
      default: null
    },
    clearTrigger: {
      type: String,
      default: 'focus'
    },
    formatTrigger: {
      type: String,
      default: 'onChange'
    }
  }),
  data: function data() {
    return {
      focused: false,
      validateFailed: false,
      validateMessage: ''
    };
  },
  watch: {
    value: function value() {
      this.updateValue(this.value);
      this.resetValidation();
      this.validateWithTrigger('onChange');
      this.$nextTick(this.adjustSize);
    }
  },
  mounted: function mounted() {
    this.updateValue(this.value, this.formatTrigger);
    this.$nextTick(this.adjustSize);
    if (this.vanForm) {
      this.vanForm.addField(this);
    }
  },
  beforeDestroy: function beforeDestroy() {
    if (this.vanForm) {
      this.vanForm.removeField(this);
    }
  },
  computed: {
    showClear: function showClear() {
      var readonly = this.getProp('readonly');
      if (this.clearable && !readonly) {
        var hasValue = isDef(this.value) && this.value !== '';
        var trigger = this.clearTrigger === 'always' || this.clearTrigger === 'focus' && this.focused;
        return hasValue && trigger;
      }
    },
    showError: function showError() {
      if (this.error !== null) {
        return this.error;
      }
      if (this.vanForm && this.vanForm.showError && this.validateFailed) {
        return true;
      }
    },
    listeners: function listeners() {
      return _extends$1({}, this.$listeners, {
        blur: this.onBlur,
        focus: this.onFocus,
        input: this.onInput,
        click: this.onClickInput,
        keypress: this.onKeypress
      });
    },
    labelStyle: function labelStyle() {
      var labelWidth = this.getProp('labelWidth');
      if (labelWidth) {
        return {
          width: addUnit(labelWidth)
        };
      }
    },
    formValue: function formValue() {
      if (this.children && (this.$scopedSlots.input || this.$slots.input)) {
        return this.children.value;
      }
      return this.value;
    }
  },
  methods: {
    // @exposed-api
    focus: function focus() {
      if (this.$refs.input) {
        this.$refs.input.focus();
      }
    },
    // @exposed-api
    blur: function blur() {
      if (this.$refs.input) {
        this.$refs.input.blur();
      }
    },
    runValidator: function runValidator(value, rule) {
      return new Promise(function (resolve) {
        var returnVal = rule.validator(value, rule);
        if (isPromise(returnVal)) {
          return returnVal.then(resolve);
        }
        resolve(returnVal);
      });
    },
    isEmptyValue: function isEmptyValue(value) {
      if (Array.isArray(value)) {
        return !value.length;
      }
      if (value === 0) {
        return false;
      }
      return !value;
    },
    runSyncRule: function runSyncRule(value, rule) {
      if (rule.required && this.isEmptyValue(value)) {
        return false;
      }
      if (rule.pattern && !rule.pattern.test(value)) {
        return false;
      }
      return true;
    },
    getRuleMessage: function getRuleMessage(value, rule) {
      var message = rule.message;
      if (isFunction(message)) {
        return message(value, rule);
      }
      return message;
    },
    runRules: function runRules(rules) {
      var _this = this;
      return rules.reduce(function (promise, rule) {
        return promise.then(function () {
          if (_this.validateFailed) {
            return;
          }
          var value = _this.formValue;
          if (rule.formatter) {
            value = rule.formatter(value, rule);
          }
          if (!_this.runSyncRule(value, rule)) {
            _this.validateFailed = true;
            _this.validateMessage = _this.getRuleMessage(value, rule);
            return;
          }
          if (rule.validator) {
            return _this.runValidator(value, rule).then(function (result) {
              if (result === false) {
                _this.validateFailed = true;
                _this.validateMessage = _this.getRuleMessage(value, rule);
              }
            });
          }
        });
      }, Promise.resolve());
    },
    validate: function validate(rules) {
      var _this2 = this;
      if (rules === void 0) {
        rules = this.rules;
      }
      return new Promise(function (resolve) {
        if (!rules) {
          resolve();
        }
        _this2.resetValidation();
        _this2.runRules(rules).then(function () {
          if (_this2.validateFailed) {
            resolve({
              name: _this2.name,
              message: _this2.validateMessage
            });
          } else {
            resolve();
          }
        });
      });
    },
    validateWithTrigger: function validateWithTrigger(trigger) {
      if (this.vanForm && this.rules) {
        var defaultTrigger = this.vanForm.validateTrigger === trigger;
        var rules = this.rules.filter(function (rule) {
          if (rule.trigger) {
            return rule.trigger === trigger;
          }
          return defaultTrigger;
        });
        if (rules.length) {
          this.validate(rules);
        }
      }
    },
    resetValidation: function resetValidation() {
      if (this.validateFailed) {
        this.validateFailed = false;
        this.validateMessage = '';
      }
    },
    updateValue: function updateValue(value, trigger) {
      if (trigger === void 0) {
        trigger = 'onChange';
      }
      value = isDef(value) ? String(value) : ''; // native maxlength have incorrect line-break counting
      // see: https://github.com/vant-ui/vant/issues/5033

      var maxlength = this.maxlength;
      if (isDef(maxlength) && value.length > maxlength) {
        if (this.value && this.value.length === +maxlength) {
          value = this.value;
        } else {
          value = value.slice(0, maxlength);
        }
      }
      if (this.type === 'number' || this.type === 'digit') {
        var isNumber = this.type === 'number';
        value = formatNumber(value, isNumber, isNumber);
      }
      if (this.formatter && trigger === this.formatTrigger) {
        value = this.formatter(value);
      }
      var input = this.$refs.input;
      if (input && value !== input.value) {
        input.value = value;
      }
      if (value !== this.value) {
        this.$emit('input', value);
      }
    },
    onInput: function onInput(event) {
      // not update v-model when composing
      if (event.target.composing) {
        return;
      }
      this.updateValue(event.target.value);
    },
    onFocus: function onFocus(event) {
      this.focused = true;
      this.$emit('focus', event); // https://github.com/vant-ui/vant/issues/9715

      this.$nextTick(this.adjustSize); // readonly not work in legacy mobile safari

      /* istanbul ignore if */

      if (this.getProp('readonly')) {
        this.blur();
      }
    },
    onBlur: function onBlur(event) {
      if (this.getProp('readonly')) {
        return;
      }
      this.focused = false;
      this.updateValue(this.value, 'onBlur');
      this.$emit('blur', event);
      this.validateWithTrigger('onBlur');
      this.$nextTick(this.adjustSize);
      resetScroll();
    },
    onClick: function onClick(event) {
      this.$emit('click', event);
    },
    onClickInput: function onClickInput(event) {
      this.$emit('click-input', event);
    },
    onClickLeftIcon: function onClickLeftIcon(event) {
      this.$emit('click-left-icon', event);
    },
    onClickRightIcon: function onClickRightIcon(event) {
      this.$emit('click-right-icon', event);
    },
    onClear: function onClear(event) {
      preventDefault(event);
      this.$emit('input', '');
      this.$emit('clear', event);
    },
    onKeypress: function onKeypress(event) {
      var ENTER_CODE = 13;
      if (event.keyCode === ENTER_CODE) {
        var submitOnEnter = this.getProp('submitOnEnter');
        if (!submitOnEnter && this.type !== 'textarea') {
          preventDefault(event);
        } // trigger blur after click keyboard search button

        if (this.type === 'search') {
          this.blur();
        }
      }
      this.$emit('keypress', event);
    },
    adjustSize: function adjustSize() {
      var input = this.$refs.input;
      if (!(this.type === 'textarea' && this.autosize) || !input) {
        return;
      }
      var scrollTop = getRootScrollTop();
      input.style.height = 'auto';
      var height = input.scrollHeight;
      if (isObject(this.autosize)) {
        var _this$autosize = this.autosize,
          maxHeight = _this$autosize.maxHeight,
          minHeight = _this$autosize.minHeight;
        if (maxHeight) {
          height = Math.min(height, maxHeight);
        }
        if (minHeight) {
          height = Math.max(height, minHeight);
        }
      }
      if (height) {
        input.style.height = height + 'px'; // https://github.com/vant-ui/vant/issues/9178

        setRootScrollTop(scrollTop);
      }
    },
    genInput: function genInput() {
      var h = this.$createElement;
      var type = this.type;
      var disabled = this.getProp('disabled');
      var readonly = this.getProp('readonly');
      var inputSlot = this.slots('input');
      var inputAlign = this.getProp('inputAlign');
      if (inputSlot) {
        return h("div", {
          "class": bem$1n('control', [inputAlign, 'custom']),
          "on": {
            "click": this.onClickInput
          }
        }, [inputSlot]);
      }
      var inputProps = {
        ref: 'input',
        class: bem$1n('control', inputAlign),
        domProps: {
          value: this.value
        },
        attrs: _extends$1({}, this.$attrs, {
          name: this.name,
          disabled: disabled,
          readonly: readonly,
          placeholder: this.placeholder
        }),
        on: this.listeners,
        // add model directive to skip IME composition
        directives: [{
          name: 'model',
          value: this.value
        }]
      };
      if (type === 'textarea') {
        return h("textarea", _mergeJSXProps([{}, inputProps]));
      }
      var inputType = type;
      var inputMode; // type="number" is weird in iOS, and can't prevent dot in Android
      // so use inputmode to set keyboard in modern browsers

      if (type === 'number') {
        inputType = 'text';
        inputMode = 'decimal';
      }
      if (type === 'digit') {
        inputType = 'tel';
        inputMode = 'numeric';
      }
      return h("input", _mergeJSXProps([{
        "attrs": {
          "type": inputType,
          "inputmode": inputMode
        }
      }, inputProps]));
    },
    genLeftIcon: function genLeftIcon() {
      var h = this.$createElement;
      var showLeftIcon = this.slots('left-icon') || this.leftIcon;
      if (showLeftIcon) {
        return h("div", {
          "class": bem$1n('left-icon'),
          "on": {
            "click": this.onClickLeftIcon
          }
        }, [this.slots('left-icon') || h(Icon$1, {
          "attrs": {
            "name": this.leftIcon,
            "classPrefix": this.iconPrefix
          }
        })]);
      }
    },
    genRightIcon: function genRightIcon() {
      var h = this.$createElement;
      var slots = this.slots;
      var showRightIcon = slots('right-icon') || this.rightIcon;
      if (showRightIcon) {
        return h("div", {
          "class": bem$1n('right-icon'),
          "on": {
            "click": this.onClickRightIcon
          }
        }, [slots('right-icon') || h(Icon$1, {
          "attrs": {
            "name": this.rightIcon,
            "classPrefix": this.iconPrefix
          }
        })]);
      }
    },
    genWordLimit: function genWordLimit() {
      var h = this.$createElement;
      if (this.showWordLimit && this.maxlength) {
        var count = (this.value || '').length;
        return h("div", {
          "class": bem$1n('word-limit')
        }, [h("span", {
          "class": bem$1n('word-num')
        }, [count]), "/", this.maxlength]);
      }
    },
    genMessage: function genMessage() {
      var h = this.$createElement;
      if (this.vanForm && this.vanForm.showErrorMessage === false) {
        return;
      }
      var message = this.errorMessage || this.validateMessage;
      if (message) {
        var errorMessageAlign = this.getProp('errorMessageAlign');
        return h("div", {
          "class": bem$1n('error-message', errorMessageAlign)
        }, [message]);
      }
    },
    getProp: function getProp(key) {
      if (isDef(this[key])) {
        return this[key];
      }
      if (this.vanForm && isDef(this.vanForm[key])) {
        return this.vanForm[key];
      }
    },
    genLabel: function genLabel() {
      var h = this.$createElement;
      var colon = this.getProp('colon') ? ':' : '';
      if (this.slots('label')) {
        return [this.slots('label'), colon];
      }
      if (this.label) {
        return h("span", [this.label + colon]);
      }
    }
  },
  render: function render() {
    var _bem;
    var h = arguments[0];
    var slots = this.slots;
    var disabled = this.getProp('disabled');
    var labelAlign = this.getProp('labelAlign');
    var scopedSlots = {
      icon: this.genLeftIcon
    };
    var Label = this.genLabel();
    if (Label) {
      scopedSlots.title = function () {
        return Label;
      };
    }
    var extra = this.slots('extra');
    if (extra) {
      scopedSlots.extra = function () {
        return extra;
      };
    }
    return h(Cell$1, {
      "attrs": {
        "icon": this.leftIcon,
        "size": this.size,
        "center": this.center,
        "border": this.border,
        "isLink": this.isLink,
        "required": this.required,
        "clickable": this.clickable,
        "titleStyle": this.labelStyle,
        "valueClass": bem$1n('value'),
        "titleClass": [bem$1n('label', labelAlign), this.labelClass],
        "arrowDirection": this.arrowDirection
      },
      "scopedSlots": scopedSlots,
      "class": bem$1n((_bem = {
        error: this.showError,
        disabled: disabled
      }, _bem["label-" + labelAlign] = labelAlign, _bem['min-height'] = this.type === 'textarea' && !this.autosize, _bem)),
      "on": {
        "click": this.onClick
      }
    }, [h("div", {
      "class": bem$1n('body')
    }, [this.genInput(), this.showClear && h(Icon$1, {
      "attrs": {
        "name": "clear"
      },
      "class": bem$1n('clear'),
      "on": {
        "touchstart": this.onClear
      }
    }), this.genRightIcon(), slots('button') && h("div", {
      "class": bem$1n('button')
    }, [slots('button')])]), this.genWordLimit(), this.genMessage()]);
  }
});

var lockCount = 0;
function lockClick(lock) {
  if (lock) {
    if (!lockCount) {
      document.body.classList.add('van-toast--unclickable');
    }
    lockCount++;
  } else {
    lockCount--;
    if (!lockCount) {
      document.body.classList.remove('van-toast--unclickable');
    }
  }
}

// Utils
var _createNamespace$1r = createNamespace('toast'),
  createComponent$1v = _createNamespace$1r[0],
  bem$1m = _createNamespace$1r[1];
var VueToast = createComponent$1v({
  mixins: [PopupMixin()],
  props: {
    icon: String,
    className: null,
    iconPrefix: String,
    loadingType: String,
    forbidClick: Boolean,
    closeOnClick: Boolean,
    message: [Number, String],
    type: {
      type: String,
      default: 'text'
    },
    position: {
      type: String,
      default: 'middle'
    },
    transition: {
      type: String,
      default: 'van-fade'
    },
    lockScroll: {
      type: Boolean,
      default: false
    }
  },
  data: function data() {
    return {
      clickable: false
    };
  },
  mounted: function mounted() {
    this.toggleClickable();
  },
  destroyed: function destroyed() {
    this.toggleClickable();
  },
  watch: {
    value: 'toggleClickable',
    forbidClick: 'toggleClickable'
  },
  methods: {
    onClick: function onClick() {
      if (this.closeOnClick) {
        this.close();
      }
    },
    toggleClickable: function toggleClickable() {
      var clickable = this.value && this.forbidClick;
      if (this.clickable !== clickable) {
        this.clickable = clickable;
        lockClick(clickable);
      }
    },
    /* istanbul ignore next */
    onAfterEnter: function onAfterEnter() {
      this.$emit('opened');
      if (this.onOpened) {
        this.onOpened();
      }
    },
    onAfterLeave: function onAfterLeave() {
      this.$emit('closed');
    },
    genIcon: function genIcon() {
      var h = this.$createElement;
      var icon = this.icon,
        type = this.type,
        iconPrefix = this.iconPrefix,
        loadingType = this.loadingType;
      var hasIcon = icon || type === 'success' || type === 'fail';
      if (hasIcon) {
        return h(Icon$1, {
          "class": bem$1m('icon'),
          "attrs": {
            "classPrefix": iconPrefix,
            "name": icon || type
          }
        });
      }
      if (type === 'loading') {
        return h(Loading$1, {
          "class": bem$1m('loading'),
          "attrs": {
            "type": loadingType
          }
        });
      }
    },
    genMessage: function genMessage() {
      var h = this.$createElement;
      var type = this.type,
        message = this.message;
      if (!isDef(message) || message === '') {
        return;
      }
      if (type === 'html') {
        return h("div", {
          "class": bem$1m('text'),
          "domProps": {
            "innerHTML": message
          }
        });
      }
      return h("div", {
        "class": bem$1m('text')
      }, [message]);
    }
  },
  render: function render() {
    var _ref;
    var h = arguments[0];
    return h("transition", {
      "attrs": {
        "name": this.transition
      },
      "on": {
        "afterEnter": this.onAfterEnter,
        "afterLeave": this.onAfterLeave
      }
    }, [h("div", {
      "directives": [{
        name: "show",
        value: this.value
      }],
      "class": [bem$1m([this.position, (_ref = {}, _ref[this.type] = !this.icon, _ref)]), this.className],
      "on": {
        "click": this.onClick
      }
    }, [this.genIcon(), this.genMessage()])]);
  }
});

var defaultOptions$1 = {
  icon: '',
  type: 'text',
  // @deprecated
  mask: false,
  value: true,
  message: '',
  className: '',
  overlay: false,
  onClose: null,
  onOpened: null,
  duration: 2000,
  iconPrefix: undefined,
  position: 'middle',
  transition: 'van-fade',
  forbidClick: false,
  loadingType: undefined,
  getContainer: 'body',
  overlayStyle: null,
  closeOnClick: false,
  closeOnClickOverlay: false
}; // default options of specific type

var defaultOptionsMap = {};
var queue = [];
var multiple = false;
var currentOptions = _extends$1({}, defaultOptions$1);
function parseOptions$1(message) {
  if (isObject(message)) {
    return message;
  }
  return {
    message: message
  };
}
function isInDocument$1(element) {
  return document.body.contains(element);
}
function createInstance() {
  /* istanbul ignore if */
  if (isServer) {
    return {};
  }
  queue = queue.filter(function (item) {
    return !item.$el.parentNode || isInDocument$1(item.$el);
  });
  if (!queue.length || multiple) {
    var toast = new (Vue.extend(VueToast))({
      el: document.createElement('div')
    });
    toast.$on('input', function (value) {
      toast.value = value;
    });
    queue.push(toast);
  }
  return queue[queue.length - 1];
} // transform toast options to popup props

function transformOptions(options) {
  return _extends$1({}, options, {
    overlay: options.mask || options.overlay,
    mask: undefined,
    duration: undefined
  });
}
function Toast(options) {
  if (options === void 0) {
    options = {};
  }
  var toast = createInstance(); // should add z-index if previous toast has not disappeared

  if (toast.value) {
    toast.updateZIndex();
  }
  options = parseOptions$1(options);
  options = _extends$1({}, currentOptions, defaultOptionsMap[options.type || currentOptions.type], options);
  options.clear = function () {
    toast.value = false;
    if (options.onClose) {
      options.onClose();
      options.onClose = null;
    }
    if (multiple && !isServer) {
      toast.$on('closed', function () {
        clearTimeout(toast.timer);
        queue = queue.filter(function (item) {
          return item !== toast;
        });
        removeNode(toast.$el);
        toast.$destroy();
      });
    }
  };
  _extends$1(toast, transformOptions(options));
  clearTimeout(toast.timer);
  if (options.duration > 0) {
    toast.timer = setTimeout(function () {
      toast.clear();
    }, options.duration);
  }
  return toast;
}
var createMethod = function createMethod(type) {
  return function (options) {
    return Toast(_extends$1({
      type: type
    }, parseOptions$1(options)));
  };
};
['loading', 'success', 'fail'].forEach(function (method) {
  Toast[method] = createMethod(method);
});
Toast.clear = function (all) {
  if (queue.length) {
    if (all) {
      queue.forEach(function (toast) {
        toast.clear();
      });
      queue = [];
    } else if (!multiple) {
      queue[0].clear();
    } else {
      queue.shift().clear();
    }
  }
};
Toast.setDefaultOptions = function (type, options) {
  if (typeof type === 'string') {
    defaultOptionsMap[type] = options;
  } else {
    _extends$1(currentOptions, type);
  }
};
Toast.resetDefaultOptions = function (type) {
  if (typeof type === 'string') {
    defaultOptionsMap[type] = null;
  } else {
    currentOptions = _extends$1({}, defaultOptions$1);
    defaultOptionsMap = {};
  }
};
Toast.allowMultiple = function (value) {
  if (value === void 0) {
    value = true;
  }
  multiple = value;
};
Toast.install = function () {
  Vue.use(VueToast);
};
Vue.prototype.$toast = Toast;

var _createNamespace$1q = createNamespace('button'),
  createComponent$1u = _createNamespace$1q[0],
  bem$1l = _createNamespace$1q[1];
function Button(h, props, slots, ctx) {
  var _ref;
  var tag = props.tag,
    icon = props.icon,
    type = props.type,
    color = props.color,
    plain = props.plain,
    disabled = props.disabled,
    loading = props.loading,
    hairline = props.hairline,
    loadingText = props.loadingText,
    iconPosition = props.iconPosition;
  var style = {};
  if (color) {
    style.color = plain ? color : 'white';
    if (!plain) {
      // Use background instead of backgroundColor to make linear-gradient work
      style.background = color;
    } // hide border when color is linear-gradient

    if (color.indexOf('gradient') !== -1) {
      style.border = 0;
    } else {
      style.borderColor = color;
    }
  }
  function onClick(event) {
    if (props.loading) {
      event.preventDefault();
    }
    if (!loading && !disabled) {
      emit(ctx, 'click', event);
      functionalRoute(ctx);
    }
  }
  function onTouchstart(event) {
    emit(ctx, 'touchstart', event);
  }
  var classes = [bem$1l([type, props.size, {
    plain: plain,
    loading: loading,
    disabled: disabled,
    hairline: hairline,
    block: props.block,
    round: props.round,
    square: props.square
  }]), (_ref = {}, _ref[BORDER_SURROUND] = hairline, _ref)];
  function renderIcon() {
    if (loading) {
      return slots.loading ? slots.loading() : h(Loading$1, {
        "class": bem$1l('loading'),
        "attrs": {
          "size": props.loadingSize,
          "type": props.loadingType,
          "color": "currentColor"
        }
      });
    }
    if (slots.icon) {
      return h("div", {
        "class": bem$1l('icon')
      }, [slots.icon()]);
    }
    if (icon) {
      return h(Icon$1, {
        "attrs": {
          "name": icon,
          "classPrefix": props.iconPrefix
        },
        "class": bem$1l('icon')
      });
    }
  }
  function renderContent() {
    var content = [];
    if (iconPosition === 'left') {
      content.push(renderIcon());
    }
    var text;
    if (loading) {
      text = loadingText;
    } else {
      text = slots.default ? slots.default() : props.text;
    }
    if (text) {
      content.push(h("span", {
        "class": bem$1l('text')
      }, [text]));
    }
    if (iconPosition === 'right') {
      content.push(renderIcon());
    }
    return content;
  }
  return h(tag, _mergeJSXProps([{
    "style": style,
    "class": classes,
    "attrs": {
      "type": props.nativeType,
      "disabled": disabled
    },
    "on": {
      "click": onClick,
      "touchstart": onTouchstart
    }
  }, inherit(ctx)]), [h("div", {
    "class": bem$1l('content')
  }, [renderContent()])]);
}
Button.props = _extends$1({}, routeProps, {
  text: String,
  icon: String,
  color: String,
  block: Boolean,
  plain: Boolean,
  round: Boolean,
  square: Boolean,
  loading: Boolean,
  hairline: Boolean,
  disabled: Boolean,
  iconPrefix: String,
  nativeType: String,
  loadingText: String,
  loadingType: String,
  tag: {
    type: String,
    default: 'button'
  },
  type: {
    type: String,
    default: 'default'
  },
  size: {
    type: String,
    default: 'normal'
  },
  loadingSize: {
    type: String,
    default: '20px'
  },
  iconPosition: {
    type: String,
    default: 'left'
  }
});
var Button$1 = createComponent$1u(Button);

function flattenVNodes(vnodes) {
  var result = [];
  function traverse(vnodes) {
    vnodes.forEach(function (vnode) {
      result.push(vnode);
      if (vnode.componentInstance) {
        traverse(vnode.componentInstance.$children.map(function (item) {
          return item.$vnode;
        }));
      }
      if (vnode.children) {
        traverse(vnode.children);
      }
    });
  }
  traverse(vnodes);
  return result;
} // sort children instances by vnodes order

function sortChildren(children, parent) {
  var componentOptions = parent.$vnode.componentOptions;
  if (!componentOptions || !componentOptions.children) {
    return;
  }
  var vnodes = flattenVNodes(componentOptions.children);
  children.sort(function (a, b) {
    return vnodes.indexOf(a.$vnode) - vnodes.indexOf(b.$vnode);
  });
}

function ChildrenMixin(_parent, options) {
  var _inject, _computed;
  if (options === void 0) {
    options = {};
  }
  var indexKey = options.indexKey || 'index';
  return {
    inject: (_inject = {}, _inject[_parent] = {
      default: null
    }, _inject),
    computed: (_computed = {
      parent: function parent() {
        if (this.disableBindRelation) {
          return null;
        }
        return this[_parent];
      }
    }, _computed[indexKey] = function () {
      this.bindRelation();
      if (this.parent) {
        return this.parent.children.indexOf(this);
      }
      return null;
    }, _computed),
    watch: {
      disableBindRelation: function disableBindRelation(val) {
        if (!val) {
          this.bindRelation();
        }
      }
    },
    mounted: function mounted() {
      this.bindRelation();
    },
    beforeDestroy: function beforeDestroy() {
      var _this = this;
      if (this.parent) {
        this.parent.children = this.parent.children.filter(function (item) {
          return item !== _this;
        });
      }
    },
    methods: {
      bindRelation: function bindRelation() {
        if (!this.parent || this.parent.children.indexOf(this) !== -1) {
          return;
        }
        var children = [].concat(this.parent.children, [this]);
        sortChildren(children, this.parent);
        this.parent.children = children;
      }
    }
  };
}
function ParentMixin(parent) {
  return {
    provide: function provide() {
      var _ref;
      return _ref = {}, _ref[parent] = this, _ref;
    },
    data: function data() {
      return {
        children: []
      };
    }
  };
}

var _createNamespace$1p = createNamespace('goods-action'),
  createComponent$1t = _createNamespace$1p[0],
  bem$1k = _createNamespace$1p[1];
var GoodsAction = createComponent$1t({
  mixins: [ParentMixin('vanGoodsAction')],
  props: {
    safeAreaInsetBottom: {
      type: Boolean,
      default: true
    }
  },
  render: function render() {
    var h = arguments[0];
    return h("div", {
      "class": bem$1k({
        unfit: !this.safeAreaInsetBottom
      })
    }, [this.slots()]);
  }
});

var _createNamespace$1o = createNamespace('goods-action-button'),
  createComponent$1s = _createNamespace$1o[0],
  bem$1j = _createNamespace$1o[1];
var GoodsActionButton = createComponent$1s({
  mixins: [ChildrenMixin('vanGoodsAction')],
  props: _extends$1({}, routeProps, {
    type: String,
    text: String,
    icon: String,
    color: String,
    loading: Boolean,
    disabled: Boolean
  }),
  computed: {
    isFirst: function isFirst() {
      var prev = this.parent && this.parent.children[this.index - 1];
      return !prev || prev.$options.name !== this.$options.name;
    },
    isLast: function isLast() {
      var next = this.parent && this.parent.children[this.index + 1];
      return !next || next.$options.name !== this.$options.name;
    }
  },
  methods: {
    onClick: function onClick(event) {
      this.$emit('click', event);
      route(this.$router, this);
    }
  },
  render: function render() {
    var h = arguments[0];
    return h(Button$1, {
      "class": bem$1j([{
        first: this.isFirst,
        last: this.isLast
      }, this.type]),
      "attrs": {
        "size": "large",
        "type": this.type,
        "icon": this.icon,
        "color": this.color,
        "loading": this.loading,
        "disabled": this.disabled
      },
      "on": {
        "click": this.onClick
      }
    }, [this.slots() || this.text]);
  }
});

var _createNamespace$1n = createNamespace('dialog'),
  createComponent$1r = _createNamespace$1n[0],
  bem$1i = _createNamespace$1n[1],
  t$p = _createNamespace$1n[2];
var VanDialog = createComponent$1r({
  mixins: [PopupMixin()],
  props: {
    title: String,
    theme: String,
    width: [Number, String],
    message: String,
    className: null,
    callback: Function,
    beforeClose: Function,
    messageAlign: String,
    cancelButtonText: String,
    cancelButtonColor: String,
    confirmButtonText: String,
    confirmButtonColor: String,
    showCancelButton: Boolean,
    overlay: {
      type: Boolean,
      default: true
    },
    allowHtml: {
      type: Boolean,
      default: true
    },
    transition: {
      type: String,
      default: 'van-dialog-bounce'
    },
    showConfirmButton: {
      type: Boolean,
      default: true
    },
    closeOnPopstate: {
      type: Boolean,
      default: true
    },
    closeOnClickOverlay: {
      type: Boolean,
      default: false
    }
  },
  data: function data() {
    return {
      loading: {
        confirm: false,
        cancel: false
      }
    };
  },
  methods: {
    onClickOverlay: function onClickOverlay() {
      this.handleAction('overlay');
    },
    handleAction: function handleAction(action) {
      var _this = this;
      this.$emit(action); // show not trigger close event when hidden

      if (!this.value) {
        return;
      }
      if (this.beforeClose) {
        this.loading[action] = true;
        this.beforeClose(action, function (state) {
          if (state !== false && _this.loading[action]) {
            _this.onClose(action);
          }
          _this.loading.confirm = false;
          _this.loading.cancel = false;
        });
      } else {
        this.onClose(action);
      }
    },
    onClose: function onClose(action) {
      this.close();
      if (this.callback) {
        this.callback(action);
      }
    },
    onOpened: function onOpened() {
      var _this2 = this;
      this.$emit('opened');
      this.$nextTick(function () {
        var _this2$$refs$dialog;
        (_this2$$refs$dialog = _this2.$refs.dialog) == null ? void 0 : _this2$$refs$dialog.focus();
      });
    },
    onClosed: function onClosed() {
      this.$emit('closed');
    },
    onKeydown: function onKeydown(event) {
      var _this3 = this;
      if (event.key === 'Escape' || event.key === 'Enter') {
        // skip keyboard events of child elements
        if (event.target !== this.$refs.dialog) {
          return;
        }
        var onEventType = {
          Enter: this.showConfirmButton ? function () {
            return _this3.handleAction('confirm');
          } : noop,
          Escape: this.showCancelButton ? function () {
            return _this3.handleAction('cancel');
          } : noop
        };
        onEventType[event.key]();
        this.$emit('keydown', event);
      }
    },
    genRoundButtons: function genRoundButtons() {
      var _this4 = this;
      var h = this.$createElement;
      return h(GoodsAction, {
        "class": bem$1i('footer')
      }, [this.showCancelButton && h(GoodsActionButton, {
        "attrs": {
          "size": "large",
          "type": "warning",
          "text": this.cancelButtonText || t$p('cancel'),
          "color": this.cancelButtonColor,
          "loading": this.loading.cancel
        },
        "class": bem$1i('cancel'),
        "on": {
          "click": function click() {
            _this4.handleAction('cancel');
          }
        }
      }), this.showConfirmButton && h(GoodsActionButton, {
        "attrs": {
          "size": "large",
          "type": "danger",
          "text": this.confirmButtonText || t$p('confirm'),
          "color": this.confirmButtonColor,
          "loading": this.loading.confirm
        },
        "class": bem$1i('confirm'),
        "on": {
          "click": function click() {
            _this4.handleAction('confirm');
          }
        }
      })]);
    },
    genButtons: function genButtons() {
      var _this5 = this,
        _ref;
      var h = this.$createElement;
      var multiple = this.showCancelButton && this.showConfirmButton;
      return h("div", {
        "class": [BORDER_TOP, bem$1i('footer')]
      }, [this.showCancelButton && h(Button$1, {
        "attrs": {
          "size": "large",
          "loading": this.loading.cancel,
          "text": this.cancelButtonText || t$p('cancel'),
          "nativeType": "button"
        },
        "class": bem$1i('cancel'),
        "style": {
          color: this.cancelButtonColor
        },
        "on": {
          "click": function click() {
            _this5.handleAction('cancel');
          }
        }
      }), this.showConfirmButton && h(Button$1, {
        "attrs": {
          "size": "large",
          "loading": this.loading.confirm,
          "text": this.confirmButtonText || t$p('confirm'),
          "nativeType": "button"
        },
        "class": [bem$1i('confirm'), (_ref = {}, _ref[BORDER_LEFT] = multiple, _ref)],
        "style": {
          color: this.confirmButtonColor
        },
        "on": {
          "click": function click() {
            _this5.handleAction('confirm');
          }
        }
      })]);
    },
    genContent: function genContent(hasTitle, messageSlot) {
      var h = this.$createElement;
      if (messageSlot) {
        return h("div", {
          "class": bem$1i('content')
        }, [messageSlot]);
      }
      var message = this.message,
        messageAlign = this.messageAlign;
      if (message) {
        var _bem, _domProps;
        var data = {
          class: bem$1i('message', (_bem = {
            'has-title': hasTitle
          }, _bem[messageAlign] = messageAlign, _bem)),
          domProps: (_domProps = {}, _domProps[this.allowHtml ? 'innerHTML' : 'textContent'] = message, _domProps)
        };
        return h("div", {
          "class": bem$1i('content', {
            isolated: !hasTitle
          })
        }, [h("div", _mergeJSXProps([{}, data]))]);
      }
    }
  },
  render: function render() {
    var h = arguments[0];
    if (!this.shouldRender) {
      return;
    }
    var message = this.message;
    var messageSlot = this.slots();
    var title = this.slots('title') || this.title;
    var Title = title && h("div", {
      "class": bem$1i('header', {
        isolated: !message && !messageSlot
      })
    }, [title]);
    return h("transition", {
      "attrs": {
        "name": this.transition
      },
      "on": {
        "afterEnter": this.onOpened,
        "afterLeave": this.onClosed
      }
    }, [h("div", {
      "directives": [{
        name: "show",
        value: this.value
      }],
      "attrs": {
        "role": "dialog",
        "aria-labelledby": this.title || message,
        "tabIndex": 0
      },
      "class": [bem$1i([this.theme]), this.className],
      "style": {
        width: addUnit(this.width)
      },
      "ref": "dialog",
      "on": {
        "keydown": this.onKeydown
      }
    }, [Title, this.genContent(title, messageSlot), this.theme === 'round-button' ? this.genRoundButtons() : this.genButtons()])]);
  }
});

var instance$2;
function isInDocument(element) {
  return document.body.contains(element);
}
function initInstance$1() {
  if (instance$2) {
    instance$2.$destroy();
  }
  instance$2 = new (Vue.extend(VanDialog))({
    el: document.createElement('div'),
    // avoid missing animation when first rendered
    propsData: {
      lazyRender: false
    }
  });
  instance$2.$on('input', function (value) {
    instance$2.value = value;
  });
}
function Dialog(options) {
  /* istanbul ignore if */
  if (isServer) {
    return Promise.resolve();
  }
  return new Promise(function (resolve, reject) {
    if (!instance$2 || !isInDocument(instance$2.$el)) {
      initInstance$1();
    }
    _extends$1(instance$2, Dialog.currentOptions, options, {
      resolve: resolve,
      reject: reject
    });
  });
}
Dialog.defaultOptions = {
  value: true,
  title: '',
  width: '',
  theme: null,
  message: '',
  overlay: true,
  className: '',
  allowHtml: true,
  lockScroll: true,
  transition: 'van-dialog-bounce',
  beforeClose: null,
  overlayClass: '',
  overlayStyle: null,
  messageAlign: '',
  getContainer: 'body',
  cancelButtonText: '',
  cancelButtonColor: null,
  confirmButtonText: '',
  confirmButtonColor: null,
  showConfirmButton: true,
  showCancelButton: false,
  closeOnPopstate: true,
  closeOnClickOverlay: false,
  callback: function callback(action) {
    instance$2[action === 'confirm' ? 'resolve' : 'reject'](action);
  }
};
Dialog.alert = Dialog;
Dialog.confirm = function (options) {
  return Dialog(_extends$1({
    showCancelButton: true
  }, options));
};
Dialog.close = function () {
  if (instance$2) {
    instance$2.value = false;
  }
};
Dialog.setDefaultOptions = function (options) {
  _extends$1(Dialog.currentOptions, options);
};
Dialog.resetDefaultOptions = function () {
  Dialog.currentOptions = _extends$1({}, Dialog.defaultOptions);
};
Dialog.resetDefaultOptions();
Dialog.install = function () {
  Vue.use(VanDialog);
};
Dialog.Component = VanDialog;
Vue.prototype.$dialog = Dialog;

var _createNamespace$1m = createNamespace('address-edit-detail'),
  createComponent$1q = _createNamespace$1m[0],
  bem$1h = _createNamespace$1m[1],
  t$o = _createNamespace$1m[2];
var android = isAndroid();
var Detail = createComponent$1q({
  props: {
    value: String,
    errorMessage: String,
    focused: Boolean,
    detailRows: [Number, String],
    searchResult: Array,
    detailMaxlength: [Number, String],
    showSearchResult: Boolean
  },
  computed: {
    shouldShowSearchResult: function shouldShowSearchResult() {
      return this.focused && this.searchResult && this.showSearchResult;
    }
  },
  methods: {
    onSelect: function onSelect(express) {
      this.$emit('select-search', express);
      this.$emit('input', ((express.address || '') + " " + (express.name || '')).trim());
    },
    onFinish: function onFinish() {
      this.$refs.field.blur();
    },
    genFinish: function genFinish() {
      var h = this.$createElement;
      var show = this.value && this.focused && android;
      if (show) {
        return h("div", {
          "class": bem$1h('finish'),
          "on": {
            "click": this.onFinish
          }
        }, [t$o('complete')]);
      }
    },
    genSearchResult: function genSearchResult() {
      var _this = this;
      var h = this.$createElement;
      var value = this.value,
        shouldShowSearchResult = this.shouldShowSearchResult,
        searchResult = this.searchResult;
      if (shouldShowSearchResult) {
        return searchResult.map(function (express) {
          return h(Cell$1, {
            "key": express.name + express.address,
            "attrs": {
              "clickable": true,
              "border": false,
              "icon": "location-o",
              "label": express.address
            },
            "class": bem$1h('search-item'),
            "on": {
              "click": function click() {
                _this.onSelect(express);
              }
            },
            "scopedSlots": {
              title: function title() {
                if (express.name) {
                  var text = express.name.replace(value, "<span class=" + bem$1h('keyword') + ">" + value + "</span>");
                  return h("div", {
                    "domProps": {
                      "innerHTML": text
                    }
                  });
                }
              }
            }
          });
        });
      }
    }
  },
  render: function render() {
    var h = arguments[0];
    return h(Cell$1, {
      "class": bem$1h()
    }, [h(Field, {
      "attrs": {
        "autosize": true,
        "rows": this.detailRows,
        "clearable": !android,
        "type": "textarea",
        "value": this.value,
        "errorMessage": this.errorMessage,
        "border": !this.shouldShowSearchResult,
        "label": t$o('label'),
        "maxlength": this.detailMaxlength,
        "placeholder": t$o('placeholder')
      },
      "ref": "field",
      "scopedSlots": {
        icon: this.genFinish
      },
      "on": _extends$1({}, this.$listeners)
    }), this.genSearchResult()]);
  }
});

/**
 * Common Switch Props
 */
var switchProps = {
  size: [Number, String],
  value: null,
  loading: Boolean,
  disabled: Boolean,
  activeColor: String,
  inactiveColor: String,
  activeValue: {
    type: null,
    default: true
  },
  inactiveValue: {
    type: null,
    default: false
  }
};

var FieldMixin = {
  inject: {
    vanField: {
      default: null
    }
  },
  watch: {
    value: function value() {
      var field = this.vanField;
      if (field) {
        field.resetValidation();
        field.validateWithTrigger('onChange');
      }
    }
  },
  created: function created() {
    var field = this.vanField;
    if (field && !field.children) {
      field.children = this;
    }
  }
};

// Utils
var _createNamespace$1l = createNamespace('switch'),
  createComponent$1p = _createNamespace$1l[0],
  bem$1g = _createNamespace$1l[1];
var Switch = createComponent$1p({
  mixins: [FieldMixin],
  props: switchProps,
  computed: {
    checked: function checked() {
      return this.value === this.activeValue;
    },
    style: function style() {
      return {
        fontSize: addUnit(this.size),
        backgroundColor: this.checked ? this.activeColor : this.inactiveColor
      };
    }
  },
  methods: {
    onClick: function onClick(event) {
      this.$emit('click', event);
      if (!this.disabled && !this.loading) {
        var newValue = this.checked ? this.inactiveValue : this.activeValue;
        this.$emit('input', newValue);
        this.$emit('change', newValue);
      }
    },
    genLoading: function genLoading() {
      var h = this.$createElement;
      if (this.loading) {
        var color = this.checked ? this.activeColor : this.inactiveColor;
        return h(Loading$1, {
          "class": bem$1g('loading'),
          "attrs": {
            "color": color
          }
        });
      }
    }
  },
  render: function render() {
    var h = arguments[0];
    var checked = this.checked,
      loading = this.loading,
      disabled = this.disabled;
    return h("div", {
      "class": bem$1g({
        on: checked,
        loading: loading,
        disabled: disabled
      }),
      "attrs": {
        "role": "switch",
        "aria-checked": String(checked)
      },
      "style": this.style,
      "on": {
        "click": this.onClick
      }
    }, [h("div", {
      "class": bem$1g('node')
    }, [this.genLoading()])]);
  }
});

var _createNamespace$1k = createNamespace('address-edit'),
  createComponent$1o = _createNamespace$1k[0],
  bem$1f = _createNamespace$1k[1],
  t$n = _createNamespace$1k[2];
var defaultData = {
  name: '',
  tel: '',
  country: '',
  province: '',
  city: '',
  county: '',
  areaCode: '',
  postalCode: '',
  addressDetail: '',
  isDefault: false
};
function isPostal(value) {
  return /^\d{6}$/.test(value);
}
var AddressEdit = createComponent$1o({
  props: {
    areaList: Object,
    isSaving: Boolean,
    isDeleting: Boolean,
    validator: Function,
    showDelete: Boolean,
    showPostal: Boolean,
    searchResult: Array,
    telMaxlength: [Number, String],
    showSetDefault: Boolean,
    saveButtonText: String,
    areaPlaceholder: String,
    deleteButtonText: String,
    showSearchResult: Boolean,
    showArea: {
      type: Boolean,
      default: true
    },
    showDetail: {
      type: Boolean,
      default: true
    },
    disableArea: Boolean,
    detailRows: {
      type: [Number, String],
      default: 1
    },
    detailMaxlength: {
      type: [Number, String],
      default: 200
    },
    addressInfo: {
      type: Object,
      default: function _default() {
        return _extends$1({}, defaultData);
      }
    },
    telValidator: {
      type: Function,
      default: isMobile
    },
    postalValidator: {
      type: Function,
      default: isPostal
    },
    areaColumnsPlaceholder: {
      type: Array,
      default: function _default() {
        return [];
      }
    }
  },
  data: function data() {
    return {
      data: {},
      showAreaPopup: false,
      detailFocused: false,
      errorInfo: {
        tel: '',
        name: '',
        areaCode: '',
        postalCode: '',
        addressDetail: ''
      }
    };
  },
  computed: {
    areaListLoaded: function areaListLoaded() {
      return isObject(this.areaList) && Object.keys(this.areaList).length;
    },
    areaText: function areaText() {
      var _this$data = this.data,
        country = _this$data.country,
        province = _this$data.province,
        city = _this$data.city,
        county = _this$data.county,
        areaCode = _this$data.areaCode;
      if (areaCode) {
        var arr = [country, province, city, county];
        if (province && province === city) {
          arr.splice(1, 1);
        }
        return arr.filter(function (text) {
          return text;
        }).join('/');
      }
      return '';
    },
    // hide bottom field when use search && detail get focused
    hideBottomFields: function hideBottomFields() {
      var searchResult = this.searchResult;
      return searchResult && searchResult.length && this.detailFocused;
    }
  },
  watch: {
    addressInfo: {
      handler: function handler(val) {
        this.data = _extends$1({}, defaultData, val);
        this.setAreaCode(val.areaCode);
      },
      deep: true,
      immediate: true
    },
    areaList: function areaList() {
      this.setAreaCode(this.data.areaCode);
    }
  },
  methods: {
    onFocus: function onFocus(key) {
      this.errorInfo[key] = '';
      this.detailFocused = key === 'addressDetail';
      this.$emit('focus', key);
    },
    onChangeDetail: function onChangeDetail(val) {
      this.data.addressDetail = val;
      this.$emit('change-detail', val);
    },
    onAreaConfirm: function onAreaConfirm(values) {
      values = values.filter(function (value) {
        return !!value;
      });
      if (values.some(function (value) {
        return !value.code;
      })) {
        Toast(t$n('areaEmpty'));
        return;
      }
      this.showAreaPopup = false;
      this.assignAreaValues();
      this.$emit('change-area', values);
    },
    assignAreaValues: function assignAreaValues() {
      var area = this.$refs.area;
      if (area) {
        var detail = area.getArea();
        detail.areaCode = detail.code;
        delete detail.code;
        _extends$1(this.data, detail);
      }
    },
    onSave: function onSave() {
      var _this = this;
      var items = ['name', 'tel'];
      if (this.showArea) {
        items.push('areaCode');
      }
      if (this.showDetail) {
        items.push('addressDetail');
      }
      if (this.showPostal) {
        items.push('postalCode');
      }
      var isValid = items.every(function (item) {
        var msg = _this.getErrorMessage(item);
        if (msg) {
          _this.errorInfo[item] = msg;
        }
        return !msg;
      });
      if (isValid && !this.isSaving) {
        this.$emit('save', this.data);
      }
    },
    getErrorMessage: function getErrorMessage(key) {
      var value = String(this.data[key] || '').trim();
      if (this.validator) {
        var message = this.validator(key, value);
        if (message) {
          return message;
        }
      }
      switch (key) {
        case 'name':
          return value ? '' : t$n('nameEmpty');
        case 'tel':
          return this.telValidator(value) ? '' : t$n('telInvalid');
        case 'areaCode':
          return value ? '' : t$n('areaEmpty');
        case 'addressDetail':
          return value ? '' : t$n('addressEmpty');
        case 'postalCode':
          return value && !this.postalValidator(value) ? t$n('postalEmpty') : '';
      }
    },
    onDelete: function onDelete() {
      var _this2 = this;
      Dialog.confirm({
        title: t$n('confirmDelete')
      }).then(function () {
        _this2.$emit('delete', _this2.data);
      }).catch(function () {
        _this2.$emit('cancel-delete', _this2.data);
      });
    },
    // get values of area component
    getArea: function getArea() {
      return this.$refs.area ? this.$refs.area.getValues() : [];
    },
    // set area code to area component
    setAreaCode: function setAreaCode(code) {
      this.data.areaCode = code || '';
      if (code) {
        this.$nextTick(this.assignAreaValues);
      }
    },
    // @exposed-api
    setAddressDetail: function setAddressDetail(value) {
      this.data.addressDetail = value;
    },
    onDetailBlur: function onDetailBlur() {
      var _this3 = this;

      // await for click search event
      setTimeout(function () {
        _this3.detailFocused = false;
      });
    },
    genSetDefaultCell: function genSetDefaultCell(h) {
      var _this4 = this;
      if (this.showSetDefault) {
        var slots = {
          'right-icon': function rightIcon() {
            return h(Switch, {
              "attrs": {
                "size": "24"
              },
              "on": {
                "change": function change(event) {
                  _this4.$emit('change-default', event);
                }
              },
              "model": {
                value: _this4.data.isDefault,
                callback: function callback($$v) {
                  _this4.$set(_this4.data, "isDefault", $$v);
                }
              }
            });
          }
        };
        return h(Cell$1, {
          "directives": [{
            name: "show",
            value: !this.hideBottomFields
          }],
          "attrs": {
            "center": true,
            "title": t$n('defaultAddress')
          },
          "class": bem$1f('default'),
          "scopedSlots": slots
        });
      }
      return h();
    }
  },
  render: function render(h) {
    var _this5 = this;
    var data = this.data,
      errorInfo = this.errorInfo,
      disableArea = this.disableArea,
      hideBottomFields = this.hideBottomFields;
    var onFocus = function onFocus(name) {
      return function () {
        return _this5.onFocus(name);
      };
    };
    return h("div", {
      "class": bem$1f()
    }, [h("div", {
      "class": bem$1f('fields')
    }, [h(Field, {
      "attrs": {
        "clearable": true,
        "label": t$n('name'),
        "placeholder": t$n('namePlaceholder'),
        "errorMessage": errorInfo.name
      },
      "on": {
        "focus": onFocus('name')
      },
      "model": {
        value: data.name,
        callback: function callback($$v) {
          _this5.$set(data, "name", $$v);
        }
      }
    }), h(Field, {
      "attrs": {
        "clearable": true,
        "type": "tel",
        "label": t$n('tel'),
        "maxlength": this.telMaxlength,
        "placeholder": t$n('telPlaceholder'),
        "errorMessage": errorInfo.tel
      },
      "on": {
        "focus": onFocus('tel')
      },
      "model": {
        value: data.tel,
        callback: function callback($$v) {
          _this5.$set(data, "tel", $$v);
        }
      }
    }), h(Field, {
      "directives": [{
        name: "show",
        value: this.showArea
      }],
      "attrs": {
        "readonly": true,
        "clickable": !disableArea,
        "label": t$n('area'),
        "placeholder": this.areaPlaceholder || t$n('areaPlaceholder'),
        "errorMessage": errorInfo.areaCode,
        "rightIcon": !disableArea ? 'arrow' : null,
        "value": this.areaText
      },
      "on": {
        "focus": onFocus('areaCode'),
        "click": function click() {
          _this5.$emit('click-area');
          _this5.showAreaPopup = !disableArea;
        }
      }
    }), h(Detail, {
      "directives": [{
        name: "show",
        value: this.showDetail
      }],
      "attrs": {
        "focused": this.detailFocused,
        "value": data.addressDetail,
        "errorMessage": errorInfo.addressDetail,
        "detailRows": this.detailRows,
        "detailMaxlength": this.detailMaxlength,
        "searchResult": this.searchResult,
        "showSearchResult": this.showSearchResult
      },
      "on": {
        "focus": onFocus('addressDetail'),
        "blur": this.onDetailBlur,
        "input": this.onChangeDetail,
        "select-search": function selectSearch(event) {
          _this5.$emit('select-search', event);
        }
      }
    }), this.showPostal && h(Field, {
      "directives": [{
        name: "show",
        value: !hideBottomFields
      }],
      "attrs": {
        "type": "tel",
        "maxlength": "6",
        "label": t$n('postal'),
        "placeholder": t$n('postal'),
        "errorMessage": errorInfo.postalCode
      },
      "on": {
        "focus": onFocus('postalCode')
      },
      "model": {
        value: data.postalCode,
        callback: function callback($$v) {
          _this5.$set(data, "postalCode", $$v);
        }
      }
    }), this.slots()]), this.genSetDefaultCell(h), h("div", {
      "directives": [{
        name: "show",
        value: !hideBottomFields
      }],
      "class": bem$1f('buttons')
    }, [h(Button$1, {
      "attrs": {
        "block": true,
        "round": true,
        "loading": this.isSaving,
        "type": "danger",
        "text": this.saveButtonText || t$n('save')
      },
      "on": {
        "click": this.onSave
      }
    }), this.showDelete && h(Button$1, {
      "attrs": {
        "block": true,
        "round": true,
        "loading": this.isDeleting,
        "text": this.deleteButtonText || t$n('delete')
      },
      "on": {
        "click": this.onDelete
      }
    })]), h(Popup, {
      "attrs": {
        "round": true,
        "position": "bottom",
        "lazyRender": false,
        "getContainer": "body"
      },
      "model": {
        value: _this5.showAreaPopup,
        callback: function callback($$v) {
          _this5.showAreaPopup = $$v;
        }
      }
    }, [h(Area, {
      "ref": "area",
      "attrs": {
        "value": data.areaCode,
        "loading": !this.areaListLoaded,
        "areaList": this.areaList,
        "columnsPlaceholder": this.areaColumnsPlaceholder
      },
      "on": {
        "confirm": this.onAreaConfirm,
        "cancel": function cancel() {
          _this5.showAreaPopup = false;
        }
      }
    })])]);
  }
});

var _createNamespace$1j = createNamespace('radio-group'),
  createComponent$1n = _createNamespace$1j[0],
  bem$1e = _createNamespace$1j[1];
var RadioGroup = createComponent$1n({
  mixins: [ParentMixin('vanRadio'), FieldMixin],
  props: {
    value: null,
    disabled: Boolean,
    direction: String,
    checkedColor: String,
    iconSize: [Number, String]
  },
  watch: {
    value: function value(_value) {
      this.$emit('change', _value);
    }
  },
  render: function render() {
    var h = arguments[0];
    return h("div", {
      "class": bem$1e([this.direction]),
      "attrs": {
        "role": "radiogroup"
      }
    }, [this.slots()]);
  }
});

var _createNamespace$1i = createNamespace('tag'),
  createComponent$1m = _createNamespace$1i[0],
  bem$1d = _createNamespace$1i[1];
function Tag(h, props, slots, ctx) {
  var _style;
  var type = props.type,
    mark = props.mark,
    plain = props.plain,
    color = props.color,
    round = props.round,
    size = props.size,
    textColor = props.textColor;
  var key = plain ? 'color' : 'backgroundColor';
  var style = (_style = {}, _style[key] = color, _style);
  if (plain) {
    style.color = textColor || color;
    style.borderColor = color;
  } else {
    style.color = textColor;
    style.background = color;
  }
  var classes = {
    mark: mark,
    plain: plain,
    round: round
  };
  if (size) {
    classes[size] = size;
  }
  var CloseIcon = props.closeable && h(Icon$1, {
    "attrs": {
      "name": "cross"
    },
    "class": bem$1d('close'),
    "on": {
      "click": function click(event) {
        event.stopPropagation();
        emit(ctx, 'close');
      }
    }
  });
  return h("transition", {
    "attrs": {
      "name": props.closeable ? 'van-fade' : null
    }
  }, [h("span", _mergeJSXProps([{
    "key": "content",
    "style": style,
    "class": bem$1d([classes, type])
  }, inherit(ctx, true)]), [slots.default == null ? void 0 : slots.default(), CloseIcon])]);
}
Tag.props = {
  size: String,
  mark: Boolean,
  color: String,
  plain: Boolean,
  round: Boolean,
  textColor: String,
  closeable: Boolean,
  type: {
    type: String,
    default: 'default'
  }
};
var Tag$1 = createComponent$1m(Tag);

/**
 * Common part of Checkbox & Radio
 */
var CheckboxMixin = function CheckboxMixin(_ref) {
  var parent = _ref.parent,
    bem = _ref.bem,
    role = _ref.role;
  return {
    mixins: [ChildrenMixin(parent), FieldMixin],
    props: {
      name: null,
      value: null,
      disabled: Boolean,
      iconSize: [Number, String],
      checkedColor: String,
      labelPosition: String,
      labelDisabled: Boolean,
      shape: {
        type: String,
        default: 'round'
      },
      bindGroup: {
        type: Boolean,
        default: true
      }
    },
    computed: {
      disableBindRelation: function disableBindRelation() {
        return !this.bindGroup;
      },
      isDisabled: function isDisabled() {
        return this.parent && this.parent.disabled || this.disabled;
      },
      direction: function direction() {
        return this.parent && this.parent.direction || null;
      },
      iconStyle: function iconStyle() {
        var checkedColor = this.checkedColor || this.parent && this.parent.checkedColor;
        if (checkedColor && this.checked && !this.isDisabled) {
          return {
            borderColor: checkedColor,
            backgroundColor: checkedColor
          };
        }
      },
      tabindex: function tabindex() {
        if (this.isDisabled || role === 'radio' && !this.checked) {
          return -1;
        }
        return 0;
      }
    },
    methods: {
      onClick: function onClick(event) {
        var _this = this;
        var target = event.target;
        var icon = this.$refs.icon;
        var iconClicked = icon === target || (icon == null ? void 0 : icon.contains(target));
        if (!this.isDisabled && (iconClicked || !this.labelDisabled)) {
          this.toggle(); // wait for toggle method to complete
          // so we can get the changed value in the click event listener

          setTimeout(function () {
            _this.$emit('click', event);
          });
        } else {
          this.$emit('click', event);
        }
      },
      genIcon: function genIcon() {
        var h = this.$createElement;
        var checked = this.checked;
        var iconSize = this.iconSize || this.parent && this.parent.iconSize;
        return h("div", {
          "ref": "icon",
          "class": bem('icon', [this.shape, {
            disabled: this.isDisabled,
            checked: checked
          }]),
          "style": {
            fontSize: addUnit(iconSize)
          }
        }, [this.slots('icon', {
          checked: checked
        }) || h(Icon$1, {
          "attrs": {
            "name": "success"
          },
          "style": this.iconStyle
        })]);
      },
      genLabel: function genLabel() {
        var h = this.$createElement;
        var slot = this.slots();
        if (slot) {
          return h("span", {
            "class": bem('label', [this.labelPosition, {
              disabled: this.isDisabled
            }])
          }, [slot]);
        }
      }
    },
    render: function render() {
      var h = arguments[0];
      var Children = [this.genIcon()];
      if (this.labelPosition === 'left') {
        Children.unshift(this.genLabel());
      } else {
        Children.push(this.genLabel());
      }
      return h("div", {
        "attrs": {
          "role": role,
          "tabindex": this.tabindex,
          "aria-checked": String(this.checked)
        },
        "class": bem([{
          disabled: this.isDisabled,
          'label-disabled': this.labelDisabled
        }, this.direction]),
        "on": {
          "click": this.onClick
        }
      }, [Children]);
    }
  };
};

var _createNamespace$1h = createNamespace('radio'),
  createComponent$1l = _createNamespace$1h[0],
  bem$1c = _createNamespace$1h[1];
var Radio = createComponent$1l({
  mixins: [CheckboxMixin({
    bem: bem$1c,
    role: 'radio',
    parent: 'vanRadio'
  })],
  computed: {
    currentValue: {
      get: function get() {
        return this.parent ? this.parent.value : this.value;
      },
      set: function set(val) {
        (this.parent || this).$emit('input', val);
      }
    },
    checked: function checked() {
      return this.currentValue === this.name;
    }
  },
  methods: {
    toggle: function toggle() {
      this.currentValue = this.name;
    }
  }
});

var _createNamespace$1g = createNamespace('address-item'),
  createComponent$1k = _createNamespace$1g[0],
  bem$1b = _createNamespace$1g[1];
function AddressItem(h, props, slots, ctx) {
  var disabled = props.disabled,
    switchable = props.switchable;
  function onClick() {
    if (switchable) {
      emit(ctx, 'select');
    }
    emit(ctx, 'click');
  }
  var genRightIcon = function genRightIcon() {
    return h(Icon$1, {
      "attrs": {
        "name": "edit"
      },
      "class": bem$1b('edit'),
      "on": {
        "click": function click(event) {
          event.stopPropagation();
          emit(ctx, 'edit');
          emit(ctx, 'click');
        }
      }
    });
  };
  function genTag() {
    if (slots.tag) {
      return slots.tag(_extends$1({}, props.data));
    }
    if (props.data.isDefault && props.defaultTagText) {
      return h(Tag$1, {
        "attrs": {
          "type": "danger",
          "round": true
        },
        "class": bem$1b('tag')
      }, [props.defaultTagText]);
    }
  }
  function genContent() {
    var data = props.data;
    var Info = [h("div", {
      "class": bem$1b('name')
    }, [data.name + " " + data.tel, genTag()]), h("div", {
      "class": bem$1b('address')
    }, [data.address])];
    if (switchable && !disabled) {
      return h(Radio, {
        "attrs": {
          "name": data.id,
          "iconSize": 18
        }
      }, [Info]);
    }
    return Info;
  }
  return h("div", {
    "class": bem$1b({
      disabled: disabled
    }),
    "on": {
      "click": onClick
    }
  }, [h(Cell$1, _mergeJSXProps([{
    "attrs": {
      "border": false,
      "valueClass": bem$1b('value')
    },
    "scopedSlots": {
      default: genContent,
      'right-icon': genRightIcon
    }
  }, inherit(ctx)])), slots.bottom == null ? void 0 : slots.bottom(_extends$1({}, props.data, {
    disabled: disabled
  }))]);
}
AddressItem.props = {
  data: Object,
  disabled: Boolean,
  switchable: Boolean,
  defaultTagText: String
};
var AddressItem$1 = createComponent$1k(AddressItem);

var _createNamespace$1f = createNamespace('address-list'),
  createComponent$1j = _createNamespace$1f[0],
  bem$1a = _createNamespace$1f[1],
  t$m = _createNamespace$1f[2];
function AddressList(h, props, slots, ctx) {
  function genList(list, disabled) {
    if (!list) {
      return;
    }
    return list.map(function (item, index) {
      return h(AddressItem$1, {
        "attrs": {
          "data": item,
          "disabled": disabled,
          "switchable": props.switchable,
          "defaultTagText": props.defaultTagText
        },
        "key": item.id,
        "scopedSlots": {
          bottom: slots['item-bottom'],
          tag: slots.tag
        },
        "on": {
          "select": function select() {
            emit(ctx, disabled ? 'select-disabled' : 'select', item, index);
            if (!disabled) {
              emit(ctx, 'input', item.id);
            }
          },
          "edit": function edit() {
            emit(ctx, disabled ? 'edit-disabled' : 'edit', item, index);
          },
          "click": function click() {
            emit(ctx, 'click-item', item, index);
          }
        }
      });
    });
  }
  var List = genList(props.list);
  var DisabledList = genList(props.disabledList, true);
  return h("div", _mergeJSXProps([{
    "class": bem$1a()
  }, inherit(ctx)]), [slots.top == null ? void 0 : slots.top(), h(RadioGroup, {
    "attrs": {
      "value": props.value
    }
  }, [List]), props.disabledText && h("div", {
    "class": bem$1a('disabled-text')
  }, [props.disabledText]), DisabledList, slots.default == null ? void 0 : slots.default(), h("div", {
    "class": bem$1a('bottom')
  }, [h(Button$1, {
    "attrs": {
      "round": true,
      "block": true,
      "type": "danger",
      "text": props.addButtonText || t$m('add')
    },
    "class": bem$1a('add'),
    "on": {
      "click": function click() {
        emit(ctx, 'add');
      }
    }
  })])]);
}
AddressList.props = {
  list: Array,
  value: [Number, String],
  disabledList: Array,
  disabledText: String,
  addButtonText: String,
  defaultTagText: String,
  switchable: {
    type: Boolean,
    default: true
  }
};
var AddressList$1 = createComponent$1j(AddressList);

var _createNamespace$1e = createNamespace('badge'),
  createComponent$1i = _createNamespace$1e[0],
  bem$19 = _createNamespace$1e[1];
var Badge = createComponent$1i({
  props: {
    dot: Boolean,
    max: [Number, String],
    color: String,
    content: [Number, String],
    tag: {
      type: String,
      default: 'div'
    }
  },
  methods: {
    hasContent: function hasContent() {
      return !!(this.$scopedSlots.content || isDef(this.content) && this.content !== '');
    },
    renderContent: function renderContent() {
      var dot = this.dot,
        max = this.max,
        content = this.content;
      if (!dot && this.hasContent()) {
        if (this.$scopedSlots.content) {
          return this.$scopedSlots.content();
        }
        if (isDef(max) && isNumeric(content) && +content > max) {
          return max + "+";
        }
        return content;
      }
    },
    renderBadge: function renderBadge() {
      var h = this.$createElement;
      if (this.hasContent() || this.dot) {
        return h("div", {
          "class": bem$19({
            dot: this.dot,
            fixed: !!this.$scopedSlots.default
          }),
          "style": {
            background: this.color
          }
        }, [this.renderContent()]);
      }
    }
  },
  render: function render() {
    var h = arguments[0];
    if (this.$scopedSlots.default) {
      var tag = this.tag;
      return h(tag, {
        "class": bem$19('wrapper')
      }, [this.$scopedSlots.default(), this.renderBadge()]);
    }
    return this.renderBadge();
  }
});

/**
 * requestAnimationFrame polyfill
 */
var prev = Date.now();
/* istanbul ignore next */

function fallback(fn) {
  var curr = Date.now();
  var ms = Math.max(0, 16 - (curr - prev));
  var id = setTimeout(fn, ms);
  prev = curr + ms;
  return id;
}
/* istanbul ignore next */

var root = isServer ? global : window;
/* istanbul ignore next */

var iRaf = root.requestAnimationFrame || fallback;
/* istanbul ignore next */

var iCancel = root.cancelAnimationFrame || root.clearTimeout;
function raf(fn) {
  return iRaf.call(root, fn);
} // double raf for animation

function doubleRaf(fn) {
  raf(function () {
    raf(fn);
  });
}
function cancelRaf(id) {
  iCancel.call(root, id);
}

function isDate(val) {
  return Object.prototype.toString.call(val) === '[object Date]' && !isNaN$1(val.getTime());
}

var _createNamespace$1d = createNamespace('calendar'),
  createComponent$1h = _createNamespace$1d[0],
  bem$18 = _createNamespace$1d[1],
  t$l = _createNamespace$1d[2];
function formatMonthTitle(date) {
  return t$l('monthTitle', date.getFullYear(), date.getMonth() + 1);
}
function compareMonth(date1, date2) {
  var year1 = date1.getFullYear();
  var year2 = date2.getFullYear();
  var month1 = date1.getMonth();
  var month2 = date2.getMonth();
  if (year1 === year2) {
    return month1 === month2 ? 0 : month1 > month2 ? 1 : -1;
  }
  return year1 > year2 ? 1 : -1;
}
function compareDay(day1, day2) {
  var compareMonthResult = compareMonth(day1, day2);
  if (compareMonthResult === 0) {
    var date1 = day1.getDate();
    var date2 = day2.getDate();
    return date1 === date2 ? 0 : date1 > date2 ? 1 : -1;
  }
  return compareMonthResult;
}
function getDayByOffset(date, offset) {
  date = new Date(date);
  date.setDate(date.getDate() + offset);
  return date;
}
function getPrevDay(date) {
  return getDayByOffset(date, -1);
}
function getNextDay(date) {
  return getDayByOffset(date, 1);
}
function calcDateNum(date) {
  var day1 = date[0].getTime();
  var day2 = date[1].getTime();
  return (day2 - day1) / (1000 * 60 * 60 * 24) + 1;
}
function copyDate(dates) {
  return new Date(dates);
}
function copyDates(dates) {
  if (Array.isArray(dates)) {
    return dates.map(function (date) {
      if (date === null) {
        return date;
      }
      return copyDate(date);
    });
  }
  return copyDate(dates);
}

function times(n, iteratee) {
  if (n < 0) {
    return [];
  }
  var index = -1;
  var result = Array(n);
  while (++index < n) {
    result[index] = iteratee(index);
  }
  return result;
}
function getTrueValue(value) {
  if (!value) {
    return 0;
  }
  while (isNaN$1(parseInt(value, 10))) {
    if (value.length > 1) {
      value = value.slice(1);
    } else {
      return 0;
    }
  }
  return parseInt(value, 10);
}
function getMonthEndDay(year, month) {
  return 32 - new Date(year, month - 1, 32).getDate();
}

var _createNamespace$1c = createNamespace('calendar-month'),
  createComponent$1g = _createNamespace$1c[0];
var Month = createComponent$1g({
  props: {
    date: Date,
    type: String,
    color: String,
    minDate: Date,
    maxDate: Date,
    showMark: Boolean,
    rowHeight: [Number, String],
    formatter: Function,
    lazyRender: Boolean,
    currentDate: [Date, Array],
    allowSameDay: Boolean,
    showSubtitle: Boolean,
    showMonthTitle: Boolean,
    firstDayOfWeek: Number
  },
  data: function data() {
    return {
      visible: false
    };
  },
  computed: {
    title: function title() {
      return formatMonthTitle(this.date);
    },
    rowHeightWithUnit: function rowHeightWithUnit() {
      return addUnit(this.rowHeight);
    },
    offset: function offset() {
      var firstDayOfWeek = this.firstDayOfWeek;
      var realDay = this.date.getDay();
      if (!firstDayOfWeek) {
        return realDay;
      }
      return (realDay + 7 - this.firstDayOfWeek) % 7;
    },
    totalDay: function totalDay() {
      return getMonthEndDay(this.date.getFullYear(), this.date.getMonth() + 1);
    },
    shouldRender: function shouldRender() {
      return this.visible || !this.lazyRender;
    },
    placeholders: function placeholders() {
      var rows = [];
      var count = Math.ceil((this.totalDay + this.offset) / 7);
      for (var day = 1; day <= count; day++) {
        rows.push({
          type: 'placeholder'
        });
      }
      return rows;
    },
    days: function days() {
      var days = [];
      var year = this.date.getFullYear();
      var month = this.date.getMonth();
      for (var day = 1; day <= this.totalDay; day++) {
        var date = new Date(year, month, day);
        var type = this.getDayType(date);
        var config = {
          date: date,
          type: type,
          text: day,
          bottomInfo: this.getBottomInfo(type)
        };
        if (this.formatter) {
          config = this.formatter(config);
        }
        days.push(config);
      }
      return days;
    }
  },
  methods: {
    getHeight: function getHeight() {
      var _this$$el;
      return ((_this$$el = this.$el) == null ? void 0 : _this$$el.getBoundingClientRect().height) || 0;
    },
    scrollIntoView: function scrollIntoView(body) {
      var _this$$refs = this.$refs,
        days = _this$$refs.days,
        month = _this$$refs.month;
      var el = this.showSubtitle ? days : month;
      var scrollTop = el.getBoundingClientRect().top - body.getBoundingClientRect().top + body.scrollTop;
      setScrollTop(body, scrollTop);
    },
    getMultipleDayType: function getMultipleDayType(day) {
      var _this = this;
      var isSelected = function isSelected(date) {
        return _this.currentDate.some(function (item) {
          return compareDay(item, date) === 0;
        });
      };
      if (isSelected(day)) {
        var prevDay = getPrevDay(day);
        var nextDay = getNextDay(day);
        var prevSelected = isSelected(prevDay);
        var nextSelected = isSelected(nextDay);
        if (prevSelected && nextSelected) {
          return 'multiple-middle';
        }
        if (prevSelected) {
          return 'end';
        }
        return nextSelected ? 'start' : 'multiple-selected';
      }
      return '';
    },
    getRangeDayType: function getRangeDayType(day) {
      var _this$currentDate = this.currentDate,
        startDay = _this$currentDate[0],
        endDay = _this$currentDate[1];
      if (!startDay) {
        return '';
      }
      var compareToStart = compareDay(day, startDay);
      if (!endDay) {
        return compareToStart === 0 ? 'start' : '';
      }
      var compareToEnd = compareDay(day, endDay);
      if (compareToStart === 0 && compareToEnd === 0 && this.allowSameDay) {
        return 'start-end';
      }
      if (compareToStart === 0) {
        return 'start';
      }
      if (compareToEnd === 0) {
        return 'end';
      }
      if (compareToStart > 0 && compareToEnd < 0) {
        return 'middle';
      }
    },
    getDayType: function getDayType(day) {
      var type = this.type,
        minDate = this.minDate,
        maxDate = this.maxDate,
        currentDate = this.currentDate;
      if (compareDay(day, minDate) < 0 || compareDay(day, maxDate) > 0) {
        return 'disabled';
      }
      if (currentDate === null) {
        return;
      }
      if (type === 'single') {
        return compareDay(day, currentDate) === 0 ? 'selected' : '';
      }
      if (type === 'multiple') {
        return this.getMultipleDayType(day);
      }
      /* istanbul ignore else */

      if (type === 'range') {
        return this.getRangeDayType(day);
      }
    },
    getBottomInfo: function getBottomInfo(type) {
      if (this.type === 'range') {
        if (type === 'start' || type === 'end') {
          return t$l(type);
        }
        if (type === 'start-end') {
          return t$l('startEnd');
        }
      }
    },
    getDayStyle: function getDayStyle(type, index) {
      var style = {
        height: this.rowHeightWithUnit
      };
      if (type === 'placeholder') {
        style.width = '100%';
        return style;
      }
      if (index === 0) {
        style.marginLeft = 100 * this.offset / 7 + "%";
      }
      if (this.color) {
        if (type === 'start' || type === 'end' || type === 'start-end' || type === 'multiple-selected' || type === 'multiple-middle') {
          style.background = this.color;
        } else if (type === 'middle') {
          style.color = this.color;
        }
      }
      return style;
    },
    genTitle: function genTitle() {
      var h = this.$createElement;
      if (this.showMonthTitle) {
        return h("div", {
          "class": bem$18('month-title')
        }, [this.title]);
      }
    },
    genMark: function genMark() {
      var h = this.$createElement;
      if (this.showMark && this.shouldRender) {
        return h("div", {
          "class": bem$18('month-mark')
        }, [this.date.getMonth() + 1]);
      }
    },
    genDays: function genDays() {
      var h = this.$createElement;
      var days = this.shouldRender ? this.days : this.placeholders;
      return h("div", {
        "ref": "days",
        "attrs": {
          "role": "grid"
        },
        "class": bem$18('days')
      }, [this.genMark(), days.map(this.genDay)]);
    },
    genTopInfo: function genTopInfo(item) {
      var h = this.$createElement;
      var slot = this.$scopedSlots['top-info'];
      if (item.topInfo || slot) {
        return h("div", {
          "class": bem$18('top-info')
        }, [slot ? slot(item) : item.topInfo]);
      }
    },
    genBottomInfo: function genBottomInfo(item) {
      var h = this.$createElement;
      var slot = this.$scopedSlots['bottom-info'];
      if (item.bottomInfo || slot) {
        return h("div", {
          "class": bem$18('bottom-info')
        }, [slot ? slot(item) : item.bottomInfo]);
      }
    },
    genDay: function genDay(item, index) {
      var _this2 = this;
      var h = this.$createElement;
      var type = item.type;
      var style = this.getDayStyle(type, index);
      var disabled = type === 'disabled';
      var onClick = function onClick() {
        if (!disabled) {
          _this2.$emit('click', item);
        }
      };
      if (type === 'selected') {
        return h("div", {
          "attrs": {
            "role": "gridcell",
            "tabindex": -1
          },
          "style": style,
          "class": [bem$18('day'), item.className],
          "on": {
            "click": onClick
          }
        }, [h("div", {
          "class": bem$18('selected-day'),
          "style": {
            width: this.rowHeightWithUnit,
            height: this.rowHeightWithUnit,
            background: this.color
          }
        }, [this.genTopInfo(item), item.text, this.genBottomInfo(item)])]);
      }
      return h("div", {
        "attrs": {
          "role": "gridcell",
          "tabindex": disabled ? null : -1
        },
        "style": style,
        "class": [bem$18('day', type), item.className],
        "on": {
          "click": onClick
        }
      }, [this.genTopInfo(item), item.text, this.genBottomInfo(item)]);
    }
  },
  render: function render() {
    var h = arguments[0];
    return h("div", {
      "class": bem$18('month'),
      "ref": "month"
    }, [this.genTitle(), this.genDays()]);
  }
});

var _createNamespace$1b = createNamespace('calendar-header'),
  createComponent$1f = _createNamespace$1b[0];
var Header = createComponent$1f({
  props: {
    title: String,
    subtitle: String,
    showTitle: Boolean,
    showSubtitle: Boolean,
    firstDayOfWeek: Number
  },
  methods: {
    genTitle: function genTitle() {
      var h = this.$createElement;
      if (this.showTitle) {
        var title = this.slots('title') || this.title || t$l('title');
        return h("div", {
          "class": bem$18('header-title')
        }, [title]);
      }
    },
    genSubtitle: function genSubtitle() {
      var h = this.$createElement;
      if (this.showSubtitle) {
        return h("div", {
          "class": bem$18('header-subtitle')
        }, [this.subtitle]);
      }
    },
    genWeekDays: function genWeekDays() {
      var h = this.$createElement;
      var weekdays = t$l('weekdays');
      var firstDayOfWeek = this.firstDayOfWeek;
      var renderWeekDays = [].concat(weekdays.slice(firstDayOfWeek, 7), weekdays.slice(0, firstDayOfWeek));
      return h("div", {
        "class": bem$18('weekdays')
      }, [renderWeekDays.map(function (item) {
        return h("span", {
          "class": bem$18('weekday')
        }, [item]);
      })]);
    }
  },
  render: function render() {
    var h = arguments[0];
    return h("div", {
      "class": bem$18('header')
    }, [this.genTitle(), this.genSubtitle(), this.genWeekDays()]);
  }
});

// Utils
var Calendar = createComponent$1h({
  props: {
    title: String,
    color: String,
    value: Boolean,
    readonly: Boolean,
    formatter: Function,
    rowHeight: [Number, String],
    confirmText: String,
    rangePrompt: String,
    defaultDate: [Date, Array],
    getContainer: [String, Function],
    allowSameDay: Boolean,
    confirmDisabledText: String,
    type: {
      type: String,
      default: 'single'
    },
    round: {
      type: Boolean,
      default: true
    },
    position: {
      type: String,
      default: 'bottom'
    },
    poppable: {
      type: Boolean,
      default: true
    },
    maxRange: {
      type: [Number, String],
      default: null
    },
    lazyRender: {
      type: Boolean,
      default: true
    },
    showMark: {
      type: Boolean,
      default: true
    },
    showTitle: {
      type: Boolean,
      default: true
    },
    showConfirm: {
      type: Boolean,
      default: true
    },
    showSubtitle: {
      type: Boolean,
      default: true
    },
    closeOnPopstate: {
      type: Boolean,
      default: true
    },
    closeOnClickOverlay: {
      type: Boolean,
      default: true
    },
    safeAreaInsetBottom: {
      type: Boolean,
      default: true
    },
    minDate: {
      type: Date,
      validator: isDate,
      default: function _default() {
        return new Date();
      }
    },
    maxDate: {
      type: Date,
      validator: isDate,
      default: function _default() {
        var now = new Date();
        return new Date(now.getFullYear(), now.getMonth() + 6, now.getDate());
      }
    },
    firstDayOfWeek: {
      type: [Number, String],
      default: 0,
      validator: function validator(val) {
        return val >= 0 && val <= 6;
      }
    }
  },
  inject: {
    vanPopup: {
      default: null
    }
  },
  data: function data() {
    return {
      subtitle: '',
      currentDate: this.getInitialDate()
    };
  },
  computed: {
    months: function months() {
      var months = [];
      var cursor = new Date(this.minDate);
      cursor.setDate(1);
      do {
        months.push(new Date(cursor));
        cursor.setMonth(cursor.getMonth() + 1);
      } while (compareMonth(cursor, this.maxDate) !== 1);
      return months;
    },
    buttonDisabled: function buttonDisabled() {
      var type = this.type,
        currentDate = this.currentDate;
      if (currentDate) {
        if (type === 'range') {
          return !currentDate[0] || !currentDate[1];
        }
        if (type === 'multiple') {
          return !currentDate.length;
        }
      }
      return !currentDate;
    },
    dayOffset: function dayOffset() {
      return this.firstDayOfWeek ? this.firstDayOfWeek % 7 : 0;
    }
  },
  watch: {
    value: 'init',
    type: function type() {
      this.reset();
    },
    defaultDate: function defaultDate(val) {
      this.currentDate = val;
      this.scrollIntoView();
    }
  },
  mounted: function mounted() {
    this.init(); // https://github.com/vant-ui/vant/issues/9845

    if (!this.poppable) {
      var _this$vanPopup;
      (_this$vanPopup = this.vanPopup) == null ? void 0 : _this$vanPopup.$on('opened', this.onScroll);
    }
  },
  /* istanbul ignore next */
  activated: function activated() {
    this.init();
  },
  methods: {
    // @exposed-api
    reset: function reset(date) {
      if (date === void 0) {
        date = this.getInitialDate();
      }
      this.currentDate = date;
      this.scrollIntoView();
    },
    init: function init() {
      var _this = this;
      if (this.poppable && !this.value) {
        return;
      }
      this.$nextTick(function () {
        // add Math.floor to avoid decimal height issues
        // https://github.com/vant-ui/vant/issues/5640
        _this.bodyHeight = Math.floor(_this.$refs.body.getBoundingClientRect().height);
        _this.onScroll();
        _this.scrollIntoView();
      });
    },
    // @exposed-api
    scrollToDate: function scrollToDate(targetDate) {
      var _this2 = this;
      raf(function () {
        var displayed = _this2.value || !_this2.poppable;
        /* istanbul ignore if */

        if (!targetDate || !displayed) {
          return;
        }
        _this2.months.some(function (month, index) {
          if (compareMonth(month, targetDate) === 0) {
            var _this2$$refs = _this2.$refs,
              body = _this2$$refs.body,
              months = _this2$$refs.months;
            months[index].scrollIntoView(body);
            return true;
          }
          return false;
        });
        _this2.onScroll();
      });
    },
    // scroll to current month
    scrollIntoView: function scrollIntoView() {
      var currentDate = this.currentDate;
      if (currentDate) {
        var targetDate = this.type === 'single' ? currentDate : currentDate[0];
        this.scrollToDate(targetDate);
      }
    },
    getInitialDate: function getInitialDate() {
      var type = this.type,
        minDate = this.minDate,
        maxDate = this.maxDate,
        defaultDate = this.defaultDate;
      if (defaultDate === null) {
        return defaultDate;
      }
      var defaultVal = new Date();
      if (compareDay(defaultVal, minDate) === -1) {
        defaultVal = minDate;
      } else if (compareDay(defaultVal, maxDate) === 1) {
        defaultVal = maxDate;
      }
      if (type === 'range') {
        var _ref = defaultDate || [],
          startDay = _ref[0],
          endDay = _ref[1];
        return [startDay || defaultVal, endDay || getNextDay(defaultVal)];
      }
      if (type === 'multiple') {
        return defaultDate || [defaultVal];
      }
      return defaultDate || defaultVal;
    },
    // calculate the position of the elements
    // and find the elements that needs to be rendered
    onScroll: function onScroll() {
      var _this$$refs = this.$refs,
        body = _this$$refs.body,
        months = _this$$refs.months;
      var top = getScrollTop(body);
      var bottom = top + this.bodyHeight;
      var heights = months.map(function (item) {
        return item.getHeight();
      });
      var heightSum = heights.reduce(function (a, b) {
        return a + b;
      }, 0); // iOS scroll bounce may exceed the range

      if (bottom > heightSum && top > 0) {
        return;
      }
      var height = 0;
      var currentMonth;
      var visibleRange = [-1, -1];
      for (var i = 0; i < months.length; i++) {
        var visible = height <= bottom && height + heights[i] >= top;
        if (visible) {
          visibleRange[1] = i;
          if (!currentMonth) {
            currentMonth = months[i];
            visibleRange[0] = i;
          }
          if (!months[i].showed) {
            months[i].showed = true;
            this.$emit('month-show', {
              date: months[i].date,
              title: months[i].title
            });
          }
        }
        height += heights[i];
      }
      months.forEach(function (month, index) {
        month.visible = index >= visibleRange[0] - 1 && index <= visibleRange[1] + 1;
      });
      /* istanbul ignore else */

      if (currentMonth) {
        this.subtitle = currentMonth.title;
      }
    },
    onClickDay: function onClickDay(item) {
      if (this.readonly) {
        return;
      }
      var date = item.date;
      var type = this.type,
        currentDate = this.currentDate;
      if (type === 'range') {
        if (!currentDate) {
          this.select([date, null]);
          return;
        }
        var startDay = currentDate[0],
          endDay = currentDate[1];
        if (startDay && !endDay) {
          var compareToStart = compareDay(date, startDay);
          if (compareToStart === 1) {
            this.select([startDay, date], true);
          } else if (compareToStart === -1) {
            this.select([date, null]);
          } else if (this.allowSameDay) {
            this.select([date, date], true);
          }
        } else {
          this.select([date, null]);
        }
      } else if (type === 'multiple') {
        if (!currentDate) {
          this.select([date]);
          return;
        }
        var selectedIndex;
        var selected = this.currentDate.some(function (dateItem, index) {
          var equal = compareDay(dateItem, date) === 0;
          if (equal) {
            selectedIndex = index;
          }
          return equal;
        });
        if (selected) {
          var _currentDate$splice = currentDate.splice(selectedIndex, 1),
            unselectedDate = _currentDate$splice[0];
          this.$emit('unselect', copyDate(unselectedDate));
        } else if (this.maxRange && currentDate.length >= this.maxRange) {
          Toast(this.rangePrompt || t$l('rangePrompt', this.maxRange));
        } else {
          this.select([].concat(currentDate, [date]));
        }
      } else {
        this.select(date, true);
      }
    },
    togglePopup: function togglePopup(val) {
      this.$emit('input', val);
    },
    select: function select(date, complete) {
      var _this3 = this;
      var emit = function emit(date) {
        _this3.currentDate = date;
        _this3.$emit('select', copyDates(_this3.currentDate));
      };
      if (complete && this.type === 'range') {
        var valid = this.checkRange(date);
        if (!valid) {
          // auto selected to max range if showConfirm
          if (this.showConfirm) {
            emit([date[0], getDayByOffset(date[0], this.maxRange - 1)]);
          } else {
            emit(date);
          }
          return;
        }
      }
      emit(date);
      if (complete && !this.showConfirm) {
        this.onConfirm();
      }
    },
    checkRange: function checkRange(date) {
      var maxRange = this.maxRange,
        rangePrompt = this.rangePrompt;
      if (maxRange && calcDateNum(date) > maxRange) {
        Toast(rangePrompt || t$l('rangePrompt', maxRange));
        return false;
      }
      return true;
    },
    onConfirm: function onConfirm() {
      this.$emit('confirm', copyDates(this.currentDate));
    },
    genMonth: function genMonth(date, index) {
      var h = this.$createElement;
      var showMonthTitle = index !== 0 || !this.showSubtitle;
      return h(Month, {
        "ref": "months",
        "refInFor": true,
        "attrs": {
          "date": date,
          "type": this.type,
          "color": this.color,
          "minDate": this.minDate,
          "maxDate": this.maxDate,
          "showMark": this.showMark,
          "formatter": this.formatter,
          "rowHeight": this.rowHeight,
          "lazyRender": this.lazyRender,
          "currentDate": this.currentDate,
          "showSubtitle": this.showSubtitle,
          "allowSameDay": this.allowSameDay,
          "showMonthTitle": showMonthTitle,
          "firstDayOfWeek": this.dayOffset
        },
        "scopedSlots": {
          'top-info': this.$scopedSlots['top-info'],
          'bottom-info': this.$scopedSlots['bottom-info']
        },
        "on": {
          "click": this.onClickDay
        }
      });
    },
    genFooterContent: function genFooterContent() {
      var h = this.$createElement;
      var slot = this.slots('footer');
      if (slot) {
        return slot;
      }
      if (this.showConfirm) {
        var text = this.buttonDisabled ? this.confirmDisabledText : this.confirmText;
        return h(Button$1, {
          "attrs": {
            "round": true,
            "block": true,
            "type": "danger",
            "color": this.color,
            "disabled": this.buttonDisabled,
            "nativeType": "button"
          },
          "class": bem$18('confirm'),
          "on": {
            "click": this.onConfirm
          }
        }, [text || t$l('confirm')]);
      }
    },
    genFooter: function genFooter() {
      var h = this.$createElement;
      return h("div", {
        "class": bem$18('footer', {
          unfit: !this.safeAreaInsetBottom
        })
      }, [this.genFooterContent()]);
    },
    genCalendar: function genCalendar() {
      var _this4 = this;
      var h = this.$createElement;
      return h("div", {
        "class": bem$18()
      }, [h(Header, {
        "attrs": {
          "title": this.title,
          "showTitle": this.showTitle,
          "subtitle": this.subtitle,
          "showSubtitle": this.showSubtitle,
          "firstDayOfWeek": this.dayOffset
        },
        "scopedSlots": {
          title: function title() {
            return _this4.slots('title');
          }
        }
      }), h("div", {
        "ref": "body",
        "class": bem$18('body'),
        "on": {
          "scroll": this.onScroll
        }
      }, [this.months.map(this.genMonth)]), this.genFooter()]);
    }
  },
  render: function render() {
    var _this5 = this;
    var h = arguments[0];
    if (this.poppable) {
      var _attrs;
      var createListener = function createListener(name) {
        return function () {
          return _this5.$emit(name);
        };
      };
      return h(Popup, {
        "attrs": (_attrs = {
          "round": true,
          "value": this.value
        }, _attrs["round"] = this.round, _attrs["position"] = this.position, _attrs["closeable"] = this.showTitle || this.showSubtitle, _attrs["getContainer"] = this.getContainer, _attrs["closeOnPopstate"] = this.closeOnPopstate, _attrs["closeOnClickOverlay"] = this.closeOnClickOverlay, _attrs),
        "class": bem$18('popup'),
        "on": {
          "input": this.togglePopup,
          "open": createListener('open'),
          "opened": createListener('opened'),
          "close": createListener('close'),
          "closed": createListener('closed')
        }
      }, [this.genCalendar()]);
    }
    return this.genCalendar();
  }
});

var _createNamespace$1a = createNamespace('image'),
  createComponent$1e = _createNamespace$1a[0],
  bem$17 = _createNamespace$1a[1];
var Image$1 = createComponent$1e({
  props: {
    src: String,
    fit: String,
    alt: String,
    round: Boolean,
    width: [Number, String],
    height: [Number, String],
    radius: [Number, String],
    lazyLoad: Boolean,
    iconPrefix: String,
    showError: {
      type: Boolean,
      default: true
    },
    showLoading: {
      type: Boolean,
      default: true
    },
    errorIcon: {
      type: String,
      default: 'photo-fail'
    },
    loadingIcon: {
      type: String,
      default: 'photo'
    }
  },
  data: function data() {
    return {
      loading: true,
      error: false
    };
  },
  watch: {
    src: function src() {
      this.loading = true;
      this.error = false;
    }
  },
  computed: {
    style: function style() {
      var style = {};
      if (isDef(this.width)) {
        style.width = addUnit(this.width);
      }
      if (isDef(this.height)) {
        style.height = addUnit(this.height);
      }
      if (isDef(this.radius)) {
        style.overflow = 'hidden';
        style.borderRadius = addUnit(this.radius);
      }
      return style;
    }
  },
  created: function created() {
    var $Lazyload = this.$Lazyload;
    if ($Lazyload && inBrowser) {
      $Lazyload.$on('loaded', this.onLazyLoaded);
      $Lazyload.$on('error', this.onLazyLoadError);
    }
  },
  beforeDestroy: function beforeDestroy() {
    var $Lazyload = this.$Lazyload;
    if ($Lazyload) {
      $Lazyload.$off('loaded', this.onLazyLoaded);
      $Lazyload.$off('error', this.onLazyLoadError);
    }
  },
  methods: {
    onLoad: function onLoad(event) {
      this.loading = false;
      this.$emit('load', event);
    },
    onLazyLoaded: function onLazyLoaded(_ref) {
      var el = _ref.el;
      if (el === this.$refs.image && this.loading) {
        this.onLoad();
      }
    },
    onLazyLoadError: function onLazyLoadError(_ref2) {
      var el = _ref2.el;
      if (el === this.$refs.image && !this.error) {
        this.onError();
      }
    },
    onError: function onError(event) {
      this.error = true;
      this.loading = false;
      this.$emit('error', event);
    },
    onClick: function onClick(event) {
      this.$emit('click', event);
    },
    genPlaceholder: function genPlaceholder() {
      var h = this.$createElement;
      if (this.loading && this.showLoading) {
        return h("div", {
          "class": bem$17('loading')
        }, [this.slots('loading') || h(Icon$1, {
          "attrs": {
            "name": this.loadingIcon,
            "classPrefix": this.iconPrefix
          },
          "class": bem$17('loading-icon')
        })]);
      }
      if (this.error && this.showError) {
        return h("div", {
          "class": bem$17('error')
        }, [this.slots('error') || h(Icon$1, {
          "attrs": {
            "name": this.errorIcon,
            "classPrefix": this.iconPrefix
          },
          "class": bem$17('error-icon')
        })]);
      }
    },
    genImage: function genImage() {
      var h = this.$createElement;
      var imgData = {
        class: bem$17('img'),
        attrs: {
          alt: this.alt
        },
        style: {
          objectFit: this.fit
        }
      };
      if (this.error) {
        return;
      }
      if (this.lazyLoad) {
        return h("img", _mergeJSXProps([{
          "ref": "image",
          "directives": [{
            name: "lazy",
            value: this.src
          }]
        }, imgData]));
      }
      return h("img", _mergeJSXProps([{
        "attrs": {
          "src": this.src
        },
        "on": {
          "load": this.onLoad,
          "error": this.onError
        }
      }, imgData]));
    }
  },
  render: function render() {
    var h = arguments[0];
    return h("div", {
      "class": bem$17({
        round: this.round
      }),
      "style": this.style,
      "on": {
        "click": this.onClick
      }
    }, [this.genImage(), this.genPlaceholder(), this.slots()]);
  }
});

var _createNamespace$19 = createNamespace('card'),
  createComponent$1d = _createNamespace$19[0],
  bem$16 = _createNamespace$19[1];
function Card(h, props, slots, ctx) {
  var _slots$priceTop;
  var thumb = props.thumb;
  var showNum = slots.num || isDef(props.num);
  var showPrice = slots.price || isDef(props.price);
  var showOriginPrice = slots['origin-price'] || isDef(props.originPrice);
  var showBottom = showNum || showPrice || showOriginPrice || slots.bottom;
  function onThumbClick(event) {
    emit(ctx, 'click-thumb', event);
  }
  function ThumbTag() {
    if (slots.tag || props.tag) {
      return h("div", {
        "class": bem$16('tag')
      }, [slots.tag ? slots.tag() : h(Tag$1, {
        "attrs": {
          "mark": true,
          "type": "danger"
        }
      }, [props.tag])]);
    }
  }
  function Thumb() {
    if (slots.thumb || thumb) {
      return h("a", {
        "attrs": {
          "href": props.thumbLink
        },
        "class": bem$16('thumb'),
        "on": {
          "click": onThumbClick
        }
      }, [slots.thumb ? slots.thumb() : h(Image$1, {
        "attrs": {
          "src": thumb,
          "width": "100%",
          "height": "100%",
          "fit": "cover",
          "lazy-load": props.lazyLoad
        }
      }), ThumbTag()]);
    }
  }
  function Title() {
    if (slots.title) {
      return slots.title();
    }
    if (props.title) {
      return h("div", {
        "class": [bem$16('title'), 'van-multi-ellipsis--l2']
      }, [props.title]);
    }
  }
  function Desc() {
    if (slots.desc) {
      return slots.desc();
    }
    if (props.desc) {
      return h("div", {
        "class": [bem$16('desc'), 'van-ellipsis']
      }, [props.desc]);
    }
  }
  function PriceContent() {
    var priceArr = props.price.toString().split('.');
    return h("div", [h("span", {
      "class": bem$16('price-currency')
    }, [props.currency]), h("span", {
      "class": bem$16('price-integer')
    }, [priceArr[0]]), ".", h("span", {
      "class": bem$16('price-decimal')
    }, [priceArr[1]])]);
  }
  function Price() {
    if (showPrice) {
      return h("div", {
        "class": bem$16('price')
      }, [slots.price ? slots.price() : PriceContent()]);
    }
  }
  function OriginPrice() {
    if (showOriginPrice) {
      var slot = slots['origin-price'];
      return h("div", {
        "class": bem$16('origin-price')
      }, [slot ? slot() : props.currency + " " + props.originPrice]);
    }
  }
  function Num() {
    if (showNum) {
      return h("div", {
        "class": bem$16('num')
      }, [slots.num ? slots.num() : "x" + props.num]);
    }
  }
  function Footer() {
    if (slots.footer) {
      return h("div", {
        "class": bem$16('footer')
      }, [slots.footer()]);
    }
  }
  return h("div", _mergeJSXProps([{
    "class": bem$16()
  }, inherit(ctx, true)]), [h("div", {
    "class": bem$16('header')
  }, [Thumb(), h("div", {
    "class": bem$16('content', {
      centered: props.centered
    })
  }, [h("div", [Title(), Desc(), slots.tags == null ? void 0 : slots.tags()]), showBottom && h("div", {
    "class": "van-card__bottom"
  }, [(_slots$priceTop = slots['price-top']) == null ? void 0 : _slots$priceTop.call(slots), Price(), OriginPrice(), Num(), slots.bottom == null ? void 0 : slots.bottom()])])]), Footer()]);
}
Card.props = {
  tag: String,
  desc: String,
  thumb: String,
  title: String,
  centered: Boolean,
  lazyLoad: Boolean,
  thumbLink: String,
  num: [Number, String],
  price: [Number, String],
  originPrice: [Number, String],
  currency: {
    type: String,
    default: '¥'
  }
};
var Card$1 = createComponent$1d(Card);

var _createNamespace$18 = createNamespace('tab'),
  createComponent$1c = _createNamespace$18[0],
  bem$15 = _createNamespace$18[1];
var Tab = createComponent$1c({
  mixins: [ChildrenMixin('vanTabs')],
  props: _extends$1({}, routeProps, {
    dot: Boolean,
    name: [Number, String],
    // @deprecated
    info: [Number, String],
    badge: [Number, String],
    title: String,
    titleStyle: null,
    titleClass: null,
    disabled: Boolean
  }),
  data: function data() {
    return {
      inited: false
    };
  },
  computed: {
    computedName: function computedName() {
      var _this$name;
      return (_this$name = this.name) != null ? _this$name : this.index;
    },
    isActive: function isActive() {
      var active = this.computedName === this.parent.currentName;
      if (active) {
        this.inited = true;
      }
      return active;
    }
  },
  watch: {
    title: function title() {
      this.parent.setLine();
      this.parent.scrollIntoView();
    },
    inited: function inited(val) {
      var _this = this;
      if (this.parent.lazyRender && val) {
        this.$nextTick(function () {
          _this.parent.$emit('rendered', _this.computedName, _this.title);
        });
      }
    }
  },
  render: function render(h) {
    var slots = this.slots,
      parent = this.parent,
      isActive = this.isActive;
    var slotContent = slots();
    if (!slotContent && !parent.animated) {
      return;
    }
    var show = parent.scrollspy || isActive;
    var shouldRender = this.inited || parent.scrollspy || !parent.lazyRender;
    var Content = shouldRender ? slotContent : h();
    if (parent.animated) {
      return h("div", {
        "attrs": {
          "role": "tabpanel",
          "aria-hidden": !isActive
        },
        "class": bem$15('pane-wrapper', {
          inactive: !isActive
        })
      }, [h("div", {
        "class": bem$15('pane')
      }, [Content])]);
    }
    return h("div", {
      "directives": [{
        name: "show",
        value: show
      }],
      "attrs": {
        "role": "tabpanel"
      },
      "class": bem$15('pane')
    }, [Content]);
  }
});

function scrollLeftTo(scroller, to, duration) {
  var count = 0;
  var from = scroller.scrollLeft;
  var frames = duration === 0 ? 1 : Math.round(duration * 1000 / 16);
  function animate() {
    scroller.scrollLeft += (to - from) / frames;
    if (++count < frames) {
      raf(animate);
    }
  }
  animate();
}
function scrollTopTo(scroller, to, duration, callback) {
  var current = getScrollTop(scroller);
  var isDown = current < to;
  var frames = duration === 0 ? 1 : Math.round(duration * 1000 / 16);
  var step = (to - current) / frames;
  function animate() {
    current += step;
    if (isDown && current > to || !isDown && current < to) {
      current = to;
    }
    setScrollTop(scroller, current);
    if (isDown && current < to || !isDown && current > to) {
      raf(animate);
    } else if (callback) {
      raf(callback);
    }
  }
  animate();
}

function isHidden(el) {
  var style = window.getComputedStyle(el);
  var hidden = style.display === 'none'; // offsetParent returns null in the following situations:
  // 1. The element or its parent element has the display property set to none.
  // 2. The element has the position property set to fixed

  var parentHidden = el.offsetParent === null && style.position !== 'fixed';
  return hidden || parentHidden;
}

function callInterceptor(options) {
  var interceptor = options.interceptor,
    args = options.args,
    done = options.done;
  if (interceptor) {
    var returnVal = interceptor.apply(void 0, args);
    if (isPromise(returnVal)) {
      returnVal.then(function (value) {
        if (value) {
          done();
        }
      }).catch(noop);
    } else if (returnVal) {
      done();
    }
  } else {
    done();
  }
}

var _createNamespace$17 = createNamespace('tab'),
  createComponent$1b = _createNamespace$17[0],
  bem$14 = _createNamespace$17[1];
var Title = createComponent$1b({
  props: {
    dot: Boolean,
    type: String,
    info: [Number, String],
    color: String,
    title: String,
    isActive: Boolean,
    disabled: Boolean,
    scrollable: Boolean,
    activeColor: String,
    inactiveColor: String
  },
  computed: {
    style: function style() {
      var style = {};
      var color = this.color,
        isActive = this.isActive;
      var isCard = this.type === 'card'; // card theme color

      if (color && isCard) {
        style.borderColor = color;
        if (!this.disabled) {
          if (isActive) {
            style.backgroundColor = color;
          } else {
            style.color = color;
          }
        }
      }
      var titleColor = isActive ? this.activeColor : this.inactiveColor;
      if (titleColor) {
        style.color = titleColor;
      }
      return style;
    }
  },
  methods: {
    onClick: function onClick() {
      this.$emit('click');
    },
    genText: function genText() {
      var h = this.$createElement;
      var Text = h("span", {
        "class": bem$14('text', {
          ellipsis: !this.scrollable
        })
      }, [this.slots() || this.title]);
      if (this.dot || isDef(this.info) && this.info !== '') {
        return h("span", {
          "class": bem$14('text-wrapper')
        }, [Text, h(Info$1, {
          "attrs": {
            "dot": this.dot,
            "info": this.info
          }
        })]);
      }
      return Text;
    }
  },
  render: function render() {
    var h = arguments[0];
    return h("div", {
      "attrs": {
        "role": "tab",
        "aria-selected": this.isActive
      },
      "class": [bem$14({
        active: this.isActive,
        disabled: this.disabled
      })],
      "style": this.style,
      "on": {
        "click": this.onClick
      }
    }, [this.genText()]);
  }
});

var _createNamespace$16 = createNamespace('sticky'),
  createComponent$1a = _createNamespace$16[0],
  bem$13 = _createNamespace$16[1];
var Sticky = createComponent$1a({
  mixins: [BindEventMixin(function (bind, isBind) {
    if (!this.scroller) {
      this.scroller = getScroller(this.$el);
    }
    if (this.observer) {
      var method = isBind ? 'observe' : 'unobserve';
      this.observer[method](this.$el);
    }
    bind(this.scroller, 'scroll', this.onScroll, true);
    this.onScroll();
  })],
  props: {
    zIndex: [Number, String],
    container: null,
    offsetTop: {
      type: [Number, String],
      default: 0
    }
  },
  data: function data() {
    return {
      fixed: false,
      height: 0,
      transform: 0
    };
  },
  computed: {
    offsetTopPx: function offsetTopPx() {
      return unitToPx(this.offsetTop);
    },
    style: function style() {
      if (!this.fixed) {
        return;
      }
      var style = {};
      if (isDef(this.zIndex)) {
        style.zIndex = this.zIndex;
      }
      if (this.offsetTopPx && this.fixed) {
        style.top = this.offsetTopPx + "px";
      }
      if (this.transform) {
        style.transform = "translate3d(0, " + this.transform + "px, 0)";
      }
      return style;
    }
  },
  watch: {
    fixed: function fixed(isFixed) {
      this.$emit('change', isFixed);
    }
  },
  created: function created() {
    var _this = this;

    // compatibility: https://caniuse.com/#feat=intersectionobserver
    if (!isServer && window.IntersectionObserver) {
      this.observer = new IntersectionObserver(function (entries) {
        // trigger scroll when visibility changed
        if (entries[0].intersectionRatio > 0) {
          _this.onScroll();
        }
      }, {
        root: document.body
      });
    }
  },
  methods: {
    onScroll: function onScroll() {
      var _this2 = this;
      if (isHidden(this.$el)) {
        return;
      }
      this.height = this.$el.offsetHeight;
      var container = this.container,
        offsetTopPx = this.offsetTopPx;
      var scrollTop = getScrollTop(window);
      var topToPageTop = getElementTop(this.$el);
      var emitScrollEvent = function emitScrollEvent() {
        _this2.$emit('scroll', {
          scrollTop: scrollTop,
          isFixed: _this2.fixed
        });
      }; // The sticky component should be kept inside the container element

      if (container) {
        var bottomToPageTop = topToPageTop + container.offsetHeight;
        if (scrollTop + offsetTopPx + this.height > bottomToPageTop) {
          var distanceToBottom = this.height + scrollTop - bottomToPageTop;
          if (distanceToBottom < this.height) {
            this.fixed = true;
            this.transform = -(distanceToBottom + offsetTopPx);
          } else {
            this.fixed = false;
          }
          emitScrollEvent();
          return;
        }
      }
      if (scrollTop + offsetTopPx > topToPageTop) {
        this.fixed = true;
        this.transform = 0;
      } else {
        this.fixed = false;
      }
      emitScrollEvent();
    }
  },
  render: function render() {
    var h = arguments[0];
    var fixed = this.fixed;
    var style = {
      height: fixed ? this.height + "px" : null
    };
    return h("div", {
      "style": style
    }, [h("div", {
      "class": bem$13({
        fixed: fixed
      }),
      "style": this.style
    }, [this.slots()])]);
  }
});

var _createNamespace$15 = createNamespace('tabs'),
  createComponent$19 = _createNamespace$15[0],
  bem$12 = _createNamespace$15[1];
var MIN_SWIPE_DISTANCE = 50;
var Content = createComponent$19({
  mixins: [TouchMixin],
  props: {
    count: Number,
    duration: [Number, String],
    animated: Boolean,
    swipeable: Boolean,
    currentIndex: Number
  },
  computed: {
    style: function style() {
      if (this.animated) {
        return {
          transform: "translate3d(" + -1 * this.currentIndex * 100 + "%, 0, 0)",
          transitionDuration: this.duration + "s"
        };
      }
    },
    listeners: function listeners() {
      if (this.swipeable) {
        return {
          touchstart: this.touchStart,
          touchmove: this.touchMove,
          touchend: this.onTouchEnd,
          touchcancel: this.onTouchEnd
        };
      }
    }
  },
  methods: {
    // watch swipe touch end
    onTouchEnd: function onTouchEnd() {
      var direction = this.direction,
        deltaX = this.deltaX,
        currentIndex = this.currentIndex;
      /* istanbul ignore else */

      if (direction === 'horizontal' && this.offsetX >= MIN_SWIPE_DISTANCE) {
        /* istanbul ignore else */
        if (deltaX > 0 && currentIndex !== 0) {
          this.$emit('change', currentIndex - 1);
        } else if (deltaX < 0 && currentIndex !== this.count - 1) {
          this.$emit('change', currentIndex + 1);
        }
      }
    },
    genChildren: function genChildren() {
      var h = this.$createElement;
      if (this.animated) {
        return h("div", {
          "class": bem$12('track'),
          "style": this.style
        }, [this.slots()]);
      }
      return this.slots();
    }
  },
  render: function render() {
    var h = arguments[0];
    return h("div", {
      "class": bem$12('content', {
        animated: this.animated
      }),
      "on": _extends$1({}, this.listeners)
    }, [this.genChildren()]);
  }
});

// Utils
var _createNamespace$14 = createNamespace('tabs'),
  createComponent$18 = _createNamespace$14[0],
  bem$11 = _createNamespace$14[1];
var Tabs = createComponent$18({
  mixins: [ParentMixin('vanTabs'), BindEventMixin(function (bind) {
    if (!this.scroller) {
      this.scroller = getScroller(this.$el);
    }
    bind(window, 'resize', this.resize, true);
    if (this.scrollspy) {
      bind(this.scroller, 'scroll', this.onScroll, true);
    }
  })],
  inject: {
    vanPopup: {
      default: null
    }
  },
  model: {
    prop: 'active'
  },
  props: {
    color: String,
    border: Boolean,
    sticky: Boolean,
    animated: Boolean,
    swipeable: Boolean,
    scrollspy: Boolean,
    background: String,
    lineWidth: [Number, String],
    lineHeight: [Number, String],
    beforeChange: Function,
    titleActiveColor: String,
    titleInactiveColor: String,
    type: {
      type: String,
      default: 'line'
    },
    active: {
      type: [Number, String],
      default: 0
    },
    ellipsis: {
      type: Boolean,
      default: true
    },
    duration: {
      type: [Number, String],
      default: 0.3
    },
    offsetTop: {
      type: [Number, String],
      default: 0
    },
    lazyRender: {
      type: Boolean,
      default: true
    },
    swipeThreshold: {
      type: [Number, String],
      default: 5
    }
  },
  data: function data() {
    return {
      position: '',
      currentIndex: null,
      lineStyle: {
        backgroundColor: this.color
      }
    };
  },
  computed: {
    // whether the nav is scrollable
    scrollable: function scrollable() {
      return this.children.length > this.swipeThreshold || !this.ellipsis;
    },
    navStyle: function navStyle() {
      return {
        borderColor: this.color,
        background: this.background
      };
    },
    currentName: function currentName() {
      var activeTab = this.children[this.currentIndex];
      if (activeTab) {
        return activeTab.computedName;
      }
    },
    offsetTopPx: function offsetTopPx() {
      return unitToPx(this.offsetTop);
    },
    scrollOffset: function scrollOffset() {
      if (this.sticky) {
        return this.offsetTopPx + this.tabHeight;
      }
      return 0;
    }
  },
  watch: {
    color: 'setLine',
    active: function active(name) {
      if (name !== this.currentName) {
        this.setCurrentIndexByName(name);
      }
    },
    children: function children() {
      var _this = this;
      this.setCurrentIndexByName(this.active);
      this.setLine();
      this.$nextTick(function () {
        _this.scrollIntoView(true);
      });
    },
    currentIndex: function currentIndex() {
      this.scrollIntoView();
      this.setLine(); // scroll to correct position

      if (this.stickyFixed && !this.scrollspy) {
        setRootScrollTop(Math.ceil(getElementTop(this.$el) - this.offsetTopPx));
      }
    },
    scrollspy: function scrollspy(val) {
      if (val) {
        on(this.scroller, 'scroll', this.onScroll, true);
      } else {
        off(this.scroller, 'scroll', this.onScroll);
      }
    }
  },
  mounted: function mounted() {
    var _this2 = this;
    this.init(); // https://github.com/vant-ui/vant/issues/7959

    if (this.vanPopup) {
      this.vanPopup.onReopen(function () {
        _this2.setLine();
      });
    }
  },
  activated: function activated() {
    this.init();
    this.setLine();
  },
  methods: {
    // @exposed-api
    resize: function resize() {
      this.setLine();
    },
    init: function init() {
      var _this3 = this;
      this.$nextTick(function () {
        _this3.inited = true;
        _this3.tabHeight = getVisibleHeight(_this3.$refs.wrap);
        _this3.scrollIntoView(true);
      });
    },
    // update nav bar style
    setLine: function setLine() {
      var _this4 = this;
      var shouldAnimate = this.inited;
      this.$nextTick(function () {
        var titles = _this4.$refs.titles;
        if (!titles || !titles[_this4.currentIndex] || _this4.type !== 'line' || isHidden(_this4.$el)) {
          return;
        }
        var title = titles[_this4.currentIndex].$el;
        var lineWidth = _this4.lineWidth,
          lineHeight = _this4.lineHeight;
        var left = title.offsetLeft + title.offsetWidth / 2;
        var lineStyle = {
          width: addUnit(lineWidth),
          backgroundColor: _this4.color,
          transform: "translateX(" + left + "px) translateX(-50%)"
        };
        if (shouldAnimate) {
          lineStyle.transitionDuration = _this4.duration + "s";
        }
        if (isDef(lineHeight)) {
          var height = addUnit(lineHeight);
          lineStyle.height = height;
          lineStyle.borderRadius = height;
        }
        _this4.lineStyle = lineStyle;
      });
    },
    // correct the index of active tab
    setCurrentIndexByName: function setCurrentIndexByName(name) {
      var matched = this.children.filter(function (tab) {
        return tab.computedName === name;
      });
      var defaultIndex = (this.children[0] || {}).index || 0;
      this.setCurrentIndex(matched.length ? matched[0].index : defaultIndex);
    },
    setCurrentIndex: function setCurrentIndex(currentIndex) {
      var newIndex = this.findAvailableTab(currentIndex);
      if (!isDef(newIndex)) {
        return;
      }
      var newTab = this.children[newIndex];
      var newName = newTab.computedName;
      var shouldEmitChange = this.currentIndex !== null;
      this.currentIndex = newIndex;
      if (newName !== this.active) {
        this.$emit('input', newName);
        if (shouldEmitChange) {
          this.$emit('change', newName, newTab.title);
        }
      }
    },
    findAvailableTab: function findAvailableTab(index) {
      var diff = index < this.currentIndex ? -1 : 1;
      while (index >= 0 && index < this.children.length) {
        if (!this.children[index].disabled) {
          return index;
        }
        index += diff;
      }
    },
    // emit event when clicked
    onClick: function onClick(item, index) {
      var _this5 = this;
      var _this$children$index = this.children[index],
        title = _this$children$index.title,
        disabled = _this$children$index.disabled,
        computedName = _this$children$index.computedName;
      if (disabled) {
        this.$emit('disabled', computedName, title);
      } else {
        callInterceptor({
          interceptor: this.beforeChange,
          args: [computedName],
          done: function done() {
            _this5.setCurrentIndex(index);
            _this5.scrollToCurrentContent();
          }
        });
        this.$emit('click', computedName, title);
        route(item.$router, item);
      }
    },
    // scroll active tab into view
    scrollIntoView: function scrollIntoView(immediate) {
      var titles = this.$refs.titles;
      if (!this.scrollable || !titles || !titles[this.currentIndex]) {
        return;
      }
      var nav = this.$refs.nav;
      var title = titles[this.currentIndex].$el;
      var to = title.offsetLeft - (nav.offsetWidth - title.offsetWidth) / 2;
      scrollLeftTo(nav, to, immediate ? 0 : +this.duration);
    },
    onSticktScroll: function onSticktScroll(params) {
      this.stickyFixed = params.isFixed;
      this.$emit('scroll', params);
    },
    // @exposed-api
    scrollTo: function scrollTo(name) {
      var _this6 = this;
      this.$nextTick(function () {
        _this6.setCurrentIndexByName(name);
        _this6.scrollToCurrentContent(true);
      });
    },
    scrollToCurrentContent: function scrollToCurrentContent(immediate) {
      var _this7 = this;
      if (immediate === void 0) {
        immediate = false;
      }
      if (this.scrollspy) {
        var target = this.children[this.currentIndex];
        var el = target == null ? void 0 : target.$el;
        if (el) {
          var to = getElementTop(el, this.scroller) - this.scrollOffset;
          this.lockScroll = true;
          scrollTopTo(this.scroller, to, immediate ? 0 : +this.duration, function () {
            _this7.lockScroll = false;
          });
        }
      }
    },
    onScroll: function onScroll() {
      if (this.scrollspy && !this.lockScroll) {
        var index = this.getCurrentIndexOnScroll();
        this.setCurrentIndex(index);
      }
    },
    getCurrentIndexOnScroll: function getCurrentIndexOnScroll() {
      var children = this.children;
      for (var index = 0; index < children.length; index++) {
        var top = getVisibleTop(children[index].$el);
        if (top > this.scrollOffset) {
          return index === 0 ? 0 : index - 1;
        }
      }
      return children.length - 1;
    }
  },
  render: function render() {
    var _this8 = this,
      _ref;
    var h = arguments[0];
    var type = this.type,
      animated = this.animated,
      scrollable = this.scrollable;
    var Nav = this.children.map(function (item, index) {
      var _item$badge;
      return h(Title, {
        "ref": "titles",
        "refInFor": true,
        "attrs": {
          "type": type,
          "dot": item.dot,
          "info": (_item$badge = item.badge) != null ? _item$badge : item.info,
          "title": item.title,
          "color": _this8.color,
          "isActive": index === _this8.currentIndex,
          "disabled": item.disabled,
          "scrollable": scrollable,
          "activeColor": _this8.titleActiveColor,
          "inactiveColor": _this8.titleInactiveColor
        },
        "style": item.titleStyle,
        "class": item.titleClass,
        "scopedSlots": {
          default: function _default() {
            return item.slots('title');
          }
        },
        "on": {
          "click": function click() {
            _this8.onClick(item, index);
          }
        }
      });
    });
    var Wrap = h("div", {
      "ref": "wrap",
      "class": [bem$11('wrap', {
        scrollable: scrollable
      }), (_ref = {}, _ref[BORDER_TOP_BOTTOM] = type === 'line' && this.border, _ref)]
    }, [h("div", {
      "ref": "nav",
      "attrs": {
        "role": "tablist"
      },
      "class": bem$11('nav', [type, {
        complete: this.scrollable
      }]),
      "style": this.navStyle
    }, [this.slots('nav-left'), Nav, type === 'line' && h("div", {
      "class": bem$11('line'),
      "style": this.lineStyle
    }), this.slots('nav-right')])]);
    return h("div", {
      "class": bem$11([type])
    }, [this.sticky ? h(Sticky, {
      "attrs": {
        "container": this.$el,
        "offsetTop": this.offsetTop
      },
      "on": {
        "scroll": this.onSticktScroll
      }
    }, [Wrap]) : Wrap, h(Content, {
      "attrs": {
        "count": this.children.length,
        "animated": animated,
        "duration": this.duration,
        "swipeable": this.swipeable,
        "currentIndex": this.currentIndex
      },
      "on": {
        "change": this.setCurrentIndex
      }
    }, [this.slots()])]);
  }
});

var _createNamespace$13 = createNamespace('cascader'),
  createComponent$17 = _createNamespace$13[0],
  bem$10 = _createNamespace$13[1],
  t$k = _createNamespace$13[2];
var Cascader = createComponent$17({
  props: {
    title: String,
    value: [Number, String],
    fieldNames: Object,
    placeholder: String,
    activeColor: String,
    options: {
      type: Array,
      default: function _default() {
        return [];
      }
    },
    closeable: {
      type: Boolean,
      default: true
    },
    showHeader: {
      type: Boolean,
      default: true
    }
  },
  data: function data() {
    return {
      tabs: [],
      activeTab: 0
    };
  },
  computed: {
    textKey: function textKey() {
      var _this$fieldNames;
      return ((_this$fieldNames = this.fieldNames) == null ? void 0 : _this$fieldNames.text) || 'text';
    },
    valueKey: function valueKey() {
      var _this$fieldNames2;
      return ((_this$fieldNames2 = this.fieldNames) == null ? void 0 : _this$fieldNames2.value) || 'value';
    },
    childrenKey: function childrenKey() {
      var _this$fieldNames3;
      return ((_this$fieldNames3 = this.fieldNames) == null ? void 0 : _this$fieldNames3.children) || 'children';
    }
  },
  watch: {
    options: {
      deep: true,
      handler: 'updateTabs'
    },
    value: function value(_value) {
      var _this = this;
      if (_value || _value === 0) {
        var values = this.tabs.map(function (tab) {
          var _tab$selectedOption;
          return (_tab$selectedOption = tab.selectedOption) == null ? void 0 : _tab$selectedOption[_this.valueKey];
        });
        if (values.indexOf(_value) !== -1) {
          return;
        }
      }
      this.updateTabs();
    }
  },
  created: function created() {
    this.updateTabs();
  },
  methods: {
    getSelectedOptionsByValue: function getSelectedOptionsByValue(options, value) {
      for (var i = 0; i < options.length; i++) {
        var option = options[i];
        if (option[this.valueKey] === value) {
          return [option];
        }
        if (option[this.childrenKey]) {
          var selectedOptions = this.getSelectedOptionsByValue(option[this.childrenKey], value);
          if (selectedOptions) {
            return [option].concat(selectedOptions);
          }
        }
      }
    },
    updateTabs: function updateTabs() {
      var _this2 = this;
      if (this.value || this.value === 0) {
        var selectedOptions = this.getSelectedOptionsByValue(this.options, this.value);
        if (selectedOptions) {
          var optionsCursor = this.options;
          this.tabs = selectedOptions.map(function (option) {
            var tab = {
              options: optionsCursor,
              selectedOption: option
            };
            var next = optionsCursor.filter(function (item) {
              return item[_this2.valueKey] === option[_this2.valueKey];
            });
            if (next.length) {
              optionsCursor = next[0][_this2.childrenKey];
            }
            return tab;
          });
          if (optionsCursor) {
            this.tabs.push({
              options: optionsCursor,
              selectedOption: null
            });
          }
          this.$nextTick(function () {
            _this2.activeTab = _this2.tabs.length - 1;
          });
          return;
        }
      }
      this.tabs = [{
        options: this.options,
        selectedOption: null
      }];
    },
    onSelect: function onSelect(option, tabIndex) {
      var _this3 = this;
      this.tabs[tabIndex].selectedOption = option;
      if (this.tabs.length > tabIndex + 1) {
        this.tabs = this.tabs.slice(0, tabIndex + 1);
      }
      if (option[this.childrenKey]) {
        var nextTab = {
          options: option[this.childrenKey],
          selectedOption: null
        };
        if (this.tabs[tabIndex + 1]) {
          this.$set(this.tabs, tabIndex + 1, nextTab);
        } else {
          this.tabs.push(nextTab);
        }
        this.$nextTick(function () {
          _this3.activeTab++;
        });
      }
      var selectedOptions = this.tabs.map(function (tab) {
        return tab.selectedOption;
      }).filter(function (item) {
        return !!item;
      });
      var eventParams = {
        value: option[this.valueKey],
        tabIndex: tabIndex,
        selectedOptions: selectedOptions
      };
      this.$emit('input', option[this.valueKey]);
      this.$emit('change', eventParams);
      if (!option[this.childrenKey]) {
        this.$emit('finish', eventParams);
      }
    },
    onClose: function onClose() {
      this.$emit('close');
    },
    renderHeader: function renderHeader() {
      var h = this.$createElement;
      if (this.showHeader) {
        return h("div", {
          "class": bem$10('header')
        }, [h("h2", {
          "class": bem$10('title')
        }, [this.slots('title') || this.title]), this.closeable ? h(Icon$1, {
          "attrs": {
            "name": "cross"
          },
          "class": bem$10('close-icon'),
          "on": {
            "click": this.onClose
          }
        }) : null]);
      }
    },
    renderOptions: function renderOptions(options, selectedOption, tabIndex) {
      var _this4 = this;
      var h = this.$createElement;
      var renderOption = function renderOption(option) {
        var isSelected = selectedOption && option[_this4.valueKey] === selectedOption[_this4.valueKey];
        var Text = _this4.slots('option', {
          option: option,
          selected: isSelected
        }) || h("span", [option[_this4.textKey]]);
        return h("li", {
          "class": bem$10('option', {
            selected: isSelected
          }),
          "style": {
            color: isSelected ? _this4.activeColor : null
          },
          "on": {
            "click": function click() {
              _this4.onSelect(option, tabIndex);
            }
          }
        }, [Text, isSelected ? h(Icon$1, {
          "attrs": {
            "name": "success"
          },
          "class": bem$10('selected-icon')
        }) : null]);
      };
      return h("ul", {
        "class": bem$10('options')
      }, [options.map(renderOption)]);
    },
    renderTab: function renderTab(item, tabIndex) {
      var h = this.$createElement;
      var options = item.options,
        selectedOption = item.selectedOption;
      var title = selectedOption ? selectedOption[this.textKey] : this.placeholder || t$k('select');
      return h(Tab, {
        "attrs": {
          "title": title,
          "titleClass": bem$10('tab', {
            unselected: !selectedOption
          })
        }
      }, [this.renderOptions(options, selectedOption, tabIndex)]);
    },
    renderTabs: function renderTabs() {
      var _this5 = this;
      var h = this.$createElement;
      return h(Tabs, {
        "attrs": {
          "animated": true,
          "swipeable": true,
          "swipeThreshold": 0,
          "color": this.activeColor
        },
        "class": bem$10('tabs'),
        "model": {
          value: _this5.activeTab,
          callback: function callback($$v) {
            _this5.activeTab = $$v;
          }
        }
      }, [this.tabs.map(this.renderTab)]);
    }
  },
  render: function render() {
    var h = arguments[0];
    return h("div", {
      "class": bem$10()
    }, [this.renderHeader(), this.renderTabs()]);
  }
});

var _createNamespace$12 = createNamespace('cell-group'),
  createComponent$16 = _createNamespace$12[0],
  bem$$ = _createNamespace$12[1];
function CellGroup(h, props, slots, ctx) {
  var _ref;
  var Group = h("div", _mergeJSXProps([{
    "class": [bem$$({
      inset: props.inset
    }), (_ref = {}, _ref[BORDER_TOP_BOTTOM] = props.border, _ref)]
  }, inherit(ctx, true)]), [slots.default == null ? void 0 : slots.default()]);
  if (props.title || slots.title) {
    return h("div", {
      "key": ctx.data.key
    }, [h("div", {
      "class": bem$$('title', {
        inset: props.inset
      })
    }, [slots.title ? slots.title() : props.title]), Group]);
  }
  return Group;
}
CellGroup.props = {
  title: String,
  inset: Boolean,
  border: {
    type: Boolean,
    default: true
  }
};
var CellGroup$1 = createComponent$16(CellGroup);

var _createNamespace$11 = createNamespace('checkbox'),
  createComponent$15 = _createNamespace$11[0],
  bem$_ = _createNamespace$11[1];
var Checkbox = createComponent$15({
  mixins: [CheckboxMixin({
    bem: bem$_,
    role: 'checkbox',
    parent: 'vanCheckbox'
  })],
  computed: {
    checked: {
      get: function get() {
        if (this.parent) {
          return this.parent.value.indexOf(this.name) !== -1;
        }
        return this.value;
      },
      set: function set(val) {
        if (this.parent) {
          this.setParentValue(val);
        } else {
          this.$emit('input', val);
        }
      }
    }
  },
  watch: {
    value: function value(val) {
      this.$emit('change', val);
    }
  },
  methods: {
    // @exposed-api
    toggle: function toggle(checked) {
      var _this = this;
      if (checked === void 0) {
        checked = !this.checked;
      }

      // When toggle method is called multiple times at the same time,
      // only the last call is valid.
      // This is a hack for usage inside Cell.
      clearTimeout(this.toggleTask);
      this.toggleTask = setTimeout(function () {
        _this.checked = checked;
      });
    },
    setParentValue: function setParentValue(val) {
      var parent = this.parent;
      var value = parent.value.slice();
      if (val) {
        if (parent.max && value.length >= parent.max) {
          return;
        }
        /* istanbul ignore else */

        if (value.indexOf(this.name) === -1) {
          value.push(this.name);
          parent.$emit('input', value);
        }
      } else {
        var index = value.indexOf(this.name);
        /* istanbul ignore else */

        if (index !== -1) {
          value.splice(index, 1);
          parent.$emit('input', value);
        }
      }
    }
  }
});

var _createNamespace$10 = createNamespace('checkbox-group'),
  createComponent$14 = _createNamespace$10[0],
  bem$Z = _createNamespace$10[1];
var CheckboxGroup = createComponent$14({
  mixins: [ParentMixin('vanCheckbox'), FieldMixin],
  props: {
    max: [Number, String],
    disabled: Boolean,
    direction: String,
    iconSize: [Number, String],
    checkedColor: String,
    value: {
      type: Array,
      default: function _default() {
        return [];
      }
    }
  },
  watch: {
    value: function value(val) {
      this.$emit('change', val);
    }
  },
  methods: {
    // @exposed-api
    toggleAll: function toggleAll(options) {
      if (options === void 0) {
        options = {};
      }
      if (typeof options === 'boolean') {
        options = {
          checked: options
        };
      }
      var _options = options,
        checked = _options.checked,
        skipDisabled = _options.skipDisabled;
      var children = this.children.filter(function (item) {
        if (item.disabled && skipDisabled) {
          return item.checked;
        }
        return checked != null ? checked : !item.checked;
      });
      var names = children.map(function (item) {
        return item.name;
      });
      this.$emit('input', names);
    }
  },
  render: function render() {
    var h = arguments[0];
    return h("div", {
      "class": bem$Z([this.direction])
    }, [this.slots()]);
  }
});

var _createNamespace$$ = createNamespace('circle'),
  createComponent$13 = _createNamespace$$[0],
  bem$Y = _createNamespace$$[1];
var PERIMETER = 3140;
var uid = 0;
function format$1(rate) {
  return Math.min(Math.max(rate, 0), 100);
}
function getPath(clockwise, viewBoxSize) {
  var sweepFlag = clockwise ? 1 : 0;
  return "M " + viewBoxSize / 2 + " " + viewBoxSize / 2 + " m 0, -500 a 500, 500 0 1, " + sweepFlag + " 0, 1000 a 500, 500 0 1, " + sweepFlag + " 0, -1000";
}
var Circle = createComponent$13({
  props: {
    text: String,
    size: [Number, String],
    color: [String, Object],
    layerColor: String,
    strokeLinecap: String,
    value: {
      type: Number,
      default: 0
    },
    speed: {
      type: [Number, String],
      default: 0
    },
    fill: {
      type: String,
      default: 'none'
    },
    rate: {
      type: [Number, String],
      default: 100
    },
    strokeWidth: {
      type: [Number, String],
      default: 40
    },
    clockwise: {
      type: Boolean,
      default: true
    }
  },
  beforeCreate: function beforeCreate() {
    this.uid = "van-circle-gradient-" + uid++;
  },
  computed: {
    style: function style() {
      var size = addUnit(this.size);
      return {
        width: size,
        height: size
      };
    },
    path: function path() {
      return getPath(this.clockwise, this.viewBoxSize);
    },
    viewBoxSize: function viewBoxSize() {
      return +this.strokeWidth + 1000;
    },
    layerStyle: function layerStyle() {
      return {
        fill: "" + this.fill,
        stroke: "" + this.layerColor,
        strokeWidth: this.strokeWidth + "px"
      };
    },
    hoverStyle: function hoverStyle() {
      var offset = PERIMETER * this.value / 100;
      return {
        stroke: "" + (this.gradient ? "url(#" + this.uid + ")" : this.color),
        strokeWidth: +this.strokeWidth + 1 + "px",
        strokeLinecap: this.strokeLinecap,
        strokeDasharray: offset + "px " + PERIMETER + "px"
      };
    },
    gradient: function gradient() {
      return isObject(this.color);
    },
    LinearGradient: function LinearGradient() {
      var _this = this;
      var h = this.$createElement;
      if (!this.gradient) {
        return;
      }
      var Stops = Object.keys(this.color).sort(function (a, b) {
        return parseFloat(a) - parseFloat(b);
      }).map(function (key, index) {
        return h("stop", {
          "key": index,
          "attrs": {
            "offset": key,
            "stop-color": _this.color[key]
          }
        });
      });
      return h("defs", [h("linearGradient", {
        "attrs": {
          "id": this.uid,
          "x1": "100%",
          "y1": "0%",
          "x2": "0%",
          "y2": "0%"
        }
      }, [Stops])]);
    }
  },
  watch: {
    rate: {
      handler: function handler(rate) {
        this.startTime = Date.now();
        this.startRate = this.value;
        this.endRate = format$1(rate);
        this.increase = this.endRate > this.startRate;
        this.duration = Math.abs((this.startRate - this.endRate) * 1000 / this.speed);
        if (this.speed) {
          cancelRaf(this.rafId);
          this.rafId = raf(this.animate);
        } else {
          this.$emit('input', this.endRate);
        }
      },
      immediate: true
    }
  },
  methods: {
    animate: function animate() {
      var now = Date.now();
      var progress = Math.min((now - this.startTime) / this.duration, 1);
      var rate = progress * (this.endRate - this.startRate) + this.startRate;
      this.$emit('input', format$1(parseFloat(rate.toFixed(1))));
      if (this.increase ? rate < this.endRate : rate > this.endRate) {
        this.rafId = raf(this.animate);
      }
    }
  },
  render: function render() {
    var h = arguments[0];
    return h("div", {
      "class": bem$Y(),
      "style": this.style
    }, [h("svg", {
      "attrs": {
        "viewBox": "0 0 " + this.viewBoxSize + " " + this.viewBoxSize
      }
    }, [this.LinearGradient, h("path", {
      "class": bem$Y('layer'),
      "style": this.layerStyle,
      "attrs": {
        "d": this.path
      }
    }), h("path", {
      "attrs": {
        "d": this.path
      },
      "class": bem$Y('hover'),
      "style": this.hoverStyle
    })]), this.slots() || this.text && h("div", {
      "class": bem$Y('text')
    }, [this.text])]);
  }
});

var _createNamespace$_ = createNamespace('col'),
  createComponent$12 = _createNamespace$_[0],
  bem$X = _createNamespace$_[1];
var Col = createComponent$12({
  mixins: [ChildrenMixin('vanRow')],
  props: {
    span: [Number, String],
    offset: [Number, String],
    tag: {
      type: String,
      default: 'div'
    }
  },
  computed: {
    style: function style() {
      var index = this.index;
      var _ref = this.parent || {},
        spaces = _ref.spaces;
      if (spaces && spaces[index]) {
        var _spaces$index = spaces[index],
          left = _spaces$index.left,
          right = _spaces$index.right;
        return {
          paddingLeft: left ? left + "px" : null,
          paddingRight: right ? right + "px" : null
        };
      }
    }
  },
  methods: {
    onClick: function onClick(event) {
      this.$emit('click', event);
    }
  },
  render: function render() {
    var _bem;
    var h = arguments[0];
    var span = this.span,
      offset = this.offset;
    return h(this.tag, {
      "style": this.style,
      "class": bem$X((_bem = {}, _bem[span] = span, _bem["offset-" + offset] = offset, _bem)),
      "on": {
        "click": this.onClick
      }
    }, [this.slots()]);
  }
});

var _createNamespace$Z = createNamespace('collapse'),
  createComponent$11 = _createNamespace$Z[0],
  bem$W = _createNamespace$Z[1];
var Collapse = createComponent$11({
  mixins: [ParentMixin('vanCollapse')],
  props: {
    accordion: Boolean,
    value: [String, Number, Array],
    border: {
      type: Boolean,
      default: true
    }
  },
  methods: {
    switch: function _switch(name, expanded) {
      if (!this.accordion) {
        name = expanded ? this.value.concat(name) : this.value.filter(function (activeName) {
          return activeName !== name;
        });
      }
      this.$emit('change', name);
      this.$emit('input', name);
    }
  },
  render: function render() {
    var _ref;
    var h = arguments[0];
    return h("div", {
      "class": [bem$W(), (_ref = {}, _ref[BORDER_TOP_BOTTOM] = this.border, _ref)]
    }, [this.slots()]);
  }
});

var _createNamespace$Y = createNamespace('collapse-item'),
  createComponent$10 = _createNamespace$Y[0],
  bem$V = _createNamespace$Y[1];
var CELL_SLOTS = ['title', 'icon', 'right-icon'];
var CollapseItem = createComponent$10({
  mixins: [ChildrenMixin('vanCollapse')],
  props: _extends$1({}, cellProps, {
    name: [Number, String],
    disabled: Boolean,
    lazyRender: {
      type: Boolean,
      default: true
    },
    isLink: {
      type: Boolean,
      default: true
    }
  }),
  data: function data() {
    return {
      show: null,
      inited: null
    };
  },
  computed: {
    currentName: function currentName() {
      var _this$name;
      return (_this$name = this.name) != null ? _this$name : this.index;
    },
    expanded: function expanded() {
      var _this = this;
      if (!this.parent) {
        return null;
      }
      var _this$parent = this.parent,
        value = _this$parent.value,
        accordion = _this$parent.accordion;
      return accordion ? value === this.currentName : value.some(function (name) {
        return name === _this.currentName;
      });
    }
  },
  created: function created() {
    this.show = this.expanded;
    this.inited = this.expanded;
  },
  watch: {
    expanded: function expanded(_expanded, prev) {
      var _this2 = this;
      if (prev === null) {
        return;
      }
      if (_expanded) {
        this.show = true;
        this.inited = true;
      } // Use raf: flick when opened in safari
      // Use nextTick: closing animation failed when set `user-select: none`

      var nextTick = _expanded ? this.$nextTick : raf;
      nextTick(function () {
        var _this2$$refs = _this2.$refs,
          content = _this2$$refs.content,
          wrapper = _this2$$refs.wrapper;
        if (!content || !wrapper) {
          return;
        }
        var offsetHeight = content.offsetHeight;
        if (offsetHeight) {
          var contentHeight = offsetHeight + "px";
          wrapper.style.height = _expanded ? 0 : contentHeight; // use double raf to ensure animation can start

          doubleRaf(function () {
            wrapper.style.height = _expanded ? contentHeight : 0;
          });
        } else {
          _this2.onTransitionEnd();
        }
      });
    }
  },
  methods: {
    onClick: function onClick() {
      if (!this.disabled) {
        this.toggle();
      }
    },
    // @exposed-api
    toggle: function toggle(expanded) {
      if (expanded === void 0) {
        expanded = !this.expanded;
      }
      var parent = this.parent,
        currentName = this.currentName;
      var close = parent.accordion && currentName === parent.value;
      var name = close ? '' : currentName;
      this.parent.switch(name, expanded);
    },
    onTransitionEnd: function onTransitionEnd() {
      if (!this.expanded) {
        this.show = false;
      } else {
        this.$refs.wrapper.style.height = '';
      }
    },
    genTitle: function genTitle() {
      var _this3 = this;
      var h = this.$createElement;
      var border = this.border,
        disabled = this.disabled,
        expanded = this.expanded;
      var titleSlots = CELL_SLOTS.reduce(function (slots, name) {
        if (_this3.slots(name)) {
          slots[name] = function () {
            return _this3.slots(name);
          };
        }
        return slots;
      }, {});
      if (this.slots('value')) {
        titleSlots.default = function () {
          return _this3.slots('value');
        };
      }
      return h(Cell$1, {
        "attrs": {
          "role": "button",
          "tabindex": disabled ? -1 : 0,
          "aria-expanded": String(expanded)
        },
        "class": bem$V('title', {
          disabled: disabled,
          expanded: expanded,
          borderless: !border
        }),
        "on": {
          "click": this.onClick
        },
        "scopedSlots": titleSlots,
        "props": _extends$1({}, this.$props)
      });
    },
    genContent: function genContent() {
      var h = this.$createElement;
      if (this.inited || !this.lazyRender) {
        return h("div", {
          "directives": [{
            name: "show",
            value: this.show
          }],
          "ref": "wrapper",
          "class": bem$V('wrapper'),
          "on": {
            "transitionend": this.onTransitionEnd
          }
        }, [h("div", {
          "ref": "content",
          "class": bem$V('content')
        }, [this.slots()])]);
      }
    }
  },
  render: function render() {
    var h = arguments[0];
    return h("div", {
      "class": [bem$V({
        border: this.index && this.border
      })]
    }, [this.genTitle(), this.genContent()]);
  }
});

var _createNamespace$X = createNamespace('contact-card'),
  createComponent$$ = _createNamespace$X[0],
  bem$U = _createNamespace$X[1],
  t$j = _createNamespace$X[2];
function ContactCard(h, props, slots, ctx) {
  var type = props.type,
    editable = props.editable;
  function onClick(event) {
    if (editable) {
      emit(ctx, 'click', event);
    }
  }
  function Content() {
    if (type === 'add') {
      return props.addText || t$j('addText');
    }
    return [h("div", [t$j('name') + "\uFF1A" + props.name]), h("div", [t$j('tel') + "\uFF1A" + props.tel])];
  }
  return h(Cell$1, _mergeJSXProps([{
    "attrs": {
      "center": true,
      "border": false,
      "isLink": editable,
      "valueClass": bem$U('value'),
      "icon": type === 'edit' ? 'contact' : 'add-square'
    },
    "class": bem$U([type]),
    "on": {
      "click": onClick
    }
  }, inherit(ctx)]), [Content()]);
}
ContactCard.props = {
  tel: String,
  name: String,
  addText: String,
  editable: {
    type: Boolean,
    default: true
  },
  type: {
    type: String,
    default: 'add'
  }
};
var ContactCard$1 = createComponent$$(ContactCard);

var _createNamespace$W = createNamespace('contact-edit'),
  createComponent$_ = _createNamespace$W[0],
  bem$T = _createNamespace$W[1],
  t$i = _createNamespace$W[2];
var defaultContact = {
  tel: '',
  name: ''
};
var ContactEdit = createComponent$_({
  props: {
    isEdit: Boolean,
    isSaving: Boolean,
    isDeleting: Boolean,
    showSetDefault: Boolean,
    setDefaultLabel: String,
    contactInfo: {
      type: Object,
      default: function _default() {
        return _extends$1({}, defaultContact);
      }
    },
    telValidator: {
      type: Function,
      default: isMobile
    }
  },
  data: function data() {
    return {
      data: _extends$1({}, defaultContact, this.contactInfo),
      errorInfo: {
        name: '',
        tel: ''
      }
    };
  },
  watch: {
    contactInfo: function contactInfo(val) {
      this.data = _extends$1({}, defaultContact, val);
    }
  },
  methods: {
    onFocus: function onFocus(key) {
      this.errorInfo[key] = '';
    },
    getErrorMessageByKey: function getErrorMessageByKey(key) {
      var value = this.data[key].trim();
      switch (key) {
        case 'name':
          return value ? '' : t$i('nameInvalid');
        case 'tel':
          return this.telValidator(value) ? '' : t$i('telInvalid');
      }
    },
    onSave: function onSave() {
      var _this = this;
      var isValid = ['name', 'tel'].every(function (item) {
        var msg = _this.getErrorMessageByKey(item);
        if (msg) {
          _this.errorInfo[item] = msg;
        }
        return !msg;
      });
      if (isValid && !this.isSaving) {
        this.$emit('save', this.data);
      }
    },
    onDelete: function onDelete() {
      var _this2 = this;
      Dialog.confirm({
        title: t$i('confirmDelete')
      }).then(function () {
        _this2.$emit('delete', _this2.data);
      });
    }
  },
  render: function render() {
    var _this3 = this;
    var h = arguments[0];
    var data = this.data,
      errorInfo = this.errorInfo;
    var onFocus = function onFocus(name) {
      return function () {
        return _this3.onFocus(name);
      };
    };
    return h("div", {
      "class": bem$T()
    }, [h("div", {
      "class": bem$T('fields')
    }, [h(Field, {
      "attrs": {
        "clearable": true,
        "maxlength": "30",
        "label": t$i('name'),
        "placeholder": t$i('nameEmpty'),
        "errorMessage": errorInfo.name
      },
      "on": {
        "focus": onFocus('name')
      },
      "model": {
        value: data.name,
        callback: function callback($$v) {
          _this3.$set(data, "name", $$v);
        }
      }
    }), h(Field, {
      "attrs": {
        "clearable": true,
        "type": "tel",
        "label": t$i('tel'),
        "placeholder": t$i('telEmpty'),
        "errorMessage": errorInfo.tel
      },
      "on": {
        "focus": onFocus('tel')
      },
      "model": {
        value: data.tel,
        callback: function callback($$v) {
          _this3.$set(data, "tel", $$v);
        }
      }
    })]), this.showSetDefault && h(Cell$1, {
      "attrs": {
        "title": this.setDefaultLabel,
        "border": false
      },
      "class": bem$T('switch-cell')
    }, [h(Switch, {
      "attrs": {
        "size": 24
      },
      "slot": "right-icon",
      "on": {
        "change": function change(event) {
          _this3.$emit('change-default', event);
        }
      },
      "model": {
        value: data.isDefault,
        callback: function callback($$v) {
          _this3.$set(data, "isDefault", $$v);
        }
      }
    })]), h("div", {
      "class": bem$T('buttons')
    }, [h(Button$1, {
      "attrs": {
        "block": true,
        "round": true,
        "type": "danger",
        "text": t$i('save'),
        "loading": this.isSaving
      },
      "on": {
        "click": this.onSave
      }
    }), this.isEdit && h(Button$1, {
      "attrs": {
        "block": true,
        "round": true,
        "text": t$i('delete'),
        "loading": this.isDeleting
      },
      "on": {
        "click": this.onDelete
      }
    })])]);
  }
});

var _createNamespace$V = createNamespace('contact-list'),
  createComponent$Z = _createNamespace$V[0],
  bem$S = _createNamespace$V[1],
  t$h = _createNamespace$V[2];
function ContactList(h, props, slots, ctx) {
  var List = props.list && props.list.map(function (item, index) {
    function onClick() {
      emit(ctx, 'input', item.id);
      emit(ctx, 'select', item, index);
    }
    function RightIcon() {
      return h(Radio, {
        "attrs": {
          "name": item.id,
          "iconSize": 16,
          "checkedColor": RED
        },
        "on": {
          "click": onClick
        }
      });
    }
    function LeftIcon() {
      return h(Icon$1, {
        "attrs": {
          "name": "edit"
        },
        "class": bem$S('edit'),
        "on": {
          "click": function click(event) {
            event.stopPropagation();
            emit(ctx, 'edit', item, index);
          }
        }
      });
    }
    function Content() {
      var nodes = [item.name + "\uFF0C" + item.tel];
      if (item.isDefault && props.defaultTagText) {
        nodes.push(h(Tag$1, {
          "attrs": {
            "type": "danger",
            "round": true
          },
          "class": bem$S('item-tag')
        }, [props.defaultTagText]));
      }
      return nodes;
    }
    return h(Cell$1, {
      "key": item.id,
      "attrs": {
        "isLink": true,
        "center": true,
        "valueClass": bem$S('item-value')
      },
      "class": bem$S('item'),
      "scopedSlots": {
        icon: LeftIcon,
        default: Content,
        'right-icon': RightIcon
      },
      "on": {
        "click": onClick
      }
    });
  });
  return h("div", _mergeJSXProps([{
    "class": bem$S()
  }, inherit(ctx)]), [h(RadioGroup, {
    "attrs": {
      "value": props.value
    },
    "class": bem$S('group')
  }, [List]), h("div", {
    "class": bem$S('bottom')
  }, [h(Button$1, {
    "attrs": {
      "round": true,
      "block": true,
      "type": "danger",
      "text": props.addText || t$h('addText')
    },
    "class": bem$S('add'),
    "on": {
      "click": function click() {
        emit(ctx, 'add');
      }
    }
  })])]);
}
ContactList.props = {
  value: null,
  list: Array,
  addText: String,
  defaultTagText: String
};
var ContactList$1 = createComponent$Z(ContactList);

var SECOND = 1000;
var MINUTE = 60 * SECOND;
var HOUR = 60 * MINUTE;
var DAY = 24 * HOUR;
function parseTimeData(time) {
  var days = Math.floor(time / DAY);
  var hours = Math.floor(time % DAY / HOUR);
  var minutes = Math.floor(time % HOUR / MINUTE);
  var seconds = Math.floor(time % MINUTE / SECOND);
  var milliseconds = Math.floor(time % SECOND);
  return {
    days: days,
    hours: hours,
    minutes: minutes,
    seconds: seconds,
    milliseconds: milliseconds
  };
}
function parseFormat(format, timeData) {
  var days = timeData.days;
  var hours = timeData.hours,
    minutes = timeData.minutes,
    seconds = timeData.seconds,
    milliseconds = timeData.milliseconds;
  if (format.indexOf('DD') === -1) {
    hours += days * 24;
  } else {
    format = format.replace('DD', padZero(days));
  }
  if (format.indexOf('HH') === -1) {
    minutes += hours * 60;
  } else {
    format = format.replace('HH', padZero(hours));
  }
  if (format.indexOf('mm') === -1) {
    seconds += minutes * 60;
  } else {
    format = format.replace('mm', padZero(minutes));
  }
  if (format.indexOf('ss') === -1) {
    milliseconds += seconds * 1000;
  } else {
    format = format.replace('ss', padZero(seconds));
  }
  if (format.indexOf('S') !== -1) {
    var ms = padZero(milliseconds, 3);
    if (format.indexOf('SSS') !== -1) {
      format = format.replace('SSS', ms);
    } else if (format.indexOf('SS') !== -1) {
      format = format.replace('SS', ms.slice(0, 2));
    } else {
      format = format.replace('S', ms.charAt(0));
    }
  }
  return format;
}
function isSameSecond(time1, time2) {
  return Math.floor(time1 / 1000) === Math.floor(time2 / 1000);
}

var _createNamespace$U = createNamespace('count-down'),
  createComponent$Y = _createNamespace$U[0],
  bem$R = _createNamespace$U[1];
var CountDown = createComponent$Y({
  props: {
    millisecond: Boolean,
    time: {
      type: [Number, String],
      default: 0
    },
    format: {
      type: String,
      default: 'HH:mm:ss'
    },
    autoStart: {
      type: Boolean,
      default: true
    }
  },
  data: function data() {
    return {
      remain: 0
    };
  },
  computed: {
    timeData: function timeData() {
      return parseTimeData(this.remain);
    },
    formattedTime: function formattedTime() {
      return parseFormat(this.format, this.timeData);
    }
  },
  watch: {
    time: {
      immediate: true,
      handler: 'reset'
    }
  },
  activated: function activated() {
    if (this.keepAlivePaused) {
      this.counting = true;
      this.keepAlivePaused = false;
      this.tick();
    }
  },
  deactivated: function deactivated() {
    if (this.counting) {
      this.pause();
      this.keepAlivePaused = true;
    }
  },
  beforeDestroy: function beforeDestroy() {
    this.pause();
  },
  methods: {
    // @exposed-api
    start: function start() {
      if (this.counting) {
        return;
      }
      this.counting = true;
      this.endTime = Date.now() + this.remain;
      this.tick();
    },
    // @exposed-api
    pause: function pause() {
      this.counting = false;
      cancelRaf(this.rafId);
    },
    // @exposed-api
    reset: function reset() {
      this.pause();
      this.remain = +this.time;
      if (this.autoStart) {
        this.start();
      }
    },
    tick: function tick() {
      // should not start counting in server
      // see: https://github.com/vant-ui/vant/issues/7807
      if (!inBrowser) {
        return;
      }
      if (this.millisecond) {
        this.microTick();
      } else {
        this.macroTick();
      }
    },
    microTick: function microTick() {
      var _this = this;
      this.rafId = raf(function () {
        /* istanbul ignore if */
        // in case of call reset immediately after finish
        if (!_this.counting) {
          return;
        }
        _this.setRemain(_this.getRemain());
        if (_this.remain > 0) {
          _this.microTick();
        }
      });
    },
    macroTick: function macroTick() {
      var _this2 = this;
      this.rafId = raf(function () {
        /* istanbul ignore if */
        // in case of call reset immediately after finish
        if (!_this2.counting) {
          return;
        }
        var remain = _this2.getRemain();
        if (!isSameSecond(remain, _this2.remain) || remain === 0) {
          _this2.setRemain(remain);
        }
        if (_this2.remain > 0) {
          _this2.macroTick();
        }
      });
    },
    getRemain: function getRemain() {
      return Math.max(this.endTime - Date.now(), 0);
    },
    setRemain: function setRemain(remain) {
      this.remain = remain;
      this.$emit('change', this.timeData);
      if (remain === 0) {
        this.pause();
        this.$emit('finish');
      }
    }
  },
  render: function render() {
    var h = arguments[0];
    return h("div", {
      "class": bem$R()
    }, [this.slots('default', this.timeData) || this.formattedTime]);
  }
});

var _createNamespace$T = createNamespace('coupon'),
  createComponent$X = _createNamespace$T[0],
  bem$Q = _createNamespace$T[1],
  t$g = _createNamespace$T[2];
function formatTimeStamp(timeStamp) {
  // compatible when the timestamp is seconds
  if (timeStamp < Math.pow(10, 12)) {
    return timeStamp * 1000;
  }
  return +timeStamp;
}
function getDate(timeStamp) {
  var date = new Date(formatTimeStamp(timeStamp));
  return date.getFullYear() + "." + padZero(date.getMonth() + 1) + "." + padZero(date.getDate());
}
function formatDiscount(discount) {
  return (discount / 10).toFixed(discount % 10 === 0 ? 0 : 1);
}
function formatAmount(amount) {
  return (amount / 100).toFixed(amount % 100 === 0 ? 0 : amount % 10 === 0 ? 1 : 2);
}
var Coupon = createComponent$X({
  props: {
    coupon: Object,
    chosen: Boolean,
    disabled: Boolean,
    currency: {
      type: String,
      default: '¥'
    }
  },
  computed: {
    validPeriod: function validPeriod() {
      var _this$coupon = this.coupon,
        startAt = _this$coupon.startAt,
        endAt = _this$coupon.endAt,
        customValidPeriod = _this$coupon.customValidPeriod;
      return customValidPeriod || getDate(startAt) + " - " + getDate(endAt);
    },
    faceAmount: function faceAmount() {
      var coupon = this.coupon;
      if (coupon.valueDesc) {
        return coupon.valueDesc + "<span>" + (coupon.unitDesc || '') + "</span>";
      }
      if (coupon.denominations) {
        var denominations = formatAmount(coupon.denominations);
        return "<span>" + this.currency + "</span> " + denominations;
      }
      if (coupon.discount) {
        return t$g('discount', formatDiscount(coupon.discount));
      }
      return '';
    },
    conditionMessage: function conditionMessage() {
      var condition = formatAmount(this.coupon.originCondition);
      return condition === '0' ? t$g('unlimited') : t$g('condition', condition);
    }
  },
  render: function render() {
    var h = arguments[0];
    var coupon = this.coupon,
      disabled = this.disabled;
    var description = disabled && coupon.reason || coupon.description;
    return h("div", {
      "class": bem$Q({
        disabled: disabled
      })
    }, [h("div", {
      "class": bem$Q('content')
    }, [h("div", {
      "class": bem$Q('head')
    }, [h("h2", {
      "class": bem$Q('amount'),
      "domProps": {
        "innerHTML": this.faceAmount
      }
    }), h("p", {
      "class": bem$Q('condition')
    }, [this.coupon.condition || this.conditionMessage])]), h("div", {
      "class": bem$Q('body')
    }, [h("p", {
      "class": bem$Q('name')
    }, [coupon.name]), h("p", {
      "class": bem$Q('valid')
    }, [this.validPeriod]), !this.disabled && h(Checkbox, {
      "attrs": {
        "size": 18,
        "value": this.chosen,
        "checkedColor": RED
      },
      "class": bem$Q('corner')
    })])]), description && h("p", {
      "class": bem$Q('description')
    }, [description])]);
  }
});

var _createNamespace$S = createNamespace('coupon-cell'),
  createComponent$W = _createNamespace$S[0],
  bem$P = _createNamespace$S[1],
  t$f = _createNamespace$S[2];
function formatValue(props) {
  var coupons = props.coupons,
    chosenCoupon = props.chosenCoupon,
    currency = props.currency;
  var coupon = coupons[+chosenCoupon];
  if (coupon) {
    var value = 0;
    if (isDef(coupon.value)) {
      value = coupon.value;
    } else if (isDef(coupon.denominations)) {
      value = coupon.denominations;
    }
    return "-" + currency + " " + (value / 100).toFixed(2);
  }
  return coupons.length === 0 ? t$f('tips') : t$f('count', coupons.length);
}
function CouponCell(h, props, slots, ctx) {
  var selected = props.coupons[+props.chosenCoupon];
  var value = formatValue(props);
  return h(Cell$1, _mergeJSXProps([{
    "class": bem$P(),
    "attrs": {
      "value": value,
      "title": props.title || t$f('title'),
      "border": props.border,
      "isLink": props.editable,
      "valueClass": bem$P('value', {
        selected: selected
      })
    }
  }, inherit(ctx, true)]));
}
CouponCell.model = {
  prop: 'chosenCoupon'
};
CouponCell.props = {
  title: String,
  coupons: {
    type: Array,
    default: function _default() {
      return [];
    }
  },
  currency: {
    type: String,
    default: '¥'
  },
  border: {
    type: Boolean,
    default: true
  },
  editable: {
    type: Boolean,
    default: true
  },
  chosenCoupon: {
    type: [Number, String],
    default: -1
  }
};
var CouponCell$1 = createComponent$W(CouponCell);

// Utils
var _createNamespace$R = createNamespace('coupon-list'),
  createComponent$V = _createNamespace$R[0],
  bem$O = _createNamespace$R[1],
  t$e = _createNamespace$R[2];
var EMPTY_IMAGE = 'https://img01.yzcdn.cn/vant/coupon-empty.png';
var CouponList = createComponent$V({
  model: {
    prop: 'code'
  },
  props: {
    code: String,
    closeButtonText: String,
    inputPlaceholder: String,
    enabledTitle: String,
    disabledTitle: String,
    exchangeButtonText: String,
    exchangeButtonLoading: Boolean,
    exchangeButtonDisabled: Boolean,
    exchangeMinLength: {
      type: Number,
      default: 1
    },
    chosenCoupon: {
      type: Number,
      default: -1
    },
    coupons: {
      type: Array,
      default: function _default() {
        return [];
      }
    },
    disabledCoupons: {
      type: Array,
      default: function _default() {
        return [];
      }
    },
    displayedCouponIndex: {
      type: Number,
      default: -1
    },
    showExchangeBar: {
      type: Boolean,
      default: true
    },
    showCloseButton: {
      type: Boolean,
      default: true
    },
    showCount: {
      type: Boolean,
      default: true
    },
    currency: {
      type: String,
      default: '¥'
    },
    emptyImage: {
      type: String,
      default: EMPTY_IMAGE
    }
  },
  data: function data() {
    return {
      tab: 0,
      winHeight: window.innerHeight,
      currentCode: this.code || ''
    };
  },
  computed: {
    buttonDisabled: function buttonDisabled() {
      return !this.exchangeButtonLoading && (this.exchangeButtonDisabled || !this.currentCode || this.currentCode.length < this.exchangeMinLength);
    },
    listStyle: function listStyle() {
      return {
        height: this.winHeight - (this.showExchangeBar ? 140 : 94) + 'px'
      };
    }
  },
  watch: {
    code: function code(_code) {
      this.currentCode = _code;
    },
    currentCode: function currentCode(code) {
      this.$emit('input', code);
    },
    displayedCouponIndex: 'scrollToShowCoupon'
  },
  mounted: function mounted() {
    this.scrollToShowCoupon(this.displayedCouponIndex);
  },
  methods: {
    onClickExchangeButton: function onClickExchangeButton() {
      this.$emit('exchange', this.currentCode); // auto clear currentCode when not use vModel

      if (!this.code) {
        this.currentCode = '';
      }
    },
    // scroll to show specific coupon
    scrollToShowCoupon: function scrollToShowCoupon(index) {
      var _this = this;
      if (index === -1) {
        return;
      }
      this.$nextTick(function () {
        var _this$$refs = _this.$refs,
          card = _this$$refs.card,
          list = _this$$refs.list;
        /* istanbul ignore next */

        if (list && card && card[index]) {
          list.scrollTop = card[index].$el.offsetTop - 100;
        }
      });
    },
    genEmpty: function genEmpty() {
      var h = this.$createElement;
      return h("div", {
        "class": bem$O('empty')
      }, [h("img", {
        "attrs": {
          "src": this.emptyImage
        }
      }), h("p", [t$e('empty')])]);
    },
    genExchangeButton: function genExchangeButton() {
      var h = this.$createElement;
      return h(Button$1, {
        "attrs": {
          "plain": true,
          "type": "danger",
          "text": this.exchangeButtonText || t$e('exchange'),
          "loading": this.exchangeButtonLoading,
          "disabled": this.buttonDisabled
        },
        "class": bem$O('exchange'),
        "on": {
          "click": this.onClickExchangeButton
        }
      });
    }
  },
  render: function render() {
    var _this2 = this;
    var h = arguments[0];
    var coupons = this.coupons,
      disabledCoupons = this.disabledCoupons;
    var count = this.showCount ? " (" + coupons.length + ")" : '';
    var title = (this.enabledTitle || t$e('enable')) + count;
    var disabledCount = this.showCount ? " (" + disabledCoupons.length + ")" : '';
    var disabledTitle = (this.disabledTitle || t$e('disabled')) + disabledCount;
    var ExchangeBar = this.showExchangeBar && h("div", {
      "class": bem$O('exchange-bar')
    }, [h(Field, {
      "attrs": {
        "clearable": true,
        "border": false,
        "placeholder": this.inputPlaceholder || t$e('placeholder'),
        "maxlength": "20"
      },
      "class": bem$O('field'),
      "model": {
        value: _this2.currentCode,
        callback: function callback($$v) {
          _this2.currentCode = $$v;
        }
      }
    }), this.genExchangeButton()]);
    var onChange = function onChange(index) {
      return function () {
        return _this2.$emit('change', index);
      };
    };
    var CouponTab = h(Tab, {
      "attrs": {
        "title": title
      }
    }, [h("div", {
      "class": bem$O('list', {
        'with-bottom': this.showCloseButton
      }),
      "style": this.listStyle
    }, [coupons.map(function (coupon, index) {
      return h(Coupon, {
        "ref": "card",
        "key": coupon.id,
        "attrs": {
          "coupon": coupon,
          "currency": _this2.currency,
          "chosen": index === _this2.chosenCoupon
        },
        "nativeOn": {
          "click": onChange(index)
        }
      });
    }), !coupons.length && this.genEmpty(), this.slots('list-footer')])]);
    var DisabledCouponTab = h(Tab, {
      "attrs": {
        "title": disabledTitle
      }
    }, [h("div", {
      "class": bem$O('list', {
        'with-bottom': this.showCloseButton
      }),
      "style": this.listStyle
    }, [disabledCoupons.map(function (coupon) {
      return h(Coupon, {
        "attrs": {
          "disabled": true,
          "coupon": coupon,
          "currency": _this2.currency
        },
        "key": coupon.id
      });
    }), !disabledCoupons.length && this.genEmpty(), this.slots('disabled-list-footer')])]);
    return h("div", {
      "class": bem$O()
    }, [ExchangeBar, h(Tabs, {
      "class": bem$O('tab'),
      "attrs": {
        "border": false
      },
      "model": {
        value: _this2.tab,
        callback: function callback($$v) {
          _this2.tab = $$v;
        }
      }
    }, [CouponTab, DisabledCouponTab]), h("div", {
      "class": bem$O('bottom')
    }, [h(Button$1, {
      "directives": [{
        name: "show",
        value: this.showCloseButton
      }],
      "attrs": {
        "round": true,
        "type": "danger",
        "block": true,
        "text": this.closeButtonText || t$e('close')
      },
      "class": bem$O('close'),
      "on": {
        "click": onChange(-1)
      }
    })])]);
  }
});

var sharedProps = _extends$1({}, pickerProps, {
  value: null,
  filter: Function,
  columnsOrder: Array,
  showToolbar: {
    type: Boolean,
    default: true
  },
  formatter: {
    type: Function,
    default: function _default(type, value) {
      return value;
    }
  }
});
var TimePickerMixin = {
  data: function data() {
    return {
      innerValue: this.formatValue(this.value)
    };
  },
  computed: {
    originColumns: function originColumns() {
      var _this = this;
      return this.ranges.map(function (_ref) {
        var type = _ref.type,
          rangeArr = _ref.range;
        var values = times(rangeArr[1] - rangeArr[0] + 1, function (index) {
          var value = padZero(rangeArr[0] + index);
          return value;
        });
        if (_this.filter) {
          values = _this.filter(type, values);
        }
        return {
          type: type,
          values: values
        };
      });
    },
    columns: function columns() {
      var _this2 = this;
      return this.originColumns.map(function (column) {
        return {
          values: column.values.map(function (value) {
            return _this2.formatter(column.type, value);
          })
        };
      });
    }
  },
  watch: {
    columns: 'updateColumnValue',
    innerValue: function innerValue(val, oldVal) {
      if (!oldVal) {
        this.$emit('input', null);
      } else {
        this.$emit('input', val);
      }
    }
  },
  mounted: function mounted() {
    var _this3 = this;
    this.updateColumnValue();
    this.$nextTick(function () {
      _this3.updateInnerValue();
    });
  },
  methods: {
    getPicker: function getPicker() {
      return this.$refs.picker;
    },
    // https://github.com/vant-ui/vant/issues/10013
    getProxiedPicker: function getProxiedPicker() {
      var _this4 = this;
      var picker = this.$refs.picker;
      if (picker) {
        var proxy = function proxy(fn) {
          return function () {
            picker[fn].apply(picker, arguments);
            _this4.updateInnerValue();
          };
        };
        return _extends$1({}, picker, {
          setValues: proxy('setValues'),
          setIndexes: proxy('setIndexes'),
          setColumnIndex: proxy('setColumnIndex'),
          setColumnValue: proxy('setColumnValue')
        });
      }
    },
    onConfirm: function onConfirm() {
      this.$emit('input', this.innerValue);
      this.$emit('confirm', this.innerValue);
    },
    onCancel: function onCancel() {
      this.$emit('cancel');
    }
  },
  render: function render() {
    var _this5 = this;
    var h = arguments[0];
    var props = {};
    Object.keys(pickerProps).forEach(function (key) {
      props[key] = _this5[key];
    });
    return h(Picker, {
      "ref": "picker",
      "attrs": {
        "columns": this.columns,
        "readonly": this.readonly
      },
      "scopedSlots": this.$scopedSlots,
      "on": {
        "change": this.onChange,
        "confirm": this.onConfirm,
        "cancel": this.onCancel
      },
      "props": _extends$1({}, props)
    });
  }
};

var _createNamespace$Q = createNamespace('time-picker'),
  createComponent$U = _createNamespace$Q[0];
var TimePicker = createComponent$U({
  mixins: [TimePickerMixin],
  props: _extends$1({}, sharedProps, {
    minHour: {
      type: [Number, String],
      default: 0
    },
    maxHour: {
      type: [Number, String],
      default: 23
    },
    minMinute: {
      type: [Number, String],
      default: 0
    },
    maxMinute: {
      type: [Number, String],
      default: 59
    }
  }),
  computed: {
    ranges: function ranges() {
      return [{
        type: 'hour',
        range: [+this.minHour, +this.maxHour]
      }, {
        type: 'minute',
        range: [+this.minMinute, +this.maxMinute]
      }];
    }
  },
  watch: {
    filter: 'updateInnerValue',
    minHour: function minHour() {
      var _this = this;
      this.$nextTick(function () {
        _this.updateInnerValue();
      });
    },
    maxHour: function maxHour(value) {
      var _this$innerValue$spli = this.innerValue.split(':'),
        hour = _this$innerValue$spli[0],
        minute = _this$innerValue$spli[1];
      if (hour >= value) {
        this.innerValue = this.formatValue(value + ":" + minute);
        this.updateColumnValue();
      } else {
        this.updateInnerValue();
      }
    },
    minMinute: 'updateInnerValue',
    maxMinute: function maxMinute(value) {
      var _this$innerValue$spli2 = this.innerValue.split(':'),
        hour = _this$innerValue$spli2[0],
        minute = _this$innerValue$spli2[1];
      if (minute >= value) {
        this.innerValue = this.formatValue(hour + ":" + value);
        this.updateColumnValue();
      } else {
        this.updateInnerValue();
      }
    },
    value: function value(val) {
      val = this.formatValue(val);
      if (val !== this.innerValue) {
        this.innerValue = val;
        this.updateColumnValue();
      }
    }
  },
  methods: {
    formatValue: function formatValue(value) {
      if (!value) {
        value = padZero(this.minHour) + ":" + padZero(this.minMinute);
      }
      var _value$split = value.split(':'),
        hour = _value$split[0],
        minute = _value$split[1];
      hour = padZero(range(hour, this.minHour, this.maxHour));
      minute = padZero(range(minute, this.minMinute, this.maxMinute));
      return hour + ":" + minute;
    },
    updateInnerValue: function updateInnerValue() {
      var _this$getPicker$getIn = this.getPicker().getIndexes(),
        hourIndex = _this$getPicker$getIn[0],
        minuteIndex = _this$getPicker$getIn[1];
      var _this$originColumns = this.originColumns,
        hourColumn = _this$originColumns[0],
        minuteColumn = _this$originColumns[1];
      var hour = hourColumn.values[hourIndex] || hourColumn.values[0];
      var minute = minuteColumn.values[minuteIndex] || minuteColumn.values[0];
      this.innerValue = this.formatValue(hour + ":" + minute);
      this.updateColumnValue();
    },
    onChange: function onChange(picker) {
      var _this2 = this;
      this.updateInnerValue();
      this.$nextTick(function () {
        _this2.$nextTick(function () {
          // https://github.com/vant-ui/vant/issues/9775
          _this2.updateInnerValue();
          _this2.$emit('change', picker);
        });
      });
    },
    updateColumnValue: function updateColumnValue() {
      var _this3 = this;
      var formatter = this.formatter;
      var pair = this.innerValue.split(':');
      var values = [formatter('hour', pair[0]), formatter('minute', pair[1])];
      this.$nextTick(function () {
        _this3.getPicker().setValues(values);
      });
    }
  }
});

function _isNativeReflectConstruct() {
  try {
    var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
  } catch (t) {}
  return (_isNativeReflectConstruct = function _isNativeReflectConstruct() {
    return !!t;
  })();
}

function _setPrototypeOf(t, e) {
  return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) {
    return t.__proto__ = e, t;
  }, _setPrototypeOf(t, e);
}

function _construct(t, e, r) {
  if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments);
  var o = [null];
  o.push.apply(o, e);
  var p = new (t.bind.apply(t, o))();
  return r && _setPrototypeOf(p, r.prototype), p;
}

var currentYear = new Date().getFullYear();
var _createNamespace$P = createNamespace('date-picker'),
  createComponent$T = _createNamespace$P[0];
var DatePicker = createComponent$T({
  mixins: [TimePickerMixin],
  props: _extends$1({}, sharedProps, {
    type: {
      type: String,
      default: 'datetime'
    },
    minDate: {
      type: Date,
      default: function _default() {
        return new Date(currentYear - 10, 0, 1);
      },
      validator: isDate
    },
    maxDate: {
      type: Date,
      default: function _default() {
        return new Date(currentYear + 10, 11, 31);
      },
      validator: isDate
    }
  }),
  watch: {
    filter: 'updateInnerValue',
    minDate: function minDate() {
      var _this = this;
      this.$nextTick(function () {
        _this.updateInnerValue();
      });
    },
    maxDate: function maxDate(value) {
      if (this.innerValue.valueOf() >= value.valueOf()) {
        this.innerValue = value;
      } else {
        this.updateInnerValue();
      }
    },
    value: function value(val) {
      val = this.formatValue(val);
      if (val && val.valueOf() !== this.innerValue.valueOf()) {
        this.innerValue = val;
      }
    }
  },
  computed: {
    ranges: function ranges() {
      var _this$getBoundary = this.getBoundary('max', this.innerValue ? this.innerValue : this.minDate),
        maxYear = _this$getBoundary.maxYear,
        maxDate = _this$getBoundary.maxDate,
        maxMonth = _this$getBoundary.maxMonth,
        maxHour = _this$getBoundary.maxHour,
        maxMinute = _this$getBoundary.maxMinute;
      var _this$getBoundary2 = this.getBoundary('min', this.innerValue ? this.innerValue : this.minDate),
        minYear = _this$getBoundary2.minYear,
        minDate = _this$getBoundary2.minDate,
        minMonth = _this$getBoundary2.minMonth,
        minHour = _this$getBoundary2.minHour,
        minMinute = _this$getBoundary2.minMinute;
      var result = [{
        type: 'year',
        range: [minYear, maxYear]
      }, {
        type: 'month',
        range: [minMonth, maxMonth]
      }, {
        type: 'day',
        range: [minDate, maxDate]
      }, {
        type: 'hour',
        range: [minHour, maxHour]
      }, {
        type: 'minute',
        range: [minMinute, maxMinute]
      }];
      switch (this.type) {
        case 'date':
          result = result.slice(0, 3);
          break;
        case 'year-month':
          result = result.slice(0, 2);
          break;
        case 'month-day':
          result = result.slice(1, 3);
          break;
        case 'datehour':
          result = result.slice(0, 4);
          break;
      }
      if (this.columnsOrder) {
        var columnsOrder = this.columnsOrder.concat(result.map(function (column) {
          return column.type;
        }));
        result.sort(function (a, b) {
          return columnsOrder.indexOf(a.type) - columnsOrder.indexOf(b.type);
        });
      }
      return result;
    }
  },
  methods: {
    formatValue: function formatValue(value) {
      var _this2 = this;
      if (!isDate(value)) {
        return null;
      }
      var minDate = new Date(this.minDate);
      var maxDate = new Date(this.maxDate);
      var dateMethods = {
        year: 'getFullYear',
        month: 'getMonth',
        day: 'getDate',
        hour: 'getHours',
        minute: 'getMinutes'
      };
      if (this.originColumns) {
        var dateColumns = this.originColumns.map(function (_ref, index) {
          var type = _ref.type,
            values = _ref.values;
          var range = _this2.ranges[index].range;
          var minDateVal = minDate[dateMethods[type]]();
          var maxDateVal = maxDate[dateMethods[type]]();
          var min = type === 'month' ? +values[0] - 1 : +values[0];
          var max = type === 'month' ? +values[values.length - 1] - 1 : +values[values.length - 1];
          return {
            type: type,
            values: [minDateVal < range[0] ? Math.max(minDateVal, min) : min || minDateVal, maxDateVal > range[1] ? Math.min(maxDateVal, max) : max || maxDateVal]
          };
        });
        if (this.type === 'month-day') {
          var year = (this.innerValue || this.minDate).getFullYear();
          dateColumns.unshift({
            type: 'year',
            values: [year, year]
          });
        }
        var dates = Object.keys(dateMethods).map(function (type) {
          var _dateColumns$filter$;
          return (_dateColumns$filter$ = dateColumns.filter(function (item) {
            return item.type === type;
          })[0]) == null ? void 0 : _dateColumns$filter$.values;
        }).filter(function (item) {
          return item;
        });
        minDate = _construct(Date, dates.map(function (val) {
          return getTrueValue(val[0]);
        }));
        maxDate = _construct(Date, dates.map(function (val) {
          return getTrueValue(val[1]);
        }));
      }
      value = Math.max(value, minDate.getTime());
      value = Math.min(value, maxDate.getTime());
      return new Date(value);
    },
    getBoundary: function getBoundary(type, value) {
      var _ref2;
      var boundary = this[type + "Date"];
      var year = boundary.getFullYear();
      var month = 1;
      var date = 1;
      var hour = 0;
      var minute = 0;
      if (type === 'max') {
        month = 12;
        date = getMonthEndDay(value.getFullYear(), value.getMonth() + 1);
        hour = 23;
        minute = 59;
      }
      if (value.getFullYear() === year) {
        month = boundary.getMonth() + 1;
        if (value.getMonth() + 1 === month) {
          date = boundary.getDate();
          if (value.getDate() === date) {
            hour = boundary.getHours();
            if (value.getHours() === hour) {
              minute = boundary.getMinutes();
            }
          }
        }
      }
      return _ref2 = {}, _ref2[type + "Year"] = year, _ref2[type + "Month"] = month, _ref2[type + "Date"] = date, _ref2[type + "Hour"] = hour, _ref2[type + "Minute"] = minute, _ref2;
    },
    updateInnerValue: function updateInnerValue() {
      var _this3 = this;
      var type = this.type;
      var indexes = this.getPicker().getIndexes();
      var getValue = function getValue(type) {
        var index = 0;
        _this3.originColumns.forEach(function (column, columnIndex) {
          if (type === column.type) {
            index = columnIndex;
          }
        });
        var values = _this3.originColumns[index].values;
        return getTrueValue(values[indexes[index]]);
      };
      var year;
      var month;
      var day;
      if (type === 'month-day') {
        year = (this.innerValue || this.minDate).getFullYear();
        month = getValue('month');
        day = getValue('day');
      } else {
        year = getValue('year');
        month = getValue('month');
        day = type === 'year-month' ? 1 : getValue('day');
      }
      var maxDay = getMonthEndDay(year, month);
      day = day > maxDay ? maxDay : day;
      var hour = 0;
      var minute = 0;
      if (type === 'datehour') {
        hour = getValue('hour');
      }
      if (type === 'datetime') {
        hour = getValue('hour');
        minute = getValue('minute');
      }
      var value = new Date(year, month - 1, day, hour, minute);
      this.innerValue = this.formatValue(value);
    },
    onChange: function onChange(picker) {
      var _this4 = this;
      this.updateInnerValue();
      this.$nextTick(function () {
        _this4.$nextTick(function () {
          // https://github.com/vant-ui/vant/issues/9775
          _this4.updateInnerValue();
          _this4.$emit('change', picker);
        });
      });
    },
    updateColumnValue: function updateColumnValue() {
      var _this5 = this;
      var value = this.innerValue ? this.innerValue : this.minDate;
      var formatter = this.formatter;
      var values = this.originColumns.map(function (column) {
        switch (column.type) {
          case 'year':
            return formatter('year', "" + value.getFullYear());
          case 'month':
            return formatter('month', padZero(value.getMonth() + 1));
          case 'day':
            return formatter('day', padZero(value.getDate()));
          case 'hour':
            return formatter('hour', padZero(value.getHours()));
          case 'minute':
            return formatter('minute', padZero(value.getMinutes()));
          default:
            // no default
            return null;
        }
      });
      this.$nextTick(function () {
        _this5.getPicker().setValues(values);
      });
    }
  }
});

var _createNamespace$O = createNamespace('datetime-picker'),
  createComponent$S = _createNamespace$O[0],
  bem$N = _createNamespace$O[1];
var DatetimePicker = createComponent$S({
  props: _extends$1({}, TimePicker.props, DatePicker.props),
  methods: {
    // @exposed-api
    getPicker: function getPicker() {
      return this.$refs.root.getProxiedPicker();
    }
  },
  render: function render() {
    var h = arguments[0];
    var Component = this.type === 'time' ? TimePicker : DatePicker;
    return h(Component, {
      "ref": "root",
      "class": bem$N(),
      "scopedSlots": this.$scopedSlots,
      "props": _extends$1({}, this.$props),
      "on": _extends$1({}, this.$listeners)
    });
  }
});

var _createNamespace$N = createNamespace('divider'),
  createComponent$R = _createNamespace$N[0],
  bem$M = _createNamespace$N[1];
function Divider(h, props, slots, ctx) {
  var _bem;
  return h("div", _mergeJSXProps([{
    "attrs": {
      "role": "separator"
    },
    "style": {
      borderColor: props.borderColor
    },
    "class": bem$M((_bem = {
      dashed: props.dashed,
      hairline: props.hairline
    }, _bem["content-" + props.contentPosition] = slots.default, _bem))
  }, inherit(ctx, true)]), [slots.default && slots.default()]);
}
Divider.props = {
  dashed: Boolean,
  hairline: {
    type: Boolean,
    default: true
  },
  contentPosition: {
    type: String,
    default: 'center'
  }
};
var Divider$1 = createComponent$R(Divider);

// Utils
var _createNamespace$M = createNamespace('dropdown-item'),
  createComponent$Q = _createNamespace$M[0],
  bem$L = _createNamespace$M[1];
var DropdownItem = createComponent$Q({
  mixins: [PortalMixin({
    ref: 'wrapper'
  }), ChildrenMixin('vanDropdownMenu')],
  props: {
    value: null,
    title: String,
    disabled: Boolean,
    titleClass: String,
    options: {
      type: Array,
      default: function _default() {
        return [];
      }
    },
    lazyRender: {
      type: Boolean,
      default: true
    }
  },
  data: function data() {
    return {
      transition: true,
      showPopup: false,
      showWrapper: false
    };
  },
  computed: {
    displayTitle: function displayTitle() {
      var _this = this;
      if (this.title) {
        return this.title;
      }
      var match = this.options.filter(function (option) {
        return option.value === _this.value;
      });
      return match.length ? match[0].text : '';
    }
  },
  watch: {
    showPopup: function showPopup(val) {
      this.bindScroll(val);
    }
  },
  beforeCreate: function beforeCreate() {
    var _this2 = this;
    var createEmitter = function createEmitter(eventName) {
      return function () {
        return _this2.$emit(eventName);
      };
    };
    this.onOpen = createEmitter('open');
    this.onClose = createEmitter('close');
    this.onOpened = createEmitter('opened');
  },
  methods: {
    // @exposed-api
    toggle: function toggle(show, options) {
      if (show === void 0) {
        show = !this.showPopup;
      }
      if (options === void 0) {
        options = {};
      }
      if (show === this.showPopup) {
        return;
      }
      this.transition = !options.immediate;
      this.showPopup = show;
      if (show) {
        this.parent.updateOffset();
        this.showWrapper = true;
      }
    },
    bindScroll: function bindScroll(bind) {
      var scroller = this.parent.scroller;
      var action = bind ? on : off;
      action(scroller, 'scroll', this.onScroll, true);
    },
    onScroll: function onScroll() {
      this.parent.updateOffset();
    },
    onClickWrapper: function onClickWrapper(event) {
      // prevent being identified as clicking outside and closed when use get-contaienr
      if (this.getContainer) {
        event.stopPropagation();
      }
    }
  },
  render: function render() {
    var _this3 = this;
    var h = arguments[0];
    var _this$parent = this.parent,
      zIndex = _this$parent.zIndex,
      offset = _this$parent.offset,
      overlay = _this$parent.overlay,
      duration = _this$parent.duration,
      direction = _this$parent.direction,
      activeColor = _this$parent.activeColor,
      closeOnClickOverlay = _this$parent.closeOnClickOverlay;
    var Options = this.options.map(function (option) {
      var active = option.value === _this3.value;
      return h(Cell$1, {
        "attrs": {
          "clickable": true,
          "icon": option.icon,
          "title": option.text
        },
        "key": option.value,
        "class": bem$L('option', {
          active: active
        }),
        "style": {
          color: active ? activeColor : ''
        },
        "on": {
          "click": function click() {
            _this3.showPopup = false;
            if (option.value !== _this3.value) {
              _this3.$emit('input', option.value);
              _this3.$emit('change', option.value);
            }
          }
        }
      }, [active && h(Icon$1, {
        "class": bem$L('icon'),
        "attrs": {
          "color": activeColor,
          "name": "success"
        }
      })]);
    });
    var style = {
      zIndex: zIndex
    };
    if (direction === 'down') {
      style.top = offset + "px";
    } else {
      style.bottom = offset + "px";
    }
    return h("div", [h("div", {
      "directives": [{
        name: "show",
        value: this.showWrapper
      }],
      "ref": "wrapper",
      "style": style,
      "class": bem$L([direction]),
      "on": {
        "click": this.onClickWrapper
      }
    }, [h(Popup, {
      "attrs": {
        "overlay": overlay,
        "position": direction === 'down' ? 'top' : 'bottom',
        "duration": this.transition ? duration : 0,
        "lazyRender": this.lazyRender,
        "overlayStyle": {
          position: 'absolute'
        },
        "closeOnClickOverlay": closeOnClickOverlay
      },
      "class": bem$L('content'),
      "on": {
        "open": this.onOpen,
        "close": this.onClose,
        "opened": this.onOpened,
        "closed": function closed() {
          _this3.showWrapper = false;
          _this3.$emit('closed');
        }
      },
      "model": {
        value: _this3.showPopup,
        callback: function callback($$v) {
          _this3.showPopup = $$v;
        }
      }
    }, [Options, this.slots('default')])])]);
  }
});

/**
 * Listen to click outside event
 */
var ClickOutsideMixin = function ClickOutsideMixin(config) {
  return {
    props: {
      closeOnClickOutside: {
        type: Boolean,
        default: true
      }
    },
    data: function data() {
      var _this = this;
      var clickOutsideHandler = function clickOutsideHandler(event) {
        if (_this.closeOnClickOutside && !_this.$el.contains(event.target)) {
          _this[config.method]();
        }
      };
      return {
        clickOutsideHandler: clickOutsideHandler
      };
    },
    mounted: function mounted() {
      on(document, config.event, this.clickOutsideHandler);
    },
    beforeDestroy: function beforeDestroy() {
      off(document, config.event, this.clickOutsideHandler);
    }
  };
};

// Utils
var _createNamespace$L = createNamespace('dropdown-menu'),
  createComponent$P = _createNamespace$L[0],
  bem$K = _createNamespace$L[1];
var DropdownMenu = createComponent$P({
  mixins: [ParentMixin('vanDropdownMenu'), ClickOutsideMixin({
    event: 'click',
    method: 'onClickOutside'
  })],
  props: {
    zIndex: [Number, String],
    activeColor: String,
    overlay: {
      type: Boolean,
      default: true
    },
    duration: {
      type: [Number, String],
      default: 0.2
    },
    direction: {
      type: String,
      default: 'down'
    },
    closeOnClickOverlay: {
      type: Boolean,
      default: true
    }
  },
  data: function data() {
    return {
      offset: 0
    };
  },
  computed: {
    scroller: function scroller() {
      return getScroller(this.$el);
    },
    opened: function opened() {
      return this.children.some(function (item) {
        return item.showWrapper;
      });
    },
    barStyle: function barStyle() {
      if (this.opened && isDef(this.zIndex)) {
        return {
          zIndex: 1 + this.zIndex
        };
      }
    }
  },
  methods: {
    updateOffset: function updateOffset() {
      if (!this.$refs.bar) {
        return;
      }
      var rect = this.$refs.bar.getBoundingClientRect();
      if (this.direction === 'down') {
        this.offset = rect.bottom;
      } else {
        this.offset = window.innerHeight - rect.top;
      }
    },
    toggleItem: function toggleItem(active) {
      this.children.forEach(function (item, index) {
        if (index === active) {
          item.toggle();
        } else if (item.showPopup) {
          item.toggle(false, {
            immediate: true
          });
        }
      });
    },
    onClickOutside: function onClickOutside() {
      this.children.forEach(function (item) {
        item.toggle(false);
      });
    }
  },
  render: function render() {
    var _this = this;
    var h = arguments[0];
    var Titles = this.children.map(function (item, index) {
      return h("div", {
        "attrs": {
          "role": "button",
          "tabindex": item.disabled ? -1 : 0
        },
        "class": bem$K('item', {
          disabled: item.disabled
        }),
        "on": {
          "click": function click() {
            if (!item.disabled) {
              _this.toggleItem(index);
            }
          }
        }
      }, [h("span", {
        "class": [bem$K('title', {
          active: item.showPopup,
          down: item.showPopup === (_this.direction === 'down')
        }), item.titleClass],
        "style": {
          color: item.showPopup ? _this.activeColor : ''
        }
      }, [h("div", {
        "class": "van-ellipsis"
      }, [item.slots('title') || item.displayTitle])])]);
    });
    return h("div", {
      "class": bem$K()
    }, [h("div", {
      "ref": "bar",
      "style": this.barStyle,
      "class": bem$K('bar', {
        opened: this.opened
      })
    }, [Titles]), this.slots('default')]);
  }
});

var prefix = 'van-empty-network-';
var Network = {
  render: function render() {
    var h = arguments[0];
    var genStop = function genStop(color, offset, opacity) {
      return h("stop", {
        "attrs": {
          "stop-color": color,
          "offset": offset + "%",
          "stop-opacity": opacity
        }
      });
    };
    return h("svg", {
      "attrs": {
        "viewBox": "0 0 160 160",
        "xmlns": "http://www.w3.org/2000/svg"
      }
    }, [h("defs", [h("linearGradient", {
      "attrs": {
        "id": prefix + "1",
        "x1": "64.022%",
        "y1": "100%",
        "x2": "64.022%",
        "y2": "0%"
      }
    }, [genStop('#FFF', 0, 0.5), genStop('#F2F3F5', 100)]), h("linearGradient", {
      "attrs": {
        "id": prefix + "2",
        "x1": "50%",
        "y1": "0%",
        "x2": "50%",
        "y2": "84.459%"
      }
    }, [genStop('#EBEDF0', 0), genStop('#DCDEE0', 100, 0)]), h("linearGradient", {
      "attrs": {
        "id": prefix + "3",
        "x1": "100%",
        "y1": "0%",
        "x2": "100%",
        "y2": "100%"
      }
    }, [genStop('#EAEDF0', 0), genStop('#DCDEE0', 100)]), h("linearGradient", {
      "attrs": {
        "id": prefix + "4",
        "x1": "100%",
        "y1": "100%",
        "x2": "100%",
        "y2": "0%"
      }
    }, [genStop('#EAEDF0', 0), genStop('#DCDEE0', 100)]), h("linearGradient", {
      "attrs": {
        "id": prefix + "5",
        "x1": "0%",
        "y1": "43.982%",
        "x2": "100%",
        "y2": "54.703%"
      }
    }, [genStop('#EAEDF0', 0), genStop('#DCDEE0', 100)]), h("linearGradient", {
      "attrs": {
        "id": prefix + "6",
        "x1": "94.535%",
        "y1": "43.837%",
        "x2": "5.465%",
        "y2": "54.948%"
      }
    }, [genStop('#EAEDF0', 0), genStop('#DCDEE0', 100)]), h("radialGradient", {
      "attrs": {
        "id": prefix + "7",
        "cx": "50%",
        "cy": "0%",
        "fx": "50%",
        "fy": "0%",
        "r": "100%",
        "gradientTransform": "matrix(0 1 -.54835 0 .5 -.5)"
      }
    }, [genStop('#EBEDF0', 0), genStop('#FFF', 100, 0)])]), h("g", {
      "attrs": {
        "fill": "none",
        "fill-rule": "evenodd"
      }
    }, [h("g", {
      "attrs": {
        "opacity": ".8"
      }
    }, [h("path", {
      "attrs": {
        "d": "M0 124V46h20v20h14v58H0z",
        "fill": "url(#" + prefix + "1)",
        "transform": "matrix(-1 0 0 1 36 7)"
      }
    }), h("path", {
      "attrs": {
        "d": "M121 8h22.231v14H152v77.37h-31V8z",
        "fill": "url(#" + prefix + "1)",
        "transform": "translate(2 7)"
      }
    })]), h("path", {
      "attrs": {
        "fill": "url(#" + prefix + "7)",
        "d": "M0 139h160v21H0z"
      }
    }), h("path", {
      "attrs": {
        "d": "M37 18a7 7 0 013 13.326v26.742c0 1.23-.997 2.227-2.227 2.227h-1.546A2.227 2.227 0 0134 58.068V31.326A7 7 0 0137 18z",
        "fill": "url(#" + prefix + "2)",
        "fill-rule": "nonzero",
        "transform": "translate(43 36)"
      }
    }), h("g", {
      "attrs": {
        "opacity": ".6",
        "stroke-linecap": "round",
        "stroke-width": "7"
      }
    }, [h("path", {
      "attrs": {
        "d": "M20.875 11.136a18.868 18.868 0 00-5.284 13.121c0 5.094 2.012 9.718 5.284 13.12",
        "stroke": "url(#" + prefix + "3)",
        "transform": "translate(43 36)"
      }
    }), h("path", {
      "attrs": {
        "d": "M9.849 0C3.756 6.225 0 14.747 0 24.146c0 9.398 3.756 17.92 9.849 24.145",
        "stroke": "url(#" + prefix + "3)",
        "transform": "translate(43 36)"
      }
    }), h("path", {
      "attrs": {
        "d": "M57.625 11.136a18.868 18.868 0 00-5.284 13.121c0 5.094 2.012 9.718 5.284 13.12",
        "stroke": "url(#" + prefix + "4)",
        "transform": "rotate(-180 76.483 42.257)"
      }
    }), h("path", {
      "attrs": {
        "d": "M73.216 0c-6.093 6.225-9.849 14.747-9.849 24.146 0 9.398 3.756 17.92 9.849 24.145",
        "stroke": "url(#" + prefix + "4)",
        "transform": "rotate(-180 89.791 42.146)"
      }
    })]), h("g", {
      "attrs": {
        "transform": "translate(31 105)",
        "fill-rule": "nonzero"
      }
    }, [h("rect", {
      "attrs": {
        "fill": "url(#" + prefix + "5)",
        "width": "98",
        "height": "34",
        "rx": "2"
      }
    }), h("rect", {
      "attrs": {
        "fill": "#FFF",
        "x": "9",
        "y": "8",
        "width": "80",
        "height": "18",
        "rx": "1.114"
      }
    }), h("rect", {
      "attrs": {
        "fill": "url(#" + prefix + "6)",
        "x": "15",
        "y": "12",
        "width": "18",
        "height": "6",
        "rx": "1.114"
      }
    })])])]);
  }
};

var _createNamespace$K = createNamespace('empty'),
  createComponent$O = _createNamespace$K[0],
  bem$J = _createNamespace$K[1];
var PRESETS = ['error', 'search', 'default'];
var Empty = createComponent$O({
  props: {
    imageSize: [Number, String],
    description: String,
    image: {
      type: String,
      default: 'default'
    }
  },
  methods: {
    genImageContent: function genImageContent() {
      var h = this.$createElement;
      var slots = this.slots('image');
      if (slots) {
        return slots;
      }
      if (this.image === 'network') {
        return h(Network);
      }
      var image = this.image;
      if (PRESETS.indexOf(image) !== -1) {
        image = "https://img01.yzcdn.cn/vant/empty-image-" + image + ".png";
      }
      return h("img", {
        "attrs": {
          "src": image
        }
      });
    },
    genImage: function genImage() {
      var h = this.$createElement;
      var imageStyle = {
        width: addUnit(this.imageSize),
        height: addUnit(this.imageSize)
      };
      return h("div", {
        "class": bem$J('image'),
        "style": imageStyle
      }, [this.genImageContent()]);
    },
    genDescription: function genDescription() {
      var h = this.$createElement;
      var description = this.slots('description') || this.description;
      if (description) {
        return h("p", {
          "class": bem$J('description')
        }, [description]);
      }
    },
    genBottom: function genBottom() {
      var h = this.$createElement;
      var slot = this.slots();
      if (slot) {
        return h("div", {
          "class": bem$J('bottom')
        }, [slot]);
      }
    }
  },
  render: function render() {
    var h = arguments[0];
    return h("div", {
      "class": bem$J()
    }, [this.genImage(), this.genDescription(), this.genBottom()]);
  }
});

var _createNamespace$J = createNamespace('form'),
  createComponent$N = _createNamespace$J[0],
  bem$I = _createNamespace$J[1];
var Form = createComponent$N({
  props: {
    colon: Boolean,
    disabled: Boolean,
    readonly: Boolean,
    labelWidth: [Number, String],
    labelAlign: String,
    inputAlign: String,
    scrollToError: Boolean,
    validateFirst: Boolean,
    errorMessageAlign: String,
    submitOnEnter: {
      type: Boolean,
      default: true
    },
    validateTrigger: {
      type: String,
      default: 'onBlur'
    },
    showError: {
      type: Boolean,
      default: true
    },
    showErrorMessage: {
      type: Boolean,
      default: true
    }
  },
  provide: function provide() {
    return {
      vanForm: this
    };
  },
  data: function data() {
    return {
      fields: []
    };
  },
  methods: {
    getFieldsByNames: function getFieldsByNames(names) {
      if (names) {
        return this.fields.filter(function (field) {
          return names.indexOf(field.name) !== -1;
        });
      }
      return this.fields;
    },
    validateSeq: function validateSeq(names) {
      var _this = this;
      return new Promise(function (resolve, reject) {
        var errors = [];
        var fields = _this.getFieldsByNames(names);
        fields.reduce(function (promise, field) {
          return promise.then(function () {
            if (!errors.length) {
              return field.validate().then(function (error) {
                if (error) {
                  errors.push(error);
                }
              });
            }
          });
        }, Promise.resolve()).then(function () {
          if (errors.length) {
            reject(errors);
          } else {
            resolve();
          }
        });
      });
    },
    validateFields: function validateFields(names) {
      var _this2 = this;
      return new Promise(function (resolve, reject) {
        var fields = _this2.getFieldsByNames(names);
        Promise.all(fields.map(function (item) {
          return item.validate();
        })).then(function (errors) {
          errors = errors.filter(function (item) {
            return item;
          });
          if (errors.length) {
            reject(errors);
          } else {
            resolve();
          }
        });
      });
    },
    // @exposed-api
    validate: function validate(name) {
      if (name && !Array.isArray(name)) {
        return this.validateField(name);
      }
      return this.validateFirst ? this.validateSeq(name) : this.validateFields(name);
    },
    validateField: function validateField(name) {
      var matched = this.fields.filter(function (item) {
        return item.name === name;
      });
      if (matched.length) {
        return new Promise(function (resolve, reject) {
          matched[0].validate().then(function (error) {
            if (error) {
              reject(error);
            } else {
              resolve();
            }
          });
        });
      }
      return Promise.reject();
    },
    // @exposed-api
    resetValidation: function resetValidation(name) {
      if (name && !Array.isArray(name)) {
        name = [name];
      }
      var fields = this.getFieldsByNames(name);
      fields.forEach(function (item) {
        item.resetValidation();
      });
    },
    // @exposed-api
    scrollToField: function scrollToField(name, options) {
      this.fields.some(function (item) {
        if (item.name === name) {
          item.$el.scrollIntoView(options);
          return true;
        }
        return false;
      });
    },
    addField: function addField(field) {
      this.fields.push(field);
      sortChildren(this.fields, this);
    },
    removeField: function removeField(field) {
      this.fields = this.fields.filter(function (item) {
        return item !== field;
      });
    },
    getValues: function getValues() {
      return this.fields.reduce(function (form, field) {
        form[field.name] = field.formValue;
        return form;
      }, {});
    },
    onSubmit: function onSubmit(event) {
      event.preventDefault();
      this.submit();
    },
    // @exposed-api
    submit: function submit() {
      var _this3 = this;
      var values = this.getValues();
      this.validate().then(function () {
        _this3.$emit('submit', values);
      }).catch(function (errors) {
        _this3.$emit('failed', {
          values: values,
          errors: errors
        });
        if (_this3.scrollToError) {
          _this3.scrollToField(errors[0].name);
        }
      });
    }
  },
  render: function render() {
    var h = arguments[0];
    return h("form", {
      "class": bem$I(),
      "on": {
        "submit": this.onSubmit
      }
    }, [this.slots()]);
  }
});

var _createNamespace$I = createNamespace('goods-action-icon'),
  createComponent$M = _createNamespace$I[0],
  bem$H = _createNamespace$I[1];
var GoodsActionIcon = createComponent$M({
  mixins: [ChildrenMixin('vanGoodsAction')],
  props: _extends$1({}, routeProps, {
    dot: Boolean,
    text: String,
    icon: String,
    color: String,
    // @deprecated
    info: [Number, String],
    badge: [Number, String],
    iconClass: null
  }),
  methods: {
    onClick: function onClick(event) {
      this.$emit('click', event);
      route(this.$router, this);
    },
    genIcon: function genIcon() {
      var _this$badge;
      var h = this.$createElement;
      var slot = this.slots('icon');
      var info = (_this$badge = this.badge) != null ? _this$badge : this.info;
      if (slot) {
        return h("div", {
          "class": bem$H('icon')
        }, [slot, h(Info$1, {
          "attrs": {
            "dot": this.dot,
            "info": info
          }
        })]);
      }
      return h(Icon$1, {
        "class": [bem$H('icon'), this.iconClass],
        "attrs": {
          "tag": "div",
          "dot": this.dot,
          "name": this.icon,
          "badge": info,
          "color": this.color
        }
      });
    }
  },
  render: function render() {
    var h = arguments[0];
    return h("div", {
      "attrs": {
        "role": "button",
        "tabindex": "0"
      },
      "class": bem$H(),
      "on": {
        "click": this.onClick
      }
    }, [this.genIcon(), this.slots() || this.text]);
  }
});

var _createNamespace$H = createNamespace('grid'),
  createComponent$L = _createNamespace$H[0],
  bem$G = _createNamespace$H[1];
var Grid = createComponent$L({
  mixins: [ParentMixin('vanGrid')],
  props: {
    square: Boolean,
    gutter: [Number, String],
    iconSize: [Number, String],
    direction: String,
    clickable: Boolean,
    columnNum: {
      type: [Number, String],
      default: 4
    },
    center: {
      type: Boolean,
      default: true
    },
    border: {
      type: Boolean,
      default: true
    }
  },
  computed: {
    style: function style() {
      var gutter = this.gutter;
      if (gutter) {
        return {
          paddingLeft: addUnit(gutter)
        };
      }
    }
  },
  render: function render() {
    var _ref;
    var h = arguments[0];
    return h("div", {
      "style": this.style,
      "class": [bem$G(), (_ref = {}, _ref[BORDER_TOP] = this.border && !this.gutter, _ref)]
    }, [this.slots()]);
  }
});

var _createNamespace$G = createNamespace('grid-item'),
  createComponent$K = _createNamespace$G[0],
  bem$F = _createNamespace$G[1];
var GridItem = createComponent$K({
  mixins: [ChildrenMixin('vanGrid')],
  props: _extends$1({}, routeProps, {
    dot: Boolean,
    text: String,
    icon: String,
    iconPrefix: String,
    // @deprecated
    info: [Number, String],
    badge: [Number, String]
  }),
  computed: {
    style: function style() {
      var _this$parent = this.parent,
        square = _this$parent.square,
        gutter = _this$parent.gutter,
        columnNum = _this$parent.columnNum;
      var percent = 100 / columnNum + "%";
      var style = {
        flexBasis: percent
      };
      if (square) {
        style.paddingTop = percent;
      } else if (gutter) {
        var gutterValue = addUnit(gutter);
        style.paddingRight = gutterValue;
        if (this.index >= columnNum) {
          style.marginTop = gutterValue;
        }
      }
      return style;
    },
    contentStyle: function contentStyle() {
      var _this$parent2 = this.parent,
        square = _this$parent2.square,
        gutter = _this$parent2.gutter;
      if (square && gutter) {
        var gutterValue = addUnit(gutter);
        return {
          right: gutterValue,
          bottom: gutterValue,
          height: 'auto'
        };
      }
    }
  },
  methods: {
    onClick: function onClick(event) {
      this.$emit('click', event);
      route(this.$router, this);
    },
    genIcon: function genIcon() {
      var _this$badge;
      var h = this.$createElement;
      var iconSlot = this.slots('icon');
      var info = (_this$badge = this.badge) != null ? _this$badge : this.info;
      if (iconSlot) {
        return h("div", {
          "class": bem$F('icon-wrapper')
        }, [iconSlot, h(Info$1, {
          "attrs": {
            "dot": this.dot,
            "info": info
          }
        })]);
      }
      if (this.icon) {
        return h(Icon$1, {
          "attrs": {
            "name": this.icon,
            "dot": this.dot,
            "badge": info,
            "size": this.parent.iconSize,
            "classPrefix": this.iconPrefix
          },
          "class": bem$F('icon')
        });
      }
    },
    getText: function getText() {
      var h = this.$createElement;
      var textSlot = this.slots('text');
      if (textSlot) {
        return textSlot;
      }
      if (this.text) {
        return h("span", {
          "class": bem$F('text')
        }, [this.text]);
      }
    },
    genContent: function genContent() {
      var slot = this.slots();
      if (slot) {
        return slot;
      }
      return [this.genIcon(), this.getText()];
    }
  },
  render: function render() {
    var _ref;
    var h = arguments[0];
    var _this$parent3 = this.parent,
      center = _this$parent3.center,
      border = _this$parent3.border,
      square = _this$parent3.square,
      gutter = _this$parent3.gutter,
      direction = _this$parent3.direction,
      clickable = _this$parent3.clickable;
    return h("div", {
      "class": [bem$F({
        square: square
      })],
      "style": this.style
    }, [h("div", {
      "style": this.contentStyle,
      "attrs": {
        "role": clickable ? 'button' : null,
        "tabindex": clickable ? 0 : null
      },
      "class": [bem$F('content', [direction, {
        center: center,
        square: square,
        clickable: clickable,
        surround: border && gutter
      }]), (_ref = {}, _ref[BORDER] = border, _ref)],
      "on": {
        "click": this.onClick
      }
    }, [this.genContent()])]);
  }
});

var _createNamespace$F = createNamespace('image-preview'),
  createComponent$J = _createNamespace$F[0],
  bem$E = _createNamespace$F[1];

// Utils
var _createNamespace$E = createNamespace('swipe'),
  createComponent$I = _createNamespace$E[0],
  bem$D = _createNamespace$E[1];
var Swipe = createComponent$I({
  mixins: [TouchMixin, ParentMixin('vanSwipe'), BindEventMixin(function (bind, isBind) {
    bind(window, 'resize', this.resize, true);
    bind(window, 'orientationchange', this.resize, true);
    bind(window, 'visibilitychange', this.onVisibilityChange);
    if (isBind) {
      this.initialize();
    } else {
      this.clear();
    }
  })],
  props: {
    width: [Number, String],
    height: [Number, String],
    autoplay: [Number, String],
    vertical: Boolean,
    lazyRender: Boolean,
    indicatorColor: String,
    loop: {
      type: Boolean,
      default: true
    },
    duration: {
      type: [Number, String],
      default: 500
    },
    touchable: {
      type: Boolean,
      default: true
    },
    initialSwipe: {
      type: [Number, String],
      default: 0
    },
    showIndicators: {
      type: Boolean,
      default: true
    },
    stopPropagation: {
      type: Boolean,
      default: true
    }
  },
  data: function data() {
    return {
      rect: null,
      offset: 0,
      active: 0,
      deltaX: 0,
      deltaY: 0,
      swiping: false,
      computedWidth: 0,
      computedHeight: 0
    };
  },
  watch: {
    children: function children() {
      this.initialize();
    },
    initialSwipe: function initialSwipe() {
      this.initialize();
    },
    autoplay: function autoplay(_autoplay) {
      if (_autoplay > 0) {
        this.autoPlay();
      } else {
        this.clear();
      }
    }
  },
  computed: {
    count: function count() {
      return this.children.length;
    },
    maxCount: function maxCount() {
      return Math.ceil(Math.abs(this.minOffset) / this.size);
    },
    delta: function delta() {
      return this.vertical ? this.deltaY : this.deltaX;
    },
    size: function size() {
      return this[this.vertical ? 'computedHeight' : 'computedWidth'];
    },
    trackSize: function trackSize() {
      return this.count * this.size;
    },
    activeIndicator: function activeIndicator() {
      return (this.active + this.count) % this.count;
    },
    isCorrectDirection: function isCorrectDirection() {
      var expect = this.vertical ? 'vertical' : 'horizontal';
      return this.direction === expect;
    },
    trackStyle: function trackStyle() {
      var style = {
        transitionDuration: (this.swiping ? 0 : this.duration) + "ms",
        transform: "translate" + (this.vertical ? 'Y' : 'X') + "(" + this.offset + "px)"
      };
      if (this.size) {
        var mainAxis = this.vertical ? 'height' : 'width';
        var crossAxis = this.vertical ? 'width' : 'height';
        style[mainAxis] = this.trackSize + "px";
        style[crossAxis] = this[crossAxis] ? this[crossAxis] + "px" : '';
      }
      return style;
    },
    indicatorStyle: function indicatorStyle() {
      return {
        backgroundColor: this.indicatorColor
      };
    },
    minOffset: function minOffset() {
      return (this.vertical ? this.rect.height : this.rect.width) - this.size * this.count;
    }
  },
  mounted: function mounted() {
    this.bindTouchEvent(this.$refs.track);
  },
  methods: {
    // initialize swipe position
    initialize: function initialize(active) {
      if (active === void 0) {
        active = +this.initialSwipe;
      }
      if (!this.$el || isHidden(this.$el)) {
        return;
      }
      clearTimeout(this.timer);
      var rect = {
        width: this.$el.offsetWidth,
        height: this.$el.offsetHeight
      };
      this.rect = rect;
      this.swiping = true;
      this.active = active;
      this.computedWidth = +this.width || rect.width;
      this.computedHeight = +this.height || rect.height;
      this.offset = this.getTargetOffset(active);
      this.children.forEach(function (swipe) {
        swipe.offset = 0;
      });
      this.autoPlay();
    },
    // @exposed-api
    resize: function resize() {
      this.initialize(this.activeIndicator);
    },
    onVisibilityChange: function onVisibilityChange() {
      if (document.hidden) {
        this.clear();
      } else {
        this.autoPlay();
      }
    },
    onTouchStart: function onTouchStart(event) {
      if (!this.touchable) return;
      this.clear();
      this.touchStartTime = Date.now();
      this.touchStart(event);
      this.correctPosition();
    },
    onTouchMove: function onTouchMove(event) {
      if (!this.touchable || !this.swiping) return;
      this.touchMove(event);
      if (this.isCorrectDirection) {
        preventDefault(event, this.stopPropagation);
        this.move({
          offset: this.delta
        });
      }
    },
    onTouchEnd: function onTouchEnd() {
      if (!this.touchable || !this.swiping) return;
      var size = this.size,
        delta = this.delta;
      var duration = Date.now() - this.touchStartTime;
      var speed = delta / duration;
      var shouldSwipe = Math.abs(speed) > 0.25 || Math.abs(delta) > size / 2;
      if (shouldSwipe && this.isCorrectDirection) {
        var offset = this.vertical ? this.offsetY : this.offsetX;
        var pace = 0;
        if (this.loop) {
          pace = offset > 0 ? delta > 0 ? -1 : 1 : 0;
        } else {
          pace = -Math[delta > 0 ? 'ceil' : 'floor'](delta / size);
        }
        this.move({
          pace: pace,
          emitChange: true
        });
      } else if (delta) {
        this.move({
          pace: 0
        });
      }
      this.swiping = false;
      this.autoPlay();
    },
    getTargetActive: function getTargetActive(pace) {
      var active = this.active,
        count = this.count,
        maxCount = this.maxCount;
      if (pace) {
        if (this.loop) {
          return range(active + pace, -1, count);
        }
        return range(active + pace, 0, maxCount);
      }
      return active;
    },
    getTargetOffset: function getTargetOffset(targetActive, offset) {
      if (offset === void 0) {
        offset = 0;
      }
      var currentPosition = targetActive * this.size;
      if (!this.loop) {
        currentPosition = Math.min(currentPosition, -this.minOffset);
      }
      var targetOffset = offset - currentPosition;
      if (!this.loop) {
        targetOffset = range(targetOffset, this.minOffset, 0);
      }
      return targetOffset;
    },
    move: function move(_ref) {
      var _ref$pace = _ref.pace,
        pace = _ref$pace === void 0 ? 0 : _ref$pace,
        _ref$offset = _ref.offset,
        offset = _ref$offset === void 0 ? 0 : _ref$offset,
        emitChange = _ref.emitChange;
      var loop = this.loop,
        count = this.count,
        active = this.active,
        children = this.children,
        trackSize = this.trackSize,
        minOffset = this.minOffset;
      if (count <= 1) {
        return;
      }
      var targetActive = this.getTargetActive(pace);
      var targetOffset = this.getTargetOffset(targetActive, offset); // auto move first and last swipe in loop mode

      if (loop) {
        if (children[0] && targetOffset !== minOffset) {
          var outRightBound = targetOffset < minOffset;
          children[0].offset = outRightBound ? trackSize : 0;
        }
        if (children[count - 1] && targetOffset !== 0) {
          var outLeftBound = targetOffset > 0;
          children[count - 1].offset = outLeftBound ? -trackSize : 0;
        }
      }
      this.active = targetActive;
      this.offset = targetOffset;
      if (emitChange && targetActive !== active) {
        this.$emit('change', this.activeIndicator);
      }
    },
    // @exposed-api
    prev: function prev() {
      var _this = this;
      this.correctPosition();
      this.resetTouchStatus();
      doubleRaf(function () {
        _this.swiping = false;
        _this.move({
          pace: -1,
          emitChange: true
        });
      });
    },
    // @exposed-api
    next: function next() {
      var _this2 = this;
      this.correctPosition();
      this.resetTouchStatus();
      doubleRaf(function () {
        _this2.swiping = false;
        _this2.move({
          pace: 1,
          emitChange: true
        });
      });
    },
    // @exposed-api
    swipeTo: function swipeTo(index, options) {
      var _this3 = this;
      if (options === void 0) {
        options = {};
      }
      this.correctPosition();
      this.resetTouchStatus();
      doubleRaf(function () {
        var targetIndex;
        if (_this3.loop && index === _this3.count) {
          targetIndex = _this3.active === 0 ? 0 : index;
        } else {
          targetIndex = index % _this3.count;
        }
        if (options.immediate) {
          doubleRaf(function () {
            _this3.swiping = false;
          });
        } else {
          _this3.swiping = false;
        }
        _this3.move({
          pace: targetIndex - _this3.active,
          emitChange: true
        });
      });
    },
    correctPosition: function correctPosition() {
      this.swiping = true;
      if (this.active <= -1) {
        this.move({
          pace: this.count
        });
      }
      if (this.active >= this.count) {
        this.move({
          pace: -this.count
        });
      }
    },
    clear: function clear() {
      clearTimeout(this.timer);
    },
    autoPlay: function autoPlay() {
      var _this4 = this;
      var autoplay = this.autoplay;
      if (autoplay > 0 && this.count > 1) {
        this.clear();
        this.timer = setTimeout(function () {
          _this4.next();
          _this4.autoPlay();
        }, autoplay);
      }
    },
    genIndicator: function genIndicator() {
      var _this5 = this;
      var h = this.$createElement;
      var count = this.count,
        activeIndicator = this.activeIndicator;
      var slot = this.slots('indicator');
      if (slot) {
        return slot;
      }
      if (this.showIndicators && count > 1) {
        return h("div", {
          "class": bem$D('indicators', {
            vertical: this.vertical
          })
        }, [Array.apply(void 0, Array(count)).map(function (empty, index) {
          return h("i", {
            "class": bem$D('indicator', {
              active: index === activeIndicator
            }),
            "style": index === activeIndicator ? _this5.indicatorStyle : null
          });
        })]);
      }
    }
  },
  render: function render() {
    var h = arguments[0];
    return h("div", {
      "class": bem$D()
    }, [h("div", {
      "ref": "track",
      "style": this.trackStyle,
      "class": bem$D('track', {
        vertical: this.vertical
      })
    }, [this.slots()]), this.genIndicator()]);
  }
});

var _createNamespace$D = createNamespace('swipe-item'),
  createComponent$H = _createNamespace$D[0],
  bem$C = _createNamespace$D[1];
var SwipeItem = createComponent$H({
  mixins: [ChildrenMixin('vanSwipe')],
  data: function data() {
    return {
      offset: 0,
      inited: false,
      mounted: false
    };
  },
  mounted: function mounted() {
    var _this = this;
    this.$nextTick(function () {
      _this.mounted = true;
    });
  },
  computed: {
    style: function style() {
      var style = {};
      var _this$parent = this.parent,
        size = _this$parent.size,
        vertical = _this$parent.vertical;
      if (size) {
        style[vertical ? 'height' : 'width'] = size + "px";
      }
      if (this.offset) {
        style.transform = "translate" + (vertical ? 'Y' : 'X') + "(" + this.offset + "px)";
      }
      return style;
    },
    shouldRender: function shouldRender() {
      var index = this.index,
        inited = this.inited,
        parent = this.parent,
        mounted = this.mounted;
      if (!parent.lazyRender || inited) {
        return true;
      } // wait for all item to mount, so we can get the exact count

      if (!mounted) {
        return false;
      }
      var active = parent.activeIndicator;
      var maxActive = parent.count - 1;
      var prevActive = active === 0 && parent.loop ? maxActive : active - 1;
      var nextActive = active === maxActive && parent.loop ? 0 : active + 1;
      var shouldRender = index === active || index === prevActive || index === nextActive;
      if (shouldRender) {
        this.inited = true;
      }
      return shouldRender;
    }
  },
  render: function render() {
    var h = arguments[0];
    return h("div", {
      "class": bem$C(),
      "style": this.style,
      "on": _extends$1({}, this.$listeners)
    }, [this.shouldRender && this.slots()]);
  }
});

// Utils
function getDistance(touches) {
  return Math.sqrt(Math.pow(touches[0].clientX - touches[1].clientX, 2) + Math.pow(touches[0].clientY - touches[1].clientY, 2));
}
var ImagePreviewItem = {
  mixins: [TouchMixin],
  props: {
    src: String,
    show: Boolean,
    active: Number,
    minZoom: [Number, String],
    maxZoom: [Number, String],
    rootWidth: Number,
    rootHeight: Number
  },
  data: function data() {
    return {
      scale: 1,
      moveX: 0,
      moveY: 0,
      moving: false,
      zooming: false,
      imageRatio: 0,
      displayWidth: 0,
      displayHeight: 0
    };
  },
  computed: {
    vertical: function vertical() {
      var rootWidth = this.rootWidth,
        rootHeight = this.rootHeight;
      var rootRatio = rootHeight / rootWidth;
      return this.imageRatio > rootRatio;
    },
    imageStyle: function imageStyle() {
      var scale = this.scale;
      var style = {
        transitionDuration: this.zooming || this.moving ? '0s' : '.3s'
      };
      if (scale !== 1) {
        var offsetX = this.moveX / scale;
        var offsetY = this.moveY / scale;
        style.transform = "scale(" + scale + ", " + scale + ") translate(" + offsetX + "px, " + offsetY + "px)";
      }
      return style;
    },
    maxMoveX: function maxMoveX() {
      if (this.imageRatio) {
        var displayWidth = this.vertical ? this.rootHeight / this.imageRatio : this.rootWidth;
        return Math.max(0, (this.scale * displayWidth - this.rootWidth) / 2);
      }
      return 0;
    },
    maxMoveY: function maxMoveY() {
      if (this.imageRatio) {
        var displayHeight = this.vertical ? this.rootHeight : this.rootWidth * this.imageRatio;
        return Math.max(0, (this.scale * displayHeight - this.rootHeight) / 2);
      }
      return 0;
    }
  },
  watch: {
    active: 'resetScale',
    show: function show(val) {
      if (!val) {
        this.resetScale();
      }
    }
  },
  mounted: function mounted() {
    this.bindTouchEvent(this.$el);
  },
  methods: {
    resetScale: function resetScale() {
      this.setScale(1);
      this.moveX = 0;
      this.moveY = 0;
    },
    setScale: function setScale(scale) {
      scale = range(scale, +this.minZoom, +this.maxZoom);
      if (scale !== this.scale) {
        this.scale = scale;
        this.$emit('scale', {
          scale: this.scale,
          index: this.active
        });
      }
    },
    toggleScale: function toggleScale() {
      var scale = this.scale > 1 ? 1 : 2;
      this.setScale(scale);
      this.moveX = 0;
      this.moveY = 0;
    },
    onTouchStart: function onTouchStart(event) {
      var touches = event.touches;
      var _this$offsetX = this.offsetX,
        offsetX = _this$offsetX === void 0 ? 0 : _this$offsetX;
      this.touchStart(event);
      this.touchStartTime = new Date();
      this.fingerNum = touches.length;
      this.startMoveX = this.moveX;
      this.startMoveY = this.moveY;
      this.moving = this.fingerNum === 1 && this.scale !== 1;
      this.zooming = this.fingerNum === 2 && !offsetX;
      if (this.zooming) {
        this.startScale = this.scale;
        this.startDistance = getDistance(event.touches);
      }
    },
    onTouchMove: function onTouchMove(event) {
      var touches = event.touches;
      this.touchMove(event);
      if (this.moving || this.zooming) {
        preventDefault(event, true);
      }
      if (this.moving) {
        var moveX = this.deltaX + this.startMoveX;
        var moveY = this.deltaY + this.startMoveY;
        this.moveX = range(moveX, -this.maxMoveX, this.maxMoveX);
        this.moveY = range(moveY, -this.maxMoveY, this.maxMoveY);
      }
      if (this.zooming && touches.length === 2) {
        var distance = getDistance(touches);
        var scale = this.startScale * distance / this.startDistance;
        this.setScale(scale);
      }
    },
    onTouchEnd: function onTouchEnd(event) {
      var stopPropagation = false;
      /* istanbul ignore else */

      if (this.moving || this.zooming) {
        stopPropagation = true;
        if (this.moving && this.startMoveX === this.moveX && this.startMoveY === this.moveY) {
          stopPropagation = false;
        }
        if (!event.touches.length) {
          if (this.zooming) {
            this.moveX = range(this.moveX, -this.maxMoveX, this.maxMoveX);
            this.moveY = range(this.moveY, -this.maxMoveY, this.maxMoveY);
            this.zooming = false;
          }
          this.moving = false;
          this.startMoveX = 0;
          this.startMoveY = 0;
          this.startScale = 1;
          if (this.scale < 1) {
            this.resetScale();
          }
        }
      } // eliminate tap delay on safari

      preventDefault(event, stopPropagation);
      this.checkTap();
      this.resetTouchStatus();
    },
    checkTap: function checkTap() {
      var _this = this;
      if (this.fingerNum > 1) {
        return;
      }
      var _this$offsetX2 = this.offsetX,
        offsetX = _this$offsetX2 === void 0 ? 0 : _this$offsetX2,
        _this$offsetY = this.offsetY,
        offsetY = _this$offsetY === void 0 ? 0 : _this$offsetY;
      var deltaTime = new Date() - this.touchStartTime;
      var TAP_TIME = 250;
      var TAP_OFFSET = 5;
      if (offsetX < TAP_OFFSET && offsetY < TAP_OFFSET && deltaTime < TAP_TIME) {
        if (this.doubleTapTimer) {
          clearTimeout(this.doubleTapTimer);
          this.doubleTapTimer = null;
          this.toggleScale();
        } else {
          this.doubleTapTimer = setTimeout(function () {
            _this.$emit('close');
            _this.doubleTapTimer = null;
          }, TAP_TIME);
        }
      }
    },
    onLoad: function onLoad(event) {
      var _event$target = event.target,
        naturalWidth = _event$target.naturalWidth,
        naturalHeight = _event$target.naturalHeight;
      this.imageRatio = naturalHeight / naturalWidth;
    }
  },
  render: function render() {
    var h = arguments[0];
    var imageSlots = {
      loading: function loading() {
        return h(Loading$1, {
          "attrs": {
            "type": "spinner"
          }
        });
      }
    };
    return h(SwipeItem, {
      "class": bem$E('swipe-item')
    }, [h(Image$1, {
      "attrs": {
        "src": this.src,
        "fit": "contain"
      },
      "class": bem$E('image', {
        vertical: this.vertical
      }),
      "style": this.imageStyle,
      "scopedSlots": imageSlots,
      "on": {
        "load": this.onLoad
      }
    })]);
  }
};

// Utils
var VueImagePreview = createComponent$J({
  mixins: [TouchMixin, PopupMixin({
    skipToggleEvent: true
  }), BindEventMixin(function (bind) {
    bind(window, 'resize', this.resize, true);
    bind(window, 'orientationchange', this.resize, true);
  })],
  props: {
    className: null,
    closeable: Boolean,
    asyncClose: Boolean,
    overlayStyle: Object,
    showIndicators: Boolean,
    images: {
      type: Array,
      default: function _default() {
        return [];
      }
    },
    loop: {
      type: Boolean,
      default: true
    },
    overlay: {
      type: Boolean,
      default: true
    },
    minZoom: {
      type: [Number, String],
      default: 1 / 3
    },
    maxZoom: {
      type: [Number, String],
      default: 3
    },
    transition: {
      type: String,
      default: 'van-fade'
    },
    showIndex: {
      type: Boolean,
      default: true
    },
    swipeDuration: {
      type: [Number, String],
      default: 300
    },
    startPosition: {
      type: [Number, String],
      default: 0
    },
    overlayClass: {
      type: String,
      default: bem$E('overlay')
    },
    closeIcon: {
      type: String,
      default: 'clear'
    },
    closeOnPopstate: {
      type: Boolean,
      default: true
    },
    closeIconPosition: {
      type: String,
      default: 'top-right'
    }
  },
  data: function data() {
    return {
      active: 0,
      rootWidth: 0,
      rootHeight: 0,
      doubleClickTimer: null
    };
  },
  mounted: function mounted() {
    this.resize();
  },
  watch: {
    startPosition: 'setActive',
    value: function value(val) {
      var _this = this;
      if (val) {
        this.setActive(+this.startPosition);
        this.$nextTick(function () {
          _this.resize();
          _this.$refs.swipe.swipeTo(+_this.startPosition, {
            immediate: true
          });
        });
      } else {
        this.$emit('close', {
          index: this.active,
          url: this.images[this.active]
        });
      }
    }
  },
  methods: {
    resize: function resize() {
      if (this.$el && this.$el.getBoundingClientRect) {
        var rect = this.$el.getBoundingClientRect();
        this.rootWidth = rect.width;
        this.rootHeight = rect.height;
      }
    },
    emitClose: function emitClose() {
      if (!this.asyncClose) {
        this.$emit('input', false);
      }
    },
    emitScale: function emitScale(args) {
      this.$emit('scale', args);
    },
    setActive: function setActive(active) {
      if (active !== this.active) {
        this.active = active;
        this.$emit('change', active);
      }
    },
    genIndex: function genIndex() {
      var h = this.$createElement;
      if (this.showIndex) {
        return h("div", {
          "class": bem$E('index')
        }, [this.slots('index', {
          index: this.active
        }) || this.active + 1 + " / " + this.images.length]);
      }
    },
    genCover: function genCover() {
      var h = this.$createElement;
      var cover = this.slots('cover');
      if (cover) {
        return h("div", {
          "class": bem$E('cover')
        }, [cover]);
      }
    },
    genImages: function genImages() {
      var _this2 = this;
      var h = this.$createElement;
      return h(Swipe, {
        "ref": "swipe",
        "attrs": {
          "lazyRender": true,
          "loop": this.loop,
          "duration": this.swipeDuration,
          "initialSwipe": this.startPosition,
          "showIndicators": this.showIndicators,
          "indicatorColor": "white"
        },
        "class": bem$E('swipe'),
        "on": {
          "change": this.setActive
        }
      }, [this.images.map(function (image) {
        return h(ImagePreviewItem, {
          "attrs": {
            "src": image,
            "show": _this2.value,
            "active": _this2.active,
            "maxZoom": _this2.maxZoom,
            "minZoom": _this2.minZoom,
            "rootWidth": _this2.rootWidth,
            "rootHeight": _this2.rootHeight
          },
          "on": {
            "scale": _this2.emitScale,
            "close": _this2.emitClose
          }
        });
      })]);
    },
    genClose: function genClose() {
      var h = this.$createElement;
      if (this.closeable) {
        return h(Icon$1, {
          "attrs": {
            "role": "button",
            "name": this.closeIcon
          },
          "class": bem$E('close-icon', this.closeIconPosition),
          "on": {
            "click": this.emitClose
          }
        });
      }
    },
    onClosed: function onClosed() {
      this.$emit('closed');
    },
    // @exposed-api
    swipeTo: function swipeTo(index, options) {
      if (this.$refs.swipe) {
        this.$refs.swipe.swipeTo(index, options);
      }
    }
  },
  render: function render() {
    var h = arguments[0];
    return h("transition", {
      "attrs": {
        "name": this.transition
      },
      "on": {
        "afterLeave": this.onClosed
      }
    }, [this.shouldRender ? h("div", {
      "directives": [{
        name: "show",
        value: this.value
      }],
      "class": [bem$E(), this.className]
    }, [this.genClose(), this.genImages(), this.genIndex(), this.genCover()]) : null]);
  }
});

var instance$1;
var defaultConfig = {
  loop: true,
  value: true,
  images: [],
  maxZoom: 3,
  minZoom: 1 / 3,
  onClose: null,
  onChange: null,
  className: '',
  showIndex: true,
  closeable: false,
  closeIcon: 'clear',
  asyncClose: false,
  transition: 'van-fade',
  getContainer: 'body',
  overlayStyle: null,
  startPosition: 0,
  swipeDuration: 300,
  showIndicators: false,
  closeOnPopstate: true,
  closeIconPosition: 'top-right'
};
var initInstance = function initInstance() {
  instance$1 = new (Vue.extend(VueImagePreview))({
    el: document.createElement('div')
  });
  document.body.appendChild(instance$1.$el);
  instance$1.$on('change', function (index) {
    if (instance$1.onChange) {
      instance$1.onChange(index);
    }
  });
  instance$1.$on('scale', function (data) {
    if (instance$1.onScale) {
      instance$1.onScale(data);
    }
  });
};
var ImagePreview = function ImagePreview(images, startPosition) {
  if (startPosition === void 0) {
    startPosition = 0;
  }

  /* istanbul ignore if */
  if (isServer) {
    return;
  }
  if (!instance$1) {
    initInstance();
  }
  var options = Array.isArray(images) ? {
    images: images,
    startPosition: startPosition
  } : images;
  _extends$1(instance$1, defaultConfig, options);
  instance$1.$once('input', function (show) {
    instance$1.value = show;
  });
  instance$1.$once('closed', function () {
    instance$1.images = [];
  });
  if (options.onClose) {
    instance$1.$off('close');
    instance$1.$once('close', options.onClose);
  }
  return instance$1;
};
ImagePreview.Component = VueImagePreview;
ImagePreview.install = function () {
  Vue.use(VueImagePreview);
};
var ImagePreview$1 = ImagePreview;

var _createNamespace$C = createNamespace('index-anchor'),
  createComponent$G = _createNamespace$C[0],
  bem$B = _createNamespace$C[1];
var IndexAnchor = createComponent$G({
  mixins: [ChildrenMixin('vanIndexBar', {
    indexKey: 'childrenIndex'
  })],
  props: {
    index: [Number, String]
  },
  data: function data() {
    return {
      top: 0,
      left: null,
      rect: {
        top: 0,
        height: 0
      },
      width: null,
      active: false
    };
  },
  computed: {
    sticky: function sticky() {
      return this.active && this.parent.sticky;
    },
    anchorStyle: function anchorStyle() {
      if (this.sticky) {
        return {
          zIndex: "" + this.parent.zIndex,
          left: this.left ? this.left + "px" : null,
          width: this.width ? this.width + "px" : null,
          transform: "translate3d(0, " + this.top + "px, 0)",
          color: this.parent.highlightColor
        };
      }
    }
  },
  mounted: function mounted() {
    var rect = this.$el.getBoundingClientRect();
    this.rect.height = rect.height;
  },
  methods: {
    scrollIntoView: function scrollIntoView() {
      this.$el.scrollIntoView();
    },
    getRect: function getRect(scroller, scrollerRect) {
      var el = this.$el;
      var elRect = el.getBoundingClientRect();
      this.rect.height = elRect.height;
      if (scroller === window || scroller === document.body) {
        this.rect.top = elRect.top + getRootScrollTop();
      } else {
        this.rect.top = elRect.top + getScrollTop(scroller) - scrollerRect.top;
      }
      return this.rect;
    }
  },
  render: function render() {
    var _ref;
    var h = arguments[0];
    var sticky = this.sticky;
    return h("div", {
      "style": {
        height: sticky ? this.rect.height + "px" : null
      }
    }, [h("div", {
      "style": this.anchorStyle,
      "class": [bem$B({
        sticky: sticky
      }), (_ref = {}, _ref[BORDER_BOTTOM] = sticky, _ref)]
    }, [this.slots('default') || this.index])]);
  }
});

// Utils
function genAlphabet() {
  var indexList = [];
  var charCodeOfA = 'A'.charCodeAt(0);
  for (var i = 0; i < 26; i++) {
    indexList.push(String.fromCharCode(charCodeOfA + i));
  }
  return indexList;
}
var _createNamespace$B = createNamespace('index-bar'),
  createComponent$F = _createNamespace$B[0],
  bem$A = _createNamespace$B[1];
var IndexBar = createComponent$F({
  mixins: [TouchMixin, ParentMixin('vanIndexBar'), BindEventMixin(function (bind) {
    if (!this.scroller) {
      this.scroller = getScroller(this.$el);
    }
    bind(this.scroller, 'scroll', this.onScroll);
  })],
  props: {
    zIndex: [Number, String],
    highlightColor: String,
    sticky: {
      type: Boolean,
      default: true
    },
    stickyOffsetTop: {
      type: Number,
      default: 0
    },
    indexList: {
      type: Array,
      default: genAlphabet
    }
  },
  data: function data() {
    return {
      activeAnchorIndex: null
    };
  },
  computed: {
    sidebarStyle: function sidebarStyle() {
      if (isDef(this.zIndex)) {
        return {
          zIndex: this.zIndex + 1
        };
      }
    },
    highlightStyle: function highlightStyle() {
      var highlightColor = this.highlightColor;
      if (highlightColor) {
        return {
          color: highlightColor
        };
      }
    }
  },
  watch: {
    indexList: function indexList() {
      this.$nextTick(this.onScroll);
    },
    activeAnchorIndex: function activeAnchorIndex(value) {
      if (value) {
        this.$emit('change', value);
      }
    }
  },
  methods: {
    onScroll: function onScroll() {
      var _this = this;
      if (isHidden(this.$el)) {
        return;
      }
      var scrollTop = getScrollTop(this.scroller);
      var scrollerRect = this.getScrollerRect();
      var rects = this.children.map(function (item) {
        return item.getRect(_this.scroller, scrollerRect);
      });
      var active = this.getActiveAnchorIndex(scrollTop, rects);
      this.activeAnchorIndex = this.indexList[active];
      if (this.sticky) {
        this.children.forEach(function (item, index) {
          if (index === active || index === active - 1) {
            var rect = item.$el.getBoundingClientRect();
            item.left = rect.left;
            item.width = rect.width;
          } else {
            item.left = null;
            item.width = null;
          }
          if (index === active) {
            item.active = true;
            item.top = Math.max(_this.stickyOffsetTop, rects[index].top - scrollTop) + scrollerRect.top;
          } else if (index === active - 1) {
            var activeItemTop = rects[active].top - scrollTop;
            item.active = activeItemTop > 0;
            item.top = activeItemTop + scrollerRect.top - rects[index].height;
          } else {
            item.active = false;
          }
        });
      }
    },
    getScrollerRect: function getScrollerRect() {
      if (this.scroller.getBoundingClientRect) {
        return this.scroller.getBoundingClientRect();
      }
      return {
        top: 0,
        left: 0
      };
    },
    getActiveAnchorIndex: function getActiveAnchorIndex(scrollTop, rects) {
      for (var i = this.children.length - 1; i >= 0; i--) {
        var prevHeight = i > 0 ? rects[i - 1].height : 0;
        var reachTop = this.sticky ? prevHeight + this.stickyOffsetTop : 0;
        if (scrollTop + reachTop >= rects[i].top) {
          return i;
        }
      }
      return -1;
    },
    onClick: function onClick(event) {
      this.scrollToElement(event.target);
    },
    onTouchMove: function onTouchMove(event) {
      this.touchMove(event);
      if (this.direction === 'vertical') {
        preventDefault(event);
        var _event$touches$ = event.touches[0],
          clientX = _event$touches$.clientX,
          clientY = _event$touches$.clientY;
        var target = document.elementFromPoint(clientX, clientY);
        if (target) {
          var index = target.dataset.index;
          /* istanbul ignore else */

          if (this.touchActiveIndex !== index) {
            this.touchActiveIndex = index;
            this.scrollToElement(target);
          }
        }
      }
    },
    scrollTo: function scrollTo(index) {
      var match = this.children.filter(function (item) {
        return String(item.index) === index;
      });
      if (match[0]) {
        match[0].scrollIntoView();
        if (this.sticky && this.stickyOffsetTop) {
          setRootScrollTop(getRootScrollTop() - this.stickyOffsetTop);
        }
        this.$emit('select', match[0].index);
      }
    },
    scrollToElement: function scrollToElement(element) {
      var index = element.dataset.index;
      this.scrollTo(index);
    },
    onTouchEnd: function onTouchEnd() {
      this.active = null;
    }
  },
  render: function render() {
    var _this2 = this;
    var h = arguments[0];
    var Indexes = this.indexList.map(function (index) {
      var active = index === _this2.activeAnchorIndex;
      return h("span", {
        "class": bem$A('index', {
          active: active
        }),
        "style": active ? _this2.highlightStyle : null,
        "attrs": {
          "data-index": index
        }
      }, [index]);
    });
    return h("div", {
      "class": bem$A()
    }, [h("div", {
      "class": bem$A('sidebar'),
      "style": this.sidebarStyle,
      "on": {
        "click": this.onClick,
        "touchstart": this.touchStart,
        "touchmove": this.onTouchMove,
        "touchend": this.onTouchEnd,
        "touchcancel": this.onTouchEnd
      }
    }, [Indexes]), this.slots('default')]);
  }
});

// Utils
var _createNamespace$A = createNamespace('list'),
  createComponent$E = _createNamespace$A[0],
  bem$z = _createNamespace$A[1],
  t$d = _createNamespace$A[2];
var List = createComponent$E({
  mixins: [BindEventMixin(function (bind) {
    if (!this.scroller) {
      this.scroller = getScroller(this.$el);
    }
    bind(this.scroller, 'scroll', this.check);
  })],
  model: {
    prop: 'loading'
  },
  props: {
    error: Boolean,
    loading: Boolean,
    finished: Boolean,
    errorText: String,
    loadingText: String,
    finishedText: String,
    immediateCheck: {
      type: Boolean,
      default: true
    },
    offset: {
      type: [Number, String],
      default: 300
    },
    direction: {
      type: String,
      default: 'down'
    }
  },
  data: function data() {
    return {
      // use sync innerLoading state to avoid repeated loading in some edge cases
      innerLoading: this.loading
    };
  },
  updated: function updated() {
    this.innerLoading = this.loading;
  },
  mounted: function mounted() {
    if (this.immediateCheck) {
      this.check();
    }
  },
  watch: {
    loading: 'check',
    finished: 'check'
  },
  methods: {
    // @exposed-api
    check: function check() {
      var _this = this;
      this.$nextTick(function () {
        if (_this.innerLoading || _this.finished || _this.error) {
          return;
        }
        var el = _this.$el,
          scroller = _this.scroller,
          offset = _this.offset,
          direction = _this.direction;
        var scrollerRect;
        if (scroller.getBoundingClientRect) {
          scrollerRect = scroller.getBoundingClientRect();
        } else {
          scrollerRect = {
            top: 0,
            bottom: scroller.innerHeight
          };
        }
        var scrollerHeight = scrollerRect.bottom - scrollerRect.top;
        /* istanbul ignore next */

        if (!scrollerHeight || isHidden(el)) {
          return false;
        }
        var isReachEdge = false;
        var placeholderRect = _this.$refs.placeholder.getBoundingClientRect();
        if (direction === 'up') {
          isReachEdge = scrollerRect.top - placeholderRect.top <= offset;
        } else {
          isReachEdge = placeholderRect.bottom - scrollerRect.bottom <= offset;
        }
        if (isReachEdge) {
          _this.innerLoading = true;
          _this.$emit('input', true);
          _this.$emit('load');
        }
      });
    },
    clickErrorText: function clickErrorText() {
      this.$emit('update:error', false);
      this.check();
    },
    genLoading: function genLoading() {
      var h = this.$createElement;
      if (this.innerLoading && !this.finished) {
        return h("div", {
          "key": "loading",
          "class": bem$z('loading')
        }, [this.slots('loading') || h(Loading$1, {
          "attrs": {
            "size": "16"
          }
        }, [this.loadingText || t$d('loading')])]);
      }
    },
    genFinishedText: function genFinishedText() {
      var h = this.$createElement;
      if (this.finished) {
        var text = this.slots('finished') || this.finishedText;
        if (text) {
          return h("div", {
            "class": bem$z('finished-text')
          }, [text]);
        }
      }
    },
    genErrorText: function genErrorText() {
      var h = this.$createElement;
      if (this.error) {
        var text = this.slots('error') || this.errorText;
        if (text) {
          return h("div", {
            "on": {
              "click": this.clickErrorText
            },
            "class": bem$z('error-text')
          }, [text]);
        }
      }
    }
  },
  render: function render() {
    var h = arguments[0];
    var Placeholder = h("div", {
      "ref": "placeholder",
      "key": "placeholder",
      "class": bem$z('placeholder')
    });
    return h("div", {
      "class": bem$z(),
      "attrs": {
        "role": "feed",
        "aria-busy": this.innerLoading
      }
    }, [this.direction === 'down' ? this.slots() : Placeholder, this.genLoading(), this.genFinishedText(), this.genErrorText(), this.direction === 'up' ? this.slots() : Placeholder]);
  }
});

// Utils
var _createNamespace$z = createNamespace('nav-bar'),
  createComponent$D = _createNamespace$z[0],
  bem$y = _createNamespace$z[1];
var NavBar = createComponent$D({
  props: {
    title: String,
    fixed: Boolean,
    zIndex: [Number, String],
    leftText: String,
    rightText: String,
    leftArrow: Boolean,
    placeholder: Boolean,
    safeAreaInsetTop: Boolean,
    border: {
      type: Boolean,
      default: true
    }
  },
  data: function data() {
    return {
      height: null
    };
  },
  mounted: function mounted() {
    var _this = this;
    if (this.placeholder && this.fixed) {
      var setHeight = function setHeight() {
        _this.height = _this.$refs.navBar.getBoundingClientRect().height;
      };
      setHeight(); // https://github.com/vant-ui/vant/issues/10131

      setTimeout(setHeight, 100);
    }
  },
  methods: {
    genLeft: function genLeft() {
      var h = this.$createElement;
      var leftSlot = this.slots('left');
      if (leftSlot) {
        return leftSlot;
      }
      return [this.leftArrow && h(Icon$1, {
        "class": bem$y('arrow'),
        "attrs": {
          "name": "arrow-left"
        }
      }), this.leftText && h("span", {
        "class": bem$y('text')
      }, [this.leftText])];
    },
    genRight: function genRight() {
      var h = this.$createElement;
      var rightSlot = this.slots('right');
      if (rightSlot) {
        return rightSlot;
      }
      if (this.rightText) {
        return h("span", {
          "class": bem$y('text')
        }, [this.rightText]);
      }
    },
    genNavBar: function genNavBar() {
      var _ref;
      var h = this.$createElement;
      return h("div", {
        "ref": "navBar",
        "style": {
          zIndex: this.zIndex
        },
        "class": [bem$y({
          fixed: this.fixed,
          'safe-area-inset-top': this.safeAreaInsetTop
        }), (_ref = {}, _ref[BORDER_BOTTOM] = this.border, _ref)]
      }, [h("div", {
        "class": bem$y('content')
      }, [this.hasLeft() && h("div", {
        "class": bem$y('left'),
        "on": {
          "click": this.onClickLeft
        }
      }, [this.genLeft()]), h("div", {
        "class": [bem$y('title'), 'van-ellipsis']
      }, [this.slots('title') || this.title]), this.hasRight() && h("div", {
        "class": bem$y('right'),
        "on": {
          "click": this.onClickRight
        }
      }, [this.genRight()])])]);
    },
    hasLeft: function hasLeft() {
      return this.leftArrow || this.leftText || this.slots('left');
    },
    hasRight: function hasRight() {
      return this.rightText || this.slots('right');
    },
    onClickLeft: function onClickLeft(event) {
      this.$emit('click-left', event);
    },
    onClickRight: function onClickRight(event) {
      this.$emit('click-right', event);
    }
  },
  render: function render() {
    var h = arguments[0];
    if (this.placeholder && this.fixed) {
      return h("div", {
        "class": bem$y('placeholder'),
        "style": {
          height: this.height + "px"
        }
      }, [this.genNavBar()]);
    }
    return this.genNavBar();
  }
});

var _createNamespace$y = createNamespace('notice-bar'),
  createComponent$C = _createNamespace$y[0],
  bem$x = _createNamespace$y[1];
var NoticeBar = createComponent$C({
  mixins: [BindEventMixin(function (bind) {
    // fix cache issues with forwards and back history in safari
    // see: https://guwii.com/cache-issues-with-forwards-and-back-history-in-safari/
    bind(window, 'pageshow', this.reset);
  })],
  inject: {
    vanPopup: {
      default: null
    }
  },
  props: {
    text: String,
    mode: String,
    color: String,
    leftIcon: String,
    wrapable: Boolean,
    background: String,
    scrollable: {
      type: Boolean,
      default: null
    },
    delay: {
      type: [Number, String],
      default: 1
    },
    speed: {
      type: [Number, String],
      default: 60
    }
  },
  data: function data() {
    return {
      show: true,
      offset: 0,
      duration: 0,
      wrapWidth: 0,
      contentWidth: 0
    };
  },
  watch: {
    scrollable: 'reset',
    text: {
      handler: 'reset',
      immediate: true
    }
  },
  created: function created() {
    // https://github.com/vant-ui/vant/issues/8634
    if (this.vanPopup) {
      this.vanPopup.onReopen(this.reset);
    }
  },
  activated: function activated() {
    this.reset();
  },
  methods: {
    onClickIcon: function onClickIcon(event) {
      if (this.mode === 'closeable') {
        this.show = false;
        this.$emit('close', event);
      }
    },
    onTransitionEnd: function onTransitionEnd() {
      var _this = this;
      this.offset = this.wrapWidth;
      this.duration = 0; // wait for Vue to render offset
      // using nextTick won't work in iOS14

      raf(function () {
        // use double raf to ensure animation can start
        doubleRaf(function () {
          _this.offset = -_this.contentWidth;
          _this.duration = (_this.contentWidth + _this.wrapWidth) / _this.speed;
          _this.$emit('replay');
        });
      });
    },
    // not an exposed-api, but may used by some users
    start: function start() {
      this.reset();
    },
    // @exposed-api
    reset: function reset() {
      var _this2 = this;
      var delay = isDef(this.delay) ? this.delay * 1000 : 0;
      this.offset = 0;
      this.duration = 0;
      this.wrapWidth = 0;
      this.contentWidth = 0;
      clearTimeout(this.startTimer);
      this.startTimer = setTimeout(function () {
        var _this2$$refs = _this2.$refs,
          wrap = _this2$$refs.wrap,
          content = _this2$$refs.content;
        if (!wrap || !content || _this2.scrollable === false) {
          return;
        }
        var wrapWidth = wrap.getBoundingClientRect().width;
        var contentWidth = content.getBoundingClientRect().width;
        if (_this2.scrollable || contentWidth > wrapWidth) {
          doubleRaf(function () {
            _this2.offset = -contentWidth;
            _this2.duration = contentWidth / _this2.speed;
            _this2.wrapWidth = wrapWidth;
            _this2.contentWidth = contentWidth;
          });
        }
      }, delay);
    }
  },
  render: function render() {
    var _this3 = this;
    var h = arguments[0];
    var slots = this.slots,
      mode = this.mode,
      leftIcon = this.leftIcon,
      onClickIcon = this.onClickIcon;
    var barStyle = {
      color: this.color,
      background: this.background
    };
    var contentStyle = {
      transform: this.offset ? "translateX(" + this.offset + "px)" : '',
      transitionDuration: this.duration + 's'
    };
    function LeftIcon() {
      var slot = slots('left-icon');
      if (slot) {
        return slot;
      }
      if (leftIcon) {
        return h(Icon$1, {
          "class": bem$x('left-icon'),
          "attrs": {
            "name": leftIcon
          }
        });
      }
    }
    function RightIcon() {
      var slot = slots('right-icon');
      if (slot) {
        return slot;
      }
      var iconName;
      if (mode === 'closeable') {
        iconName = 'cross';
      } else if (mode === 'link') {
        iconName = 'arrow';
      }
      if (iconName) {
        return h(Icon$1, {
          "class": bem$x('right-icon'),
          "attrs": {
            "name": iconName
          },
          "on": {
            "click": onClickIcon
          }
        });
      }
    }
    return h("div", {
      "attrs": {
        "role": "alert"
      },
      "directives": [{
        name: "show",
        value: this.show
      }],
      "class": bem$x({
        wrapable: this.wrapable
      }),
      "style": barStyle,
      "on": {
        "click": function click(event) {
          _this3.$emit('click', event);
        }
      }
    }, [LeftIcon(), h("div", {
      "ref": "wrap",
      "class": bem$x('wrap'),
      "attrs": {
        "role": "marquee"
      }
    }, [h("div", {
      "ref": "content",
      "class": [bem$x('content'), {
        'van-ellipsis': this.scrollable === false && !this.wrapable
      }],
      "style": contentStyle,
      "on": {
        "transitionend": this.onTransitionEnd
      }
    }, [this.slots() || this.text])]), RightIcon()]);
  }
});

var _createNamespace$x = createNamespace('notify'),
  createComponent$B = _createNamespace$x[0],
  bem$w = _createNamespace$x[1];
function Notify$1(h, props, slots, ctx) {
  var style = {
    color: props.color,
    background: props.background
  };
  return h(Popup, _mergeJSXProps([{
    "attrs": {
      "value": props.value,
      "position": "top",
      "overlay": false,
      "duration": 0.2,
      "lockScroll": false
    },
    "style": style,
    "class": [bem$w([props.type]), props.className]
  }, inherit(ctx, true)]), [(slots.default == null ? void 0 : slots.default()) || props.message]);
}
Notify$1.props = _extends$1({}, popupMixinProps, {
  color: String,
  message: [Number, String],
  duration: [Number, String],
  className: null,
  background: String,
  getContainer: [String, Function],
  type: {
    type: String,
    default: 'danger'
  }
});
var VanNotify = createComponent$B(Notify$1);

var timer;
var instance;
function parseOptions(message) {
  return isObject(message) ? message : {
    message: message
  };
}
function Notify(options) {
  /* istanbul ignore if */
  if (isServer) {
    return;
  }
  if (!instance) {
    instance = mount(VanNotify, {
      on: {
        click: function click(event) {
          if (instance.onClick) {
            instance.onClick(event);
          }
        },
        close: function close() {
          if (instance.onClose) {
            instance.onClose();
          }
        },
        opened: function opened() {
          if (instance.onOpened) {
            instance.onOpened();
          }
        }
      }
    });
  }
  options = _extends$1({}, Notify.currentOptions, parseOptions(options));
  _extends$1(instance, options);
  clearTimeout(timer);
  if (options.duration && options.duration > 0) {
    timer = setTimeout(Notify.clear, options.duration);
  }
  return instance;
}
function defaultOptions() {
  return {
    type: 'danger',
    value: true,
    message: '',
    color: undefined,
    background: undefined,
    duration: 3000,
    className: '',
    onClose: null,
    onClick: null,
    onOpened: null
  };
}
Notify.clear = function () {
  if (instance) {
    instance.value = false;
  }
};
Notify.currentOptions = defaultOptions();
Notify.setDefaultOptions = function (options) {
  _extends$1(Notify.currentOptions, options);
};
Notify.resetDefaultOptions = function () {
  Notify.currentOptions = defaultOptions();
};
Notify.install = function () {
  Vue.use(VanNotify);
};
Notify.Component = VanNotify;
Vue.prototype.$notify = Notify;

var DeleteIcon = {
  render: function render() {
    var h = arguments[0];
    return h("svg", {
      "attrs": {
        "viewBox": "0 0 32 22",
        "xmlns": "http://www.w3.org/2000/svg"
      }
    }, [h("path", {
      "attrs": {
        "d": "M28.016 0A3.991 3.991 0 0132 3.987v14.026c0 2.2-1.787 3.987-3.98 3.987H10.382c-.509 0-.996-.206-1.374-.585L.89 13.09C.33 12.62 0 11.84 0 11.006c0-.86.325-1.62.887-2.08L9.01.585A1.936 1.936 0 0110.383 0zm0 1.947H10.368L2.24 10.28c-.224.226-.312.432-.312.73 0 .287.094.51.312.729l8.128 8.333h17.648a2.041 2.041 0 002.037-2.04V3.987c0-1.127-.915-2.04-2.037-2.04zM23.028 6a.96.96 0 01.678.292.95.95 0 01-.003 1.377l-3.342 3.348 3.326 3.333c.189.188.292.43.292.679 0 .248-.103.49-.292.679a.96.96 0 01-.678.292.959.959 0 01-.677-.292L18.99 12.36l-3.343 3.345a.96.96 0 01-.677.292.96.96 0 01-.678-.292.962.962 0 01-.292-.68c0-.248.104-.49.292-.679l3.342-3.348-3.342-3.348A.963.963 0 0114 6.971c0-.248.104-.49.292-.679A.96.96 0 0114.97 6a.96.96 0 01.677.292l3.358 3.348 3.345-3.348A.96.96 0 0123.028 6z",
        "fill": "currentColor"
      }
    })]);
  }
};

var CollapseIcon = {
  render: function render() {
    var h = arguments[0];
    return h("svg", {
      "attrs": {
        "viewBox": "0 0 30 24",
        "xmlns": "http://www.w3.org/2000/svg"
      }
    }, [h("path", {
      "attrs": {
        "d": "M25.877 12.843h-1.502c-.188 0-.188 0-.188.19v1.512c0 .188 0 .188.188.188h1.5c.187 0 .187 0 .187-.188v-1.511c0-.19 0-.191-.185-.191zM17.999 10.2c0 .188 0 .188.188.188h1.687c.188 0 .188 0 .188-.188V8.688c0-.187.004-.187-.186-.19h-1.69c-.187 0-.187 0-.187.19V10.2zm2.25-3.967h1.5c.188 0 .188 0 .188-.188v-1.7c0-.19 0-.19-.188-.19h-1.5c-.189 0-.189 0-.189.19v1.7c0 .188 0 .188.19.188zm2.063 4.157h3.563c.187 0 .187 0 .187-.189V4.346c0-.19.004-.19-.185-.19h-1.69c-.187 0-.187 0-.187.188v4.155h-1.688c-.187 0-.187 0-.187.189v1.514c0 .19 0 .19.187.19zM14.812 24l2.812-3.4H12l2.813 3.4zm-9-11.157H4.31c-.188 0-.188 0-.188.19v1.512c0 .188 0 .188.188.188h1.502c.187 0 .187 0 .187-.188v-1.511c0-.19.01-.191-.189-.191zm15.937 0H8.25c-.188 0-.188 0-.188.19v1.512c0 .188 0 .188.188.188h13.5c.188 0 .188 0 .188-.188v-1.511c0-.19 0-.191-.188-.191zm-11.438-2.454h1.5c.188 0 .188 0 .188-.188V8.688c0-.187 0-.187-.188-.189h-1.5c-.187 0-.187 0-.187.189V10.2c0 .188 0 .188.187.188zM27.94 0c.563 0 .917.21 1.313.567.518.466.748.757.748 1.51v14.92c0 .567-.188 1.134-.562 1.512-.376.378-.938.566-1.313.566H2.063c-.563 0-.938-.188-1.313-.566-.562-.378-.75-.945-.75-1.511V2.078C0 1.51.188.944.562.567.938.189 1.5 0 1.875 0zm-.062 2H2v14.92h25.877V2zM5.81 4.157c.19 0 .19 0 .19.189v1.762c-.003.126-.024.126-.188.126H4.249c-.126-.003-.126-.023-.126-.188v-1.7c-.187-.19 0-.19.188-.19zm10.5 2.077h1.503c.187 0 .187 0 .187-.188v-1.7c0-.19 0-.19-.187-.19h-1.502c-.188 0-.188.001-.188.19v1.7c0 .188 0 .188.188.188zM7.875 8.5c.187 0 .187.002.187.189V10.2c0 .188 0 .188-.187.188H4.249c-.126-.002-.126-.023-.126-.188V8.625c.003-.126.024-.126.188-.126zm7.875 0c.19.002.19.002.19.189v1.575c-.003.126-.024.126-.19.126h-1.563c-.126-.002-.126-.023-.126-.188V8.625c.002-.126.023-.126.189-.126zm-6-4.342c.187 0 .187 0 .187.189v1.7c0 .188 0 .188-.187.188H8.187c-.126-.003-.126-.023-.126-.188V4.283c.003-.126.024-.126.188-.126zm3.94 0c.185 0 .372 0 .372.189v1.762c-.002.126-.023.126-.187.126h-1.75C12 6.231 12 6.211 12 6.046v-1.7c0-.19.187-.19.187-.19z",
        "fill": "currentColor"
      }
    })]);
  }
};

var _createNamespace$w = createNamespace('key'),
  createComponent$A = _createNamespace$w[0],
  bem$v = _createNamespace$w[1];
var Key = createComponent$A({
  mixins: [TouchMixin],
  props: {
    type: String,
    text: [Number, String],
    color: String,
    wider: Boolean,
    large: Boolean,
    loading: Boolean
  },
  data: function data() {
    return {
      active: false
    };
  },
  mounted: function mounted() {
    this.bindTouchEvent(this.$el);
  },
  methods: {
    onTouchStart: function onTouchStart(event) {
      // compatible with Vue 2.6 event bubble bug
      event.stopPropagation();
      this.touchStart(event);
      this.active = true;
    },
    onTouchMove: function onTouchMove(event) {
      this.touchMove(event);
      if (this.direction) {
        this.active = false;
      }
    },
    onTouchEnd: function onTouchEnd(event) {
      if (this.active) {
        // eliminate tap delay on safari
        // see: https://github.com/vant-ui/vant/issues/6836
        if (!this.slots('default')) {
          event.preventDefault();
        }
        this.active = false;
        this.$emit('press', this.text, this.type);
      }
    },
    genContent: function genContent() {
      var h = this.$createElement;
      var isExtra = this.type === 'extra';
      var isDelete = this.type === 'delete';
      var text = this.slots('default') || this.text;
      if (this.loading) {
        return h(Loading$1, {
          "class": bem$v('loading-icon')
        });
      }
      if (isDelete) {
        return text || h(DeleteIcon, {
          "class": bem$v('delete-icon')
        });
      }
      if (isExtra) {
        return text || h(CollapseIcon, {
          "class": bem$v('collapse-icon')
        });
      }
      return text;
    }
  },
  render: function render() {
    var h = arguments[0];
    return h("div", {
      "class": bem$v('wrapper', {
        wider: this.wider
      })
    }, [h("div", {
      "attrs": {
        "role": "button",
        "tabindex": "0"
      },
      "class": bem$v([this.color, {
        large: this.large,
        active: this.active,
        delete: this.type === 'delete'
      }])
    }, [this.genContent()])]);
  }
});

var _createNamespace$v = createNamespace('number-keyboard'),
  createComponent$z = _createNamespace$v[0],
  bem$u = _createNamespace$v[1];
var NumberKeyboard = createComponent$z({
  mixins: [PortalMixin(), BindEventMixin(function (bind) {
    if (this.hideOnClickOutside) {
      bind(document.body, 'touchstart', this.onBlur);
    }
  })],
  model: {
    event: 'update:value'
  },
  props: {
    show: Boolean,
    title: String,
    zIndex: [Number, String],
    randomKeyOrder: Boolean,
    closeButtonText: String,
    deleteButtonText: String,
    closeButtonLoading: Boolean,
    theme: {
      type: String,
      default: 'default'
    },
    value: {
      type: String,
      default: ''
    },
    extraKey: {
      type: [String, Array],
      default: ''
    },
    maxlength: {
      type: [Number, String],
      default: Number.MAX_VALUE
    },
    transition: {
      type: Boolean,
      default: true
    },
    showDeleteKey: {
      type: Boolean,
      default: true
    },
    hideOnClickOutside: {
      type: Boolean,
      default: true
    },
    safeAreaInsetBottom: {
      type: Boolean,
      default: true
    }
  },
  watch: {
    show: function show(val) {
      if (!this.transition) {
        this.$emit(val ? 'show' : 'hide');
      }
    }
  },
  computed: {
    keys: function keys() {
      if (this.theme === 'custom') {
        return this.genCustomKeys();
      }
      return this.genDefaultKeys();
    }
  },
  methods: {
    genBasicKeys: function genBasicKeys() {
      var keys = [];
      for (var i = 1; i <= 9; i++) {
        keys.push({
          text: i
        });
      }
      if (this.randomKeyOrder) {
        keys.sort(function () {
          return Math.random() > 0.5 ? 1 : -1;
        });
      }
      return keys;
    },
    genDefaultKeys: function genDefaultKeys() {
      return [].concat(this.genBasicKeys(), [{
        text: this.extraKey,
        type: 'extra'
      }, {
        text: 0
      }, {
        text: this.showDeleteKey ? this.deleteButtonText : '',
        type: this.showDeleteKey ? 'delete' : ''
      }]);
    },
    genCustomKeys: function genCustomKeys() {
      var keys = this.genBasicKeys();
      var extraKey = this.extraKey;
      var extraKeys = Array.isArray(extraKey) ? extraKey : [extraKey];
      if (extraKeys.length === 1) {
        keys.push({
          text: 0,
          wider: true
        }, {
          text: extraKeys[0],
          type: 'extra'
        });
      } else if (extraKeys.length === 2) {
        keys.push({
          text: extraKeys[0],
          type: 'extra'
        }, {
          text: 0
        }, {
          text: extraKeys[1],
          type: 'extra'
        });
      }
      return keys;
    },
    onBlur: function onBlur() {
      this.show && this.$emit('blur');
    },
    onClose: function onClose() {
      this.$emit('close');
      this.onBlur();
    },
    onAnimationEnd: function onAnimationEnd() {
      this.$emit(this.show ? 'show' : 'hide');
    },
    onPress: function onPress(text, type) {
      if (text === '') {
        if (type === 'extra') {
          this.onBlur();
        }
        return;
      }
      var value = this.value;
      if (type === 'delete') {
        this.$emit('delete');
        this.$emit('update:value', value.slice(0, value.length - 1));
      } else if (type === 'close') {
        this.onClose();
      } else if (value.length < this.maxlength) {
        this.$emit('input', text);
        this.$emit('update:value', value + text);
      }
    },
    genTitle: function genTitle() {
      var h = this.$createElement;
      var title = this.title,
        theme = this.theme,
        closeButtonText = this.closeButtonText;
      var titleLeft = this.slots('title-left');
      var showClose = closeButtonText && theme === 'default';
      var showTitle = title || showClose || titleLeft;
      if (!showTitle) {
        return;
      }
      return h("div", {
        "class": bem$u('header')
      }, [titleLeft && h("span", {
        "class": bem$u('title-left')
      }, [titleLeft]), title && h("h2", {
        "class": bem$u('title')
      }, [title]), showClose && h("button", {
        "attrs": {
          "type": "button"
        },
        "class": bem$u('close'),
        "on": {
          "click": this.onClose
        }
      }, [closeButtonText])]);
    },
    genKeys: function genKeys() {
      var _this = this;
      var h = this.$createElement;
      return this.keys.map(function (key) {
        return h(Key, {
          "key": key.text,
          "attrs": {
            "text": key.text,
            "type": key.type,
            "wider": key.wider,
            "color": key.color
          },
          "on": {
            "press": _this.onPress
          }
        }, [key.type === 'delete' && _this.slots('delete'), key.type === 'extra' && _this.slots('extra-key')]);
      });
    },
    genSidebar: function genSidebar() {
      var h = this.$createElement;
      if (this.theme === 'custom') {
        return h("div", {
          "class": bem$u('sidebar')
        }, [this.showDeleteKey && h(Key, {
          "attrs": {
            "large": true,
            "text": this.deleteButtonText,
            "type": "delete"
          },
          "on": {
            "press": this.onPress
          }
        }, [this.slots('delete')]), h(Key, {
          "attrs": {
            "large": true,
            "text": this.closeButtonText,
            "type": "close",
            "color": "blue",
            "loading": this.closeButtonLoading
          },
          "on": {
            "press": this.onPress
          }
        })]);
      }
    }
  },
  render: function render() {
    var h = arguments[0];
    var Title = this.genTitle();
    return h("transition", {
      "attrs": {
        "name": this.transition ? 'van-slide-up' : ''
      }
    }, [h("div", {
      "directives": [{
        name: "show",
        value: this.show
      }],
      "style": {
        zIndex: this.zIndex
      },
      "class": bem$u({
        unfit: !this.safeAreaInsetBottom,
        'with-title': Title
      }),
      "on": {
        "touchstart": stopPropagation,
        "animationend": this.onAnimationEnd,
        "webkitAnimationEnd": this.onAnimationEnd
      }
    }, [Title, h("div", {
      "class": bem$u('body')
    }, [h("div", {
      "class": bem$u('keys')
    }, [this.genKeys()]), this.genSidebar()])])]);
  }
});

var _createNamespace$u = createNamespace('pagination'),
  createComponent$y = _createNamespace$u[0],
  bem$t = _createNamespace$u[1],
  t$c = _createNamespace$u[2];
function makePage(number, text, active) {
  return {
    number: number,
    text: text,
    active: active
  };
}
var Pagination = createComponent$y({
  props: {
    prevText: String,
    nextText: String,
    forceEllipses: Boolean,
    mode: {
      type: String,
      default: 'multi'
    },
    value: {
      type: Number,
      default: 0
    },
    pageCount: {
      type: [Number, String],
      default: 0
    },
    totalItems: {
      type: [Number, String],
      default: 0
    },
    itemsPerPage: {
      type: [Number, String],
      default: 10
    },
    showPageSize: {
      type: [Number, String],
      default: 5
    }
  },
  computed: {
    count: function count() {
      var count = this.pageCount || Math.ceil(this.totalItems / this.itemsPerPage);
      return Math.max(1, count);
    },
    pages: function pages() {
      var pages = [];
      var pageCount = this.count;
      var showPageSize = +this.showPageSize;
      if (this.mode !== 'multi') {
        return pages;
      } // Default page limits

      var startPage = 1;
      var endPage = pageCount;
      var isMaxSized = showPageSize < pageCount; // recompute if showPageSize

      if (isMaxSized) {
        // Current page is displayed in the middle of the visible ones
        startPage = Math.max(this.value - Math.floor(showPageSize / 2), 1);
        endPage = startPage + showPageSize - 1; // Adjust if limit is exceeded

        if (endPage > pageCount) {
          endPage = pageCount;
          startPage = endPage - showPageSize + 1;
        }
      } // Add page number links

      for (var number = startPage; number <= endPage; number++) {
        var page = makePage(number, number, number === this.value);
        pages.push(page);
      } // Add links to move between page sets

      if (isMaxSized && showPageSize > 0 && this.forceEllipses) {
        if (startPage > 1) {
          var previousPageSet = makePage(startPage - 1, '...', false);
          pages.unshift(previousPageSet);
        }
        if (endPage < pageCount) {
          var nextPageSet = makePage(endPage + 1, '...', false);
          pages.push(nextPageSet);
        }
      }
      return pages;
    }
  },
  watch: {
    value: {
      handler: function handler(page) {
        this.select(page || this.value);
      },
      immediate: true
    }
  },
  methods: {
    select: function select(page, emitChange) {
      page = Math.min(this.count, Math.max(1, page));
      if (this.value !== page) {
        this.$emit('input', page);
        if (emitChange) {
          this.$emit('change', page);
        }
      }
    }
  },
  render: function render() {
    var _this = this,
      _this$slots,
      _this$slots3;
    var h = arguments[0];
    var value = this.value;
    var simple = this.mode !== 'multi';
    var onSelect = function onSelect(value) {
      return function () {
        _this.select(value, true);
      };
    };
    return h("ul", {
      "class": bem$t({
        simple: simple
      })
    }, [h("li", {
      "class": [bem$t('item', {
        disabled: value === 1
      }), bem$t('prev'), BORDER],
      "on": {
        "click": onSelect(value - 1)
      }
    }, [((_this$slots = this.slots('prev-text')) != null ? _this$slots : this.prevText) || t$c('prev')]), this.pages.map(function (page) {
      var _this$slots2;
      return h("li", {
        "class": [bem$t('item', {
          active: page.active
        }), bem$t('page'), BORDER],
        "on": {
          "click": onSelect(page.number)
        }
      }, [(_this$slots2 = _this.slots('page', page)) != null ? _this$slots2 : page.text]);
    }), simple && h("li", {
      "class": bem$t('page-desc')
    }, [this.slots('pageDesc') || value + "/" + this.count]), h("li", {
      "class": [bem$t('item', {
        disabled: value === this.count
      }), bem$t('next'), BORDER],
      "on": {
        "click": onSelect(value + 1)
      }
    }, [((_this$slots3 = this.slots('next-text')) != null ? _this$slots3 : this.nextText) || t$c('next')])]);
  }
});

var _createNamespace$t = createNamespace('panel'),
  createComponent$x = _createNamespace$t[0],
  bem$s = _createNamespace$t[1];
function Panel(h, props, slots, ctx) {
  var Content = function Content() {
    return [slots.header ? slots.header() : h(Cell$1, {
      "attrs": {
        "icon": props.icon,
        "label": props.desc,
        "title": props.title,
        "value": props.status,
        "valueClass": bem$s('header-value')
      },
      "class": bem$s('header')
    }), h("div", {
      "class": bem$s('content')
    }, [slots.default && slots.default()]), slots.footer && h("div", {
      "class": [bem$s('footer'), BORDER_TOP]
    }, [slots.footer()])];
  };
  return h(CellGroup$1, _mergeJSXProps([{
    "class": bem$s(),
    "scopedSlots": {
      default: Content
    }
  }, inherit(ctx, true)]));
}
Panel.props = {
  icon: String,
  desc: String,
  title: String,
  status: String
};
var Panel$1 = createComponent$x(Panel);

var _createNamespace$s = createNamespace('password-input'),
  createComponent$w = _createNamespace$s[0],
  bem$r = _createNamespace$s[1];
function PasswordInput(h, props, slots, ctx) {
  var _ref2;
  var mask = props.mask,
    value = props.value,
    length = props.length,
    gutter = props.gutter,
    focused = props.focused,
    errorInfo = props.errorInfo;
  var info = errorInfo || props.info;
  var Points = [];
  for (var i = 0; i < length; i++) {
    var _ref;
    var _char = value[i];
    var showBorder = i !== 0 && !gutter;
    var showCursor = focused && i === value.length;
    var style = void 0;
    if (i !== 0 && gutter) {
      style = {
        marginLeft: addUnit(gutter)
      };
    }
    Points.push(h("li", {
      "class": [(_ref = {}, _ref[BORDER_LEFT] = showBorder, _ref), bem$r('item', {
        focus: showCursor
      })],
      "style": style
    }, [mask ? h("i", {
      "style": {
        visibility: _char ? 'visible' : 'hidden'
      }
    }) : _char, showCursor && h("div", {
      "class": bem$r('cursor')
    })]));
  }
  return h("div", {
    "class": bem$r()
  }, [h("ul", _mergeJSXProps([{
    "class": [bem$r('security'), (_ref2 = {}, _ref2[BORDER_SURROUND] = !gutter, _ref2)],
    "on": {
      "touchstart": function touchstart(event) {
        event.stopPropagation();
        emit(ctx, 'focus', event);
      }
    }
  }, inherit(ctx, true)]), [Points]), info && h("div", {
    "class": bem$r(errorInfo ? 'error-info' : 'info')
  }, [info])]);
}
PasswordInput.props = {
  info: String,
  gutter: [Number, String],
  focused: Boolean,
  errorInfo: String,
  mask: {
    type: Boolean,
    default: true
  },
  value: {
    type: String,
    default: ''
  },
  length: {
    type: [Number, String],
    default: 6
  }
};
var PasswordInput$1 = createComponent$w(PasswordInput);

// ../../node_modules/.pnpm/@popperjs+core@2.11.6/node_modules/@popperjs/core/lib/dom-utils/getWindow.js
function getWindow$1(node) {
  if (node == null) {
    return window;
  }
  if (node.toString() !== "[object Window]") {
    var ownerDocument = node.ownerDocument;
    return ownerDocument ? ownerDocument.defaultView || window : window;
  }
  return node;
}

// ../../node_modules/.pnpm/@popperjs+core@2.11.6/node_modules/@popperjs/core/lib/dom-utils/instanceOf.js
function isElement$2(node) {
  var OwnElement = getWindow$1(node).Element;
  return node instanceof OwnElement || node instanceof Element;
}
function isHTMLElement$1(node) {
  var OwnElement = getWindow$1(node).HTMLElement;
  return node instanceof OwnElement || node instanceof HTMLElement;
}
function isShadowRoot$1(node) {
  if (typeof ShadowRoot === "undefined") {
    return false;
  }
  var OwnElement = getWindow$1(node).ShadowRoot;
  return node instanceof OwnElement || node instanceof ShadowRoot;
}

// ../../node_modules/.pnpm/@popperjs+core@2.11.6/node_modules/@popperjs/core/lib/utils/math.js
var round$1 = Math.round;

// ../../node_modules/.pnpm/@popperjs+core@2.11.6/node_modules/@popperjs/core/lib/utils/userAgent.js
function getUAString$1() {
  var uaData = navigator.userAgentData;
  if (uaData != null && uaData.brands) {
    return uaData.brands.map(function (item) {
      return item.brand + "/" + item.version;
    }).join(" ");
  }
  return navigator.userAgent;
}

// ../../node_modules/.pnpm/@popperjs+core@2.11.6/node_modules/@popperjs/core/lib/dom-utils/isLayoutViewport.js
function isLayoutViewport$1() {
  return !/^((?!chrome|android).)*safari/i.test(getUAString$1());
}

// ../../node_modules/.pnpm/@popperjs+core@2.11.6/node_modules/@popperjs/core/lib/dom-utils/getBoundingClientRect.js
function getBoundingClientRect$1(element, includeScale, isFixedStrategy) {
  if (includeScale === void 0) {
    includeScale = false;
  }
  if (isFixedStrategy === void 0) {
    isFixedStrategy = false;
  }
  var clientRect = element.getBoundingClientRect();
  var scaleX = 1;
  var scaleY = 1;
  if (includeScale && isHTMLElement$1(element)) {
    scaleX = element.offsetWidth > 0 ? round$1(clientRect.width) / element.offsetWidth || 1 : 1;
    scaleY = element.offsetHeight > 0 ? round$1(clientRect.height) / element.offsetHeight || 1 : 1;
  }
  var _ref = isElement$2(element) ? getWindow$1(element) : window,
    visualViewport = _ref.visualViewport;
  var addVisualOffsets = !isLayoutViewport$1() && isFixedStrategy;
  var x = (clientRect.left + (addVisualOffsets && visualViewport ? visualViewport.offsetLeft : 0)) / scaleX;
  var y = (clientRect.top + (addVisualOffsets && visualViewport ? visualViewport.offsetTop : 0)) / scaleY;
  var width = clientRect.width / scaleX;
  var height = clientRect.height / scaleY;
  return {
    width,
    height,
    top: y,
    right: x + width,
    bottom: y + height,
    left: x,
    x,
    y
  };
}

// ../../node_modules/.pnpm/@popperjs+core@2.11.6/node_modules/@popperjs/core/lib/dom-utils/getWindowScroll.js
function getWindowScroll$1(node) {
  var win = getWindow$1(node);
  var scrollLeft = win.pageXOffset;
  var scrollTop = win.pageYOffset;
  return {
    scrollLeft,
    scrollTop
  };
}

// ../../node_modules/.pnpm/@popperjs+core@2.11.6/node_modules/@popperjs/core/lib/dom-utils/getHTMLElementScroll.js
function getHTMLElementScroll$1(element) {
  return {
    scrollLeft: element.scrollLeft,
    scrollTop: element.scrollTop
  };
}

// ../../node_modules/.pnpm/@popperjs+core@2.11.6/node_modules/@popperjs/core/lib/dom-utils/getNodeScroll.js
function getNodeScroll$1(node) {
  if (node === getWindow$1(node) || !isHTMLElement$1(node)) {
    return getWindowScroll$1(node);
  } else {
    return getHTMLElementScroll$1(node);
  }
}

// ../../node_modules/.pnpm/@popperjs+core@2.11.6/node_modules/@popperjs/core/lib/dom-utils/getNodeName.js
function getNodeName$1(element) {
  return element ? (element.nodeName || "").toLowerCase() : null;
}

// ../../node_modules/.pnpm/@popperjs+core@2.11.6/node_modules/@popperjs/core/lib/dom-utils/getDocumentElement.js
function getDocumentElement$1(element) {
  return ((isElement$2(element) ? element.ownerDocument : element.document) || window.document).documentElement;
}

// ../../node_modules/.pnpm/@popperjs+core@2.11.6/node_modules/@popperjs/core/lib/dom-utils/getWindowScrollBarX.js
function getWindowScrollBarX$1(element) {
  return getBoundingClientRect$1(getDocumentElement$1(element)).left + getWindowScroll$1(element).scrollLeft;
}

// ../../node_modules/.pnpm/@popperjs+core@2.11.6/node_modules/@popperjs/core/lib/dom-utils/getComputedStyle.js
function getComputedStyle$2(element) {
  return getWindow$1(element).getComputedStyle(element);
}

// ../../node_modules/.pnpm/@popperjs+core@2.11.6/node_modules/@popperjs/core/lib/dom-utils/isScrollParent.js
function isScrollParent$1(element) {
  var _getComputedStyle = getComputedStyle$2(element),
    overflow = _getComputedStyle.overflow,
    overflowX = _getComputedStyle.overflowX,
    overflowY = _getComputedStyle.overflowY;
  return /auto|scroll|overlay|hidden/.test(overflow + overflowY + overflowX);
}

// ../../node_modules/.pnpm/@popperjs+core@2.11.6/node_modules/@popperjs/core/lib/dom-utils/getCompositeRect.js
function isElementScaled$1(element) {
  var rect = element.getBoundingClientRect();
  var scaleX = round$1(rect.width) / element.offsetWidth || 1;
  var scaleY = round$1(rect.height) / element.offsetHeight || 1;
  return scaleX !== 1 || scaleY !== 1;
}
function getCompositeRect$1(elementOrVirtualElement, offsetParent, isFixed) {
  if (isFixed === void 0) {
    isFixed = false;
  }
  var isOffsetParentAnElement = isHTMLElement$1(offsetParent);
  var offsetParentIsScaled = isHTMLElement$1(offsetParent) && isElementScaled$1(offsetParent);
  var documentElement = getDocumentElement$1(offsetParent);
  var rect = getBoundingClientRect$1(elementOrVirtualElement, offsetParentIsScaled, isFixed);
  var scroll = {
    scrollLeft: 0,
    scrollTop: 0
  };
  var offsets = {
    x: 0,
    y: 0
  };
  if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {
    if (getNodeName$1(offsetParent) !== "body" || isScrollParent$1(documentElement)) {
      scroll = getNodeScroll$1(offsetParent);
    }
    if (isHTMLElement$1(offsetParent)) {
      offsets = getBoundingClientRect$1(offsetParent, true);
      offsets.x += offsetParent.clientLeft;
      offsets.y += offsetParent.clientTop;
    } else if (documentElement) {
      offsets.x = getWindowScrollBarX$1(documentElement);
    }
  }
  return {
    x: rect.left + scroll.scrollLeft - offsets.x,
    y: rect.top + scroll.scrollTop - offsets.y,
    width: rect.width,
    height: rect.height
  };
}

// ../../node_modules/.pnpm/@popperjs+core@2.11.6/node_modules/@popperjs/core/lib/dom-utils/getLayoutRect.js
function getLayoutRect$1(element) {
  var clientRect = getBoundingClientRect$1(element);
  var width = element.offsetWidth;
  var height = element.offsetHeight;
  if (Math.abs(clientRect.width - width) <= 1) {
    width = clientRect.width;
  }
  if (Math.abs(clientRect.height - height) <= 1) {
    height = clientRect.height;
  }
  return {
    x: element.offsetLeft,
    y: element.offsetTop,
    width,
    height
  };
}

// ../../node_modules/.pnpm/@popperjs+core@2.11.6/node_modules/@popperjs/core/lib/dom-utils/getParentNode.js
function getParentNode$1(element) {
  if (getNodeName$1(element) === "html") {
    return element;
  }
  return element.assignedSlot || element.parentNode || (isShadowRoot$1(element) ? element.host : null) || getDocumentElement$1(element);
}

// ../../node_modules/.pnpm/@popperjs+core@2.11.6/node_modules/@popperjs/core/lib/dom-utils/getScrollParent.js
function getScrollParent$1(node) {
  if (["html", "body", "#document"].indexOf(getNodeName$1(node)) >= 0) {
    return node.ownerDocument.body;
  }
  if (isHTMLElement$1(node) && isScrollParent$1(node)) {
    return node;
  }
  return getScrollParent$1(getParentNode$1(node));
}

// ../../node_modules/.pnpm/@popperjs+core@2.11.6/node_modules/@popperjs/core/lib/dom-utils/listScrollParents.js
function listScrollParents$1(element, list) {
  var _element$ownerDocumen;
  if (list === void 0) {
    list = [];
  }
  var scrollParent = getScrollParent$1(element);
  var isBody = scrollParent === ((_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body);
  var win = getWindow$1(scrollParent);
  var target = isBody ? [win].concat(win.visualViewport || [], isScrollParent$1(scrollParent) ? scrollParent : []) : scrollParent;
  var updatedList = list.concat(target);
  return isBody ? updatedList : updatedList.concat(listScrollParents$1(getParentNode$1(target)));
}

// ../../node_modules/.pnpm/@popperjs+core@2.11.6/node_modules/@popperjs/core/lib/dom-utils/isTableElement.js
function isTableElement$1(element) {
  return ["table", "td", "th"].indexOf(getNodeName$1(element)) >= 0;
}

// ../../node_modules/.pnpm/@popperjs+core@2.11.6/node_modules/@popperjs/core/lib/dom-utils/getOffsetParent.js
function getTrueOffsetParent$1(element) {
  if (!isHTMLElement$1(element) || getComputedStyle$2(element).position === "fixed") {
    return null;
  }
  return element.offsetParent;
}
function getContainingBlock$1(element) {
  var isFirefox = /firefox/i.test(getUAString$1());
  var isIE = /Trident/i.test(getUAString$1());
  if (isIE && isHTMLElement$1(element)) {
    var elementCss = getComputedStyle$2(element);
    if (elementCss.position === "fixed") {
      return null;
    }
  }
  var currentNode = getParentNode$1(element);
  if (isShadowRoot$1(currentNode)) {
    currentNode = currentNode.host;
  }
  while (isHTMLElement$1(currentNode) && ["html", "body"].indexOf(getNodeName$1(currentNode)) < 0) {
    var css = getComputedStyle$2(currentNode);
    if (css.transform !== "none" || css.perspective !== "none" || css.contain === "paint" || ["transform", "perspective"].indexOf(css.willChange) !== -1 || isFirefox && css.willChange === "filter" || isFirefox && css.filter && css.filter !== "none") {
      return currentNode;
    } else {
      currentNode = currentNode.parentNode;
    }
  }
  return null;
}
function getOffsetParent$1(element) {
  var window2 = getWindow$1(element);
  var offsetParent = getTrueOffsetParent$1(element);
  while (offsetParent && isTableElement$1(offsetParent) && getComputedStyle$2(offsetParent).position === "static") {
    offsetParent = getTrueOffsetParent$1(offsetParent);
  }
  if (offsetParent && (getNodeName$1(offsetParent) === "html" || getNodeName$1(offsetParent) === "body" && getComputedStyle$2(offsetParent).position === "static")) {
    return window2;
  }
  return offsetParent || getContainingBlock$1(element) || window2;
}

// ../../node_modules/.pnpm/@popperjs+core@2.11.6/node_modules/@popperjs/core/lib/enums.js
var top$1 = "top";
var bottom$1 = "bottom";
var right$1 = "right";
var left$1 = "left";
var auto$1 = "auto";
var basePlacements$1 = [top$1, bottom$1, right$1, left$1];
var start$1 = "start";
var end$1 = "end";
var placements$1 = /* @__PURE__ */[].concat(basePlacements$1, [auto$1]).reduce(function (acc, placement) {
  return acc.concat([placement, placement + "-" + start$1, placement + "-" + end$1]);
}, []);
var beforeRead$1 = "beforeRead";
var read$1 = "read";
var afterRead$1 = "afterRead";
var beforeMain$1 = "beforeMain";
var main$1 = "main";
var afterMain$1 = "afterMain";
var beforeWrite$1 = "beforeWrite";
var write$1 = "write";
var afterWrite$1 = "afterWrite";
var modifierPhases$1 = [beforeRead$1, read$1, afterRead$1, beforeMain$1, main$1, afterMain$1, beforeWrite$1, write$1, afterWrite$1];

// ../../node_modules/.pnpm/@popperjs+core@2.11.6/node_modules/@popperjs/core/lib/utils/orderModifiers.js
function order$1(modifiers) {
  var map = /* @__PURE__ */new Map();
  var visited = /* @__PURE__ */new Set();
  var result = [];
  modifiers.forEach(function (modifier) {
    map.set(modifier.name, modifier);
  });
  function sort(modifier) {
    visited.add(modifier.name);
    var requires = [].concat(modifier.requires || [], modifier.requiresIfExists || []);
    requires.forEach(function (dep) {
      if (!visited.has(dep)) {
        var depModifier = map.get(dep);
        if (depModifier) {
          sort(depModifier);
        }
      }
    });
    result.push(modifier);
  }
  modifiers.forEach(function (modifier) {
    if (!visited.has(modifier.name)) {
      sort(modifier);
    }
  });
  return result;
}
function orderModifiers$1(modifiers) {
  var orderedModifiers = order$1(modifiers);
  return modifierPhases$1.reduce(function (acc, phase) {
    return acc.concat(orderedModifiers.filter(function (modifier) {
      return modifier.phase === phase;
    }));
  }, []);
}

// ../../node_modules/.pnpm/@popperjs+core@2.11.6/node_modules/@popperjs/core/lib/utils/debounce.js
function debounce$2(fn2) {
  var pending;
  return function () {
    if (!pending) {
      pending = new Promise(function (resolve) {
        Promise.resolve().then(function () {
          pending = void 0;
          resolve(fn2());
        });
      });
    }
    return pending;
  };
}

// ../../node_modules/.pnpm/@popperjs+core@2.11.6/node_modules/@popperjs/core/lib/utils/format.js
function format(str) {
  for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
    args[_key - 1] = arguments[_key];
  }
  return [].concat(args).reduce(function (p, c) {
    return p.replace(/%s/, c);
  }, str);
}

// ../../node_modules/.pnpm/@popperjs+core@2.11.6/node_modules/@popperjs/core/lib/utils/validateModifiers.js
var INVALID_MODIFIER_ERROR = 'Popper: modifier "%s" provided an invalid %s property, expected %s but got %s';
var MISSING_DEPENDENCY_ERROR = 'Popper: modifier "%s" requires "%s", but "%s" modifier is not available';
var VALID_PROPERTIES = ["name", "enabled", "phase", "fn", "effect", "requires", "options"];
function validateModifiers(modifiers) {
  modifiers.forEach(function (modifier) {
    [].concat(Object.keys(modifier), VALID_PROPERTIES).filter(function (value, index, self) {
      return self.indexOf(value) === index;
    }).forEach(function (key) {
      switch (key) {
        case "name":
          if (typeof modifier.name !== "string") {
            console.error(format(INVALID_MODIFIER_ERROR, String(modifier.name), '"name"', '"string"', '"' + String(modifier.name) + '"'));
          }
          break;
        case "enabled":
          if (typeof modifier.enabled !== "boolean") {
            console.error(format(INVALID_MODIFIER_ERROR, modifier.name, '"enabled"', '"boolean"', '"' + String(modifier.enabled) + '"'));
          }
          break;
        case "phase":
          if (modifierPhases$1.indexOf(modifier.phase) < 0) {
            console.error(format(INVALID_MODIFIER_ERROR, modifier.name, '"phase"', "either " + modifierPhases$1.join(", "), '"' + String(modifier.phase) + '"'));
          }
          break;
        case "fn":
          if (typeof modifier.fn !== "function") {
            console.error(format(INVALID_MODIFIER_ERROR, modifier.name, '"fn"', '"function"', '"' + String(modifier.fn) + '"'));
          }
          break;
        case "effect":
          if (modifier.effect != null && typeof modifier.effect !== "function") {
            console.error(format(INVALID_MODIFIER_ERROR, modifier.name, '"effect"', '"function"', '"' + String(modifier.fn) + '"'));
          }
          break;
        case "requires":
          if (modifier.requires != null && !Array.isArray(modifier.requires)) {
            console.error(format(INVALID_MODIFIER_ERROR, modifier.name, '"requires"', '"array"', '"' + String(modifier.requires) + '"'));
          }
          break;
        case "requiresIfExists":
          if (!Array.isArray(modifier.requiresIfExists)) {
            console.error(format(INVALID_MODIFIER_ERROR, modifier.name, '"requiresIfExists"', '"array"', '"' + String(modifier.requiresIfExists) + '"'));
          }
          break;
        case "options":
        case "data":
          break;
        default:
          console.error('PopperJS: an invalid property has been provided to the "' + modifier.name + '" modifier, valid properties are ' + VALID_PROPERTIES.map(function (s) {
            return '"' + s + '"';
          }).join(", ") + '; but "' + key + '" was provided.');
      }
      modifier.requires && modifier.requires.forEach(function (requirement) {
        if (modifiers.find(function (mod) {
          return mod.name === requirement;
        }) == null) {
          console.error(format(MISSING_DEPENDENCY_ERROR, String(modifier.name), requirement, requirement));
        }
      });
    });
  });
}

// ../../node_modules/.pnpm/@popperjs+core@2.11.6/node_modules/@popperjs/core/lib/utils/uniqueBy.js
function uniqueBy(arr, fn2) {
  var identifiers = /* @__PURE__ */new Set();
  return arr.filter(function (item) {
    var identifier = fn2(item);
    if (!identifiers.has(identifier)) {
      identifiers.add(identifier);
      return true;
    }
  });
}

// ../../node_modules/.pnpm/@popperjs+core@2.11.6/node_modules/@popperjs/core/lib/utils/getBasePlacement.js
function getBasePlacement$2(placement) {
  return placement.split("-")[0];
}

// ../../node_modules/.pnpm/@popperjs+core@2.11.6/node_modules/@popperjs/core/lib/utils/mergeByName.js
function mergeByName$1(modifiers) {
  var merged = modifiers.reduce(function (merged2, current) {
    var existing = merged2[current.name];
    merged2[current.name] = existing ? Object.assign({}, existing, current, {
      options: Object.assign({}, existing.options, current.options),
      data: Object.assign({}, existing.data, current.data)
    }) : current;
    return merged2;
  }, {});
  return Object.keys(merged).map(function (key) {
    return merged[key];
  });
}

// ../../node_modules/.pnpm/@popperjs+core@2.11.6/node_modules/@popperjs/core/lib/utils/getVariation.js
function getVariation$1(placement) {
  return placement.split("-")[1];
}

// ../../node_modules/.pnpm/@popperjs+core@2.11.6/node_modules/@popperjs/core/lib/utils/getMainAxisFromPlacement.js
function getMainAxisFromPlacement$1(placement) {
  return ["top", "bottom"].indexOf(placement) >= 0 ? "x" : "y";
}

// ../../node_modules/.pnpm/@popperjs+core@2.11.6/node_modules/@popperjs/core/lib/utils/computeOffsets.js
function computeOffsets$1(_ref) {
  var reference = _ref.reference,
    element = _ref.element,
    placement = _ref.placement;
  var basePlacement = placement ? getBasePlacement$2(placement) : null;
  var variation = placement ? getVariation$1(placement) : null;
  var commonX = reference.x + reference.width / 2 - element.width / 2;
  var commonY = reference.y + reference.height / 2 - element.height / 2;
  var offsets;
  switch (basePlacement) {
    case top$1:
      offsets = {
        x: commonX,
        y: reference.y - element.height
      };
      break;
    case bottom$1:
      offsets = {
        x: commonX,
        y: reference.y + reference.height
      };
      break;
    case right$1:
      offsets = {
        x: reference.x + reference.width,
        y: commonY
      };
      break;
    case left$1:
      offsets = {
        x: reference.x - element.width,
        y: commonY
      };
      break;
    default:
      offsets = {
        x: reference.x,
        y: reference.y
      };
  }
  var mainAxis = basePlacement ? getMainAxisFromPlacement$1(basePlacement) : null;
  if (mainAxis != null) {
    var len = mainAxis === "y" ? "height" : "width";
    switch (variation) {
      case start$1:
        offsets[mainAxis] = offsets[mainAxis] - (reference[len] / 2 - element[len] / 2);
        break;
      case end$1:
        offsets[mainAxis] = offsets[mainAxis] + (reference[len] / 2 - element[len] / 2);
        break;
    }
  }
  return offsets;
}

// ../../node_modules/.pnpm/@popperjs+core@2.11.6/node_modules/@popperjs/core/lib/createPopper.js
var INVALID_ELEMENT_ERROR = "Popper: Invalid reference or popper argument provided. They must be either a DOM element or virtual element.";
var INFINITE_LOOP_ERROR = "Popper: An infinite loop in the modifiers cycle has been detected! The cycle has been interrupted to prevent a browser crash.";
var DEFAULT_OPTIONS$1 = {
  placement: "bottom",
  modifiers: [],
  strategy: "absolute"
};
function areValidElements$1() {
  for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
    args[_key] = arguments[_key];
  }
  return !args.some(function (element) {
    return !(element && typeof element.getBoundingClientRect === "function");
  });
}
function popperGenerator$1(generatorOptions) {
  if (generatorOptions === void 0) {
    generatorOptions = {};
  }
  var _generatorOptions = generatorOptions,
    _generatorOptions$def = _generatorOptions.defaultModifiers,
    defaultModifiers2 = _generatorOptions$def === void 0 ? [] : _generatorOptions$def,
    _generatorOptions$def2 = _generatorOptions.defaultOptions,
    defaultOptions = _generatorOptions$def2 === void 0 ? DEFAULT_OPTIONS$1 : _generatorOptions$def2;
  return function createPopper2(reference, popper, options) {
    if (options === void 0) {
      options = defaultOptions;
    }
    var state = {
      placement: "bottom",
      orderedModifiers: [],
      options: Object.assign({}, DEFAULT_OPTIONS$1, defaultOptions),
      modifiersData: {},
      elements: {
        reference,
        popper
      },
      attributes: {},
      styles: {}
    };
    var effectCleanupFns = [];
    var isDestroyed = false;
    var instance = {
      state,
      setOptions: function setOptions(setOptionsAction) {
        var options2 = typeof setOptionsAction === "function" ? setOptionsAction(state.options) : setOptionsAction;
        cleanupModifierEffects();
        state.options = Object.assign({}, defaultOptions, state.options, options2);
        state.scrollParents = {
          reference: isElement$2(reference) ? listScrollParents$1(reference) : reference.contextElement ? listScrollParents$1(reference.contextElement) : [],
          popper: listScrollParents$1(popper)
        };
        var orderedModifiers = orderModifiers$1(mergeByName$1([].concat(defaultModifiers2, state.options.modifiers)));
        state.orderedModifiers = orderedModifiers.filter(function (m) {
          return m.enabled;
        });
        {
          var modifiers = uniqueBy([].concat(orderedModifiers, state.options.modifiers), function (_ref) {
            var name = _ref.name;
            return name;
          });
          validateModifiers(modifiers);
          if (getBasePlacement$2(state.options.placement) === auto$1) {
            var flipModifier = state.orderedModifiers.find(function (_ref2) {
              var name = _ref2.name;
              return name === "flip";
            });
            if (!flipModifier) {
              console.error(['Popper: "auto" placements require the "flip" modifier be', "present and enabled to work."].join(" "));
            }
          }
          var _getComputedStyle = getComputedStyle$2(popper),
            marginTop = _getComputedStyle.marginTop,
            marginRight = _getComputedStyle.marginRight,
            marginBottom = _getComputedStyle.marginBottom,
            marginLeft = _getComputedStyle.marginLeft;
          if ([marginTop, marginRight, marginBottom, marginLeft].some(function (margin) {
            return parseFloat(margin);
          })) {
            console.warn(['Popper: CSS "margin" styles cannot be used to apply padding', "between the popper and its reference element or boundary.", "To replicate margin, use the `offset` modifier, as well as", "the `padding` option in the `preventOverflow` and `flip`", "modifiers."].join(" "));
          }
        }
        runModifierEffects();
        return instance.update();
      },
      forceUpdate: function forceUpdate() {
        if (isDestroyed) {
          return;
        }
        var _state$elements = state.elements,
          reference2 = _state$elements.reference,
          popper2 = _state$elements.popper;
        if (!areValidElements$1(reference2, popper2)) {
          {
            console.error(INVALID_ELEMENT_ERROR);
          }
          return;
        }
        state.rects = {
          reference: getCompositeRect$1(reference2, getOffsetParent$1(popper2), state.options.strategy === "fixed"),
          popper: getLayoutRect$1(popper2)
        };
        state.reset = false;
        state.placement = state.options.placement;
        state.orderedModifiers.forEach(function (modifier) {
          return state.modifiersData[modifier.name] = Object.assign({}, modifier.data);
        });
        var __debug_loops__ = 0;
        for (var index = 0; index < state.orderedModifiers.length; index++) {
          {
            __debug_loops__ += 1;
            if (__debug_loops__ > 100) {
              console.error(INFINITE_LOOP_ERROR);
              break;
            }
          }
          if (state.reset === true) {
            state.reset = false;
            index = -1;
            continue;
          }
          var _state$orderedModifie = state.orderedModifiers[index],
            fn2 = _state$orderedModifie.fn,
            _state$orderedModifie2 = _state$orderedModifie.options,
            _options = _state$orderedModifie2 === void 0 ? {} : _state$orderedModifie2,
            name = _state$orderedModifie.name;
          if (typeof fn2 === "function") {
            state = fn2({
              state,
              options: _options,
              name,
              instance
            }) || state;
          }
        }
      },
      update: debounce$2(function () {
        return new Promise(function (resolve) {
          instance.forceUpdate();
          resolve(state);
        });
      }),
      destroy: function destroy() {
        cleanupModifierEffects();
        isDestroyed = true;
      }
    };
    if (!areValidElements$1(reference, popper)) {
      {
        console.error(INVALID_ELEMENT_ERROR);
      }
      return instance;
    }
    instance.setOptions(options).then(function (state2) {
      if (!isDestroyed && options.onFirstUpdate) {
        options.onFirstUpdate(state2);
      }
    });
    function runModifierEffects() {
      state.orderedModifiers.forEach(function (_ref3) {
        var name = _ref3.name,
          _ref3$options = _ref3.options,
          options2 = _ref3$options === void 0 ? {} : _ref3$options,
          effect3 = _ref3.effect;
        if (typeof effect3 === "function") {
          var cleanupFn = effect3({
            state,
            name,
            instance,
            options: options2
          });
          var noopFn = function noopFn2() {};
          effectCleanupFns.push(cleanupFn || noopFn);
        }
      });
    }
    function cleanupModifierEffects() {
      effectCleanupFns.forEach(function (fn2) {
        return fn2();
      });
      effectCleanupFns = [];
    }
    return instance;
  };
}

// ../../node_modules/.pnpm/@popperjs+core@2.11.6/node_modules/@popperjs/core/lib/modifiers/eventListeners.js
var passive$1 = {
  passive: true
};
function effect$3(_ref) {
  var state = _ref.state,
    instance = _ref.instance,
    options = _ref.options;
  var _options$scroll = options.scroll,
    scroll = _options$scroll === void 0 ? true : _options$scroll,
    _options$resize = options.resize,
    resize = _options$resize === void 0 ? true : _options$resize;
  var window2 = getWindow$1(state.elements.popper);
  var scrollParents = [].concat(state.scrollParents.reference, state.scrollParents.popper);
  if (scroll) {
    scrollParents.forEach(function (scrollParent) {
      scrollParent.addEventListener("scroll", instance.update, passive$1);
    });
  }
  if (resize) {
    window2.addEventListener("resize", instance.update, passive$1);
  }
  return function () {
    if (scroll) {
      scrollParents.forEach(function (scrollParent) {
        scrollParent.removeEventListener("scroll", instance.update, passive$1);
      });
    }
    if (resize) {
      window2.removeEventListener("resize", instance.update, passive$1);
    }
  };
}
var eventListeners_default = {
  name: "eventListeners",
  enabled: true,
  phase: "write",
  fn: function fn() {},
  effect: effect$3,
  data: {}
};

// ../../node_modules/.pnpm/@popperjs+core@2.11.6/node_modules/@popperjs/core/lib/modifiers/popperOffsets.js
function popperOffsets$2(_ref) {
  var state = _ref.state,
    name = _ref.name;
  state.modifiersData[name] = computeOffsets$1({
    reference: state.rects.reference,
    element: state.rects.popper,
    strategy: "absolute",
    placement: state.placement
  });
}
var popperOffsets_default = {
  name: "popperOffsets",
  enabled: true,
  phase: "read",
  fn: popperOffsets$2,
  data: {}
};

// ../../node_modules/.pnpm/@popperjs+core@2.11.6/node_modules/@popperjs/core/lib/modifiers/computeStyles.js
var unsetSides$1 = {
  top: "auto",
  right: "auto",
  bottom: "auto",
  left: "auto"
};
function roundOffsetsByDPR$1(_ref) {
  var x = _ref.x,
    y = _ref.y;
  var win = window;
  var dpr = win.devicePixelRatio || 1;
  return {
    x: round$1(x * dpr) / dpr || 0,
    y: round$1(y * dpr) / dpr || 0
  };
}
function mapToStyles$1(_ref2) {
  var _Object$assign2;
  var popper = _ref2.popper,
    popperRect = _ref2.popperRect,
    placement = _ref2.placement,
    variation = _ref2.variation,
    offsets = _ref2.offsets,
    position = _ref2.position,
    gpuAcceleration = _ref2.gpuAcceleration,
    adaptive = _ref2.adaptive,
    roundOffsets = _ref2.roundOffsets,
    isFixed = _ref2.isFixed;
  var _offsets$x = offsets.x,
    x = _offsets$x === void 0 ? 0 : _offsets$x,
    _offsets$y = offsets.y,
    y = _offsets$y === void 0 ? 0 : _offsets$y;
  var _ref3 = typeof roundOffsets === "function" ? roundOffsets({
    x,
    y
  }) : {
    x,
    y
  };
  x = _ref3.x;
  y = _ref3.y;
  var hasX = offsets.hasOwnProperty("x");
  var hasY = offsets.hasOwnProperty("y");
  var sideX = left$1;
  var sideY = top$1;
  var win = window;
  if (adaptive) {
    var offsetParent = getOffsetParent$1(popper);
    var heightProp = "clientHeight";
    var widthProp = "clientWidth";
    if (offsetParent === getWindow$1(popper)) {
      offsetParent = getDocumentElement$1(popper);
      if (getComputedStyle$2(offsetParent).position !== "static" && position === "absolute") {
        heightProp = "scrollHeight";
        widthProp = "scrollWidth";
      }
    }
    offsetParent = offsetParent;
    if (placement === top$1 || (placement === left$1 || placement === right$1) && variation === end$1) {
      sideY = bottom$1;
      var offsetY = isFixed && offsetParent === win && win.visualViewport ? win.visualViewport.height : offsetParent[heightProp];
      y -= offsetY - popperRect.height;
      y *= gpuAcceleration ? 1 : -1;
    }
    if (placement === left$1 || (placement === top$1 || placement === bottom$1) && variation === end$1) {
      sideX = right$1;
      var offsetX = isFixed && offsetParent === win && win.visualViewport ? win.visualViewport.width : offsetParent[widthProp];
      x -= offsetX - popperRect.width;
      x *= gpuAcceleration ? 1 : -1;
    }
  }
  var commonStyles = Object.assign({
    position
  }, adaptive && unsetSides$1);
  var _ref4 = roundOffsets === true ? roundOffsetsByDPR$1({
    x,
    y
  }) : {
    x,
    y
  };
  x = _ref4.x;
  y = _ref4.y;
  if (gpuAcceleration) {
    var _Object$assign;
    return Object.assign({}, commonStyles, (_Object$assign = {}, _Object$assign[sideY] = hasY ? "0" : "", _Object$assign[sideX] = hasX ? "0" : "", _Object$assign.transform = (win.devicePixelRatio || 1) <= 1 ? "translate(" + x + "px, " + y + "px)" : "translate3d(" + x + "px, " + y + "px, 0)", _Object$assign));
  }
  return Object.assign({}, commonStyles, (_Object$assign2 = {}, _Object$assign2[sideY] = hasY ? y + "px" : "", _Object$assign2[sideX] = hasX ? x + "px" : "", _Object$assign2.transform = "", _Object$assign2));
}
function computeStyles$2(_ref5) {
  var state = _ref5.state,
    options = _ref5.options;
  var _options$gpuAccelerat = options.gpuAcceleration,
    gpuAcceleration = _options$gpuAccelerat === void 0 ? true : _options$gpuAccelerat,
    _options$adaptive = options.adaptive,
    adaptive = _options$adaptive === void 0 ? true : _options$adaptive,
    _options$roundOffsets = options.roundOffsets,
    roundOffsets = _options$roundOffsets === void 0 ? true : _options$roundOffsets;
  {
    var transitionProperty = getComputedStyle$2(state.elements.popper).transitionProperty || "";
    if (adaptive && ["transform", "top", "right", "bottom", "left"].some(function (property) {
      return transitionProperty.indexOf(property) >= 0;
    })) {
      console.warn(["Popper: Detected CSS transitions on at least one of the following", 'CSS properties: "transform", "top", "right", "bottom", "left".', "\n\n", 'Disable the "computeStyles" modifier\'s `adaptive` option to allow', "for smooth transitions, or remove these properties from the CSS", "transition declaration on the popper element if only transitioning", "opacity or background-color for example.", "\n\n", "We recommend using the popper element as a wrapper around an inner", "element that can have any CSS property transitioned for animations."].join(" "));
    }
  }
  var commonStyles = {
    placement: getBasePlacement$2(state.placement),
    variation: getVariation$1(state.placement),
    popper: state.elements.popper,
    popperRect: state.rects.popper,
    gpuAcceleration,
    isFixed: state.options.strategy === "fixed"
  };
  if (state.modifiersData.popperOffsets != null) {
    state.styles.popper = Object.assign({}, state.styles.popper, mapToStyles$1(Object.assign({}, commonStyles, {
      offsets: state.modifiersData.popperOffsets,
      position: state.options.strategy,
      adaptive,
      roundOffsets
    })));
  }
  if (state.modifiersData.arrow != null) {
    state.styles.arrow = Object.assign({}, state.styles.arrow, mapToStyles$1(Object.assign({}, commonStyles, {
      offsets: state.modifiersData.arrow,
      position: "absolute",
      adaptive: false,
      roundOffsets
    })));
  }
  state.attributes.popper = Object.assign({}, state.attributes.popper, {
    "data-popper-placement": state.placement
  });
}
var computeStyles_default = {
  name: "computeStyles",
  enabled: true,
  phase: "beforeWrite",
  fn: computeStyles$2,
  data: {}
};

// ../../node_modules/.pnpm/@popperjs+core@2.11.6/node_modules/@popperjs/core/lib/modifiers/applyStyles.js
function applyStyles$2(_ref) {
  var state = _ref.state;
  Object.keys(state.elements).forEach(function (name) {
    var style = state.styles[name] || {};
    var attributes = state.attributes[name] || {};
    var element = state.elements[name];
    if (!isHTMLElement$1(element) || !getNodeName$1(element)) {
      return;
    }
    Object.assign(element.style, style);
    Object.keys(attributes).forEach(function (name2) {
      var value = attributes[name2];
      if (value === false) {
        element.removeAttribute(name2);
      } else {
        element.setAttribute(name2, value === true ? "" : value);
      }
    });
  });
}
function effect2(_ref2) {
  var state = _ref2.state;
  var initialStyles = {
    popper: {
      position: state.options.strategy,
      left: "0",
      top: "0",
      margin: "0"
    },
    arrow: {
      position: "absolute"
    },
    reference: {}
  };
  Object.assign(state.elements.popper.style, initialStyles.popper);
  state.styles = initialStyles;
  if (state.elements.arrow) {
    Object.assign(state.elements.arrow.style, initialStyles.arrow);
  }
  return function () {
    Object.keys(state.elements).forEach(function (name) {
      var element = state.elements[name];
      var attributes = state.attributes[name] || {};
      var styleProperties = Object.keys(state.styles.hasOwnProperty(name) ? state.styles[name] : initialStyles[name]);
      var style = styleProperties.reduce(function (style2, property) {
        style2[property] = "";
        return style2;
      }, {});
      if (!isHTMLElement$1(element) || !getNodeName$1(element)) {
        return;
      }
      Object.assign(element.style, style);
      Object.keys(attributes).forEach(function (attribute) {
        element.removeAttribute(attribute);
      });
    });
  };
}
var applyStyles_default = {
  name: "applyStyles",
  enabled: true,
  phase: "write",
  fn: applyStyles$2,
  effect: effect2,
  requires: ["computeStyles"]
};

// ../../node_modules/.pnpm/@popperjs+core@2.11.6/node_modules/@popperjs/core/lib/popper-lite.js
var defaultModifiers$1 = [eventListeners_default, popperOffsets_default, computeStyles_default, applyStyles_default];
var createPopper$1 = /* @__PURE__ */popperGenerator$1({
  defaultModifiers: defaultModifiers$1
});

// ../../node_modules/.pnpm/@popperjs+core@2.11.6/node_modules/@popperjs/core/lib/modifiers/offset.js
function distanceAndSkiddingToXY$1(placement, rects, offset2) {
  var basePlacement = getBasePlacement$2(placement);
  var invertDistance = [left$1, top$1].indexOf(basePlacement) >= 0 ? -1 : 1;
  var _ref = typeof offset2 === "function" ? offset2(Object.assign({}, rects, {
      placement
    })) : offset2,
    skidding = _ref[0],
    distance = _ref[1];
  skidding = skidding || 0;
  distance = (distance || 0) * invertDistance;
  return [left$1, right$1].indexOf(basePlacement) >= 0 ? {
    x: distance,
    y: skidding
  } : {
    x: skidding,
    y: distance
  };
}
function offset$2(_ref2) {
  var state = _ref2.state,
    options = _ref2.options,
    name = _ref2.name;
  var _options$offset = options.offset,
    offset2 = _options$offset === void 0 ? [0, 0] : _options$offset;
  var data = placements$1.reduce(function (acc, placement) {
    acc[placement] = distanceAndSkiddingToXY$1(placement, state.rects, offset2);
    return acc;
  }, {});
  var _data$state$placement = data[state.placement],
    x = _data$state$placement.x,
    y = _data$state$placement.y;
  if (state.modifiersData.popperOffsets != null) {
    state.modifiersData.popperOffsets.x += x;
    state.modifiersData.popperOffsets.y += y;
  }
  state.modifiersData[name] = data;
}
var offset_default = {
  name: "offset",
  enabled: true,
  phase: "main",
  requires: ["popperOffsets"],
  fn: offset$2
};

var _createNamespace$r = createNamespace('popover'),
  createComponent$v = _createNamespace$r[0],
  bem$q = _createNamespace$r[1];
var Popover = createComponent$v({
  mixins: [ClickOutsideMixin({
    event: 'touchstart',
    method: 'onClickOutside'
  })],
  props: {
    value: Boolean,
    trigger: String,
    overlay: Boolean,
    offset: {
      type: Array,
      default: function _default() {
        return [0, 8];
      }
    },
    theme: {
      type: String,
      default: 'light'
    },
    actions: {
      type: Array,
      default: function _default() {
        return [];
      }
    },
    placement: {
      type: String,
      default: 'bottom'
    },
    getContainer: {
      type: [String, Function],
      default: 'body'
    },
    closeOnClickAction: {
      type: Boolean,
      default: true
    }
  },
  watch: {
    value: 'updateLocation',
    placement: 'updateLocation'
  },
  mounted: function mounted() {
    this.updateLocation();
  },
  beforeDestroy: function beforeDestroy() {
    if (this.popper) {
      if (!isServer) {
        window.removeEventListener('animationend', this.updateLocation);
        window.removeEventListener('transitionend', this.updateLocation);
      }
      this.popper.destroy();
      this.popper = null;
    }
  },
  methods: {
    createPopper: function createPopper() {
      var popper = createPopper$1(this.$refs.wrapper, this.$refs.popover.$el, {
        placement: this.placement,
        modifiers: [{
          name: 'computeStyles',
          options: {
            adaptive: false,
            gpuAcceleration: false
          }
        }, _extends$1({}, offset_default, {
          options: {
            offset: this.offset
          }
        })]
      });
      if (!isServer) {
        window.addEventListener('animationend', this.updateLocation);
        window.addEventListener('transitionend', this.updateLocation);
      }
      return popper;
    },
    updateLocation: function updateLocation() {
      var _this = this;
      this.$nextTick(function () {
        if (!_this.value) {
          return;
        }
        if (!_this.popper) {
          _this.popper = _this.createPopper();
        } else {
          _this.popper.setOptions({
            placement: _this.placement
          });
        }
      });
    },
    renderAction: function renderAction(action, index) {
      var _this2 = this;
      var h = this.$createElement;
      var icon = action.icon,
        text = action.text,
        disabled = action.disabled,
        className = action.className;
      return h("div", {
        "attrs": {
          "role": "menuitem"
        },
        "class": [bem$q('action', {
          disabled: disabled,
          'with-icon': icon
        }), className],
        "on": {
          "click": function click() {
            return _this2.onClickAction(action, index);
          }
        }
      }, [icon && h(Icon$1, {
        "attrs": {
          "name": icon
        },
        "class": bem$q('action-icon')
      }), h("div", {
        "class": [bem$q('action-text'), BORDER_BOTTOM]
      }, [text])]);
    },
    onToggle: function onToggle(value) {
      this.$emit('input', value);
    },
    onClickWrapper: function onClickWrapper() {
      if (this.trigger === 'click') {
        this.onToggle(!this.value);
      }
    },
    onTouchstart: function onTouchstart(event) {
      event.stopPropagation();
      this.$emit('touchstart', event);
    },
    onClickAction: function onClickAction(action, index) {
      if (action.disabled) {
        return;
      }
      this.$emit('select', action, index);
      if (this.closeOnClickAction) {
        this.$emit('input', false);
      }
    },
    onClickOutside: function onClickOutside() {
      this.$emit('input', false);
    },
    onOpen: function onOpen() {
      this.$emit('open');
    },
    /* istanbul ignore next */
    onOpened: function onOpened() {
      this.$emit('opened');
    },
    onClose: function onClose() {
      this.$emit('close');
    },
    /* istanbul ignore next */
    onClosed: function onClosed() {
      this.$emit('closed');
    }
  },
  render: function render() {
    var h = arguments[0];
    return h("span", {
      "ref": "wrapper",
      "class": bem$q('wrapper'),
      "on": {
        "click": this.onClickWrapper
      }
    }, [h(Popup, {
      "ref": "popover",
      "attrs": {
        "value": this.value,
        "overlay": this.overlay,
        "position": null,
        "transition": "van-popover-zoom",
        "lockScroll": false,
        "getContainer": this.getContainer
      },
      "class": bem$q([this.theme]),
      "on": {
        "open": this.onOpen,
        "close": this.onClose,
        "input": this.onToggle,
        "opened": this.onOpened,
        "closed": this.onClosed
      },
      "nativeOn": {
        "touchstart": this.onTouchstart
      }
    }, [h("div", {
      "class": bem$q('arrow')
    }), h("div", {
      "class": bem$q('content'),
      "attrs": {
        "role": "menu"
      }
    }, [this.slots('default') || this.actions.map(this.renderAction)])]), this.slots('reference')]);
  }
});

var _createNamespace$q = createNamespace('progress'),
  createComponent$u = _createNamespace$q[0],
  bem$p = _createNamespace$q[1];
var Progress = createComponent$u({
  mixins: [BindEventMixin(function (bind) {
    bind(window, 'resize', this.resize, true);
    bind(window, 'orientationchange', this.resize, true);
  })],
  props: {
    color: String,
    inactive: Boolean,
    pivotText: String,
    textColor: String,
    pivotColor: String,
    trackColor: String,
    strokeWidth: [Number, String],
    percentage: {
      type: [Number, String],
      required: true,
      validator: function validator(value) {
        return value >= 0 && value <= 100;
      }
    },
    showPivot: {
      type: Boolean,
      default: true
    }
  },
  data: function data() {
    return {
      pivotWidth: 0,
      progressWidth: 0
    };
  },
  mounted: function mounted() {
    this.resize();
  },
  watch: {
    showPivot: 'resize',
    pivotText: 'resize'
  },
  methods: {
    // @exposed-api
    resize: function resize() {
      var _this = this;
      this.$nextTick(function () {
        _this.progressWidth = _this.$el.offsetWidth;
        _this.pivotWidth = _this.$refs.pivot ? _this.$refs.pivot.offsetWidth : 0;
      });
    }
  },
  render: function render() {
    var h = arguments[0];
    var pivotText = this.pivotText,
      percentage = this.percentage;
    var text = pivotText != null ? pivotText : percentage + '%';
    var showPivot = this.showPivot && text;
    var background = this.inactive ? '#cacaca' : this.color;
    var pivotStyle = {
      color: this.textColor,
      left: (this.progressWidth - this.pivotWidth) * percentage / 100 + "px",
      background: this.pivotColor || background
    };
    var portionStyle = {
      background: background,
      width: this.progressWidth * percentage / 100 + 'px'
    };
    var wrapperStyle = {
      background: this.trackColor,
      height: addUnit(this.strokeWidth)
    };
    return h("div", {
      "class": bem$p(),
      "style": wrapperStyle
    }, [h("span", {
      "class": bem$p('portion'),
      "style": portionStyle
    }, [showPivot && h("span", {
      "ref": "pivot",
      "style": pivotStyle,
      "class": bem$p('pivot')
    }, [text])])]);
  }
});

// Utils
var _createNamespace$p = createNamespace('pull-refresh'),
  createComponent$t = _createNamespace$p[0],
  bem$o = _createNamespace$p[1],
  t$b = _createNamespace$p[2];
var DEFAULT_HEAD_HEIGHT = 50;
var TEXT_STATUS = ['pulling', 'loosing', 'success'];
var PullRefresh = createComponent$t({
  mixins: [TouchMixin],
  props: {
    disabled: Boolean,
    successText: String,
    pullingText: String,
    loosingText: String,
    loadingText: String,
    pullDistance: [Number, String],
    value: {
      type: Boolean,
      required: true
    },
    successDuration: {
      type: [Number, String],
      default: 500
    },
    animationDuration: {
      type: [Number, String],
      default: 300
    },
    headHeight: {
      type: [Number, String],
      default: DEFAULT_HEAD_HEIGHT
    }
  },
  data: function data() {
    return {
      status: 'normal',
      distance: 0,
      duration: 0
    };
  },
  computed: {
    touchable: function touchable() {
      return this.status !== 'loading' && this.status !== 'success' && !this.disabled;
    },
    headStyle: function headStyle() {
      if (this.headHeight !== DEFAULT_HEAD_HEIGHT) {
        return {
          height: this.headHeight + "px"
        };
      }
    }
  },
  watch: {
    value: function value(loading) {
      this.duration = this.animationDuration;
      if (loading) {
        this.setStatus(+this.headHeight, true);
      } else if (this.slots('success') || this.successText) {
        this.showSuccessTip();
      } else {
        this.setStatus(0, false);
      }
    }
  },
  mounted: function mounted() {
    this.bindTouchEvent(this.$refs.track);
    this.scrollEl = getScroller(this.$el);
  },
  methods: {
    checkPullStart: function checkPullStart(event) {
      this.ceiling = getScrollTop(this.scrollEl) === 0;
      if (this.ceiling) {
        this.duration = 0;
        this.touchStart(event);
      }
    },
    onTouchStart: function onTouchStart(event) {
      if (this.touchable) {
        this.checkPullStart(event);
      }
    },
    onTouchMove: function onTouchMove(event) {
      if (!this.touchable) {
        return;
      }
      if (!this.ceiling) {
        this.checkPullStart(event);
      }
      this.touchMove(event);
      if (this.ceiling && this.deltaY >= 0 && this.direction === 'vertical') {
        preventDefault(event);
        this.setStatus(this.ease(this.deltaY));
      }
    },
    onTouchEnd: function onTouchEnd() {
      var _this = this;
      if (this.touchable && this.ceiling && this.deltaY) {
        this.duration = this.animationDuration;
        if (this.status === 'loosing') {
          this.setStatus(+this.headHeight, true);
          this.$emit('input', true); // ensure value change can be watched

          this.$nextTick(function () {
            _this.$emit('refresh');
          });
        } else {
          this.setStatus(0);
        }
      }
    },
    ease: function ease(distance) {
      var pullDistance = +(this.pullDistance || this.headHeight);
      if (distance > pullDistance) {
        if (distance < pullDistance * 2) {
          distance = pullDistance + (distance - pullDistance) / 2;
        } else {
          distance = pullDistance * 1.5 + (distance - pullDistance * 2) / 4;
        }
      }
      return Math.round(distance);
    },
    setStatus: function setStatus(distance, isLoading) {
      var status;
      if (isLoading) {
        status = 'loading';
      } else if (distance === 0) {
        status = 'normal';
      } else {
        status = distance < (this.pullDistance || this.headHeight) ? 'pulling' : 'loosing';
      }
      this.distance = distance;
      if (status !== this.status) {
        this.status = status;
      }
    },
    genStatus: function genStatus() {
      var h = this.$createElement;
      var status = this.status,
        distance = this.distance;
      var slot = this.slots(status, {
        distance: distance
      });
      if (slot) {
        return slot;
      }
      var nodes = [];
      var text = this[status + "Text"] || t$b(status);
      if (TEXT_STATUS.indexOf(status) !== -1) {
        nodes.push(h("div", {
          "class": bem$o('text')
        }, [text]));
      }
      if (status === 'loading') {
        nodes.push(h(Loading$1, {
          "attrs": {
            "size": "16"
          }
        }, [text]));
      }
      return nodes;
    },
    showSuccessTip: function showSuccessTip() {
      var _this2 = this;
      this.status = 'success';
      setTimeout(function () {
        _this2.setStatus(0);
      }, this.successDuration);
    }
  },
  render: function render() {
    var h = arguments[0];
    var trackStyle = {
      transitionDuration: this.duration + "ms",
      transform: this.distance ? "translate3d(0," + this.distance + "px, 0)" : ''
    };
    return h("div", {
      "class": bem$o()
    }, [h("div", {
      "ref": "track",
      "class": bem$o('track'),
      "style": trackStyle
    }, [h("div", {
      "class": bem$o('head'),
      "style": this.headStyle
    }, [this.genStatus()]), this.slots()])]);
  }
});

// Utils
var _createNamespace$o = createNamespace('rate'),
  createComponent$s = _createNamespace$o[0],
  bem$n = _createNamespace$o[1];
function getRateStatus(value, index, allowHalf) {
  if (value >= index) {
    return 'full';
  }
  if (value + 0.5 >= index && allowHalf) {
    return 'half';
  }
  return 'void';
}
var Rate = createComponent$s({
  mixins: [TouchMixin, FieldMixin],
  props: {
    size: [Number, String],
    color: String,
    gutter: [Number, String],
    readonly: Boolean,
    disabled: Boolean,
    allowHalf: Boolean,
    voidColor: String,
    iconPrefix: String,
    disabledColor: String,
    value: {
      type: Number,
      default: 0
    },
    icon: {
      type: String,
      default: 'star'
    },
    voidIcon: {
      type: String,
      default: 'star-o'
    },
    count: {
      type: [Number, String],
      default: 5
    },
    touchable: {
      type: Boolean,
      default: true
    }
  },
  computed: {
    list: function list() {
      var list = [];
      for (var i = 1; i <= this.count; i++) {
        list.push(getRateStatus(this.value, i, this.allowHalf));
      }
      return list;
    },
    sizeWithUnit: function sizeWithUnit() {
      return addUnit(this.size);
    },
    gutterWithUnit: function gutterWithUnit() {
      return addUnit(this.gutter);
    }
  },
  mounted: function mounted() {
    this.bindTouchEvent(this.$el);
  },
  methods: {
    select: function select(index) {
      if (!this.disabled && !this.readonly && index !== this.value) {
        this.$emit('input', index);
        this.$emit('change', index);
      }
    },
    onTouchStart: function onTouchStart(event) {
      var _this = this;
      if (this.readonly || this.disabled || !this.touchable) {
        return;
      }
      this.touchStart(event);
      var rects = this.$refs.items.map(function (item) {
        return item.getBoundingClientRect();
      });
      var ranges = [];
      rects.forEach(function (rect, index) {
        if (_this.allowHalf) {
          ranges.push({
            score: index + 0.5,
            left: rect.left
          }, {
            score: index + 1,
            left: rect.left + rect.width / 2
          });
        } else {
          ranges.push({
            score: index + 1,
            left: rect.left
          });
        }
      });
      this.ranges = ranges;
    },
    onTouchMove: function onTouchMove(event) {
      if (this.readonly || this.disabled || !this.touchable) {
        return;
      }
      this.touchMove(event);
      if (this.direction === 'horizontal') {
        preventDefault(event);
        var clientX = event.touches[0].clientX;
        this.select(this.getScoreByPosition(clientX));
      }
    },
    getScoreByPosition: function getScoreByPosition(x) {
      for (var i = this.ranges.length - 1; i > 0; i--) {
        if (x > this.ranges[i].left) {
          return this.ranges[i].score;
        }
      }
      return this.allowHalf ? 0.5 : 1;
    },
    genStar: function genStar(status, index) {
      var _this2 = this;
      var h = this.$createElement;
      var icon = this.icon,
        color = this.color,
        count = this.count,
        voidIcon = this.voidIcon,
        disabled = this.disabled,
        voidColor = this.voidColor,
        disabledColor = this.disabledColor;
      var score = index + 1;
      var isFull = status === 'full';
      var isVoid = status === 'void';
      var style;
      if (this.gutterWithUnit && score !== +count) {
        style = {
          paddingRight: this.gutterWithUnit
        };
      }
      return h("div", {
        "ref": "items",
        "refInFor": true,
        "key": index,
        "attrs": {
          "role": "radio",
          "tabindex": "0",
          "aria-setsize": count,
          "aria-posinset": score,
          "aria-checked": String(!isVoid)
        },
        "style": style,
        "class": bem$n('item')
      }, [h(Icon$1, {
        "attrs": {
          "size": this.sizeWithUnit,
          "name": isFull ? icon : voidIcon,
          "color": disabled ? disabledColor : isFull ? color : voidColor,
          "classPrefix": this.iconPrefix,
          "data-score": score
        },
        "class": bem$n('icon', {
          disabled: disabled,
          full: isFull
        }),
        "on": {
          "click": function click() {
            _this2.select(score);
          }
        }
      }), this.allowHalf && h(Icon$1, {
        "attrs": {
          "size": this.sizeWithUnit,
          "name": isVoid ? voidIcon : icon,
          "color": disabled ? disabledColor : isVoid ? voidColor : color,
          "classPrefix": this.iconPrefix,
          "data-score": score - 0.5
        },
        "class": bem$n('icon', ['half', {
          disabled: disabled,
          full: !isVoid
        }]),
        "on": {
          "click": function click() {
            _this2.select(score - 0.5);
          }
        }
      })]);
    }
  },
  render: function render() {
    var _this3 = this;
    var h = arguments[0];
    return h("div", {
      "class": bem$n({
        readonly: this.readonly,
        disabled: this.disabled
      }),
      "attrs": {
        "tabindex": "0",
        "role": "radiogroup"
      }
    }, [this.list.map(function (status, index) {
      return _this3.genStar(status, index);
    })]);
  }
});

var _createNamespace$n = createNamespace('row'),
  createComponent$r = _createNamespace$n[0],
  bem$m = _createNamespace$n[1];
var Row = createComponent$r({
  mixins: [ParentMixin('vanRow')],
  props: {
    type: String,
    align: String,
    justify: String,
    tag: {
      type: String,
      default: 'div'
    },
    gutter: {
      type: [Number, String],
      default: 0
    }
  },
  computed: {
    spaces: function spaces() {
      var gutter = Number(this.gutter);
      if (!gutter) {
        return;
      }
      var spaces = [];
      var groups = [[]];
      var totalSpan = 0;
      this.children.forEach(function (item, index) {
        totalSpan += Number(item.span);
        if (totalSpan > 24) {
          groups.push([index]);
          totalSpan -= 24;
        } else {
          groups[groups.length - 1].push(index);
        }
      });
      groups.forEach(function (group) {
        var averagePadding = gutter * (group.length - 1) / group.length;
        group.forEach(function (item, index) {
          if (index === 0) {
            spaces.push({
              right: averagePadding
            });
          } else {
            var left = gutter - spaces[item - 1].right;
            var right = averagePadding - left;
            spaces.push({
              left: left,
              right: right
            });
          }
        });
      });
      return spaces;
    }
  },
  methods: {
    onClick: function onClick(event) {
      this.$emit('click', event);
    }
  },
  render: function render() {
    var _bem;
    var h = arguments[0];
    var align = this.align,
      justify = this.justify;
    var flex = this.type === 'flex';
    return h(this.tag, {
      "class": bem$m((_bem = {
        flex: flex
      }, _bem["align-" + align] = flex && align, _bem["justify-" + justify] = flex && justify, _bem)),
      "on": {
        "click": this.onClick
      }
    }, [this.slots()]);
  }
});

var _createNamespace$m = createNamespace('search'),
  createComponent$q = _createNamespace$m[0],
  bem$l = _createNamespace$m[1],
  t$a = _createNamespace$m[2];
function Search(h, props, slots, ctx) {
  function Label() {
    if (slots.label || props.label) {
      return h("div", {
        "class": bem$l('label')
      }, [slots.label ? slots.label() : props.label]);
    }
  }
  function Action() {
    if (!props.showAction) {
      return;
    }
    function onCancel() {
      if (slots.action) {
        return;
      }
      emit(ctx, 'input', '');
      emit(ctx, 'cancel');
    }
    return h("div", {
      "class": bem$l('action'),
      "attrs": {
        "role": "button",
        "tabindex": "0"
      },
      "on": {
        "click": onCancel
      }
    }, [slots.action ? slots.action() : props.actionText || t$a('cancel')]);
  }
  var fieldData = {
    attrs: ctx.data.attrs,
    on: _extends$1({}, ctx.listeners, {
      keypress: function keypress(event) {
        // press enter
        if (event.keyCode === 13) {
          preventDefault(event);
          emit(ctx, 'search', props.value);
        }
        emit(ctx, 'keypress', event);
      }
    })
  };
  var inheritData = inherit(ctx);
  inheritData.attrs = undefined;
  return h("div", _mergeJSXProps([{
    "class": bem$l({
      'show-action': props.showAction
    }),
    "style": {
      background: props.background
    }
  }, inheritData]), [slots.left == null ? void 0 : slots.left(), h("div", {
    "class": bem$l('content', props.shape)
  }, [Label(), h(Field, _mergeJSXProps([{
    "attrs": {
      "type": "search",
      "border": false,
      "value": props.value,
      "leftIcon": props.leftIcon,
      "rightIcon": props.rightIcon,
      "clearable": props.clearable,
      "clearTrigger": props.clearTrigger
    },
    "scopedSlots": {
      'left-icon': slots['left-icon'],
      'right-icon': slots['right-icon']
    }
  }, fieldData]))]), Action()]);
}
Search.props = {
  value: String,
  label: String,
  rightIcon: String,
  actionText: String,
  background: String,
  showAction: Boolean,
  clearTrigger: String,
  shape: {
    type: String,
    default: 'square'
  },
  clearable: {
    type: Boolean,
    default: true
  },
  leftIcon: {
    type: String,
    default: 'search'
  }
};
var Search$1 = createComponent$q(Search);

var PRESET_ICONS = ['qq', 'link', 'weibo', 'wechat', 'poster', 'qrcode', 'weapp-qrcode', 'wechat-moments'];
var _createNamespace$l = createNamespace('share-sheet'),
  createComponent$p = _createNamespace$l[0],
  bem$k = _createNamespace$l[1],
  t$9 = _createNamespace$l[2];
var ShareSheet = createComponent$p({
  props: _extends$1({}, popupMixinProps, {
    title: String,
    duration: String,
    cancelText: String,
    description: String,
    getContainer: [String, Function],
    options: {
      type: Array,
      default: function _default() {
        return [];
      }
    },
    overlay: {
      type: Boolean,
      default: true
    },
    closeOnPopstate: {
      type: Boolean,
      default: true
    },
    safeAreaInsetBottom: {
      type: Boolean,
      default: true
    },
    closeOnClickOverlay: {
      type: Boolean,
      default: true
    }
  }),
  methods: {
    onCancel: function onCancel() {
      this.toggle(false);
      this.$emit('cancel');
    },
    onSelect: function onSelect(option, index) {
      this.$emit('select', option, index);
    },
    toggle: function toggle(val) {
      this.$emit('input', val);
    },
    getIconURL: function getIconURL(icon) {
      if (PRESET_ICONS.indexOf(icon) !== -1) {
        return "https://img01.yzcdn.cn/vant/share-sheet-" + icon + ".png";
      }
      return icon;
    },
    genHeader: function genHeader() {
      var h = this.$createElement;
      var title = this.slots('title') || this.title;
      var description = this.slots('description') || this.description;
      if (!title && !description) {
        return;
      }
      return h("div", {
        "class": bem$k('header')
      }, [title && h("h2", {
        "class": bem$k('title')
      }, [title]), description && h("span", {
        "class": bem$k('description')
      }, [description])]);
    },
    genOptions: function genOptions(options, showBorder) {
      var _this = this;
      var h = this.$createElement;
      return h("div", {
        "class": bem$k('options', {
          border: showBorder
        })
      }, [options.map(function (option, index) {
        return h("div", {
          "attrs": {
            "role": "button",
            "tabindex": "0"
          },
          "class": [bem$k('option'), option.className],
          "on": {
            "click": function click() {
              _this.onSelect(option, index);
            }
          }
        }, [h("img", {
          "attrs": {
            "src": _this.getIconURL(option.icon)
          },
          "class": bem$k('icon')
        }), option.name && h("span", {
          "class": bem$k('name')
        }, [option.name]), option.description && h("span", {
          "class": bem$k('option-description')
        }, [option.description])]);
      })]);
    },
    genRows: function genRows() {
      var _this2 = this;
      var options = this.options;
      if (Array.isArray(options[0])) {
        return options.map(function (item, index) {
          return _this2.genOptions(item, index !== 0);
        });
      }
      return this.genOptions(options);
    },
    genCancelText: function genCancelText() {
      var _this$cancelText;
      var h = this.$createElement;
      var cancelText = (_this$cancelText = this.cancelText) != null ? _this$cancelText : t$9('cancel');
      if (cancelText) {
        return h("button", {
          "attrs": {
            "type": "button"
          },
          "class": bem$k('cancel'),
          "on": {
            "click": this.onCancel
          }
        }, [cancelText]);
      }
    },
    onClickOverlay: function onClickOverlay() {
      this.$emit('click-overlay');
    }
  },
  render: function render() {
    var h = arguments[0];
    return h(Popup, {
      "attrs": {
        "round": true,
        "value": this.value,
        "position": "bottom",
        "overlay": this.overlay,
        "duration": this.duration,
        "lazyRender": this.lazyRender,
        "lockScroll": this.lockScroll,
        "getContainer": this.getContainer,
        "closeOnPopstate": this.closeOnPopstate,
        "closeOnClickOverlay": this.closeOnClickOverlay,
        "safeAreaInsetBottom": this.safeAreaInsetBottom
      },
      "class": bem$k(),
      "on": {
        "input": this.toggle,
        "click-overlay": this.onClickOverlay
      }
    }, [this.genHeader(), this.genRows(), this.genCancelText()]);
  }
});

var _createNamespace$k = createNamespace('sidebar'),
  createComponent$o = _createNamespace$k[0],
  bem$j = _createNamespace$k[1];
var Sidebar = createComponent$o({
  mixins: [ParentMixin('vanSidebar')],
  model: {
    prop: 'activeKey'
  },
  props: {
    activeKey: {
      type: [Number, String],
      default: 0
    }
  },
  data: function data() {
    return {
      index: +this.activeKey
    };
  },
  watch: {
    activeKey: function activeKey() {
      this.setIndex(+this.activeKey);
    }
  },
  methods: {
    setIndex: function setIndex(index) {
      if (index !== this.index) {
        this.index = index;
        this.$emit('change', index);
      }
    }
  },
  render: function render() {
    var h = arguments[0];
    return h("div", {
      "class": bem$j()
    }, [this.slots()]);
  }
});

var _createNamespace$j = createNamespace('sidebar-item'),
  createComponent$n = _createNamespace$j[0],
  bem$i = _createNamespace$j[1];
var SidebarItem = createComponent$n({
  mixins: [ChildrenMixin('vanSidebar')],
  props: _extends$1({}, routeProps, {
    dot: Boolean,
    // @deprecated
    info: [Number, String],
    badge: [Number, String],
    title: String,
    disabled: Boolean
  }),
  computed: {
    select: function select() {
      return this.index === +this.parent.activeKey;
    }
  },
  methods: {
    onClick: function onClick() {
      if (this.disabled) {
        return;
      }
      this.$emit('click', this.index);
      this.parent.$emit('input', this.index);
      this.parent.setIndex(this.index);
      route(this.$router, this);
    }
  },
  render: function render() {
    var _this$slots, _this$badge;
    var h = arguments[0];
    return h("a", {
      "class": bem$i({
        select: this.select,
        disabled: this.disabled
      }),
      "on": {
        "click": this.onClick
      }
    }, [h("div", {
      "class": bem$i('text')
    }, [(_this$slots = this.slots('title')) != null ? _this$slots : this.title, h(Info$1, {
      "attrs": {
        "dot": this.dot,
        "info": (_this$badge = this.badge) != null ? _this$badge : this.info
      },
      "class": bem$i('info')
    })])]);
  }
});

var _createNamespace$i = createNamespace('skeleton'),
  createComponent$m = _createNamespace$i[0],
  bem$h = _createNamespace$i[1];
var DEFAULT_ROW_WIDTH = '100%';
var DEFAULT_LAST_ROW_WIDTH = '60%';
function Skeleton(h, props, slots, ctx) {
  if (!props.loading) {
    return slots.default && slots.default();
  }
  function Title() {
    if (props.title) {
      return h("h3", {
        "class": bem$h('title'),
        "style": {
          width: addUnit(props.titleWidth)
        }
      });
    }
  }
  function Rows() {
    var Rows = [];
    var rowWidth = props.rowWidth;
    function getRowWidth(index) {
      if (rowWidth === DEFAULT_ROW_WIDTH && index === +props.row - 1) {
        return DEFAULT_LAST_ROW_WIDTH;
      }
      if (Array.isArray(rowWidth)) {
        return rowWidth[index];
      }
      return rowWidth;
    }
    for (var i = 0; i < props.row; i++) {
      Rows.push(h("div", {
        "class": bem$h('row'),
        "style": {
          width: addUnit(getRowWidth(i))
        }
      }));
    }
    return Rows;
  }
  function Avatar() {
    if (props.avatar) {
      var size = addUnit(props.avatarSize);
      return h("div", {
        "class": bem$h('avatar', props.avatarShape),
        "style": {
          width: size,
          height: size
        }
      });
    }
  }
  return h("div", _mergeJSXProps([{
    "class": bem$h({
      animate: props.animate,
      round: props.round
    })
  }, inherit(ctx)]), [Avatar(), h("div", {
    "class": bem$h('content')
  }, [Title(), Rows()])]);
}
Skeleton.props = {
  title: Boolean,
  round: Boolean,
  avatar: Boolean,
  titleWidth: [Number, String],
  avatarSize: [Number, String],
  row: {
    type: [Number, String],
    default: 0
  },
  loading: {
    type: Boolean,
    default: true
  },
  animate: {
    type: Boolean,
    default: true
  },
  avatarShape: {
    type: String,
    default: 'round'
  },
  rowWidth: {
    type: [Number, String, Array],
    default: DEFAULT_ROW_WIDTH
  }
};
var Skeleton$1 = createComponent$m(Skeleton);

/**
 * Sku only provide zh-CN lang by default
 */
var lang = {
  'zh-CN': {
    vanSku: {
      select: '请选择',
      selected: '已选',
      selectSku: '请先选择商品规格',
      soldout: '库存不足',
      originPrice: '原价',
      minusTip: '至少选择一件',
      minusStartTip: function minusStartTip(start) {
        return start + "\u4EF6\u8D77\u552E";
      },
      unavailable: '商品已经无法购买啦',
      stock: '剩余',
      stockUnit: '件',
      quotaTip: function quotaTip(quota) {
        return "\u6BCF\u4EBA\u9650\u8D2D" + quota + "\u4EF6";
      },
      quotaUsedTip: function quotaUsedTip(quota, count) {
        return "\u6BCF\u4EBA\u9650\u8D2D" + quota + "\u4EF6\uFF0C\u4F60\u5DF2\u8D2D\u4E70" + count + "\u4EF6";
      }
    },
    vanSkuActions: {
      buy: '立即购买',
      addCart: '加入购物车'
    },
    vanSkuImgUploader: {
      oversize: function oversize(maxSize) {
        return "\u6700\u5927\u53EF\u4E0A\u4F20\u56FE\u7247\u4E3A" + maxSize + "MB\uFF0C\u8BF7\u5C1D\u8BD5\u538B\u7F29\u56FE\u7247\u5C3A\u5BF8";
      },
      fail: '上传失败',
      uploading: '上传中...'
    },
    vanSkuStepper: {
      quotaLimit: function quotaLimit(quota) {
        return "\u9650\u8D2D" + quota + "\u4EF6";
      },
      quotaStart: function quotaStart(start) {
        return start + "\u4EF6\u8D77\u552E";
      },
      comma: '，',
      num: '购买数量'
    },
    vanSkuMessages: {
      fill: '请填写',
      upload: '请上传',
      imageLabel: '仅限一张',
      invalid: {
        tel: '请填写正确的数字格式留言',
        mobile: '手机号长度为6-20位数字',
        email: '请填写正确的邮箱',
        id_no: '请填写正确的身份证号码'
      },
      placeholder: {
        id_no: '请填写身份证号',
        text: '请填写留言',
        tel: '请填写数字',
        email: '请填写邮箱',
        date: '请选择日期',
        time: '请选择时间',
        textarea: '请填写留言',
        mobile: '请填写手机号'
      }
    },
    vanSkuRow: {
      multiple: '可多选'
    },
    vanSkuDatetimeField: {
      title: {
        date: '选择年月日',
        time: '选择时间',
        datetime: '选择日期时间'
      },
      format: {
        year: '年',
        month: '月',
        day: '日',
        hour: '时',
        minute: '分'
      }
    }
  }
};

var LIMIT_TYPE = {
  QUOTA_LIMIT: 0,
  STOCK_LIMIT: 1
};
var UNSELECTED_SKU_VALUE_ID = '';
var constants = {
  LIMIT_TYPE: LIMIT_TYPE,
  UNSELECTED_SKU_VALUE_ID: UNSELECTED_SKU_VALUE_ID
};

/*
  normalize sku tree

  [
    {
      count: 2,
      k: "品种", // 规格名称 skuKeyName
      k_id: "1200", // skuKeyId
      k_s: "s1" // skuKeyStr
      v: [ // skuValues
        { // skuValue
          id: "1201", // skuValueId
          name: "萌" // 具体的规格值 skuValueName
        }, {
          id: "973",
          name: "帅"
        }
      ]
    },
    ...
  ]
                |
                v
  {
    s1: [{
      id: "1201",
      name: "萌"
    }, {
      id: "973",
      name: "帅"
    }],
    ...
  }
 */

var normalizeSkuTree = function normalizeSkuTree(skuTree) {
  var normalizedTree = {};
  skuTree.forEach(function (treeItem) {
    normalizedTree[treeItem.k_s] = treeItem.v;
  });
  return normalizedTree;
};
var normalizePropList = function normalizePropList(propList) {
  var normalizedProp = {};
  propList.forEach(function (item) {
    var itemObj = {};
    item.v.forEach(function (it) {
      itemObj[it.id] = it;
    });
    normalizedProp[item.k_id] = itemObj;
  });
  return normalizedProp;
}; // 判断是否所有的sku都已经选中

var isAllSelected = function isAllSelected(skuTree, selectedSku) {
  // 筛选selectedSku对象中key值不为空的值
  var selected = Object.keys(selectedSku).filter(function (skuKeyStr) {
    return selectedSku[skuKeyStr] !== UNSELECTED_SKU_VALUE_ID;
  });
  return skuTree.length === selected.length;
}; // 根据已选择的 sku 获取 skuComb

var getSkuComb = function getSkuComb(skuList, selectedSku) {
  var skuComb = skuList.filter(function (item) {
    return Object.keys(selectedSku).every(function (skuKeyStr) {
      return String(item[skuKeyStr]) === String(selectedSku[skuKeyStr]);
    });
  });
  return skuComb[0];
}; // 获取已选择的sku名称

var getSelectedSkuValues = function getSelectedSkuValues(skuTree, selectedSku) {
  var normalizedTree = normalizeSkuTree(skuTree);
  return Object.keys(selectedSku).reduce(function (selectedValues, skuKeyStr) {
    var skuValues = normalizedTree[skuKeyStr] || [];
    var skuValueId = selectedSku[skuKeyStr];
    if (skuValueId !== UNSELECTED_SKU_VALUE_ID && skuValues.length > 0) {
      var skuValue = skuValues.filter(function (value) {
        return value.id === skuValueId;
      })[0];
      skuValue && selectedValues.push(skuValue);
    }
    return selectedValues;
  }, []);
}; // 判断sku是否可选

var isSkuChoosable = function isSkuChoosable(skuList, selectedSku, skuToChoose) {
  var _extends2;
  var key = skuToChoose.key,
    valueId = skuToChoose.valueId; // 先假设sku已选中，拼入已选中sku对象中

  var matchedSku = _extends$1({}, selectedSku, (_extends2 = {}, _extends2[key] = valueId, _extends2)); // 再判断剩余sku是否全部不可选，若不可选则当前sku不可选中

  var skusToCheck = Object.keys(matchedSku).filter(function (skuKey) {
    return matchedSku[skuKey] !== UNSELECTED_SKU_VALUE_ID;
  });
  var filteredSku = skuList.filter(function (sku) {
    return skusToCheck.every(function (skuKey) {
      return String(matchedSku[skuKey]) === String(sku[skuKey]);
    });
  });
  var stock = filteredSku.reduce(function (total, sku) {
    total += sku.stock_num;
    return total;
  }, 0);
  return stock > 0;
};
var getSelectedPropValues = function getSelectedPropValues(propList, selectedProp) {
  var normalizeProp = normalizePropList(propList);
  return Object.keys(selectedProp).reduce(function (acc, cur) {
    selectedProp[cur].forEach(function (it) {
      acc.push(_extends$1({}, normalizeProp[cur][it]));
    });
    return acc;
  }, []);
};
var getSelectedProperties = function getSelectedProperties(propList, selectedProp) {
  var list = [];
  (propList || []).forEach(function (prop) {
    if (selectedProp[prop.k_id] && selectedProp[prop.k_id].length > 0) {
      var v = [];
      prop.v.forEach(function (it) {
        if (selectedProp[prop.k_id].indexOf(it.id) > -1) {
          v.push(_extends$1({}, it));
        }
      });
      list.push(_extends$1({}, prop, {
        v: v
      }));
    }
  });
  return list;
};
var skuHelper = {
  normalizeSkuTree: normalizeSkuTree,
  getSkuComb: getSkuComb,
  getSelectedSkuValues: getSelectedSkuValues,
  isAllSelected: isAllSelected,
  isSkuChoosable: isSkuChoosable,
  getSelectedPropValues: getSelectedPropValues,
  getSelectedProperties: getSelectedProperties
};

var _createNamespace$h = createNamespace('sku-header'),
  createComponent$l = _createNamespace$h[0],
  bem$g = _createNamespace$h[1];
function getSkuImgValue(sku, selectedSku) {
  var imgValue;
  sku.tree.some(function (item) {
    var id = selectedSku[item.k_s];
    if (id && item.v) {
      var matchedSku = item.v.filter(function (skuValue) {
        return skuValue.id === id;
      })[0] || {};
      var img = matchedSku.previewImgUrl || matchedSku.imgUrl || matchedSku.img_url;
      if (img) {
        imgValue = _extends$1({}, matchedSku, {
          ks: item.k_s,
          imgUrl: img
        });
        return true;
      }
    }
    return false;
  });
  return imgValue;
}
function SkuHeader$1(h, props, slots, ctx) {
  var _slots$skuHeaderIma;
  var sku = props.sku,
    goods = props.goods,
    skuEventBus = props.skuEventBus,
    selectedSku = props.selectedSku,
    _props$showHeaderImag = props.showHeaderImage,
    showHeaderImage = _props$showHeaderImag === void 0 ? true : _props$showHeaderImag;
  var selectedValue = getSkuImgValue(sku, selectedSku);
  var imgUrl = selectedValue ? selectedValue.imgUrl : goods.picture;
  var previewImage = function previewImage() {
    skuEventBus.$emit('sku:previewImage', selectedValue);
  };
  return h("div", _mergeJSXProps([{
    "class": [bem$g(), BORDER_BOTTOM]
  }, inherit(ctx)]), [showHeaderImage && h(Image$1, {
    "attrs": {
      "fit": "cover",
      "src": imgUrl
    },
    "class": bem$g('img-wrap'),
    "on": {
      "click": previewImage
    }
  }, [(_slots$skuHeaderIma = slots['sku-header-image-extra']) == null ? void 0 : _slots$skuHeaderIma.call(slots)]), h("div", {
    "class": bem$g('goods-info')
  }, [slots.default == null ? void 0 : slots.default()])]);
}
SkuHeader$1.props = {
  sku: Object,
  goods: Object,
  skuEventBus: Object,
  selectedSku: Object,
  showHeaderImage: Boolean
};
var SkuHeader$2 = createComponent$l(SkuHeader$1);

var _createNamespace$g = createNamespace('sku-header-item'),
  createComponent$k = _createNamespace$g[0],
  bem$f = _createNamespace$g[1];
function SkuHeader(h, props, slots, ctx) {
  return h("div", _mergeJSXProps([{
    "class": bem$f()
  }, inherit(ctx)]), [slots.default && slots.default()]);
}
var SkuHeaderItem = createComponent$k(SkuHeader);

// Utils
var _createNamespace$f = createNamespace('sku-row'),
  createComponent$j = _createNamespace$f[0],
  bem$e = _createNamespace$f[1],
  t$8 = _createNamespace$f[2];
var SkuRow = createComponent$j({
  mixins: [ParentMixin('vanSkuRows'), BindEventMixin(function (bind) {
    if (this.scrollable && this.$refs.scroller) {
      bind(this.$refs.scroller, 'scroll', this.onScroll);
    }
  })],
  props: {
    skuRow: Object
  },
  data: function data() {
    return {
      progress: 0
    };
  },
  computed: {
    scrollable: function scrollable() {
      return this.skuRow.largeImageMode && this.skuRow.v.length > 6;
    }
  },
  methods: {
    onScroll: function onScroll() {
      var _this$$refs = this.$refs,
        scroller = _this$$refs.scroller,
        row = _this$$refs.row;
      var distance = row.offsetWidth - scroller.offsetWidth;
      this.progress = scroller.scrollLeft / distance;
    },
    genTitle: function genTitle() {
      var h = this.$createElement;
      return h("div", {
        "class": bem$e('title')
      }, [this.skuRow.k, this.skuRow.is_multiple && h("span", {
        "class": bem$e('title-multiple')
      }, ["\uFF08", t$8('multiple'), "\uFF09"])]);
    },
    genIndicator: function genIndicator() {
      var h = this.$createElement;
      if (this.scrollable) {
        var style = {
          transform: "translate3d(" + this.progress * 20 + "px, 0, 0)"
        };
        return h("div", {
          "class": bem$e('indicator-wrapper')
        }, [h("div", {
          "class": bem$e('indicator')
        }, [h("div", {
          "class": bem$e('indicator-slider'),
          "style": style
        })])]);
      }
    },
    genContent: function genContent() {
      var h = this.$createElement;
      var nodes = this.slots();
      if (this.skuRow.largeImageMode) {
        var top = [];
        var bottom = [];
        nodes.forEach(function (node, index) {
          var group = Math.floor(index / 3) % 2 === 0 ? top : bottom;
          group.push(node);
        });
        return h("div", {
          "class": bem$e('scroller'),
          "ref": "scroller"
        }, [h("div", {
          "class": bem$e('row'),
          "ref": "row"
        }, [top]), bottom.length ? h("div", {
          "class": bem$e('row')
        }, [bottom]) : null]);
      }
      return nodes;
    },
    centerItem: function centerItem(selectSkuId) {
      if (!this.skuRow.largeImageMode || !selectSkuId) {
        return;
      }
      var _this$children = this.children,
        children = _this$children === void 0 ? [] : _this$children;
      var _this$$refs2 = this.$refs,
        scroller = _this$$refs2.scroller,
        row = _this$$refs2.row;
      var child = children.find(function (it) {
        return +it.skuValue.id === +selectSkuId;
      });
      if (scroller && row && child && child.$el) {
        var target = child.$el;
        var to = target.offsetLeft - (scroller.offsetWidth - target.offsetWidth) / 2;
        scroller.scrollLeft = to;
      }
    }
  },
  render: function render() {
    var h = arguments[0];
    return h("div", {
      "class": [bem$e(), BORDER_BOTTOM]
    }, [this.genTitle(), this.genContent(), this.genIndicator()]);
  }
});

var _createNamespace$e = createNamespace('sku-row-item'),
  createComponent$i = _createNamespace$e[0];
var SkuRowItem = createComponent$i({
  mixins: [ChildrenMixin('vanSkuRows')],
  props: {
    lazyLoad: Boolean,
    skuValue: Object,
    skuKeyStr: String,
    skuEventBus: Object,
    selectedSku: Object,
    largeImageMode: Boolean,
    disableSoldoutSku: Boolean,
    skuList: {
      type: Array,
      default: function _default() {
        return [];
      }
    }
  },
  computed: {
    imgUrl: function imgUrl() {
      var url = this.skuValue.imgUrl || this.skuValue.img_url;
      return this.largeImageMode ? url || 'https://img01.yzcdn.cn/upload_files/2020/06/24/FmKWDg0bN9rMcTp9ne8MXiQWGtLn.png' : url;
    },
    choosable: function choosable() {
      if (!this.disableSoldoutSku) {
        return true;
      }
      return isSkuChoosable(this.skuList, this.selectedSku, {
        key: this.skuKeyStr,
        valueId: this.skuValue.id
      });
    }
  },
  methods: {
    onSelect: function onSelect() {
      if (this.choosable) {
        this.skuEventBus.$emit('sku:select', _extends$1({}, this.skuValue, {
          skuKeyStr: this.skuKeyStr
        }));
      }
    },
    onPreviewImg: function onPreviewImg(event) {
      event.stopPropagation();
      var skuValue = this.skuValue,
        skuKeyStr = this.skuKeyStr;
      this.skuEventBus.$emit('sku:previewImage', _extends$1({}, skuValue, {
        ks: skuKeyStr,
        imgUrl: skuValue.imgUrl || skuValue.img_url
      }));
    },
    genImage: function genImage(classPrefix) {
      var h = this.$createElement;
      if (this.imgUrl) {
        return h(Image$1, {
          "attrs": {
            "fit": "cover",
            "src": this.imgUrl,
            "lazyLoad": this.lazyLoad
          },
          "class": classPrefix + "-img"
        });
      }
    }
  },
  render: function render() {
    var h = arguments[0];
    var choosed = this.skuValue.id === this.selectedSku[this.skuKeyStr];
    var classPrefix = this.largeImageMode ? bem$e('image-item') : bem$e('item');
    return h("span", {
      "class": [classPrefix, choosed ? classPrefix + "--active" : '', !this.choosable ? classPrefix + "--disabled" : ''],
      "on": {
        "click": this.onSelect
      }
    }, [this.genImage(classPrefix), h("div", {
      "class": classPrefix + "-name"
    }, [this.largeImageMode ? h("span", {
      "class": {
        'van-multi-ellipsis--l2': this.largeImageMode
      }
    }, [this.skuValue.name]) : this.skuValue.name]), this.largeImageMode && h(Icon$1, {
      "attrs": {
        "name": "enlarge"
      },
      "class": classPrefix + "-img-icon",
      "on": {
        "click": this.onPreviewImg
      }
    })]);
  }
});

var _createNamespace$d = createNamespace('sku-row-prop-item'),
  createComponent$h = _createNamespace$d[0];
var SkuRowPropItem = createComponent$h({
  props: {
    skuValue: Object,
    skuKeyStr: String,
    skuEventBus: Object,
    selectedProp: Object,
    multiple: Boolean,
    disabled: Boolean
  },
  computed: {
    choosed: function choosed() {
      var selectedProp = this.selectedProp,
        skuKeyStr = this.skuKeyStr,
        skuValue = this.skuValue;
      if (selectedProp && selectedProp[skuKeyStr]) {
        return selectedProp[skuKeyStr].indexOf(skuValue.id) > -1;
      }
      return false;
    }
  },
  methods: {
    onSelect: function onSelect() {
      if (this.disabled) return;
      this.skuEventBus.$emit('sku:propSelect', _extends$1({}, this.skuValue, {
        skuKeyStr: this.skuKeyStr,
        multiple: this.multiple
      }));
    }
  },
  render: function render() {
    var h = arguments[0];
    return h("span", {
      "class": ['van-sku-row__item', {
        'van-sku-row__item--active': this.choosed
      }, {
        'van-sku-row__item--disabled': this.disabled
      }],
      "on": {
        "click": this.onSelect
      }
    }, [h("span", {
      "class": "van-sku-row__item-name"
    }, [this.skuValue.name])]);
  }
});

var _createNamespace$c = createNamespace('stepper'),
  createComponent$g = _createNamespace$c[0],
  bem$d = _createNamespace$c[1];
var LONG_PRESS_START_TIME = 600;
var LONG_PRESS_INTERVAL = 200;
function equal(value1, value2) {
  return String(value1) === String(value2);
}
var Stepper = createComponent$g({
  mixins: [FieldMixin],
  props: {
    value: null,
    theme: String,
    integer: Boolean,
    disabled: Boolean,
    allowEmpty: Boolean,
    inputWidth: [Number, String],
    buttonSize: [Number, String],
    asyncChange: Boolean,
    placeholder: String,
    disablePlus: Boolean,
    disableMinus: Boolean,
    disableInput: Boolean,
    decimalLength: [Number, String],
    name: {
      type: [Number, String],
      default: ''
    },
    min: {
      type: [Number, String],
      default: 1
    },
    max: {
      type: [Number, String],
      default: Infinity
    },
    step: {
      type: [Number, String],
      default: 1
    },
    defaultValue: {
      type: [Number, String],
      default: 1
    },
    showPlus: {
      type: Boolean,
      default: true
    },
    showMinus: {
      type: Boolean,
      default: true
    },
    showInput: {
      type: Boolean,
      default: true
    },
    longPress: {
      type: Boolean,
      default: true
    }
  },
  data: function data() {
    var _this$value;
    var defaultValue = (_this$value = this.value) != null ? _this$value : this.defaultValue;
    var value = this.format(defaultValue);
    if (!equal(value, this.value)) {
      this.$emit('input', value);
    }
    return {
      currentValue: value
    };
  },
  computed: {
    minusDisabled: function minusDisabled() {
      return this.disabled || this.disableMinus || this.currentValue <= +this.min;
    },
    plusDisabled: function plusDisabled() {
      return this.disabled || this.disablePlus || this.currentValue >= +this.max;
    },
    inputStyle: function inputStyle() {
      var style = {};
      if (this.inputWidth) {
        style.width = addUnit(this.inputWidth);
      }
      if (this.buttonSize) {
        style.height = addUnit(this.buttonSize);
      }
      return style;
    },
    buttonStyle: function buttonStyle() {
      if (this.buttonSize) {
        var size = addUnit(this.buttonSize);
        return {
          width: size,
          height: size
        };
      }
    }
  },
  watch: {
    max: 'check',
    min: 'check',
    integer: 'check',
    decimalLength: 'check',
    value: function value(val) {
      if (!equal(val, this.currentValue)) {
        this.currentValue = this.format(val);
      }
    },
    currentValue: function currentValue(val) {
      this.$emit('input', val);
      this.$emit('change', val, {
        name: this.name
      });
    }
  },
  methods: {
    check: function check() {
      var val = this.format(this.currentValue);
      if (!equal(val, this.currentValue)) {
        this.currentValue = val;
      }
    },
    // formatNumber illegal characters
    formatNumber: function formatNumber$1(value) {
      return formatNumber(String(value), !this.integer);
    },
    format: function format(value) {
      if (this.allowEmpty && value === '') {
        return value;
      }
      value = this.formatNumber(value); // format range

      value = value === '' ? 0 : +value;
      value = isNaN$1(value) ? this.min : value;
      value = Math.max(Math.min(this.max, value), this.min); // format decimal

      if (isDef(this.decimalLength)) {
        value = value.toFixed(this.decimalLength);
      }
      return value;
    },
    onInput: function onInput(event) {
      var value = event.target.value;
      var formatted = this.formatNumber(value); // limit max decimal length

      if (isDef(this.decimalLength) && formatted.indexOf('.') !== -1) {
        var pair = formatted.split('.');
        formatted = pair[0] + "." + pair[1].slice(0, this.decimalLength);
      }
      if (!equal(value, formatted)) {
        event.target.value = formatted;
      } // prefer number type

      if (formatted === String(+formatted)) {
        formatted = +formatted;
      }
      this.emitChange(formatted);
    },
    emitChange: function emitChange(value) {
      if (this.asyncChange) {
        this.$emit('input', value);
        this.$emit('change', value, {
          name: this.name
        });
      } else {
        this.currentValue = value;
      }
    },
    onChange: function onChange() {
      var type = this.type;
      if (this[type + "Disabled"]) {
        this.$emit('overlimit', type);
        return;
      }
      var diff = type === 'minus' ? -this.step : +this.step;
      var value = this.format(addNumber(+this.currentValue, diff));
      this.emitChange(value);
      this.$emit(type);
    },
    onFocus: function onFocus(event) {
      // readonly not work in legacy mobile safari
      if (this.disableInput && this.$refs.input) {
        this.$refs.input.blur();
      } else {
        this.$emit('focus', event);
      }
    },
    onBlur: function onBlur(event) {
      var value = this.format(event.target.value);
      event.target.value = value;
      this.emitChange(value);
      this.$emit('blur', event);
      resetScroll();
    },
    longPressStep: function longPressStep() {
      var _this = this;
      this.longPressTimer = setTimeout(function () {
        _this.onChange();
        _this.longPressStep(_this.type);
      }, LONG_PRESS_INTERVAL);
    },
    onTouchStart: function onTouchStart() {
      var _this2 = this;
      if (!this.longPress) {
        return;
      }
      clearTimeout(this.longPressTimer);
      this.isLongPress = false;
      this.longPressTimer = setTimeout(function () {
        _this2.isLongPress = true;
        _this2.onChange();
        _this2.longPressStep();
      }, LONG_PRESS_START_TIME);
    },
    onTouchEnd: function onTouchEnd(event) {
      if (!this.longPress) {
        return;
      }
      clearTimeout(this.longPressTimer);
      if (this.isLongPress) {
        preventDefault(event);
      }
    },
    onMousedown: function onMousedown(event) {
      // fix mobile safari page scroll down issue
      // see: https://github.com/vant-ui/vant/issues/7690
      if (this.disableInput) {
        event.preventDefault();
      }
    }
  },
  render: function render() {
    var _this3 = this;
    var h = arguments[0];
    var createListeners = function createListeners(type) {
      return {
        on: {
          click: function click(e) {
            // disable double tap scrolling on mobile safari
            e.preventDefault();
            _this3.type = type;
            _this3.onChange();
          },
          touchstart: function touchstart() {
            _this3.type = type;
            _this3.onTouchStart();
          },
          touchend: _this3.onTouchEnd,
          touchcancel: _this3.onTouchEnd
        }
      };
    };
    return h("div", {
      "class": bem$d([this.theme])
    }, [h("button", _mergeJSXProps([{
      "directives": [{
        name: "show",
        value: this.showMinus
      }],
      "attrs": {
        "type": "button"
      },
      "style": this.buttonStyle,
      "class": bem$d('minus', {
        disabled: this.minusDisabled
      })
    }, createListeners('minus')])), h("input", {
      "directives": [{
        name: "show",
        value: this.showInput
      }],
      "ref": "input",
      "attrs": {
        "type": this.integer ? 'tel' : 'text',
        "role": "spinbutton",
        "disabled": this.disabled,
        "readonly": this.disableInput,
        "inputmode": this.integer ? 'numeric' : 'decimal',
        "placeholder": this.placeholder,
        "aria-valuemax": this.max,
        "aria-valuemin": this.min,
        "aria-valuenow": this.currentValue
      },
      "class": bem$d('input'),
      "domProps": {
        "value": this.currentValue
      },
      "style": this.inputStyle,
      "on": {
        "input": this.onInput,
        "focus": this.onFocus,
        "blur": this.onBlur,
        "mousedown": this.onMousedown
      }
    }), h("button", _mergeJSXProps([{
      "directives": [{
        name: "show",
        value: this.showPlus
      }],
      "attrs": {
        "type": "button"
      },
      "style": this.buttonStyle,
      "class": bem$d('plus', {
        disabled: this.plusDisabled
      })
    }, createListeners('plus')]))]);
  }
});

var namespace$3 = createNamespace('sku-stepper');
var createComponent$f = namespace$3[0];
var t$7 = namespace$3[2];
var QUOTA_LIMIT$1 = LIMIT_TYPE.QUOTA_LIMIT,
  STOCK_LIMIT = LIMIT_TYPE.STOCK_LIMIT;
var SkuStepper = createComponent$f({
  props: {
    stock: Number,
    skuEventBus: Object,
    skuStockNum: Number,
    selectedNum: Number,
    stepperTitle: String,
    disableStepperInput: Boolean,
    customStepperConfig: Object,
    hideQuotaText: Boolean,
    quota: {
      type: Number,
      default: 0
    },
    quotaUsed: {
      type: Number,
      default: 0
    },
    startSaleNum: {
      type: Number,
      default: 1
    }
  },
  data: function data() {
    return {
      currentNum: this.selectedNum,
      // 购买限制类型: 限购/库存
      limitType: STOCK_LIMIT
    };
  },
  watch: {
    currentNum: function currentNum(num) {
      var intValue = parseInt(num, 10);
      if (intValue >= this.stepperMinLimit && intValue <= this.stepperLimit) {
        this.skuEventBus.$emit('sku:numChange', intValue);
      }
    },
    stepperLimit: function stepperLimit(limit) {
      if (limit < this.currentNum && this.stepperMinLimit <= limit) {
        this.currentNum = limit;
      }
      this.checkState(this.stepperMinLimit, limit);
    },
    stepperMinLimit: function stepperMinLimit(start) {
      if (start > this.currentNum || start > this.stepperLimit) {
        this.currentNum = start;
      }
      this.checkState(start, this.stepperLimit);
    }
  },
  computed: {
    stepperLimit: function stepperLimit() {
      var quotaLimit = this.quota - this.quotaUsed;
      var limit; // 无限购时直接取库存，有限购时取限购数和库存数中小的那个

      if (this.quota > 0 && quotaLimit <= this.stock) {
        // 修正负的limit
        limit = quotaLimit < 0 ? 0 : quotaLimit;
        this.limitType = QUOTA_LIMIT$1;
      } else {
        limit = this.stock;
        this.limitType = STOCK_LIMIT;
      }
      return limit;
    },
    stepperMinLimit: function stepperMinLimit() {
      return this.startSaleNum < 1 ? 1 : this.startSaleNum;
    },
    quotaText: function quotaText() {
      var _this$customStepperCo = this.customStepperConfig,
        quotaText = _this$customStepperCo.quotaText,
        hideQuotaText = _this$customStepperCo.hideQuotaText;
      if (hideQuotaText) return '';
      var text = '';
      if (quotaText) {
        text = quotaText;
      } else {
        var textArr = [];
        if (this.startSaleNum > 1) {
          textArr.push(t$7('quotaStart', this.startSaleNum));
        }
        if (this.quota > 0) {
          textArr.push(t$7('quotaLimit', this.quota));
        }
        text = textArr.join(t$7('comma'));
      }
      return text;
    }
  },
  created: function created() {
    this.checkState(this.stepperMinLimit, this.stepperLimit);
  },
  methods: {
    setCurrentNum: function setCurrentNum(num) {
      this.currentNum = num;
      this.checkState(this.stepperMinLimit, this.stepperLimit);
    },
    onOverLimit: function onOverLimit(action) {
      this.skuEventBus.$emit('sku:overLimit', {
        action: action,
        limitType: this.limitType,
        quota: this.quota,
        quotaUsed: this.quotaUsed,
        startSaleNum: this.startSaleNum
      });
    },
    onChange: function onChange(currentValue) {
      var intValue = parseInt(currentValue, 10);
      var handleStepperChange = this.customStepperConfig.handleStepperChange;
      handleStepperChange && handleStepperChange(intValue);
      this.$emit('change', intValue);
    },
    checkState: function checkState(min, max) {
      // 如果选择小于起售，则强制变为起售
      if (this.currentNum < min || min > max) {
        this.currentNum = min;
      } else if (this.currentNum > max) {
        // 当前选择数量大于最大可选时，需要重置已选数量
        this.currentNum = max;
      }
      this.skuEventBus.$emit('sku:stepperState', {
        valid: min <= max,
        min: min,
        max: max,
        limitType: this.limitType,
        quota: this.quota,
        quotaUsed: this.quotaUsed,
        startSaleNum: this.startSaleNum
      });
    }
  },
  render: function render() {
    var _this = this;
    var h = arguments[0];
    return h("div", {
      "class": "van-sku-stepper-stock"
    }, [h("div", {
      "class": "van-sku__stepper-title"
    }, [this.stepperTitle || t$7('num')]), h(Stepper, {
      "attrs": {
        "integer": true,
        "min": this.stepperMinLimit,
        "max": this.stepperLimit,
        "disableInput": this.disableStepperInput
      },
      "class": "van-sku__stepper",
      "on": {
        "overlimit": this.onOverLimit,
        "change": this.onChange
      },
      "model": {
        value: _this.currentNum,
        callback: function callback($$v) {
          _this.currentNum = $$v;
        }
      }
    }), !this.hideQuotaText && this.quotaText && h("span", {
      "class": "van-sku__stepper-quota"
    }, ["(", this.quotaText, ")"])]);
  }
});

/* eslint-disable */
function isEmail(value) {
  var reg = /^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/;
  return reg.test(value.trim());
}

function toArray(item) {
  if (Array.isArray(item)) {
    return item;
  }
  return [item];
}
function readFile(file, resultType) {
  return new Promise(function (resolve) {
    if (resultType === 'file') {
      resolve(null);
      return;
    }
    var reader = new FileReader();
    reader.onload = function (event) {
      resolve(event.target.result);
    };
    if (resultType === 'dataUrl') {
      reader.readAsDataURL(file);
    } else if (resultType === 'text') {
      reader.readAsText(file);
    }
  });
}
function isOversize(files, maxSize) {
  return toArray(files).some(function (file) {
    if (file) {
      if (isFunction(maxSize)) {
        return maxSize(file);
      }
      return file.size > maxSize;
    }
    return false;
  });
}
var IMAGE_REGEXP = /\.(jpeg|jpg|gif|png|svg|webp|jfif|bmp|dpg)/i;
function isImageUrl(url) {
  return IMAGE_REGEXP.test(url);
}
function isImageFile(item) {
  // some special urls cannot be recognized
  // user can add `isImage` flag to mark it as an image url
  if (item.isImage) {
    return true;
  }
  if (item.file && item.file.type) {
    return item.file.type.indexOf('image') === 0;
  }
  if (item.url) {
    return isImageUrl(item.url);
  }
  if (item.content) {
    return item.content.indexOf('data:image') === 0;
  }
  return false;
}

var _createNamespace$b = createNamespace('uploader'),
  createComponent$e = _createNamespace$b[0],
  bem$c = _createNamespace$b[1];
var Uploader = createComponent$e({
  inheritAttrs: false,
  mixins: [FieldMixin],
  model: {
    prop: 'fileList'
  },
  props: {
    disabled: Boolean,
    readonly: Boolean,
    lazyLoad: Boolean,
    uploadText: String,
    afterRead: Function,
    beforeRead: Function,
    beforeDelete: Function,
    previewSize: [Number, String],
    previewOptions: Object,
    name: {
      type: [Number, String],
      default: ''
    },
    accept: {
      type: String,
      default: 'image/*'
    },
    fileList: {
      type: Array,
      default: function _default() {
        return [];
      }
    },
    maxSize: {
      type: [Number, String, Function],
      default: Number.MAX_VALUE
    },
    maxCount: {
      type: [Number, String],
      default: Number.MAX_VALUE
    },
    deletable: {
      type: Boolean,
      default: true
    },
    showUpload: {
      type: Boolean,
      default: true
    },
    previewImage: {
      type: Boolean,
      default: true
    },
    previewFullImage: {
      type: Boolean,
      default: true
    },
    imageFit: {
      type: String,
      default: 'cover'
    },
    resultType: {
      type: String,
      default: 'dataUrl'
    },
    uploadIcon: {
      type: String,
      default: 'photograph'
    }
  },
  computed: {
    previewSizeWithUnit: function previewSizeWithUnit() {
      return addUnit(this.previewSize);
    },
    // for form
    value: function value() {
      return this.fileList;
    }
  },
  created: function created() {
    this.urls = [];
  },
  beforeDestroy: function beforeDestroy() {
    this.urls.forEach(function (url) {
      return URL.revokeObjectURL(url);
    });
  },
  methods: {
    getDetail: function getDetail(index) {
      if (index === void 0) {
        index = this.fileList.length;
      }
      return {
        name: this.name,
        index: index
      };
    },
    onChange: function onChange(event) {
      var _this = this;
      var files = event.target.files;
      if (this.disabled || !files.length) {
        return;
      }
      files = files.length === 1 ? files[0] : [].slice.call(files);
      if (this.beforeRead) {
        var response = this.beforeRead(files, this.getDetail());
        if (!response) {
          this.resetInput();
          return;
        }
        if (isPromise(response)) {
          response.then(function (data) {
            if (data) {
              _this.readFile(data);
            } else {
              _this.readFile(files);
            }
          }).catch(this.resetInput);
          return;
        }
      }
      this.readFile(files);
    },
    readFile: function readFile$1(files) {
      var _this2 = this;
      var oversize = isOversize(files, this.maxSize);
      if (Array.isArray(files)) {
        var maxCount = this.maxCount - this.fileList.length;
        if (files.length > maxCount) {
          files = files.slice(0, maxCount);
        }
        Promise.all(files.map(function (file) {
          return readFile(file, _this2.resultType);
        })).then(function (contents) {
          var fileList = files.map(function (file, index) {
            var result = {
              file: file,
              status: '',
              message: ''
            };
            if (contents[index]) {
              result.content = contents[index];
            }
            return result;
          });
          _this2.onAfterRead(fileList, oversize);
        });
      } else {
        readFile(files, this.resultType).then(function (content) {
          var result = {
            file: files,
            status: '',
            message: ''
          };
          if (content) {
            result.content = content;
          }
          _this2.onAfterRead(result, oversize);
        });
      }
    },
    onAfterRead: function onAfterRead(files, oversize) {
      var _this3 = this;
      this.resetInput();
      var validFiles = files;
      if (oversize) {
        var oversizeFiles = files;
        if (Array.isArray(files)) {
          oversizeFiles = [];
          validFiles = [];
          files.forEach(function (item) {
            if (item.file) {
              if (isOversize(item.file, _this3.maxSize)) {
                oversizeFiles.push(item);
              } else {
                validFiles.push(item);
              }
            }
          });
        } else {
          validFiles = null;
        }
        this.$emit('oversize', oversizeFiles, this.getDetail());
      }
      var isValidFiles = Array.isArray(validFiles) ? Boolean(validFiles.length) : Boolean(validFiles);
      if (isValidFiles) {
        this.$emit('input', [].concat(this.fileList, toArray(validFiles)));
        if (this.afterRead) {
          this.afterRead(validFiles, this.getDetail());
        }
      }
    },
    onDelete: function onDelete(file, index) {
      var _file$beforeDelete,
        _this4 = this;
      var beforeDelete = (_file$beforeDelete = file.beforeDelete) != null ? _file$beforeDelete : this.beforeDelete;
      if (beforeDelete) {
        var response = beforeDelete(file, this.getDetail(index));
        if (!response) {
          return;
        }
        if (isPromise(response)) {
          response.then(function () {
            _this4.deleteFile(file, index);
          }).catch(noop);
          return;
        }
      }
      this.deleteFile(file, index);
    },
    deleteFile: function deleteFile(file, index) {
      var fileList = this.fileList.slice(0);
      fileList.splice(index, 1);
      this.$emit('input', fileList);
      this.$emit('delete', file, this.getDetail(index));
    },
    resetInput: function resetInput() {
      /* istanbul ignore else */
      if (this.$refs.input) {
        this.$refs.input.value = '';
      }
    },
    onClickUpload: function onClickUpload(event) {
      this.$emit('click-upload', event);
    },
    onPreviewImage: function onPreviewImage(item) {
      var _this5 = this;
      if (!this.previewFullImage) {
        return;
      }
      var imageFiles = this.fileList.filter(function (item) {
        return isImageFile(item);
      });
      var imageContents = imageFiles.map(function (item) {
        if (item.file && !item.url && item.status !== 'failed') {
          item.url = URL.createObjectURL(item.file);
          _this5.urls.push(item.url);
        }
        return item.url;
      });
      this.imagePreview = ImagePreview$1(_extends$1({
        images: imageContents,
        startPosition: imageFiles.indexOf(item),
        onClose: function onClose() {
          _this5.$emit('close-preview');
        }
      }, this.previewOptions));
    },
    // @exposed-api
    closeImagePreview: function closeImagePreview() {
      if (this.imagePreview) {
        this.imagePreview.close();
      }
    },
    // @exposed-api
    chooseFile: function chooseFile() {
      if (this.disabled) {
        return;
      }
      /* istanbul ignore else */

      if (this.$refs.input) {
        this.$refs.input.click();
      }
    },
    genPreviewMask: function genPreviewMask(item) {
      var h = this.$createElement;
      var status = item.status,
        message = item.message;
      if (status === 'uploading' || status === 'failed') {
        var MaskIcon = status === 'failed' ? h(Icon$1, {
          "attrs": {
            "name": "close"
          },
          "class": bem$c('mask-icon')
        }) : h(Loading$1, {
          "class": bem$c('loading')
        });
        var showMessage = isDef(message) && message !== '';
        return h("div", {
          "class": bem$c('mask')
        }, [MaskIcon, showMessage && h("div", {
          "class": bem$c('mask-message')
        }, [message])]);
      }
    },
    genPreviewItem: function genPreviewItem(item, index) {
      var _item$deletable,
        _this6 = this,
        _item$previewSize,
        _item$imageFit;
      var h = this.$createElement;
      var deleteAble = (_item$deletable = item.deletable) != null ? _item$deletable : this.deletable;
      var showDelete = item.status !== 'uploading' && deleteAble;
      var DeleteIcon = showDelete && h("div", {
        "class": bem$c('preview-delete'),
        "on": {
          "click": function click(event) {
            event.stopPropagation();
            _this6.onDelete(item, index);
          }
        }
      }, [h(Icon$1, {
        "attrs": {
          "name": "cross"
        },
        "class": bem$c('preview-delete-icon')
      })]);
      var PreviewCoverContent = this.slots('preview-cover', _extends$1({
        index: index
      }, item));
      var PreviewCover = PreviewCoverContent && h("div", {
        "class": bem$c('preview-cover')
      }, [PreviewCoverContent]);
      var previewSize = (_item$previewSize = item.previewSize) != null ? _item$previewSize : this.previewSize;
      var imageFit = (_item$imageFit = item.imageFit) != null ? _item$imageFit : this.imageFit;
      var Preview = isImageFile(item) ? h(Image$1, {
        "attrs": {
          "fit": imageFit,
          "src": item.content || item.url,
          "width": previewSize,
          "height": previewSize,
          "lazyLoad": this.lazyLoad
        },
        "class": bem$c('preview-image'),
        "on": {
          "click": function click() {
            _this6.onPreviewImage(item);
          }
        }
      }, [PreviewCover]) : h("div", {
        "class": bem$c('file'),
        "style": {
          width: this.previewSizeWithUnit,
          height: this.previewSizeWithUnit
        }
      }, [h(Icon$1, {
        "class": bem$c('file-icon'),
        "attrs": {
          "name": "description"
        }
      }), h("div", {
        "class": [bem$c('file-name'), 'van-ellipsis']
      }, [item.file ? item.file.name : item.url]), PreviewCover]);
      return h("div", {
        "class": bem$c('preview'),
        "on": {
          "click": function click() {
            _this6.$emit('click-preview', item, _this6.getDetail(index));
          }
        }
      }, [Preview, this.genPreviewMask(item), DeleteIcon]);
    },
    genPreviewList: function genPreviewList() {
      if (this.previewImage) {
        return this.fileList.map(this.genPreviewItem);
      }
    },
    genUpload: function genUpload() {
      var h = this.$createElement;
      if (this.fileList.length >= this.maxCount) {
        return;
      }
      var slot = this.slots();
      var Input = this.readonly ? null : h("input", {
        "attrs": _extends$1({}, this.$attrs, {
          "type": "file",
          "accept": this.accept,
          "disabled": this.disabled
        }),
        "ref": "input",
        "class": bem$c('input'),
        "on": {
          "change": this.onChange
        }
      });
      if (slot) {
        return h("div", {
          "class": bem$c('input-wrapper'),
          "key": "input-wrapper",
          "on": {
            "click": this.onClickUpload
          }
        }, [slot, Input]);
      }
      var style;
      if (this.previewSize) {
        var size = this.previewSizeWithUnit;
        style = {
          width: size,
          height: size
        };
      }
      return h("div", {
        "directives": [{
          name: "show",
          value: this.showUpload
        }],
        "class": bem$c('upload', {
          readonly: this.readonly
        }),
        "style": style,
        "on": {
          "click": this.onClickUpload
        }
      }, [h(Icon$1, {
        "attrs": {
          "name": this.uploadIcon
        },
        "class": bem$c('upload-icon')
      }), this.uploadText && h("span", {
        "class": bem$c('upload-text')
      }, [this.uploadText]), Input]);
    }
  },
  render: function render() {
    var h = arguments[0];
    return h("div", {
      "class": bem$c()
    }, [h("div", {
      "class": bem$c('wrapper', {
        disabled: this.disabled
      })
    }, [this.genPreviewList(), this.genUpload()])]);
  }
});

// Utils
var namespace$2 = createNamespace('sku-img-uploader');
var createComponent$d = namespace$2[0];
var t$6 = namespace$2[2];
var SkuImgUploader = createComponent$d({
  props: {
    value: String,
    uploadImg: Function,
    customUpload: Function,
    maxSize: {
      type: Number,
      default: 6
    }
  },
  data: function data() {
    return {
      fileList: []
    };
  },
  watch: {
    value: function value(val) {
      if (val) {
        this.fileList = [{
          url: val,
          isImage: true
        }];
      } else {
        this.fileList = [];
      }
    }
  },
  methods: {
    afterReadFile: function afterReadFile(file) {
      var _this = this;
      file.status = 'uploading';
      file.message = t$6('uploading');
      this.uploadImg(file.file, file.content).then(function (img) {
        file.status = 'done';
        _this.$emit('input', img);
      }).catch(function () {
        file.status = 'failed';
        file.message = t$6('fail');
      });
    },
    onOversize: function onOversize() {
      this.$toast(t$6('oversize', this.maxSize));
    },
    onDelete: function onDelete() {
      this.$emit('input', '');
    },
    onClickUpload: function onClickUpload() {
      var _this2 = this;
      if (this.customUpload) {
        this.customUpload().then(function (url) {
          _this2.fileList.push({
            url: url
          });
          _this2.$emit('input', url);
        });
      }
    }
  },
  render: function render() {
    var _this3 = this;
    var h = arguments[0];
    return h(Uploader, {
      "attrs": {
        "maxCount": 1,
        "readonly": !!this.customUpload,
        "maxSize": this.maxSize * 1024 * 1024,
        "afterRead": this.afterReadFile
      },
      "on": {
        "oversize": this.onOversize,
        "delete": this.onDelete,
        "click-upload": this.onClickUpload
      },
      "model": {
        value: _this3.fileList,
        callback: function callback($$v) {
          _this3.fileList = $$v;
        }
      }
    });
  }
});

// 只处理 YYYY-MM-DD 或者 YYYY-MM-DD HH:MM 格式

function stringToDate(timeString) {
  if (!timeString) {
    return null;
  }
  return new Date(timeString.replace(/-/g, '/'));
} // Date 转字符串
// type: date or datetime

function dateToString(date, type) {
  if (type === void 0) {
    type = 'date';
  }
  if (!date) {
    return '';
  }
  var year = date.getFullYear();
  var month = date.getMonth() + 1;
  var day = date.getDate();
  var timeString = year + "-" + padZero(month) + "-" + padZero(day);
  if (type === 'datetime') {
    var hours = date.getHours();
    var minute = date.getMinutes();
    timeString += " " + padZero(hours) + ":" + padZero(minute);
  }
  return timeString;
}

// Utils
var namespace$1 = createNamespace('sku-datetime-field');
var createComponent$c = namespace$1[0];
var t$5 = namespace$1[2];
var SkuDateTimeField = createComponent$c({
  props: {
    value: String,
    label: String,
    required: Boolean,
    placeholder: String,
    type: {
      type: String,
      default: 'date'
    }
  },
  data: function data() {
    return {
      showDatePicker: false,
      currentDate: this.type === 'time' ? '' : new Date(),
      minDate: new Date(new Date().getFullYear() - 60, 0, 1)
    };
  },
  watch: {
    value: function value(val) {
      switch (this.type) {
        case 'time':
          this.currentDate = val;
          break;
        case 'date':
        case 'datetime':
          this.currentDate = stringToDate(val) || new Date();
          break;
      }
    }
  },
  computed: {
    title: function title() {
      return t$5("title." + this.type);
    }
  },
  methods: {
    onClick: function onClick() {
      this.showDatePicker = true;
    },
    onConfirm: function onConfirm(val) {
      var data = val;
      if (this.type !== 'time') {
        data = dateToString(val, this.type);
      }
      this.$emit('input', data);
      this.showDatePicker = false;
    },
    onCancel: function onCancel() {
      this.showDatePicker = false;
    },
    formatter: function formatter(type, val) {
      var word = t$5("format." + type);
      return "" + val + word;
    }
  },
  render: function render() {
    var _this = this;
    var h = arguments[0];
    return h(Field, {
      "attrs": {
        "readonly": true,
        "is-link": true,
        "center": true,
        "value": this.value,
        "label": this.label,
        "required": this.required,
        "placeholder": this.placeholder
      },
      "on": {
        "click": this.onClick
      }
    }, [h(Popup, {
      "attrs": {
        "round": true,
        "position": "bottom",
        "getContainer": "body"
      },
      "slot": "extra",
      "model": {
        value: _this.showDatePicker,
        callback: function callback($$v) {
          _this.showDatePicker = $$v;
        }
      }
    }, [h(DatetimePicker, {
      "attrs": {
        "type": this.type,
        "title": this.title,
        "value": this.currentDate,
        "minDate": this.minDate,
        "formatter": this.formatter
      },
      "on": {
        "cancel": this.onCancel,
        "confirm": this.onConfirm
      }
    })])]);
  }
});

// Utils
var _createNamespace$a = createNamespace('sku-messages'),
  createComponent$b = _createNamespace$a[0],
  bem$b = _createNamespace$a[1],
  t$4 = _createNamespace$a[2];
var SkuMessages = createComponent$b({
  props: {
    messageConfig: Object,
    goodsId: [Number, String],
    messages: {
      type: Array,
      default: function _default() {
        return [];
      }
    }
  },
  data: function data() {
    return {
      messageValues: this.resetMessageValues(this.messages)
    };
  },
  watch: {
    messages: function messages(val) {
      this.messageValues = this.resetMessageValues(val);
    }
  },
  methods: {
    resetMessageValues: function resetMessageValues(messages) {
      var messageConfig = this.messageConfig;
      var _messageConfig$initia = messageConfig.initialMessages,
        initialMessages = _messageConfig$initia === void 0 ? {} : _messageConfig$initia;
      return (messages || []).map(function (message) {
        return {
          value: initialMessages[message.name] || ''
        };
      });
    },
    getType: function getType(message) {
      if (+message.multiple === 1) {
        return 'textarea';
      }
      if (message.type === 'id_no') {
        return 'text';
      }
      return message.datetime > 0 ? 'datetime' : message.type;
    },
    getMessages: function getMessages() {
      var messages = {};
      this.messageValues.forEach(function (item, index) {
        messages["message_" + index] = item.value;
      });
      return messages;
    },
    getCartMessages: function getCartMessages() {
      var _this = this;
      var messages = {};
      this.messageValues.forEach(function (item, index) {
        var message = _this.messages[index];
        messages[message.name] = item.value;
      });
      return messages;
    },
    getPlaceholder: function getPlaceholder(message) {
      var type = +message.multiple === 1 ? 'textarea' : message.type;
      var map = this.messageConfig.placeholderMap || {};
      return message.placeholder || map[type] || t$4("placeholder." + type);
    },
    validateMessages: function validateMessages() {
      var values = this.messageValues;
      for (var i = 0; i < values.length; i++) {
        var value = values[i].value;
        var message = this.messages[i];
        if (value === '') {
          // 必填字段的校验
          if (String(message.required) === '1') {
            var textType = t$4(message.type === 'image' ? 'upload' : 'fill');
            return textType + message.name;
          }
        } else {
          if (message.type === 'tel' && !isNumeric(value)) {
            return t$4('invalid.tel');
          }
          if (message.type === 'mobile' && !/^\d{6,20}$/.test(value)) {
            return t$4('invalid.mobile');
          }
          if (message.type === 'email' && !isEmail(value)) {
            return t$4('invalid.email');
          }
          if (message.type === 'id_no' && (value.length < 15 || value.length > 18)) {
            return t$4('invalid.id_no');
          }
        }
      }
    },
    /**
     * The phone number copied from IOS mobile phone address book
     * will add spaces and invisible Unicode characters
     * which cannot pass the /^\d+$/ verification
     * so keep numbers and dots
     */
    getFormatter: function getFormatter(message) {
      return function formatter(value) {
        if (message.type === 'mobile' || message.type === 'tel') {
          return value.replace(/[^\d.]/g, '');
        }
        return value;
      };
    },
    getExtraDesc: function getExtraDesc(message) {
      var h = this.$createElement;
      var extraDesc = message.extraDesc;
      if (extraDesc) {
        return h("div", {
          "class": bem$b('extra-message')
        }, [extraDesc]);
      }
    },
    genMessage: function genMessage(message, index) {
      var _this2 = this;
      var h = this.$createElement;
      if (message.type === 'image') {
        return h(Cell$1, {
          "key": this.goodsId + "-" + index,
          "attrs": {
            "title": message.name,
            "required": String(message.required) === '1',
            "valueClass": bem$b('image-cell-value')
          },
          "class": bem$b('image-cell')
        }, [h(SkuImgUploader, {
          "attrs": {
            "maxSize": this.messageConfig.uploadMaxSize,
            "uploadImg": this.messageConfig.uploadImg,
            "customUpload": this.messageConfig.customUpload
          },
          "model": {
            value: _this2.messageValues[index].value,
            callback: function callback($$v) {
              _this2.$set(_this2.messageValues[index], "value", $$v);
            }
          }
        }), h("div", {
          "class": bem$b('image-cell-label')
        }, [t$4('imageLabel')])]);
      } // 时间和日期使用的vant选择器

      var isDateOrTime = ['date', 'time'].indexOf(message.type) > -1;
      if (isDateOrTime) {
        return h(SkuDateTimeField, {
          "attrs": {
            "label": message.name,
            "required": String(message.required) === '1',
            "placeholder": this.getPlaceholder(message),
            "type": this.getType(message)
          },
          "key": this.goodsId + "-" + index,
          "model": {
            value: _this2.messageValues[index].value,
            callback: function callback($$v) {
              _this2.$set(_this2.messageValues[index], "value", $$v);
            }
          }
        });
      }
      return h("div", {
        "class": bem$b('cell-block')
      }, [h(Field, {
        "attrs": {
          "maxlength": "200",
          "center": !message.multiple,
          "label": message.name,
          "required": String(message.required) === '1',
          "placeholder": this.getPlaceholder(message),
          "type": this.getType(message),
          "formatter": this.getFormatter(message),
          "border": false
        },
        "key": this.goodsId + "-" + index,
        "model": {
          value: _this2.messageValues[index].value,
          callback: function callback($$v) {
            _this2.$set(_this2.messageValues[index], "value", $$v);
          }
        }
      }), this.getExtraDesc(message)]);
    }
  },
  render: function render() {
    var h = arguments[0];
    return h("div", {
      "class": bem$b()
    }, [this.messages.map(this.genMessage)]);
  }
});

var _createNamespace$9 = createNamespace('sku-actions'),
  createComponent$a = _createNamespace$9[0],
  bem$a = _createNamespace$9[1],
  t$3 = _createNamespace$9[2];
function SkuActions(h, props, slots, ctx) {
  var createEmitter = function createEmitter(name) {
    return function () {
      props.skuEventBus.$emit(name);
    };
  };
  return h("div", _mergeJSXProps([{
    "class": bem$a()
  }, inherit(ctx)]), [props.showAddCartBtn && h(Button$1, {
    "attrs": {
      "size": "large",
      "type": "warning",
      "text": props.addCartText || t$3('addCart')
    },
    "on": {
      "click": createEmitter('sku:addCart')
    }
  }), h(Button$1, {
    "attrs": {
      "size": "large",
      "type": "danger",
      "text": props.buyText || t$3('buy')
    },
    "on": {
      "click": createEmitter('sku:buy')
    }
  })]);
}
SkuActions.props = {
  buyText: String,
  addCartText: String,
  skuEventBus: Object,
  showAddCartBtn: Boolean
};
var SkuActions$1 = createComponent$a(SkuActions);

var namespace = createNamespace('sku');
var createComponent$9 = namespace[0],
  bem$9 = namespace[1],
  t$2 = namespace[2];
var QUOTA_LIMIT = LIMIT_TYPE.QUOTA_LIMIT;
var Sku = createComponent$9({
  props: {
    sku: Object,
    goods: Object,
    value: Boolean,
    buyText: String,
    goodsId: [Number, String],
    priceTag: String,
    lazyLoad: Boolean,
    hideStock: Boolean,
    properties: Array,
    addCartText: String,
    stepperTitle: String,
    getContainer: [String, Function],
    hideQuotaText: Boolean,
    hideSelectedText: Boolean,
    resetStepperOnHide: Boolean,
    customSkuValidator: Function,
    disableStepperInput: Boolean,
    resetSelectedSkuOnHide: Boolean,
    quota: {
      type: Number,
      default: 0
    },
    quotaUsed: {
      type: Number,
      default: 0
    },
    startSaleNum: {
      type: Number,
      default: 1
    },
    initialSku: {
      type: Object,
      default: function _default() {
        return {};
      }
    },
    stockThreshold: {
      type: Number,
      default: 50
    },
    showSoldoutSku: {
      type: Boolean,
      default: true
    },
    showAddCartBtn: {
      type: Boolean,
      default: true
    },
    disableSoldoutSku: {
      type: Boolean,
      default: true
    },
    customStepperConfig: {
      type: Object,
      default: function _default() {
        return {};
      }
    },
    showHeaderImage: {
      type: Boolean,
      default: true
    },
    previewOnClickImage: {
      type: Boolean,
      default: true
    },
    safeAreaInsetBottom: {
      type: Boolean,
      default: true
    },
    closeOnClickOverlay: {
      type: Boolean,
      default: true
    },
    bodyOffsetTop: {
      type: Number,
      default: 200
    },
    messageConfig: {
      type: Object,
      default: function _default() {
        return {
          initialMessages: {},
          placeholderMap: {},
          uploadImg: function uploadImg() {
            return Promise.resolve();
          },
          uploadMaxSize: 5
        };
      }
    }
  },
  data: function data() {
    return {
      selectedSku: {},
      selectedProp: {},
      selectedNum: 1,
      show: this.value
    };
  },
  watch: {
    show: function show(val) {
      this.$emit('input', val);
      if (!val) {
        this.$emit('sku-close', {
          selectedSkuValues: this.selectedSkuValues,
          selectedNum: this.selectedNum,
          selectedSkuComb: this.selectedSkuComb
        });
        if (this.resetStepperOnHide) {
          this.resetStepper();
        }
        if (this.resetSelectedSkuOnHide) {
          this.resetSelectedSku();
        }
      }
    },
    value: function value(val) {
      this.show = val;
    },
    skuTree: 'resetSelectedSku',
    initialSku: function initialSku() {
      this.resetStepper();
      this.resetSelectedSku();
    }
  },
  computed: {
    skuGroupClass: function skuGroupClass() {
      return ['van-sku-group-container', {
        'van-sku-group-container--hide-soldout': !this.showSoldoutSku
      }];
    },
    bodyStyle: function bodyStyle() {
      if (this.$isServer) {
        return;
      }
      var maxHeight = window.innerHeight - this.bodyOffsetTop;
      return {
        maxHeight: maxHeight + 'px'
      };
    },
    isSkuCombSelected: function isSkuCombSelected() {
      var _this = this;

      // SKU 未选完
      if (this.hasSku && !isAllSelected(this.skuTree, this.selectedSku)) {
        return false;
      } // 属性未全选

      return !this.propList.filter(function (i) {
        return i.is_necessary !== false;
      }).some(function (i) {
        return (_this.selectedProp[i.k_id] || []).length === 0;
      });
    },
    isSkuEmpty: function isSkuEmpty() {
      return Object.keys(this.sku).length === 0;
    },
    hasSku: function hasSku() {
      return !this.sku.none_sku;
    },
    hasSkuOrAttr: function hasSkuOrAttr() {
      return this.hasSku || this.propList.length > 0;
    },
    selectedSkuComb: function selectedSkuComb() {
      var skuComb = null;
      if (this.isSkuCombSelected) {
        if (this.hasSku) {
          skuComb = getSkuComb(this.skuList, this.selectedSku);
        } else {
          skuComb = {
            id: this.sku.collection_id,
            price: Math.round(this.sku.price * 100),
            stock_num: this.sku.stock_num
          };
        }
        if (skuComb) {
          skuComb.properties = getSelectedProperties(this.propList, this.selectedProp);
          skuComb.property_price = this.selectedPropValues.reduce(function (acc, cur) {
            return acc + (cur.price || 0);
          }, 0);
        }
      }
      return skuComb;
    },
    selectedSkuValues: function selectedSkuValues() {
      return getSelectedSkuValues(this.skuTree, this.selectedSku);
    },
    selectedPropValues: function selectedPropValues() {
      return getSelectedPropValues(this.propList, this.selectedProp);
    },
    price: function price() {
      if (this.selectedSkuComb) {
        return ((this.selectedSkuComb.price + this.selectedSkuComb.property_price) / 100).toFixed(2);
      } // sku.price是一个格式化好的价格区间

      return this.sku.price;
    },
    originPrice: function originPrice() {
      if (this.selectedSkuComb && this.selectedSkuComb.origin_price) {
        return ((this.selectedSkuComb.origin_price + this.selectedSkuComb.property_price) / 100).toFixed(2);
      }
      return this.sku.origin_price;
    },
    skuTree: function skuTree() {
      return this.sku.tree || [];
    },
    skuList: function skuList() {
      return this.sku.list || [];
    },
    propList: function propList() {
      return this.properties || [];
    },
    imageList: function imageList() {
      var imageList = [this.goods.picture];
      if (this.skuTree.length > 0) {
        this.skuTree.forEach(function (treeItem) {
          if (!treeItem.v) {
            return;
          }
          treeItem.v.forEach(function (vItem) {
            var imgUrl = vItem.previewImgUrl || vItem.imgUrl || vItem.img_url;
            if (imgUrl && imageList.indexOf(imgUrl) === -1) {
              imageList.push(imgUrl);
            }
          });
        });
      }
      return imageList;
    },
    stock: function stock() {
      var stockNum = this.customStepperConfig.stockNum;
      if (stockNum !== undefined) {
        return stockNum;
      }
      if (this.selectedSkuComb) {
        return this.selectedSkuComb.stock_num;
      }
      return this.sku.stock_num;
    },
    stockText: function stockText() {
      var h = this.$createElement;
      var stockFormatter = this.customStepperConfig.stockFormatter;
      if (stockFormatter) {
        return stockFormatter(this.stock);
      }
      return [t$2('stock') + " ", h("span", {
        "class": bem$9('stock-num', {
          highlight: this.stock < this.stockThreshold
        })
      }, [this.stock]), " " + t$2('stockUnit')];
    },
    selectedText: function selectedText() {
      var _this2 = this;
      if (this.selectedSkuComb) {
        var values = this.selectedSkuValues.concat(this.selectedPropValues);
        return t$2('selected') + " " + values.map(function (item) {
          return item.name;
        }).join(' ');
      }
      var unselectedSku = this.skuTree.filter(function (item) {
        return _this2.selectedSku[item.k_s] === UNSELECTED_SKU_VALUE_ID;
      }).map(function (item) {
        return item.k;
      });
      var unselectedProp = this.propList.filter(function (item) {
        return (_this2.selectedProp[item.k_id] || []).length < 1;
      }).map(function (item) {
        return item.k;
      });
      return t$2('select') + " " + unselectedSku.concat(unselectedProp).join(' ');
    }
  },
  created: function created() {
    var skuEventBus = new Vue();
    this.skuEventBus = skuEventBus;
    skuEventBus.$on('sku:select', this.onSelect);
    skuEventBus.$on('sku:propSelect', this.onPropSelect);
    skuEventBus.$on('sku:numChange', this.onNumChange);
    skuEventBus.$on('sku:previewImage', this.onPreviewImage);
    skuEventBus.$on('sku:overLimit', this.onOverLimit);
    skuEventBus.$on('sku:stepperState', this.onStepperState);
    skuEventBus.$on('sku:addCart', this.onAddCart);
    skuEventBus.$on('sku:buy', this.onBuy);
    this.resetStepper();
    this.resetSelectedSku(); // 组件初始化后的钩子，抛出skuEventBus

    this.$emit('after-sku-create', skuEventBus);
  },
  methods: {
    resetStepper: function resetStepper() {
      var skuStepper = this.$refs.skuStepper;
      var selectedNum = this.initialSku.selectedNum;
      var num = selectedNum != null ? selectedNum : this.startSaleNum; // 用来缓存不合法的情况

      this.stepperError = null;
      if (skuStepper) {
        skuStepper.setCurrentNum(num);
      } else {
        // 当首次加载（skuStepper 为空）时，传入数量如果不合法，可能会存在问题
        this.selectedNum = num;
      }
    },
    // @exposed-api
    resetSelectedSku: function resetSelectedSku() {
      var _this3 = this;
      this.selectedSku = {}; // 重置 selectedSku

      this.skuTree.forEach(function (item) {
        _this3.selectedSku[item.k_s] = UNSELECTED_SKU_VALUE_ID;
      });
      this.skuTree.forEach(function (item) {
        var key = item.k_s; // 规格值只有1个时，优先判断

        var valueId = item.v.length === 1 ? item.v[0].id : _this3.initialSku[key];
        if (valueId && isSkuChoosable(_this3.skuList, _this3.selectedSku, {
          key: key,
          valueId: valueId
        })) {
          _this3.selectedSku[key] = valueId;
        }
      });
      var skuValues = this.selectedSkuValues;
      if (skuValues.length > 0) {
        this.$nextTick(function () {
          _this3.$emit('sku-selected', {
            skuValue: skuValues[skuValues.length - 1],
            selectedSku: _this3.selectedSku,
            selectedSkuComb: _this3.selectedSkuComb
          });
        });
      } // 重置商品属性

      this.selectedProp = {};
      var _this$initialSku$sele = this.initialSku.selectedProp,
        selectedProp = _this$initialSku$sele === void 0 ? {} : _this$initialSku$sele; // 选中外部传入信息

      this.propList.forEach(function (item) {
        if (selectedProp[item.k_id]) {
          _this3.selectedProp[item.k_id] = selectedProp[item.k_id];
        }
      });
      if (isEmpty(this.selectedProp)) {
        this.propList.forEach(function (item) {
          var _item$v;

          // 没有加价的属性，默认选中第一个
          if ((item == null ? void 0 : (_item$v = item.v) == null ? void 0 : _item$v.length) > 0) {
            var v = item.v,
              k_id = item.k_id;
            var isHasConfigPrice = v.some(function (i) {
              return +i.price !== 0;
            }); // 没有加价属性

            if (!isHasConfigPrice) {
              // 找到第一个不被禁用的属性
              // 历史如果没有 text_status 字段的，就相当于沿用直接原来的逻辑取第一个属性
              var firstEnableProp = v.find(function (prop) {
                return prop.text_status !== 0;
              });
              if (firstEnableProp) {
                _this3.selectedProp[k_id] = [firstEnableProp.id];
              }
            }
          }
        });
      }
      var propValues = this.selectedPropValues;
      if (propValues.length > 0) {
        this.$emit('sku-prop-selected', {
          propValue: propValues[propValues.length - 1],
          selectedProp: this.selectedProp,
          selectedSkuComb: this.selectedSkuComb
        });
      } // 抛出重置事件

      this.$emit('sku-reset', {
        selectedSku: this.selectedSku,
        selectedProp: this.selectedProp,
        selectedSkuComb: this.selectedSkuComb
      });
      this.centerInitialSku();
    },
    getSkuMessages: function getSkuMessages() {
      return this.$refs.skuMessages ? this.$refs.skuMessages.getMessages() : {};
    },
    getSkuCartMessages: function getSkuCartMessages() {
      return this.$refs.skuMessages ? this.$refs.skuMessages.getCartMessages() : {};
    },
    validateSkuMessages: function validateSkuMessages() {
      return this.$refs.skuMessages ? this.$refs.skuMessages.validateMessages() : '';
    },
    validateSku: function validateSku() {
      if (this.selectedNum === 0) {
        return t$2('unavailable');
      }
      if (this.isSkuCombSelected) {
        return this.validateSkuMessages();
      } // 自定义sku校验

      if (this.customSkuValidator) {
        var err = this.customSkuValidator(this);
        if (err) return err;
      }
      return t$2('selectSku');
    },
    onSelect: function onSelect(skuValue) {
      var _extends2, _extends3;

      // 点击已选中的sku时则取消选中
      this.selectedSku = this.selectedSku[skuValue.skuKeyStr] === skuValue.id ? _extends$1({}, this.selectedSku, (_extends2 = {}, _extends2[skuValue.skuKeyStr] = UNSELECTED_SKU_VALUE_ID, _extends2)) : _extends$1({}, this.selectedSku, (_extends3 = {}, _extends3[skuValue.skuKeyStr] = skuValue.id, _extends3));
      this.$emit('sku-selected', {
        skuValue: skuValue,
        selectedSku: this.selectedSku,
        selectedSkuComb: this.selectedSkuComb
      });
    },
    onPropSelect: function onPropSelect(propValue) {
      var _extends4;
      var arr = this.selectedProp[propValue.skuKeyStr] || [];
      var pos = arr.indexOf(propValue.id);
      if (pos > -1) {
        arr.splice(pos, 1);
      } else if (propValue.multiple) {
        arr.push(propValue.id);
      } else {
        arr.splice(0, 1, propValue.id);
      }
      this.selectedProp = _extends$1({}, this.selectedProp, (_extends4 = {}, _extends4[propValue.skuKeyStr] = arr, _extends4));
      this.$emit('sku-prop-selected', {
        propValue: propValue,
        selectedProp: this.selectedProp,
        selectedSkuComb: this.selectedSkuComb
      });
    },
    onNumChange: function onNumChange(num) {
      this.selectedNum = num;
    },
    onPreviewImage: function onPreviewImage(selectedValue) {
      var _this4 = this;
      var imageList = this.imageList;
      var index = 0;
      var indexImage = imageList[0];
      if (selectedValue && selectedValue.imgUrl) {
        this.imageList.some(function (image, pos) {
          if (image === selectedValue.imgUrl) {
            index = pos;
            return true;
          }
          return false;
        });
        indexImage = selectedValue.imgUrl;
      }
      var params = _extends$1({}, selectedValue, {
        index: index,
        imageList: this.imageList,
        indexImage: indexImage
      });
      this.$emit('open-preview', params);
      if (!this.previewOnClickImage) {
        return;
      }
      ImagePreview$1({
        images: this.imageList,
        startPosition: index,
        onClose: function onClose() {
          _this4.$emit('close-preview', params);
        }
      });
    },
    onOverLimit: function onOverLimit(data) {
      var action = data.action,
        limitType = data.limitType,
        quota = data.quota,
        quotaUsed = data.quotaUsed;
      var handleOverLimit = this.customStepperConfig.handleOverLimit;
      if (handleOverLimit) {
        handleOverLimit(data);
        return;
      }
      if (action === 'minus') {
        if (this.startSaleNum > 1) {
          Toast(t$2('minusStartTip', this.startSaleNum));
        } else {
          Toast(t$2('minusTip'));
        }
      } else if (action === 'plus') {
        if (limitType === QUOTA_LIMIT) {
          if (quotaUsed > 0) {
            Toast(t$2('quotaUsedTip', quota, quotaUsed));
          } else {
            Toast(t$2('quotaTip', quota));
          }
        } else {
          Toast(t$2('soldout'));
        }
      }
    },
    onStepperState: function onStepperState(data) {
      this.stepperError = data.valid ? null : _extends$1({}, data, {
        action: 'plus'
      });
    },
    onAddCart: function onAddCart() {
      this.onBuyOrAddCart('add-cart');
    },
    onBuy: function onBuy() {
      this.onBuyOrAddCart('buy-clicked');
    },
    onBuyOrAddCart: function onBuyOrAddCart(type) {
      // sku 不符合购买条件
      if (this.stepperError) {
        return this.onOverLimit(this.stepperError);
      }
      var error = this.validateSku();
      if (error) {
        Toast(error);
      } else {
        this.$emit(type, this.getSkuData());
      }
    },
    // @exposed-api
    getSkuData: function getSkuData() {
      return {
        goodsId: this.goodsId,
        messages: this.getSkuMessages(),
        selectedNum: this.selectedNum,
        cartMessages: this.getSkuCartMessages(),
        selectedSkuComb: this.selectedSkuComb
      };
    },
    // 当 popup 完全打开后执行
    onOpened: function onOpened() {
      this.centerInitialSku();
    },
    centerInitialSku: function centerInitialSku() {
      var _this5 = this;
      (this.$refs.skuRows || []).forEach(function (it) {
        var _ref = it.skuRow || {},
          k_s = _ref.k_s;
        it.centerItem(_this5.initialSku[k_s]);
      });
    }
  },
  render: function render() {
    var _this6 = this;
    var h = arguments[0];
    if (this.isSkuEmpty) {
      return;
    }
    var sku = this.sku,
      skuList = this.skuList,
      goods = this.goods,
      price = this.price,
      lazyLoad = this.lazyLoad,
      originPrice = this.originPrice,
      skuEventBus = this.skuEventBus,
      selectedSku = this.selectedSku,
      selectedProp = this.selectedProp,
      selectedNum = this.selectedNum,
      stepperTitle = this.stepperTitle,
      selectedSkuComb = this.selectedSkuComb,
      showHeaderImage = this.showHeaderImage,
      disableSoldoutSku = this.disableSoldoutSku;
    var slotsProps = {
      price: price,
      originPrice: originPrice,
      selectedNum: selectedNum,
      skuEventBus: skuEventBus,
      selectedSku: selectedSku,
      selectedSkuComb: selectedSkuComb
    };
    var slots = function slots(name) {
      return _this6.slots(name, slotsProps);
    };
    var Header = slots('sku-header') || h(SkuHeader$2, {
      "attrs": {
        "sku": sku,
        "goods": goods,
        "skuEventBus": skuEventBus,
        "selectedSku": selectedSku,
        "showHeaderImage": showHeaderImage
      }
    }, [h("template", {
      "slot": "sku-header-image-extra"
    }, [slots('sku-header-image-extra')]), slots('sku-header-price') || h("div", {
      "class": "van-sku__goods-price"
    }, [h("span", {
      "class": "van-sku__price-symbol"
    }, ["\uFFE5"]), h("span", {
      "class": "van-sku__price-num"
    }, [price]), this.priceTag && h("span", {
      "class": "van-sku__price-tag"
    }, [this.priceTag])]), slots('sku-header-origin-price') || originPrice && h(SkuHeaderItem, [t$2('originPrice'), " \uFFE5", originPrice]), !this.hideStock && h(SkuHeaderItem, [h("span", {
      "class": "van-sku__stock"
    }, [this.stockText])]), this.hasSkuOrAttr && !this.hideSelectedText && h(SkuHeaderItem, [this.selectedText]), slots('sku-header-extra')]);
    var Group = slots('sku-group') || this.hasSkuOrAttr && h("div", {
      "class": this.skuGroupClass
    }, [this.skuTree.map(function (skuTreeItem) {
      return h(SkuRow, {
        "attrs": {
          "skuRow": skuTreeItem
        },
        "ref": "skuRows",
        "refInFor": true
      }, [skuTreeItem.v.map(function (skuValue) {
        return h(SkuRowItem, {
          "attrs": {
            "skuList": skuList,
            "lazyLoad": lazyLoad,
            "skuValue": skuValue,
            "skuKeyStr": skuTreeItem.k_s,
            "selectedSku": selectedSku,
            "skuEventBus": skuEventBus,
            "disableSoldoutSku": disableSoldoutSku,
            "largeImageMode": skuTreeItem.largeImageMode
          }
        });
      })]);
    }), this.propList.map(function (skuTreeItem) {
      return h(SkuRow, {
        "attrs": {
          "skuRow": skuTreeItem
        }
      }, [skuTreeItem.v.map(function (skuValue) {
        return h(SkuRowPropItem, {
          "attrs": {
            "skuValue": skuValue,
            "skuKeyStr": skuTreeItem.k_id + '',
            "selectedProp": selectedProp,
            "skuEventBus": skuEventBus,
            "multiple": skuTreeItem.is_multiple,
            "disabled": skuValue.text_status === 0
          }
        });
      })]);
    })]);
    var Stepper = slots('sku-stepper') || h(SkuStepper, {
      "ref": "skuStepper",
      "attrs": {
        "stock": this.stock,
        "quota": this.quota,
        "quotaUsed": this.quotaUsed,
        "startSaleNum": this.startSaleNum,
        "skuEventBus": skuEventBus,
        "selectedNum": selectedNum,
        "stepperTitle": stepperTitle,
        "skuStockNum": sku.stock_num,
        "disableStepperInput": this.disableStepperInput,
        "customStepperConfig": this.customStepperConfig,
        "hideQuotaText": this.hideQuotaText
      },
      "on": {
        "change": function change(event) {
          _this6.$emit('stepper-change', event);
        }
      }
    });
    var Messages = slots('sku-messages') || h(SkuMessages, {
      "ref": "skuMessages",
      "attrs": {
        "goodsId": this.goodsId,
        "messageConfig": this.messageConfig,
        "messages": sku.messages
      }
    });
    var Actions = slots('sku-actions') || h(SkuActions$1, {
      "attrs": {
        "buyText": this.buyText,
        "skuEventBus": skuEventBus,
        "addCartText": this.addCartText,
        "showAddCartBtn": this.showAddCartBtn
      }
    });
    return h(Popup, {
      "attrs": {
        "round": true,
        "closeable": true,
        "position": "bottom",
        "getContainer": this.getContainer,
        "closeOnClickOverlay": this.closeOnClickOverlay,
        "safeAreaInsetBottom": this.safeAreaInsetBottom
      },
      "class": "van-sku-container",
      "on": {
        "opened": this.onOpened
      },
      "model": {
        value: _this6.show,
        callback: function callback($$v) {
          _this6.show = $$v;
        }
      }
    }, [Header, h("div", {
      "class": "van-sku-body",
      "style": this.bodyStyle
    }, [slots('sku-body-top'), Group, slots('extra-sku-group'), Stepper, slots('before-sku-messages'), Messages, slots('after-sku-messages')]), slots('sku-actions-top'), Actions]);
  }
});

// Utils
Locale.add(lang);
Sku.SkuActions = SkuActions$1;
Sku.SkuHeader = SkuHeader$2;
Sku.SkuHeaderItem = SkuHeaderItem;
Sku.SkuMessages = SkuMessages;
Sku.SkuStepper = SkuStepper;
Sku.SkuRow = SkuRow;
Sku.SkuRowItem = SkuRowItem;
Sku.SkuRowPropItem = SkuRowPropItem;
Sku.skuHelper = skuHelper;
Sku.skuConstants = constants;

var _createNamespace$8 = createNamespace('slider'),
  createComponent$8 = _createNamespace$8[0],
  bem$8 = _createNamespace$8[1];
var isSameValue = function isSameValue(newValue, oldValue) {
  return JSON.stringify(newValue) === JSON.stringify(oldValue);
};
var Slider = createComponent$8({
  mixins: [TouchMixin, FieldMixin],
  props: {
    disabled: Boolean,
    vertical: Boolean,
    range: Boolean,
    barHeight: [Number, String],
    buttonSize: [Number, String],
    activeColor: String,
    inactiveColor: String,
    min: {
      type: [Number, String],
      default: 0
    },
    max: {
      type: [Number, String],
      default: 100
    },
    step: {
      type: [Number, String],
      default: 1
    },
    value: {
      type: [Number, Array],
      default: 0
    }
  },
  data: function data() {
    return {
      dragStatus: ''
    };
  },
  computed: {
    scope: function scope() {
      return this.max - this.min;
    },
    buttonStyle: function buttonStyle() {
      if (this.buttonSize) {
        var size = addUnit(this.buttonSize);
        return {
          width: size,
          height: size
        };
      }
    }
  },
  created: function created() {
    // format initial value
    this.updateValue(this.value);
  },
  mounted: function mounted() {
    if (this.range) {
      this.bindTouchEvent(this.$refs.wrapper0);
      this.bindTouchEvent(this.$refs.wrapper1);
    } else {
      this.bindTouchEvent(this.$refs.wrapper);
    }
  },
  methods: {
    onTouchStart: function onTouchStart(event) {
      if (this.disabled) {
        return;
      }
      this.touchStart(event);
      this.currentValue = this.value;
      if (this.range) {
        this.startValue = this.value.map(this.format);
      } else {
        this.startValue = this.format(this.value);
      }
      this.dragStatus = 'start';
    },
    onTouchMove: function onTouchMove(event) {
      if (this.disabled) {
        return;
      }
      if (this.dragStatus === 'start') {
        this.$emit('drag-start');
      }
      preventDefault(event, true);
      this.touchMove(event);
      this.dragStatus = 'draging';
      var rect = this.$el.getBoundingClientRect();
      var delta = this.vertical ? this.deltaY : this.deltaX;
      var total = this.vertical ? rect.height : rect.width;
      var diff = delta / total * this.scope;
      if (this.range) {
        this.currentValue[this.index] = this.startValue[this.index] + diff;
      } else {
        this.currentValue = this.startValue + diff;
      }
      this.updateValue(this.currentValue);
    },
    onTouchEnd: function onTouchEnd() {
      if (this.disabled) {
        return;
      }
      if (this.dragStatus === 'draging') {
        this.updateValue(this.currentValue, true);
        this.$emit('drag-end');
      }
      this.dragStatus = '';
    },
    onClick: function onClick(event) {
      event.stopPropagation();
      if (this.disabled) return;
      var rect = this.$el.getBoundingClientRect();
      var delta = this.vertical ? event.clientY - rect.top : event.clientX - rect.left;
      var total = this.vertical ? rect.height : rect.width;
      var value = +this.min + delta / total * this.scope;
      if (this.range) {
        var _this$value = this.value,
          left = _this$value[0],
          right = _this$value[1];
        var middle = (left + right) / 2;
        if (value <= middle) {
          left = value;
        } else {
          right = value;
        }
        value = [left, right];
      }
      this.startValue = this.value;
      this.updateValue(value, true);
    },
    // 处理两个滑块重叠之后的情况
    handleOverlap: function handleOverlap(value) {
      if (value[0] > value[1]) {
        value = deepClone(value);
        return value.reverse();
      }
      return value;
    },
    updateValue: function updateValue(value, end) {
      if (this.range) {
        value = this.handleOverlap(value).map(this.format);
      } else {
        value = this.format(value);
      }
      if (!isSameValue(value, this.value)) {
        this.$emit('input', value);
      }
      if (end && !isSameValue(value, this.startValue)) {
        this.$emit('change', value);
      }
    },
    format: function format(value) {
      var min = +this.min;
      var max = +this.max;
      var step = +this.step;
      value = range(value, min, max);
      var diff = Math.round((value - min) / step) * step;
      return addNumber(min, diff);
    }
  },
  render: function render() {
    var _wrapperStyle,
      _this = this,
      _barStyle;
    var h = arguments[0];
    var vertical = this.vertical;
    var mainAxis = vertical ? 'height' : 'width';
    var crossAxis = vertical ? 'width' : 'height';
    var wrapperStyle = (_wrapperStyle = {
      background: this.inactiveColor
    }, _wrapperStyle[crossAxis] = addUnit(this.barHeight), _wrapperStyle); // 计算选中条的长度百分比

    var calcMainAxis = function calcMainAxis() {
      var value = _this.value,
        min = _this.min,
        range = _this.range,
        scope = _this.scope;
      if (range) {
        return (value[1] - value[0]) * 100 / scope + "%";
      }
      return (value - min) * 100 / scope + "%";
    }; // 计算选中条的开始位置的偏移量

    var calcOffset = function calcOffset() {
      var value = _this.value,
        min = _this.min,
        range = _this.range,
        scope = _this.scope;
      if (range) {
        return (value[0] - min) * 100 / scope + "%";
      }
      return null;
    };
    var barStyle = (_barStyle = {}, _barStyle[mainAxis] = calcMainAxis(), _barStyle.left = this.vertical ? null : calcOffset(), _barStyle.top = this.vertical ? calcOffset() : null, _barStyle.background = this.activeColor, _barStyle);
    if (this.dragStatus) {
      barStyle.transition = 'none';
    }
    var renderButton = function renderButton(i) {
      var map = ['left', 'right'];
      var isNumber = typeof i === 'number';
      var current = isNumber ? _this.value[i] : _this.value;
      var getClassName = function getClassName() {
        if (isNumber) {
          return "button-wrapper-" + map[i];
        }
        return "button-wrapper";
      };
      var getRefName = function getRefName() {
        if (isNumber) {
          return "wrapper" + i;
        }
        return "wrapper";
      };
      var renderButtonContent = function renderButtonContent() {
        if (isNumber) {
          var slot = _this.slots(i === 0 ? 'left-button' : 'right-button', {
            value: current
          });
          if (slot) {
            return slot;
          }
        }
        if (_this.slots('button')) {
          return _this.slots('button');
        }
        return h("div", {
          "class": bem$8('button'),
          "style": _this.buttonStyle
        });
      };
      return h("div", {
        "ref": getRefName(),
        "attrs": {
          "role": "slider",
          "tabindex": _this.disabled ? -1 : 0,
          "aria-valuemin": _this.min,
          "aria-valuenow": _this.value,
          "aria-valuemax": _this.max,
          "aria-orientation": _this.vertical ? 'vertical' : 'horizontal'
        },
        "class": bem$8(getClassName()),
        "on": {
          "touchstart": function touchstart() {
            if (isNumber) {
              // 保存当前按钮的索引
              _this.index = i;
            }
          },
          "click": function click(e) {
            return e.stopPropagation();
          }
        }
      }, [renderButtonContent()]);
    };
    return h("div", {
      "style": wrapperStyle,
      "class": bem$8({
        disabled: this.disabled,
        vertical: vertical
      }),
      "on": {
        "click": this.onClick
      }
    }, [h("div", {
      "class": bem$8('bar'),
      "style": barStyle
    }, [this.range ? [renderButton(0), renderButton(1)] : renderButton()])]);
  }
});

var _createNamespace$7 = createNamespace('step'),
  createComponent$7 = _createNamespace$7[0],
  bem$7 = _createNamespace$7[1];
var Step = createComponent$7({
  mixins: [ChildrenMixin('vanSteps')],
  computed: {
    status: function status() {
      if (this.index < this.parent.active) {
        return 'finish';
      }
      if (this.index === +this.parent.active) {
        return 'process';
      }
    },
    active: function active() {
      return this.status === 'process';
    },
    lineStyle: function lineStyle() {
      var _this$parent = this.parent,
        activeColor = _this$parent.activeColor,
        inactiveColor = _this$parent.inactiveColor,
        center = _this$parent.center,
        direction = _this$parent.direction;
      var style = {
        background: this.status === 'finish' ? activeColor : inactiveColor
      };
      if (center && direction === 'vertical') {
        style.top = '50%';
      }
      return style;
    },
    circleContainerStyle: function circleContainerStyle() {
      if (this.parent.center && this.parent.direction === 'vertical') {
        return {
          top: '50%'
        };
      }
    },
    titleStyle: function titleStyle() {
      if (this.active) {
        return {
          color: this.parent.activeColor
        };
      }
      if (!this.status) {
        return {
          color: this.parent.inactiveColor
        };
      }
    }
  },
  methods: {
    genCircle: function genCircle() {
      var h = this.$createElement;
      var _this$parent2 = this.parent,
        activeIcon = _this$parent2.activeIcon,
        iconPrefix = _this$parent2.iconPrefix,
        activeColor = _this$parent2.activeColor,
        finishIcon = _this$parent2.finishIcon,
        inactiveIcon = _this$parent2.inactiveIcon;
      if (this.active) {
        return this.slots('active-icon') || h(Icon$1, {
          "class": bem$7('icon', 'active'),
          "attrs": {
            "name": activeIcon,
            "color": activeColor,
            "classPrefix": iconPrefix
          }
        });
      }
      var finishIconSlot = this.slots('finish-icon');
      if (this.status === 'finish' && (finishIcon || finishIconSlot)) {
        return finishIconSlot || h(Icon$1, {
          "class": bem$7('icon', 'finish'),
          "attrs": {
            "name": finishIcon,
            "color": activeColor,
            "classPrefix": iconPrefix
          }
        });
      }
      var inactiveIconSlot = this.slots('inactive-icon');
      if (inactiveIcon || inactiveIconSlot) {
        return inactiveIconSlot || h(Icon$1, {
          "class": bem$7('icon'),
          "attrs": {
            "name": inactiveIcon,
            "classPrefix": iconPrefix
          }
        });
      }
      return h("i", {
        "class": bem$7('circle'),
        "style": this.lineStyle
      });
    },
    onClickStep: function onClickStep() {
      this.parent.$emit('click-step', this.index);
    }
  },
  render: function render() {
    var _ref;
    var h = arguments[0];
    var status = this.status,
      active = this.active;
    var direction = this.parent.direction;
    return h("div", {
      "class": [BORDER, bem$7([direction, (_ref = {}, _ref[status] = status, _ref)])]
    }, [h("div", {
      "class": bem$7('title', {
        active: active
      }),
      "style": this.titleStyle,
      "on": {
        "click": this.onClickStep
      }
    }, [this.slots()]), h("div", {
      "class": bem$7('circle-container'),
      "on": {
        "click": this.onClickStep
      },
      "style": this.circleContainerStyle
    }, [this.genCircle()]), h("div", {
      "class": bem$7('line'),
      "style": this.lineStyle
    })]);
  }
});

var _createNamespace$6 = createNamespace('steps'),
  createComponent$6 = _createNamespace$6[0],
  bem$6 = _createNamespace$6[1];
var Steps = createComponent$6({
  mixins: [ParentMixin('vanSteps')],
  props: {
    center: Boolean,
    iconPrefix: String,
    finishIcon: String,
    activeColor: String,
    inactiveIcon: String,
    inactiveColor: String,
    active: {
      type: [Number, String],
      default: 0
    },
    direction: {
      type: String,
      default: 'horizontal'
    },
    activeIcon: {
      type: String,
      default: 'checked'
    }
  },
  render: function render() {
    var h = arguments[0];
    return h("div", {
      "class": bem$6([this.direction])
    }, [h("div", {
      "class": bem$6('items')
    }, [this.slots()])]);
  }
});

var _createNamespace$5 = createNamespace('submit-bar'),
  createComponent$5 = _createNamespace$5[0],
  bem$5 = _createNamespace$5[1],
  t$1 = _createNamespace$5[2];
function SubmitBar(h, props, slots, ctx) {
  var tip = props.tip,
    price = props.price,
    tipIcon = props.tipIcon;
  function Text() {
    if (typeof price === 'number') {
      var priceArr = (price / 100).toFixed(props.decimalLength).split('.');
      var decimalStr = props.decimalLength ? "." + priceArr[1] : '';
      return h("div", {
        "style": {
          textAlign: props.textAlign ? props.textAlign : ''
        },
        "class": bem$5('text')
      }, [h("span", [props.label || t$1('label')]), h("span", {
        "class": bem$5('price')
      }, [props.currency, h("span", {
        "class": bem$5('price', 'integer')
      }, [priceArr[0]]), decimalStr]), props.suffixLabel && h("span", {
        "class": bem$5('suffix-label')
      }, [props.suffixLabel])]);
    }
  }
  function Tip() {
    if (slots.tip || tip) {
      return h("div", {
        "class": bem$5('tip')
      }, [tipIcon && h(Icon$1, {
        "class": bem$5('tip-icon'),
        "attrs": {
          "name": tipIcon
        }
      }), tip && h("span", {
        "class": bem$5('tip-text')
      }, [tip]), slots.tip && slots.tip()]);
    }
  }
  return h("div", _mergeJSXProps([{
    "class": bem$5({
      unfit: !props.safeAreaInsetBottom
    })
  }, inherit(ctx)]), [slots.top && slots.top(), Tip(), h("div", {
    "class": bem$5('bar')
  }, [slots.default && slots.default(), Text(), slots.button ? slots.button() : h(Button$1, {
    "attrs": {
      "round": true,
      "type": props.buttonType,
      "text": props.loading ? '' : props.buttonText,
      "color": props.buttonColor,
      "loading": props.loading,
      "disabled": props.disabled
    },
    "class": bem$5('button', props.buttonType),
    "on": {
      "click": function click() {
        emit(ctx, 'submit');
      }
    }
  })])]);
}
SubmitBar.props = {
  tip: String,
  label: String,
  price: Number,
  tipIcon: String,
  loading: Boolean,
  disabled: Boolean,
  textAlign: String,
  buttonText: String,
  buttonColor: String,
  suffixLabel: String,
  safeAreaInsetBottom: {
    type: Boolean,
    default: true
  },
  decimalLength: {
    type: [Number, String],
    default: 2
  },
  currency: {
    type: String,
    default: '¥'
  },
  buttonType: {
    type: String,
    default: 'danger'
  }
};
var SubmitBar$1 = createComponent$5(SubmitBar);

// Utils
var _createNamespace$4 = createNamespace('swipe-cell'),
  createComponent$4 = _createNamespace$4[0],
  bem$4 = _createNamespace$4[1];
var THRESHOLD = 0.15;
var SwipeCell = createComponent$4({
  mixins: [TouchMixin, ClickOutsideMixin({
    event: 'touchstart',
    method: 'onClick'
  })],
  props: {
    // @deprecated
    // should be removed in next major version, use beforeClose instead
    onClose: Function,
    disabled: Boolean,
    leftWidth: [Number, String],
    rightWidth: [Number, String],
    beforeClose: Function,
    stopPropagation: Boolean,
    name: {
      type: [Number, String],
      default: ''
    }
  },
  data: function data() {
    return {
      offset: 0,
      dragging: false
    };
  },
  computed: {
    computedLeftWidth: function computedLeftWidth() {
      return +this.leftWidth || this.getWidthByRef('left');
    },
    computedRightWidth: function computedRightWidth() {
      return +this.rightWidth || this.getWidthByRef('right');
    }
  },
  mounted: function mounted() {
    this.bindTouchEvent(this.$el);
  },
  methods: {
    getWidthByRef: function getWidthByRef(ref) {
      if (this.$refs[ref]) {
        var rect = this.$refs[ref].getBoundingClientRect();
        return rect.width;
      }
      return 0;
    },
    // @exposed-api
    open: function open(position) {
      var offset = position === 'left' ? this.computedLeftWidth : -this.computedRightWidth;
      this.opened = true;
      this.offset = offset;
      this.$emit('open', {
        position: position,
        name: this.name,
        // @deprecated
        // should be removed in next major version
        detail: this.name
      });
    },
    // @exposed-api
    close: function close(position) {
      this.offset = 0;
      if (this.opened) {
        this.opened = false;
        this.$emit('close', {
          position: position,
          name: this.name
        });
      }
    },
    onTouchStart: function onTouchStart(event) {
      if (this.disabled) {
        return;
      }
      this.startOffset = this.offset;
      this.touchStart(event);
    },
    onTouchMove: function onTouchMove(event) {
      if (this.disabled) {
        return;
      }
      this.touchMove(event);
      if (this.direction === 'horizontal') {
        this.dragging = true;
        this.lockClick = true;
        var isPrevent = !this.opened || this.deltaX * this.startOffset < 0;
        if (isPrevent) {
          preventDefault(event, this.stopPropagation);
        }
        this.offset = range(this.deltaX + this.startOffset, -this.computedRightWidth, this.computedLeftWidth);
      }
    },
    onTouchEnd: function onTouchEnd() {
      var _this = this;
      if (this.disabled) {
        return;
      }
      if (this.dragging) {
        this.toggle(this.offset > 0 ? 'left' : 'right');
        this.dragging = false; // compatible with desktop scenario

        setTimeout(function () {
          _this.lockClick = false;
        }, 0);
      }
    },
    toggle: function toggle(direction) {
      var offset = Math.abs(this.offset);
      var threshold = this.opened ? 1 - THRESHOLD : THRESHOLD;
      var computedLeftWidth = this.computedLeftWidth,
        computedRightWidth = this.computedRightWidth;
      if (computedRightWidth && direction === 'right' && offset > computedRightWidth * threshold) {
        this.open('right');
      } else if (computedLeftWidth && direction === 'left' && offset > computedLeftWidth * threshold) {
        this.open('left');
      } else {
        this.close();
      }
    },
    onClick: function onClick(position) {
      if (position === void 0) {
        position = 'outside';
      }
      this.$emit('click', position);
      if (this.opened && !this.lockClick) {
        if (this.beforeClose) {
          this.beforeClose({
            position: position,
            name: this.name,
            instance: this
          });
        } else if (this.onClose) {
          this.onClose(position, this, {
            name: this.name
          });
        } else {
          this.close(position);
        }
      }
    },
    getClickHandler: function getClickHandler(position, stop) {
      var _this2 = this;
      return function (event) {
        if (stop) {
          event.stopPropagation();
        }
        _this2.onClick(position);
      };
    },
    genLeftPart: function genLeftPart() {
      var h = this.$createElement;
      var content = this.slots('left');
      if (content) {
        return h("div", {
          "ref": "left",
          "class": bem$4('left'),
          "on": {
            "click": this.getClickHandler('left', true)
          }
        }, [content]);
      }
    },
    genRightPart: function genRightPart() {
      var h = this.$createElement;
      var content = this.slots('right');
      if (content) {
        return h("div", {
          "ref": "right",
          "class": bem$4('right'),
          "on": {
            "click": this.getClickHandler('right', true)
          }
        }, [content]);
      }
    }
  },
  render: function render() {
    var h = arguments[0];
    var wrapperStyle = {
      transform: "translate3d(" + this.offset + "px, 0, 0)",
      transitionDuration: this.dragging ? '0s' : '.6s'
    };
    return h("div", {
      "class": bem$4(),
      "on": {
        "click": this.getClickHandler('cell')
      }
    }, [h("div", {
      "class": bem$4('wrapper'),
      "style": wrapperStyle
    }, [this.genLeftPart(), this.slots(), this.genRightPart()])]);
  }
});

var _createNamespace$3 = createNamespace('switch-cell'),
  createComponent$3 = _createNamespace$3[0],
  bem$3 = _createNamespace$3[1];
function SwitchCell(h, props, slots, ctx) {
  return h(Cell$1, _mergeJSXProps([{
    "attrs": {
      "center": true,
      "size": props.cellSize,
      "title": props.title,
      "border": props.border
    },
    "class": bem$3([props.cellSize])
  }, inherit(ctx)]), [h(Switch, {
    "props": _extends$1({}, props),
    "on": _extends$1({}, ctx.listeners)
  })]);
}
SwitchCell.props = _extends$1({}, switchProps, {
  title: String,
  cellSize: String,
  border: {
    type: Boolean,
    default: true
  },
  size: {
    type: String,
    default: '24px'
  }
});
var SwitchCell$1 = createComponent$3(SwitchCell);

var _createNamespace$2 = createNamespace('tabbar'),
  createComponent$2 = _createNamespace$2[0],
  bem$2 = _createNamespace$2[1];
var Tabbar = createComponent$2({
  mixins: [ParentMixin('vanTabbar')],
  props: {
    route: Boolean,
    zIndex: [Number, String],
    placeholder: Boolean,
    activeColor: String,
    beforeChange: Function,
    inactiveColor: String,
    value: {
      type: [Number, String],
      default: 0
    },
    border: {
      type: Boolean,
      default: true
    },
    fixed: {
      type: Boolean,
      default: true
    },
    safeAreaInsetBottom: {
      type: Boolean,
      default: null
    }
  },
  data: function data() {
    return {
      height: null
    };
  },
  computed: {
    fit: function fit() {
      if (this.safeAreaInsetBottom !== null) {
        return this.safeAreaInsetBottom;
      } // enable safe-area-inset-bottom by default when fixed

      return this.fixed;
    }
  },
  watch: {
    value: 'setActiveItem',
    children: 'setActiveItem'
  },
  mounted: function mounted() {
    var _this = this;
    if (this.placeholder && this.fixed) {
      var setHeight = function setHeight() {
        _this.height = _this.$refs.tabbar.getBoundingClientRect().height;
      };
      setHeight(); // https://github.com/vant-ui/vant/issues/10131

      setTimeout(setHeight, 100);
    }
  },
  methods: {
    setActiveItem: function setActiveItem() {
      var _this2 = this;
      this.children.forEach(function (item, index) {
        item.nameMatched = item.name === _this2.value || index === _this2.value;
      });
    },
    triggerChange: function triggerChange(active, afterChange) {
      var _this3 = this;
      callInterceptor({
        interceptor: this.beforeChange,
        args: [active],
        done: function done() {
          _this3.$emit('input', active);
          _this3.$emit('change', active);
          afterChange();
        }
      });
    },
    genTabbar: function genTabbar() {
      var _ref;
      var h = this.$createElement;
      return h("div", {
        "ref": "tabbar",
        "style": {
          zIndex: this.zIndex
        },
        "class": [(_ref = {}, _ref[BORDER_TOP_BOTTOM] = this.border, _ref), bem$2({
          unfit: !this.fit,
          fixed: this.fixed
        })]
      }, [this.slots()]);
    }
  },
  render: function render() {
    var h = arguments[0];
    if (this.placeholder && this.fixed) {
      return h("div", {
        "class": bem$2('placeholder'),
        "style": {
          height: this.height + "px"
        }
      }, [this.genTabbar()]);
    }
    return this.genTabbar();
  }
});

var _createNamespace$1 = createNamespace('tabbar-item'),
  createComponent$1 = _createNamespace$1[0],
  bem$1 = _createNamespace$1[1];
var TabbarItem = createComponent$1({
  mixins: [ChildrenMixin('vanTabbar')],
  props: _extends$1({}, routeProps, {
    dot: Boolean,
    icon: String,
    name: [Number, String],
    // @deprecated
    info: [Number, String],
    badge: [Number, String],
    iconPrefix: String
  }),
  data: function data() {
    return {
      nameMatched: false
    };
  },
  computed: {
    active: function active() {
      var routeMode = this.parent.route;
      if (routeMode && '$route' in this) {
        var to = this.to,
          $route = this.$route;
        var config = isObject(to) ? to : {
          path: to
        };
        return !!$route.matched.find(function (r) {
          // vue-router 3.x $route.matched[0].path is empty in / and its children paths
          var path = r.path === '' ? '/' : r.path;
          var pathMatched = config.path === path;
          var nameMatched = isDef(config.name) && config.name === r.name;
          return pathMatched || nameMatched;
        });
      }
      return this.nameMatched;
    }
  },
  methods: {
    onClick: function onClick(event) {
      var _this = this;
      if (!this.active) {
        this.parent.triggerChange(this.name || this.index, function () {
          route(_this.$router, _this);
        });
      }
      this.$emit('click', event);
    },
    genIcon: function genIcon() {
      var h = this.$createElement;
      var slot = this.slots('icon', {
        active: this.active
      });
      if (slot) {
        return slot;
      }
      if (this.icon) {
        return h(Icon$1, {
          "attrs": {
            "name": this.icon,
            "classPrefix": this.iconPrefix
          }
        });
      }
    }
  },
  render: function render() {
    var _this$badge;
    var h = arguments[0];
    var active = this.active;
    var color = this.parent[active ? 'activeColor' : 'inactiveColor'];
    return h("div", {
      "class": bem$1({
        active: active
      }),
      "style": {
        color: color
      },
      "on": {
        "click": this.onClick
      }
    }, [h("div", {
      "class": bem$1('icon')
    }, [this.genIcon(), h(Info$1, {
      "attrs": {
        "dot": this.dot,
        "info": (_this$badge = this.badge) != null ? _this$badge : this.info
      }
    })]), h("div", {
      "class": bem$1('text')
    }, [this.slots('default', {
      active: active
    })])]);
  }
});

var _createNamespace = createNamespace('tree-select'),
  createComponent = _createNamespace[0],
  bem = _createNamespace[1];
function TreeSelect(h, props, slots, ctx) {
  var items = props.items,
    height = props.height,
    activeId = props.activeId,
    selectedIcon = props.selectedIcon,
    mainActiveIndex = props.mainActiveIndex;
  var selectedItem = items[+mainActiveIndex] || {};
  var subItems = selectedItem.children || [];
  var isMultiple = Array.isArray(activeId);
  function isActiveItem(id) {
    return isMultiple ? activeId.indexOf(id) !== -1 : activeId === id;
  }
  var Navs = items.map(function (item) {
    var _item$badge;
    return h(SidebarItem, {
      "attrs": {
        "dot": item.dot,
        "info": (_item$badge = item.badge) != null ? _item$badge : item.info,
        "title": item.text,
        "disabled": item.disabled
      },
      "class": [bem('nav-item'), item.className]
    });
  });
  function Content() {
    if (slots.content) {
      return slots.content();
    }
    return subItems.map(function (item) {
      return h("div", {
        "key": item.id,
        "class": ['van-ellipsis', bem('item', {
          active: isActiveItem(item.id),
          disabled: item.disabled
        })],
        "on": {
          "click": function click() {
            if (!item.disabled) {
              var newActiveId = item.id;
              if (isMultiple) {
                newActiveId = activeId.slice();
                var index = newActiveId.indexOf(item.id);
                if (index !== -1) {
                  newActiveId.splice(index, 1);
                } else if (newActiveId.length < props.max) {
                  newActiveId.push(item.id);
                }
              }
              emit(ctx, 'update:active-id', newActiveId);
              emit(ctx, 'click-item', item); // compatible with legacy usage, should be removed in next major version

              emit(ctx, 'itemclick', item);
            }
          }
        }
      }, [item.text, isActiveItem(item.id) && h(Icon$1, {
        "attrs": {
          "name": selectedIcon
        },
        "class": bem('selected')
      })]);
    });
  }
  return h("div", _mergeJSXProps([{
    "class": bem(),
    "style": {
      height: addUnit(height)
    }
  }, inherit(ctx)]), [h(Sidebar, {
    "class": bem('nav'),
    "attrs": {
      "activeKey": mainActiveIndex
    },
    "on": {
      "change": function change(index) {
        emit(ctx, 'update:main-active-index', index);
        emit(ctx, 'click-nav', index); // compatible with legacy usage, should be removed in next major version

        emit(ctx, 'navclick', index);
      }
    }
  }, [Navs]), h("div", {
    "class": bem('content')
  }, [Content()])]);
}
TreeSelect.props = {
  max: {
    type: [Number, String],
    default: Infinity
  },
  items: {
    type: Array,
    default: function _default() {
      return [];
    }
  },
  height: {
    type: [Number, String],
    default: 300
  },
  activeId: {
    type: [Number, String, Array],
    default: 0
  },
  selectedIcon: {
    type: String,
    default: 'success'
  },
  mainActiveIndex: {
    type: [Number, String],
    default: 0
  }
};
var TreeSelect$1 = createComponent(TreeSelect);

function install(Vue) {
  var components = [ActionSheet$1, AddressEdit, AddressList$1, Area, Badge, Button$1, Calendar, Card$1, Cascader, Cell$1, CellGroup$1, Checkbox, CheckboxGroup, Circle, Col, Collapse, CollapseItem, ContactCard$1, ContactEdit, ContactList$1, CountDown, Coupon, CouponCell$1, CouponList, DatetimePicker, Dialog, Divider$1, DropdownItem, DropdownMenu, Empty, Field, Form, GoodsAction, GoodsActionButton, GoodsActionIcon, Grid, GridItem, Icon$1, Image$1, ImagePreview$1, IndexAnchor, IndexBar, Info$1, List, Loading$1, Locale, NavBar, NoticeBar, Notify, NumberKeyboard, Overlay$1, Pagination, Panel$1, PasswordInput$1, Picker, Popover, Popup, Progress, PullRefresh, Radio, RadioGroup, Rate, Row, Search$1, ShareSheet, Sidebar, SidebarItem, Skeleton$1, Sku, Slider, Step, Stepper, Steps, Sticky, SubmitBar$1, Swipe, SwipeCell, SwipeItem, Switch, SwitchCell$1, Tab, Tabbar, TabbarItem, Tabs, Tag$1, Toast, TreeSelect$1, Uploader];
  components.forEach(function (item) {
    if (item.install) {
      Vue.use(item);
    } else if (item.name) {
      Vue.component(item.name, item);
    }
  });
}
if (typeof window !== 'undefined' && window.Vue) {
  install(window.Vue);
}

var top = 'top';
var bottom = 'bottom';
var right = 'right';
var left = 'left';
var auto = 'auto';
var basePlacements = [top, bottom, right, left];
var start = 'start';
var end = 'end';
var clippingParents = 'clippingParents';
var viewport = 'viewport';
var popper = 'popper';
var reference = 'reference';
var variationPlacements = /*#__PURE__*/basePlacements.reduce(function (acc, placement) {
  return acc.concat([placement + "-" + start, placement + "-" + end]);
}, []);
var placements = /*#__PURE__*/[].concat(basePlacements, [auto]).reduce(function (acc, placement) {
  return acc.concat([placement, placement + "-" + start, placement + "-" + end]);
}, []); // modifiers that need to read the DOM

var beforeRead = 'beforeRead';
var read = 'read';
var afterRead = 'afterRead'; // pure-logic modifiers

var beforeMain = 'beforeMain';
var main = 'main';
var afterMain = 'afterMain'; // modifier with the purpose to write to the DOM (or write into a framework state)

var beforeWrite = 'beforeWrite';
var write = 'write';
var afterWrite = 'afterWrite';
var modifierPhases = [beforeRead, read, afterRead, beforeMain, main, afterMain, beforeWrite, write, afterWrite];

function getNodeName(element) {
  return element ? (element.nodeName || '').toLowerCase() : null;
}

function getWindow(node) {
  if (node == null) {
    return window;
  }
  if (node.toString() !== '[object Window]') {
    var ownerDocument = node.ownerDocument;
    return ownerDocument ? ownerDocument.defaultView || window : window;
  }
  return node;
}

function isElement$1(node) {
  var OwnElement = getWindow(node).Element;
  return node instanceof OwnElement || node instanceof Element;
}
function isHTMLElement(node) {
  var OwnElement = getWindow(node).HTMLElement;
  return node instanceof OwnElement || node instanceof HTMLElement;
}
function isShadowRoot(node) {
  // IE 11 has no ShadowRoot
  if (typeof ShadowRoot === 'undefined') {
    return false;
  }
  var OwnElement = getWindow(node).ShadowRoot;
  return node instanceof OwnElement || node instanceof ShadowRoot;
}

// and applies them to the HTMLElements such as popper and arrow

function applyStyles(_ref) {
  var state = _ref.state;
  Object.keys(state.elements).forEach(function (name) {
    var style = state.styles[name] || {};
    var attributes = state.attributes[name] || {};
    var element = state.elements[name]; // arrow is optional + virtual elements

    if (!isHTMLElement(element) || !getNodeName(element)) {
      return;
    } // Flow doesn't support to extend this property, but it's the most
    // effective way to apply styles to an HTMLElement
    // $FlowFixMe[cannot-write]

    Object.assign(element.style, style);
    Object.keys(attributes).forEach(function (name) {
      var value = attributes[name];
      if (value === false) {
        element.removeAttribute(name);
      } else {
        element.setAttribute(name, value === true ? '' : value);
      }
    });
  });
}
function effect$2(_ref2) {
  var state = _ref2.state;
  var initialStyles = {
    popper: {
      position: state.options.strategy,
      left: '0',
      top: '0',
      margin: '0'
    },
    arrow: {
      position: 'absolute'
    },
    reference: {}
  };
  Object.assign(state.elements.popper.style, initialStyles.popper);
  state.styles = initialStyles;
  if (state.elements.arrow) {
    Object.assign(state.elements.arrow.style, initialStyles.arrow);
  }
  return function () {
    Object.keys(state.elements).forEach(function (name) {
      var element = state.elements[name];
      var attributes = state.attributes[name] || {};
      var styleProperties = Object.keys(state.styles.hasOwnProperty(name) ? state.styles[name] : initialStyles[name]); // Set all values to an empty string to unset them

      var style = styleProperties.reduce(function (style, property) {
        style[property] = '';
        return style;
      }, {}); // arrow is optional + virtual elements

      if (!isHTMLElement(element) || !getNodeName(element)) {
        return;
      }
      Object.assign(element.style, style);
      Object.keys(attributes).forEach(function (attribute) {
        element.removeAttribute(attribute);
      });
    });
  };
} // eslint-disable-next-line import/no-unused-modules

var applyStyles$1 = {
  name: 'applyStyles',
  enabled: true,
  phase: 'write',
  fn: applyStyles,
  effect: effect$2,
  requires: ['computeStyles']
};

function getBasePlacement$1(placement) {
  return placement.split('-')[0];
}

var max = Math.max;
var min = Math.min;
var round = Math.round;

function getUAString() {
  var uaData = navigator.userAgentData;
  if (uaData != null && uaData.brands && Array.isArray(uaData.brands)) {
    return uaData.brands.map(function (item) {
      return item.brand + "/" + item.version;
    }).join(' ');
  }
  return navigator.userAgent;
}

function isLayoutViewport() {
  return !/^((?!chrome|android).)*safari/i.test(getUAString());
}

function getBoundingClientRect(element, includeScale, isFixedStrategy) {
  if (includeScale === void 0) {
    includeScale = false;
  }
  if (isFixedStrategy === void 0) {
    isFixedStrategy = false;
  }
  var clientRect = element.getBoundingClientRect();
  var scaleX = 1;
  var scaleY = 1;
  if (includeScale && isHTMLElement(element)) {
    scaleX = element.offsetWidth > 0 ? round(clientRect.width) / element.offsetWidth || 1 : 1;
    scaleY = element.offsetHeight > 0 ? round(clientRect.height) / element.offsetHeight || 1 : 1;
  }
  var _ref = isElement$1(element) ? getWindow(element) : window,
    visualViewport = _ref.visualViewport;
  var addVisualOffsets = !isLayoutViewport() && isFixedStrategy;
  var x = (clientRect.left + (addVisualOffsets && visualViewport ? visualViewport.offsetLeft : 0)) / scaleX;
  var y = (clientRect.top + (addVisualOffsets && visualViewport ? visualViewport.offsetTop : 0)) / scaleY;
  var width = clientRect.width / scaleX;
  var height = clientRect.height / scaleY;
  return {
    width: width,
    height: height,
    top: y,
    right: x + width,
    bottom: y + height,
    left: x,
    x: x,
    y: y
  };
}

// means it doesn't take into account transforms.

function getLayoutRect(element) {
  var clientRect = getBoundingClientRect(element); // Use the clientRect sizes if it's not been transformed.
  // Fixes https://github.com/popperjs/popper-core/issues/1223

  var width = element.offsetWidth;
  var height = element.offsetHeight;
  if (Math.abs(clientRect.width - width) <= 1) {
    width = clientRect.width;
  }
  if (Math.abs(clientRect.height - height) <= 1) {
    height = clientRect.height;
  }
  return {
    x: element.offsetLeft,
    y: element.offsetTop,
    width: width,
    height: height
  };
}

function contains(parent, child) {
  var rootNode = child.getRootNode && child.getRootNode(); // First, attempt with faster native method

  if (parent.contains(child)) {
    return true;
  } // then fallback to custom implementation with Shadow DOM support
  else if (rootNode && isShadowRoot(rootNode)) {
    var next = child;
    do {
      if (next && parent.isSameNode(next)) {
        return true;
      } // $FlowFixMe[prop-missing]: need a better way to handle this...

      next = next.parentNode || next.host;
    } while (next);
  } // Give up, the result is false

  return false;
}

function getComputedStyle$1(element) {
  return getWindow(element).getComputedStyle(element);
}

function isTableElement(element) {
  return ['table', 'td', 'th'].indexOf(getNodeName(element)) >= 0;
}

function getDocumentElement(element) {
  // $FlowFixMe[incompatible-return]: assume body is always available
  return ((isElement$1(element) ? element.ownerDocument :
  // $FlowFixMe[prop-missing]
  element.document) || window.document).documentElement;
}

function getParentNode(element) {
  if (getNodeName(element) === 'html') {
    return element;
  }
  return (
    // this is a quicker (but less type safe) way to save quite some bytes from the bundle
    // $FlowFixMe[incompatible-return]
    // $FlowFixMe[prop-missing]
    element.assignedSlot ||
    // step into the shadow DOM of the parent of a slotted node
    element.parentNode || (
    // DOM Element detected
    isShadowRoot(element) ? element.host : null) ||
    // ShadowRoot detected
    // $FlowFixMe[incompatible-call]: HTMLElement is a Node
    getDocumentElement(element) // fallback
  );
}

function getTrueOffsetParent(element) {
  if (!isHTMLElement(element) ||
  // https://github.com/popperjs/popper-core/issues/837
  getComputedStyle$1(element).position === 'fixed') {
    return null;
  }
  return element.offsetParent;
} // `.offsetParent` reports `null` for fixed elements, while absolute elements
// return the containing block

function getContainingBlock(element) {
  var isFirefox = /firefox/i.test(getUAString());
  var isIE = /Trident/i.test(getUAString());
  if (isIE && isHTMLElement(element)) {
    // In IE 9, 10 and 11 fixed elements containing block is always established by the viewport
    var elementCss = getComputedStyle$1(element);
    if (elementCss.position === 'fixed') {
      return null;
    }
  }
  var currentNode = getParentNode(element);
  if (isShadowRoot(currentNode)) {
    currentNode = currentNode.host;
  }
  while (isHTMLElement(currentNode) && ['html', 'body'].indexOf(getNodeName(currentNode)) < 0) {
    var css = getComputedStyle$1(currentNode); // This is non-exhaustive but covers the most common CSS properties that
    // create a containing block.
    // https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block

    if (css.transform !== 'none' || css.perspective !== 'none' || css.contain === 'paint' || ['transform', 'perspective'].indexOf(css.willChange) !== -1 || isFirefox && css.willChange === 'filter' || isFirefox && css.filter && css.filter !== 'none') {
      return currentNode;
    } else {
      currentNode = currentNode.parentNode;
    }
  }
  return null;
} // Gets the closest ancestor positioned element. Handles some edge cases,
// such as table ancestors and cross browser bugs.

function getOffsetParent(element) {
  var window = getWindow(element);
  var offsetParent = getTrueOffsetParent(element);
  while (offsetParent && isTableElement(offsetParent) && getComputedStyle$1(offsetParent).position === 'static') {
    offsetParent = getTrueOffsetParent(offsetParent);
  }
  if (offsetParent && (getNodeName(offsetParent) === 'html' || getNodeName(offsetParent) === 'body' && getComputedStyle$1(offsetParent).position === 'static')) {
    return window;
  }
  return offsetParent || getContainingBlock(element) || window;
}

function getMainAxisFromPlacement(placement) {
  return ['top', 'bottom'].indexOf(placement) >= 0 ? 'x' : 'y';
}

function within(min$1, value, max$1) {
  return max(min$1, min(value, max$1));
}
function withinMaxClamp(min, value, max) {
  var v = within(min, value, max);
  return v > max ? max : v;
}

function getFreshSideObject() {
  return {
    top: 0,
    right: 0,
    bottom: 0,
    left: 0
  };
}

function mergePaddingObject(paddingObject) {
  return Object.assign({}, getFreshSideObject(), paddingObject);
}

function expandToHashMap(value, keys) {
  return keys.reduce(function (hashMap, key) {
    hashMap[key] = value;
    return hashMap;
  }, {});
}

var toPaddingObject = function toPaddingObject(padding, state) {
  padding = typeof padding === 'function' ? padding(Object.assign({}, state.rects, {
    placement: state.placement
  })) : padding;
  return mergePaddingObject(typeof padding !== 'number' ? padding : expandToHashMap(padding, basePlacements));
};
function arrow(_ref) {
  var _state$modifiersData$;
  var state = _ref.state,
    name = _ref.name,
    options = _ref.options;
  var arrowElement = state.elements.arrow;
  var popperOffsets = state.modifiersData.popperOffsets;
  var basePlacement = getBasePlacement$1(state.placement);
  var axis = getMainAxisFromPlacement(basePlacement);
  var isVertical = [left, right].indexOf(basePlacement) >= 0;
  var len = isVertical ? 'height' : 'width';
  if (!arrowElement || !popperOffsets) {
    return;
  }
  var paddingObject = toPaddingObject(options.padding, state);
  var arrowRect = getLayoutRect(arrowElement);
  var minProp = axis === 'y' ? top : left;
  var maxProp = axis === 'y' ? bottom : right;
  var endDiff = state.rects.reference[len] + state.rects.reference[axis] - popperOffsets[axis] - state.rects.popper[len];
  var startDiff = popperOffsets[axis] - state.rects.reference[axis];
  var arrowOffsetParent = getOffsetParent(arrowElement);
  var clientSize = arrowOffsetParent ? axis === 'y' ? arrowOffsetParent.clientHeight || 0 : arrowOffsetParent.clientWidth || 0 : 0;
  var centerToReference = endDiff / 2 - startDiff / 2; // Make sure the arrow doesn't overflow the popper if the center point is
  // outside of the popper bounds

  var min = paddingObject[minProp];
  var max = clientSize - arrowRect[len] - paddingObject[maxProp];
  var center = clientSize / 2 - arrowRect[len] / 2 + centerToReference;
  var offset = within(min, center, max); // Prevents breaking syntax highlighting...

  var axisProp = axis;
  state.modifiersData[name] = (_state$modifiersData$ = {}, _state$modifiersData$[axisProp] = offset, _state$modifiersData$.centerOffset = offset - center, _state$modifiersData$);
}
function effect$1(_ref2) {
  var state = _ref2.state,
    options = _ref2.options;
  var _options$element = options.element,
    arrowElement = _options$element === void 0 ? '[data-popper-arrow]' : _options$element;
  if (arrowElement == null) {
    return;
  } // CSS selector

  if (typeof arrowElement === 'string') {
    arrowElement = state.elements.popper.querySelector(arrowElement);
    if (!arrowElement) {
      return;
    }
  }
  if (!contains(state.elements.popper, arrowElement)) {
    return;
  }
  state.elements.arrow = arrowElement;
} // eslint-disable-next-line import/no-unused-modules

var arrow$1 = {
  name: 'arrow',
  enabled: true,
  phase: 'main',
  fn: arrow,
  effect: effect$1,
  requires: ['popperOffsets'],
  requiresIfExists: ['preventOverflow']
};

function getVariation(placement) {
  return placement.split('-')[1];
}

var unsetSides = {
  top: 'auto',
  right: 'auto',
  bottom: 'auto',
  left: 'auto'
}; // Round the offsets to the nearest suitable subpixel based on the DPR.
// Zooming can change the DPR, but it seems to report a value that will
// cleanly divide the values into the appropriate subpixels.

function roundOffsetsByDPR(_ref, win) {
  var x = _ref.x,
    y = _ref.y;
  var dpr = win.devicePixelRatio || 1;
  return {
    x: round(x * dpr) / dpr || 0,
    y: round(y * dpr) / dpr || 0
  };
}
function mapToStyles(_ref2) {
  var _Object$assign2;
  var popper = _ref2.popper,
    popperRect = _ref2.popperRect,
    placement = _ref2.placement,
    variation = _ref2.variation,
    offsets = _ref2.offsets,
    position = _ref2.position,
    gpuAcceleration = _ref2.gpuAcceleration,
    adaptive = _ref2.adaptive,
    roundOffsets = _ref2.roundOffsets,
    isFixed = _ref2.isFixed;
  var _offsets$x = offsets.x,
    x = _offsets$x === void 0 ? 0 : _offsets$x,
    _offsets$y = offsets.y,
    y = _offsets$y === void 0 ? 0 : _offsets$y;
  var _ref3 = typeof roundOffsets === 'function' ? roundOffsets({
    x: x,
    y: y
  }) : {
    x: x,
    y: y
  };
  x = _ref3.x;
  y = _ref3.y;
  var hasX = offsets.hasOwnProperty('x');
  var hasY = offsets.hasOwnProperty('y');
  var sideX = left;
  var sideY = top;
  var win = window;
  if (adaptive) {
    var offsetParent = getOffsetParent(popper);
    var heightProp = 'clientHeight';
    var widthProp = 'clientWidth';
    if (offsetParent === getWindow(popper)) {
      offsetParent = getDocumentElement(popper);
      if (getComputedStyle$1(offsetParent).position !== 'static' && position === 'absolute') {
        heightProp = 'scrollHeight';
        widthProp = 'scrollWidth';
      }
    } // $FlowFixMe[incompatible-cast]: force type refinement, we compare offsetParent with window above, but Flow doesn't detect it

    offsetParent = offsetParent;
    if (placement === top || (placement === left || placement === right) && variation === end) {
      sideY = bottom;
      var offsetY = isFixed && offsetParent === win && win.visualViewport ? win.visualViewport.height :
      // $FlowFixMe[prop-missing]
      offsetParent[heightProp];
      y -= offsetY - popperRect.height;
      y *= gpuAcceleration ? 1 : -1;
    }
    if (placement === left || (placement === top || placement === bottom) && variation === end) {
      sideX = right;
      var offsetX = isFixed && offsetParent === win && win.visualViewport ? win.visualViewport.width :
      // $FlowFixMe[prop-missing]
      offsetParent[widthProp];
      x -= offsetX - popperRect.width;
      x *= gpuAcceleration ? 1 : -1;
    }
  }
  var commonStyles = Object.assign({
    position: position
  }, adaptive && unsetSides);
  var _ref4 = roundOffsets === true ? roundOffsetsByDPR({
    x: x,
    y: y
  }, getWindow(popper)) : {
    x: x,
    y: y
  };
  x = _ref4.x;
  y = _ref4.y;
  if (gpuAcceleration) {
    var _Object$assign;
    return Object.assign({}, commonStyles, (_Object$assign = {}, _Object$assign[sideY] = hasY ? '0' : '', _Object$assign[sideX] = hasX ? '0' : '', _Object$assign.transform = (win.devicePixelRatio || 1) <= 1 ? "translate(" + x + "px, " + y + "px)" : "translate3d(" + x + "px, " + y + "px, 0)", _Object$assign));
  }
  return Object.assign({}, commonStyles, (_Object$assign2 = {}, _Object$assign2[sideY] = hasY ? y + "px" : '', _Object$assign2[sideX] = hasX ? x + "px" : '', _Object$assign2.transform = '', _Object$assign2));
}
function computeStyles(_ref5) {
  var state = _ref5.state,
    options = _ref5.options;
  var _options$gpuAccelerat = options.gpuAcceleration,
    gpuAcceleration = _options$gpuAccelerat === void 0 ? true : _options$gpuAccelerat,
    _options$adaptive = options.adaptive,
    adaptive = _options$adaptive === void 0 ? true : _options$adaptive,
    _options$roundOffsets = options.roundOffsets,
    roundOffsets = _options$roundOffsets === void 0 ? true : _options$roundOffsets;
  var commonStyles = {
    placement: getBasePlacement$1(state.placement),
    variation: getVariation(state.placement),
    popper: state.elements.popper,
    popperRect: state.rects.popper,
    gpuAcceleration: gpuAcceleration,
    isFixed: state.options.strategy === 'fixed'
  };
  if (state.modifiersData.popperOffsets != null) {
    state.styles.popper = Object.assign({}, state.styles.popper, mapToStyles(Object.assign({}, commonStyles, {
      offsets: state.modifiersData.popperOffsets,
      position: state.options.strategy,
      adaptive: adaptive,
      roundOffsets: roundOffsets
    })));
  }
  if (state.modifiersData.arrow != null) {
    state.styles.arrow = Object.assign({}, state.styles.arrow, mapToStyles(Object.assign({}, commonStyles, {
      offsets: state.modifiersData.arrow,
      position: 'absolute',
      adaptive: false,
      roundOffsets: roundOffsets
    })));
  }
  state.attributes.popper = Object.assign({}, state.attributes.popper, {
    'data-popper-placement': state.placement
  });
} // eslint-disable-next-line import/no-unused-modules

var computeStyles$1 = {
  name: 'computeStyles',
  enabled: true,
  phase: 'beforeWrite',
  fn: computeStyles,
  data: {}
};

var passive = {
  passive: true
};
function effect(_ref) {
  var state = _ref.state,
    instance = _ref.instance,
    options = _ref.options;
  var _options$scroll = options.scroll,
    scroll = _options$scroll === void 0 ? true : _options$scroll,
    _options$resize = options.resize,
    resize = _options$resize === void 0 ? true : _options$resize;
  var window = getWindow(state.elements.popper);
  var scrollParents = [].concat(state.scrollParents.reference, state.scrollParents.popper);
  if (scroll) {
    scrollParents.forEach(function (scrollParent) {
      scrollParent.addEventListener('scroll', instance.update, passive);
    });
  }
  if (resize) {
    window.addEventListener('resize', instance.update, passive);
  }
  return function () {
    if (scroll) {
      scrollParents.forEach(function (scrollParent) {
        scrollParent.removeEventListener('scroll', instance.update, passive);
      });
    }
    if (resize) {
      window.removeEventListener('resize', instance.update, passive);
    }
  };
} // eslint-disable-next-line import/no-unused-modules

var eventListeners = {
  name: 'eventListeners',
  enabled: true,
  phase: 'write',
  fn: function fn() {},
  effect: effect,
  data: {}
};

var hash$1 = {
  left: 'right',
  right: 'left',
  bottom: 'top',
  top: 'bottom'
};
function getOppositePlacement(placement) {
  return placement.replace(/left|right|bottom|top/g, function (matched) {
    return hash$1[matched];
  });
}

var hash = {
  start: 'end',
  end: 'start'
};
function getOppositeVariationPlacement(placement) {
  return placement.replace(/start|end/g, function (matched) {
    return hash[matched];
  });
}

function getWindowScroll(node) {
  var win = getWindow(node);
  var scrollLeft = win.pageXOffset;
  var scrollTop = win.pageYOffset;
  return {
    scrollLeft: scrollLeft,
    scrollTop: scrollTop
  };
}

function getWindowScrollBarX(element) {
  // If <html> has a CSS width greater than the viewport, then this will be
  // incorrect for RTL.
  // Popper 1 is broken in this case and never had a bug report so let's assume
  // it's not an issue. I don't think anyone ever specifies width on <html>
  // anyway.
  // Browsers where the left scrollbar doesn't cause an issue report `0` for
  // this (e.g. Edge 2019, IE11, Safari)
  return getBoundingClientRect(getDocumentElement(element)).left + getWindowScroll(element).scrollLeft;
}

function getViewportRect(element, strategy) {
  var win = getWindow(element);
  var html = getDocumentElement(element);
  var visualViewport = win.visualViewport;
  var width = html.clientWidth;
  var height = html.clientHeight;
  var x = 0;
  var y = 0;
  if (visualViewport) {
    width = visualViewport.width;
    height = visualViewport.height;
    var layoutViewport = isLayoutViewport();
    if (layoutViewport || !layoutViewport && strategy === 'fixed') {
      x = visualViewport.offsetLeft;
      y = visualViewport.offsetTop;
    }
  }
  return {
    width: width,
    height: height,
    x: x + getWindowScrollBarX(element),
    y: y
  };
}

// of the `<html>` and `<body>` rect bounds if horizontally scrollable

function getDocumentRect(element) {
  var _element$ownerDocumen;
  var html = getDocumentElement(element);
  var winScroll = getWindowScroll(element);
  var body = (_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body;
  var width = max(html.scrollWidth, html.clientWidth, body ? body.scrollWidth : 0, body ? body.clientWidth : 0);
  var height = max(html.scrollHeight, html.clientHeight, body ? body.scrollHeight : 0, body ? body.clientHeight : 0);
  var x = -winScroll.scrollLeft + getWindowScrollBarX(element);
  var y = -winScroll.scrollTop;
  if (getComputedStyle$1(body || html).direction === 'rtl') {
    x += max(html.clientWidth, body ? body.clientWidth : 0) - width;
  }
  return {
    width: width,
    height: height,
    x: x,
    y: y
  };
}

function isScrollParent(element) {
  // Firefox wants us to check `-x` and `-y` variations as well
  var _getComputedStyle = getComputedStyle$1(element),
    overflow = _getComputedStyle.overflow,
    overflowX = _getComputedStyle.overflowX,
    overflowY = _getComputedStyle.overflowY;
  return /auto|scroll|overlay|hidden/.test(overflow + overflowY + overflowX);
}

function getScrollParent(node) {
  if (['html', 'body', '#document'].indexOf(getNodeName(node)) >= 0) {
    // $FlowFixMe[incompatible-return]: assume body is always available
    return node.ownerDocument.body;
  }
  if (isHTMLElement(node) && isScrollParent(node)) {
    return node;
  }
  return getScrollParent(getParentNode(node));
}

/*
given a DOM element, return the list of all scroll parents, up the list of ancesors
until we get to the top window object. This list is what we attach scroll listeners
to, because if any of these parent elements scroll, we'll need to re-calculate the
reference element's position.
*/

function listScrollParents(element, list) {
  var _element$ownerDocumen;
  if (list === void 0) {
    list = [];
  }
  var scrollParent = getScrollParent(element);
  var isBody = scrollParent === ((_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body);
  var win = getWindow(scrollParent);
  var target = isBody ? [win].concat(win.visualViewport || [], isScrollParent(scrollParent) ? scrollParent : []) : scrollParent;
  var updatedList = list.concat(target);
  return isBody ? updatedList :
  // $FlowFixMe[incompatible-call]: isBody tells us target will be an HTMLElement here
  updatedList.concat(listScrollParents(getParentNode(target)));
}

function rectToClientRect(rect) {
  return Object.assign({}, rect, {
    left: rect.x,
    top: rect.y,
    right: rect.x + rect.width,
    bottom: rect.y + rect.height
  });
}

function getInnerBoundingClientRect(element, strategy) {
  var rect = getBoundingClientRect(element, false, strategy === 'fixed');
  rect.top = rect.top + element.clientTop;
  rect.left = rect.left + element.clientLeft;
  rect.bottom = rect.top + element.clientHeight;
  rect.right = rect.left + element.clientWidth;
  rect.width = element.clientWidth;
  rect.height = element.clientHeight;
  rect.x = rect.left;
  rect.y = rect.top;
  return rect;
}
function getClientRectFromMixedType(element, clippingParent, strategy) {
  return clippingParent === viewport ? rectToClientRect(getViewportRect(element, strategy)) : isElement$1(clippingParent) ? getInnerBoundingClientRect(clippingParent, strategy) : rectToClientRect(getDocumentRect(getDocumentElement(element)));
} // A "clipping parent" is an overflowable container with the characteristic of
// clipping (or hiding) overflowing elements with a position different from
// `initial`

function getClippingParents(element) {
  var clippingParents = listScrollParents(getParentNode(element));
  var canEscapeClipping = ['absolute', 'fixed'].indexOf(getComputedStyle$1(element).position) >= 0;
  var clipperElement = canEscapeClipping && isHTMLElement(element) ? getOffsetParent(element) : element;
  if (!isElement$1(clipperElement)) {
    return [];
  } // $FlowFixMe[incompatible-return]: https://github.com/facebook/flow/issues/1414

  return clippingParents.filter(function (clippingParent) {
    return isElement$1(clippingParent) && contains(clippingParent, clipperElement) && getNodeName(clippingParent) !== 'body';
  });
} // Gets the maximum area that the element is visible in due to any number of
// clipping parents

function getClippingRect(element, boundary, rootBoundary, strategy) {
  var mainClippingParents = boundary === 'clippingParents' ? getClippingParents(element) : [].concat(boundary);
  var clippingParents = [].concat(mainClippingParents, [rootBoundary]);
  var firstClippingParent = clippingParents[0];
  var clippingRect = clippingParents.reduce(function (accRect, clippingParent) {
    var rect = getClientRectFromMixedType(element, clippingParent, strategy);
    accRect.top = max(rect.top, accRect.top);
    accRect.right = min(rect.right, accRect.right);
    accRect.bottom = min(rect.bottom, accRect.bottom);
    accRect.left = max(rect.left, accRect.left);
    return accRect;
  }, getClientRectFromMixedType(element, firstClippingParent, strategy));
  clippingRect.width = clippingRect.right - clippingRect.left;
  clippingRect.height = clippingRect.bottom - clippingRect.top;
  clippingRect.x = clippingRect.left;
  clippingRect.y = clippingRect.top;
  return clippingRect;
}

function computeOffsets(_ref) {
  var reference = _ref.reference,
    element = _ref.element,
    placement = _ref.placement;
  var basePlacement = placement ? getBasePlacement$1(placement) : null;
  var variation = placement ? getVariation(placement) : null;
  var commonX = reference.x + reference.width / 2 - element.width / 2;
  var commonY = reference.y + reference.height / 2 - element.height / 2;
  var offsets;
  switch (basePlacement) {
    case top:
      offsets = {
        x: commonX,
        y: reference.y - element.height
      };
      break;
    case bottom:
      offsets = {
        x: commonX,
        y: reference.y + reference.height
      };
      break;
    case right:
      offsets = {
        x: reference.x + reference.width,
        y: commonY
      };
      break;
    case left:
      offsets = {
        x: reference.x - element.width,
        y: commonY
      };
      break;
    default:
      offsets = {
        x: reference.x,
        y: reference.y
      };
  }
  var mainAxis = basePlacement ? getMainAxisFromPlacement(basePlacement) : null;
  if (mainAxis != null) {
    var len = mainAxis === 'y' ? 'height' : 'width';
    switch (variation) {
      case start:
        offsets[mainAxis] = offsets[mainAxis] - (reference[len] / 2 - element[len] / 2);
        break;
      case end:
        offsets[mainAxis] = offsets[mainAxis] + (reference[len] / 2 - element[len] / 2);
        break;
    }
  }
  return offsets;
}

function detectOverflow(state, options) {
  if (options === void 0) {
    options = {};
  }
  var _options = options,
    _options$placement = _options.placement,
    placement = _options$placement === void 0 ? state.placement : _options$placement,
    _options$strategy = _options.strategy,
    strategy = _options$strategy === void 0 ? state.strategy : _options$strategy,
    _options$boundary = _options.boundary,
    boundary = _options$boundary === void 0 ? clippingParents : _options$boundary,
    _options$rootBoundary = _options.rootBoundary,
    rootBoundary = _options$rootBoundary === void 0 ? viewport : _options$rootBoundary,
    _options$elementConte = _options.elementContext,
    elementContext = _options$elementConte === void 0 ? popper : _options$elementConte,
    _options$altBoundary = _options.altBoundary,
    altBoundary = _options$altBoundary === void 0 ? false : _options$altBoundary,
    _options$padding = _options.padding,
    padding = _options$padding === void 0 ? 0 : _options$padding;
  var paddingObject = mergePaddingObject(typeof padding !== 'number' ? padding : expandToHashMap(padding, basePlacements));
  var altContext = elementContext === popper ? reference : popper;
  var popperRect = state.rects.popper;
  var element = state.elements[altBoundary ? altContext : elementContext];
  var clippingClientRect = getClippingRect(isElement$1(element) ? element : element.contextElement || getDocumentElement(state.elements.popper), boundary, rootBoundary, strategy);
  var referenceClientRect = getBoundingClientRect(state.elements.reference);
  var popperOffsets = computeOffsets({
    reference: referenceClientRect,
    element: popperRect,
    strategy: 'absolute',
    placement: placement
  });
  var popperClientRect = rectToClientRect(Object.assign({}, popperRect, popperOffsets));
  var elementClientRect = elementContext === popper ? popperClientRect : referenceClientRect; // positive = overflowing the clipping rect
  // 0 or negative = within the clipping rect

  var overflowOffsets = {
    top: clippingClientRect.top - elementClientRect.top + paddingObject.top,
    bottom: elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom,
    left: clippingClientRect.left - elementClientRect.left + paddingObject.left,
    right: elementClientRect.right - clippingClientRect.right + paddingObject.right
  };
  var offsetData = state.modifiersData.offset; // Offsets can be applied only to the popper element

  if (elementContext === popper && offsetData) {
    var offset = offsetData[placement];
    Object.keys(overflowOffsets).forEach(function (key) {
      var multiply = [right, bottom].indexOf(key) >= 0 ? 1 : -1;
      var axis = [top, bottom].indexOf(key) >= 0 ? 'y' : 'x';
      overflowOffsets[key] += offset[axis] * multiply;
    });
  }
  return overflowOffsets;
}

function computeAutoPlacement(state, options) {
  if (options === void 0) {
    options = {};
  }
  var _options = options,
    placement = _options.placement,
    boundary = _options.boundary,
    rootBoundary = _options.rootBoundary,
    padding = _options.padding,
    flipVariations = _options.flipVariations,
    _options$allowedAutoP = _options.allowedAutoPlacements,
    allowedAutoPlacements = _options$allowedAutoP === void 0 ? placements : _options$allowedAutoP;
  var variation = getVariation(placement);
  var placements$1 = variation ? flipVariations ? variationPlacements : variationPlacements.filter(function (placement) {
    return getVariation(placement) === variation;
  }) : basePlacements;
  var allowedPlacements = placements$1.filter(function (placement) {
    return allowedAutoPlacements.indexOf(placement) >= 0;
  });
  if (allowedPlacements.length === 0) {
    allowedPlacements = placements$1;
  } // $FlowFixMe[incompatible-type]: Flow seems to have problems with two array unions...

  var overflows = allowedPlacements.reduce(function (acc, placement) {
    acc[placement] = detectOverflow(state, {
      placement: placement,
      boundary: boundary,
      rootBoundary: rootBoundary,
      padding: padding
    })[getBasePlacement$1(placement)];
    return acc;
  }, {});
  return Object.keys(overflows).sort(function (a, b) {
    return overflows[a] - overflows[b];
  });
}

function getExpandedFallbackPlacements(placement) {
  if (getBasePlacement$1(placement) === auto) {
    return [];
  }
  var oppositePlacement = getOppositePlacement(placement);
  return [getOppositeVariationPlacement(placement), oppositePlacement, getOppositeVariationPlacement(oppositePlacement)];
}
function flip(_ref) {
  var state = _ref.state,
    options = _ref.options,
    name = _ref.name;
  if (state.modifiersData[name]._skip) {
    return;
  }
  var _options$mainAxis = options.mainAxis,
    checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis,
    _options$altAxis = options.altAxis,
    checkAltAxis = _options$altAxis === void 0 ? true : _options$altAxis,
    specifiedFallbackPlacements = options.fallbackPlacements,
    padding = options.padding,
    boundary = options.boundary,
    rootBoundary = options.rootBoundary,
    altBoundary = options.altBoundary,
    _options$flipVariatio = options.flipVariations,
    flipVariations = _options$flipVariatio === void 0 ? true : _options$flipVariatio,
    allowedAutoPlacements = options.allowedAutoPlacements;
  var preferredPlacement = state.options.placement;
  var basePlacement = getBasePlacement$1(preferredPlacement);
  var isBasePlacement = basePlacement === preferredPlacement;
  var fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipVariations ? [getOppositePlacement(preferredPlacement)] : getExpandedFallbackPlacements(preferredPlacement));
  var placements = [preferredPlacement].concat(fallbackPlacements).reduce(function (acc, placement) {
    return acc.concat(getBasePlacement$1(placement) === auto ? computeAutoPlacement(state, {
      placement: placement,
      boundary: boundary,
      rootBoundary: rootBoundary,
      padding: padding,
      flipVariations: flipVariations,
      allowedAutoPlacements: allowedAutoPlacements
    }) : placement);
  }, []);
  var referenceRect = state.rects.reference;
  var popperRect = state.rects.popper;
  var checksMap = new Map();
  var makeFallbackChecks = true;
  var firstFittingPlacement = placements[0];
  for (var i = 0; i < placements.length; i++) {
    var placement = placements[i];
    var _basePlacement = getBasePlacement$1(placement);
    var isStartVariation = getVariation(placement) === start;
    var isVertical = [top, bottom].indexOf(_basePlacement) >= 0;
    var len = isVertical ? 'width' : 'height';
    var overflow = detectOverflow(state, {
      placement: placement,
      boundary: boundary,
      rootBoundary: rootBoundary,
      altBoundary: altBoundary,
      padding: padding
    });
    var mainVariationSide = isVertical ? isStartVariation ? right : left : isStartVariation ? bottom : top;
    if (referenceRect[len] > popperRect[len]) {
      mainVariationSide = getOppositePlacement(mainVariationSide);
    }
    var altVariationSide = getOppositePlacement(mainVariationSide);
    var checks = [];
    if (checkMainAxis) {
      checks.push(overflow[_basePlacement] <= 0);
    }
    if (checkAltAxis) {
      checks.push(overflow[mainVariationSide] <= 0, overflow[altVariationSide] <= 0);
    }
    if (checks.every(function (check) {
      return check;
    })) {
      firstFittingPlacement = placement;
      makeFallbackChecks = false;
      break;
    }
    checksMap.set(placement, checks);
  }
  if (makeFallbackChecks) {
    // `2` may be desired in some cases – research later
    var numberOfChecks = flipVariations ? 3 : 1;
    var _loop = function _loop(_i) {
      var fittingPlacement = placements.find(function (placement) {
        var checks = checksMap.get(placement);
        if (checks) {
          return checks.slice(0, _i).every(function (check) {
            return check;
          });
        }
      });
      if (fittingPlacement) {
        firstFittingPlacement = fittingPlacement;
        return "break";
      }
    };
    for (var _i = numberOfChecks; _i > 0; _i--) {
      var _ret = _loop(_i);
      if (_ret === "break") break;
    }
  }
  if (state.placement !== firstFittingPlacement) {
    state.modifiersData[name]._skip = true;
    state.placement = firstFittingPlacement;
    state.reset = true;
  }
} // eslint-disable-next-line import/no-unused-modules

var flip$1 = {
  name: 'flip',
  enabled: true,
  phase: 'main',
  fn: flip,
  requiresIfExists: ['offset'],
  data: {
    _skip: false
  }
};

function getSideOffsets(overflow, rect, preventedOffsets) {
  if (preventedOffsets === void 0) {
    preventedOffsets = {
      x: 0,
      y: 0
    };
  }
  return {
    top: overflow.top - rect.height - preventedOffsets.y,
    right: overflow.right - rect.width + preventedOffsets.x,
    bottom: overflow.bottom - rect.height + preventedOffsets.y,
    left: overflow.left - rect.width - preventedOffsets.x
  };
}
function isAnySideFullyClipped(overflow) {
  return [top, right, bottom, left].some(function (side) {
    return overflow[side] >= 0;
  });
}
function hide(_ref) {
  var state = _ref.state,
    name = _ref.name;
  var referenceRect = state.rects.reference;
  var popperRect = state.rects.popper;
  var preventedOffsets = state.modifiersData.preventOverflow;
  var referenceOverflow = detectOverflow(state, {
    elementContext: 'reference'
  });
  var popperAltOverflow = detectOverflow(state, {
    altBoundary: true
  });
  var referenceClippingOffsets = getSideOffsets(referenceOverflow, referenceRect);
  var popperEscapeOffsets = getSideOffsets(popperAltOverflow, popperRect, preventedOffsets);
  var isReferenceHidden = isAnySideFullyClipped(referenceClippingOffsets);
  var hasPopperEscaped = isAnySideFullyClipped(popperEscapeOffsets);
  state.modifiersData[name] = {
    referenceClippingOffsets: referenceClippingOffsets,
    popperEscapeOffsets: popperEscapeOffsets,
    isReferenceHidden: isReferenceHidden,
    hasPopperEscaped: hasPopperEscaped
  };
  state.attributes.popper = Object.assign({}, state.attributes.popper, {
    'data-popper-reference-hidden': isReferenceHidden,
    'data-popper-escaped': hasPopperEscaped
  });
} // eslint-disable-next-line import/no-unused-modules

var hide$1 = {
  name: 'hide',
  enabled: true,
  phase: 'main',
  requiresIfExists: ['preventOverflow'],
  fn: hide
};

function distanceAndSkiddingToXY(placement, rects, offset) {
  var basePlacement = getBasePlacement$1(placement);
  var invertDistance = [left, top].indexOf(basePlacement) >= 0 ? -1 : 1;
  var _ref = typeof offset === 'function' ? offset(Object.assign({}, rects, {
      placement: placement
    })) : offset,
    skidding = _ref[0],
    distance = _ref[1];
  skidding = skidding || 0;
  distance = (distance || 0) * invertDistance;
  return [left, right].indexOf(basePlacement) >= 0 ? {
    x: distance,
    y: skidding
  } : {
    x: skidding,
    y: distance
  };
}
function offset(_ref2) {
  var state = _ref2.state,
    options = _ref2.options,
    name = _ref2.name;
  var _options$offset = options.offset,
    offset = _options$offset === void 0 ? [0, 0] : _options$offset;
  var data = placements.reduce(function (acc, placement) {
    acc[placement] = distanceAndSkiddingToXY(placement, state.rects, offset);
    return acc;
  }, {});
  var _data$state$placement = data[state.placement],
    x = _data$state$placement.x,
    y = _data$state$placement.y;
  if (state.modifiersData.popperOffsets != null) {
    state.modifiersData.popperOffsets.x += x;
    state.modifiersData.popperOffsets.y += y;
  }
  state.modifiersData[name] = data;
} // eslint-disable-next-line import/no-unused-modules

var offset$1 = {
  name: 'offset',
  enabled: true,
  phase: 'main',
  requires: ['popperOffsets'],
  fn: offset
};

function popperOffsets(_ref) {
  var state = _ref.state,
    name = _ref.name;
  // Offsets are the actual position the popper needs to have to be
  // properly positioned near its reference element
  // This is the most basic placement, and will be adjusted by
  // the modifiers in the next step
  state.modifiersData[name] = computeOffsets({
    reference: state.rects.reference,
    element: state.rects.popper,
    strategy: 'absolute',
    placement: state.placement
  });
} // eslint-disable-next-line import/no-unused-modules

var popperOffsets$1 = {
  name: 'popperOffsets',
  enabled: true,
  phase: 'read',
  fn: popperOffsets,
  data: {}
};

function getAltAxis(axis) {
  return axis === 'x' ? 'y' : 'x';
}

function preventOverflow(_ref) {
  var state = _ref.state,
    options = _ref.options,
    name = _ref.name;
  var _options$mainAxis = options.mainAxis,
    checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis,
    _options$altAxis = options.altAxis,
    checkAltAxis = _options$altAxis === void 0 ? false : _options$altAxis,
    boundary = options.boundary,
    rootBoundary = options.rootBoundary,
    altBoundary = options.altBoundary,
    padding = options.padding,
    _options$tether = options.tether,
    tether = _options$tether === void 0 ? true : _options$tether,
    _options$tetherOffset = options.tetherOffset,
    tetherOffset = _options$tetherOffset === void 0 ? 0 : _options$tetherOffset;
  var overflow = detectOverflow(state, {
    boundary: boundary,
    rootBoundary: rootBoundary,
    padding: padding,
    altBoundary: altBoundary
  });
  var basePlacement = getBasePlacement$1(state.placement);
  var variation = getVariation(state.placement);
  var isBasePlacement = !variation;
  var mainAxis = getMainAxisFromPlacement(basePlacement);
  var altAxis = getAltAxis(mainAxis);
  var popperOffsets = state.modifiersData.popperOffsets;
  var referenceRect = state.rects.reference;
  var popperRect = state.rects.popper;
  var tetherOffsetValue = typeof tetherOffset === 'function' ? tetherOffset(Object.assign({}, state.rects, {
    placement: state.placement
  })) : tetherOffset;
  var normalizedTetherOffsetValue = typeof tetherOffsetValue === 'number' ? {
    mainAxis: tetherOffsetValue,
    altAxis: tetherOffsetValue
  } : Object.assign({
    mainAxis: 0,
    altAxis: 0
  }, tetherOffsetValue);
  var offsetModifierState = state.modifiersData.offset ? state.modifiersData.offset[state.placement] : null;
  var data = {
    x: 0,
    y: 0
  };
  if (!popperOffsets) {
    return;
  }
  if (checkMainAxis) {
    var _offsetModifierState$;
    var mainSide = mainAxis === 'y' ? top : left;
    var altSide = mainAxis === 'y' ? bottom : right;
    var len = mainAxis === 'y' ? 'height' : 'width';
    var offset = popperOffsets[mainAxis];
    var min$1 = offset + overflow[mainSide];
    var max$1 = offset - overflow[altSide];
    var additive = tether ? -popperRect[len] / 2 : 0;
    var minLen = variation === start ? referenceRect[len] : popperRect[len];
    var maxLen = variation === start ? -popperRect[len] : -referenceRect[len]; // We need to include the arrow in the calculation so the arrow doesn't go
    // outside the reference bounds

    var arrowElement = state.elements.arrow;
    var arrowRect = tether && arrowElement ? getLayoutRect(arrowElement) : {
      width: 0,
      height: 0
    };
    var arrowPaddingObject = state.modifiersData['arrow#persistent'] ? state.modifiersData['arrow#persistent'].padding : getFreshSideObject();
    var arrowPaddingMin = arrowPaddingObject[mainSide];
    var arrowPaddingMax = arrowPaddingObject[altSide]; // If the reference length is smaller than the arrow length, we don't want
    // to include its full size in the calculation. If the reference is small
    // and near the edge of a boundary, the popper can overflow even if the
    // reference is not overflowing as well (e.g. virtual elements with no
    // width or height)

    var arrowLen = within(0, referenceRect[len], arrowRect[len]);
    var minOffset = isBasePlacement ? referenceRect[len] / 2 - additive - arrowLen - arrowPaddingMin - normalizedTetherOffsetValue.mainAxis : minLen - arrowLen - arrowPaddingMin - normalizedTetherOffsetValue.mainAxis;
    var maxOffset = isBasePlacement ? -referenceRect[len] / 2 + additive + arrowLen + arrowPaddingMax + normalizedTetherOffsetValue.mainAxis : maxLen + arrowLen + arrowPaddingMax + normalizedTetherOffsetValue.mainAxis;
    var arrowOffsetParent = state.elements.arrow && getOffsetParent(state.elements.arrow);
    var clientOffset = arrowOffsetParent ? mainAxis === 'y' ? arrowOffsetParent.clientTop || 0 : arrowOffsetParent.clientLeft || 0 : 0;
    var offsetModifierValue = (_offsetModifierState$ = offsetModifierState == null ? void 0 : offsetModifierState[mainAxis]) != null ? _offsetModifierState$ : 0;
    var tetherMin = offset + minOffset - offsetModifierValue - clientOffset;
    var tetherMax = offset + maxOffset - offsetModifierValue;
    var preventedOffset = within(tether ? min(min$1, tetherMin) : min$1, offset, tether ? max(max$1, tetherMax) : max$1);
    popperOffsets[mainAxis] = preventedOffset;
    data[mainAxis] = preventedOffset - offset;
  }
  if (checkAltAxis) {
    var _offsetModifierState$2;
    var _mainSide = mainAxis === 'x' ? top : left;
    var _altSide = mainAxis === 'x' ? bottom : right;
    var _offset = popperOffsets[altAxis];
    var _len = altAxis === 'y' ? 'height' : 'width';
    var _min = _offset + overflow[_mainSide];
    var _max = _offset - overflow[_altSide];
    var isOriginSide = [top, left].indexOf(basePlacement) !== -1;
    var _offsetModifierValue = (_offsetModifierState$2 = offsetModifierState == null ? void 0 : offsetModifierState[altAxis]) != null ? _offsetModifierState$2 : 0;
    var _tetherMin = isOriginSide ? _min : _offset - referenceRect[_len] - popperRect[_len] - _offsetModifierValue + normalizedTetherOffsetValue.altAxis;
    var _tetherMax = isOriginSide ? _offset + referenceRect[_len] + popperRect[_len] - _offsetModifierValue - normalizedTetherOffsetValue.altAxis : _max;
    var _preventedOffset = tether && isOriginSide ? withinMaxClamp(_tetherMin, _offset, _tetherMax) : within(tether ? _tetherMin : _min, _offset, tether ? _tetherMax : _max);
    popperOffsets[altAxis] = _preventedOffset;
    data[altAxis] = _preventedOffset - _offset;
  }
  state.modifiersData[name] = data;
} // eslint-disable-next-line import/no-unused-modules

var preventOverflow$1 = {
  name: 'preventOverflow',
  enabled: true,
  phase: 'main',
  fn: preventOverflow,
  requiresIfExists: ['offset']
};

function getHTMLElementScroll(element) {
  return {
    scrollLeft: element.scrollLeft,
    scrollTop: element.scrollTop
  };
}

function getNodeScroll(node) {
  if (node === getWindow(node) || !isHTMLElement(node)) {
    return getWindowScroll(node);
  } else {
    return getHTMLElementScroll(node);
  }
}

function isElementScaled(element) {
  var rect = element.getBoundingClientRect();
  var scaleX = round(rect.width) / element.offsetWidth || 1;
  var scaleY = round(rect.height) / element.offsetHeight || 1;
  return scaleX !== 1 || scaleY !== 1;
} // Returns the composite rect of an element relative to its offsetParent.
// Composite means it takes into account transforms as well as layout.

function getCompositeRect(elementOrVirtualElement, offsetParent, isFixed) {
  if (isFixed === void 0) {
    isFixed = false;
  }
  var isOffsetParentAnElement = isHTMLElement(offsetParent);
  var offsetParentIsScaled = isHTMLElement(offsetParent) && isElementScaled(offsetParent);
  var documentElement = getDocumentElement(offsetParent);
  var rect = getBoundingClientRect(elementOrVirtualElement, offsetParentIsScaled, isFixed);
  var scroll = {
    scrollLeft: 0,
    scrollTop: 0
  };
  var offsets = {
    x: 0,
    y: 0
  };
  if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {
    if (getNodeName(offsetParent) !== 'body' ||
    // https://github.com/popperjs/popper-core/issues/1078
    isScrollParent(documentElement)) {
      scroll = getNodeScroll(offsetParent);
    }
    if (isHTMLElement(offsetParent)) {
      offsets = getBoundingClientRect(offsetParent, true);
      offsets.x += offsetParent.clientLeft;
      offsets.y += offsetParent.clientTop;
    } else if (documentElement) {
      offsets.x = getWindowScrollBarX(documentElement);
    }
  }
  return {
    x: rect.left + scroll.scrollLeft - offsets.x,
    y: rect.top + scroll.scrollTop - offsets.y,
    width: rect.width,
    height: rect.height
  };
}

function order(modifiers) {
  var map = new Map();
  var visited = new Set();
  var result = [];
  modifiers.forEach(function (modifier) {
    map.set(modifier.name, modifier);
  }); // On visiting object, check for its dependencies and visit them recursively

  function sort(modifier) {
    visited.add(modifier.name);
    var requires = [].concat(modifier.requires || [], modifier.requiresIfExists || []);
    requires.forEach(function (dep) {
      if (!visited.has(dep)) {
        var depModifier = map.get(dep);
        if (depModifier) {
          sort(depModifier);
        }
      }
    });
    result.push(modifier);
  }
  modifiers.forEach(function (modifier) {
    if (!visited.has(modifier.name)) {
      // check for visited object
      sort(modifier);
    }
  });
  return result;
}
function orderModifiers(modifiers) {
  // order based on dependencies
  var orderedModifiers = order(modifiers); // order based on phase

  return modifierPhases.reduce(function (acc, phase) {
    return acc.concat(orderedModifiers.filter(function (modifier) {
      return modifier.phase === phase;
    }));
  }, []);
}

function debounce$1(fn) {
  var pending;
  return function () {
    if (!pending) {
      pending = new Promise(function (resolve) {
        Promise.resolve().then(function () {
          pending = undefined;
          resolve(fn());
        });
      });
    }
    return pending;
  };
}

function mergeByName(modifiers) {
  var merged = modifiers.reduce(function (merged, current) {
    var existing = merged[current.name];
    merged[current.name] = existing ? Object.assign({}, existing, current, {
      options: Object.assign({}, existing.options, current.options),
      data: Object.assign({}, existing.data, current.data)
    }) : current;
    return merged;
  }, {}); // IE11 does not support Object.values

  return Object.keys(merged).map(function (key) {
    return merged[key];
  });
}

var DEFAULT_OPTIONS = {
  placement: 'bottom',
  modifiers: [],
  strategy: 'absolute'
};
function areValidElements() {
  for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
    args[_key] = arguments[_key];
  }
  return !args.some(function (element) {
    return !(element && typeof element.getBoundingClientRect === 'function');
  });
}
function popperGenerator(generatorOptions) {
  if (generatorOptions === void 0) {
    generatorOptions = {};
  }
  var _generatorOptions = generatorOptions,
    _generatorOptions$def = _generatorOptions.defaultModifiers,
    defaultModifiers = _generatorOptions$def === void 0 ? [] : _generatorOptions$def,
    _generatorOptions$def2 = _generatorOptions.defaultOptions,
    defaultOptions = _generatorOptions$def2 === void 0 ? DEFAULT_OPTIONS : _generatorOptions$def2;
  return function createPopper(reference, popper, options) {
    if (options === void 0) {
      options = defaultOptions;
    }
    var state = {
      placement: 'bottom',
      orderedModifiers: [],
      options: Object.assign({}, DEFAULT_OPTIONS, defaultOptions),
      modifiersData: {},
      elements: {
        reference: reference,
        popper: popper
      },
      attributes: {},
      styles: {}
    };
    var effectCleanupFns = [];
    var isDestroyed = false;
    var instance = {
      state: state,
      setOptions: function setOptions(setOptionsAction) {
        var options = typeof setOptionsAction === 'function' ? setOptionsAction(state.options) : setOptionsAction;
        cleanupModifierEffects();
        state.options = Object.assign({}, defaultOptions, state.options, options);
        state.scrollParents = {
          reference: isElement$1(reference) ? listScrollParents(reference) : reference.contextElement ? listScrollParents(reference.contextElement) : [],
          popper: listScrollParents(popper)
        }; // Orders the modifiers based on their dependencies and `phase`
        // properties

        var orderedModifiers = orderModifiers(mergeByName([].concat(defaultModifiers, state.options.modifiers))); // Strip out disabled modifiers

        state.orderedModifiers = orderedModifiers.filter(function (m) {
          return m.enabled;
        });
        runModifierEffects();
        return instance.update();
      },
      // Sync update – it will always be executed, even if not necessary. This
      // is useful for low frequency updates where sync behavior simplifies the
      // logic.
      // For high frequency updates (e.g. `resize` and `scroll` events), always
      // prefer the async Popper#update method
      forceUpdate: function forceUpdate() {
        if (isDestroyed) {
          return;
        }
        var _state$elements = state.elements,
          reference = _state$elements.reference,
          popper = _state$elements.popper; // Don't proceed if `reference` or `popper` are not valid elements
        // anymore

        if (!areValidElements(reference, popper)) {
          return;
        } // Store the reference and popper rects to be read by modifiers

        state.rects = {
          reference: getCompositeRect(reference, getOffsetParent(popper), state.options.strategy === 'fixed'),
          popper: getLayoutRect(popper)
        }; // Modifiers have the ability to reset the current update cycle. The
        // most common use case for this is the `flip` modifier changing the
        // placement, which then needs to re-run all the modifiers, because the
        // logic was previously ran for the previous placement and is therefore
        // stale/incorrect

        state.reset = false;
        state.placement = state.options.placement; // On each update cycle, the `modifiersData` property for each modifier
        // is filled with the initial data specified by the modifier. This means
        // it doesn't persist and is fresh on each update.
        // To ensure persistent data, use `${name}#persistent`

        state.orderedModifiers.forEach(function (modifier) {
          return state.modifiersData[modifier.name] = Object.assign({}, modifier.data);
        });
        for (var index = 0; index < state.orderedModifiers.length; index++) {
          if (state.reset === true) {
            state.reset = false;
            index = -1;
            continue;
          }
          var _state$orderedModifie = state.orderedModifiers[index],
            fn = _state$orderedModifie.fn,
            _state$orderedModifie2 = _state$orderedModifie.options,
            _options = _state$orderedModifie2 === void 0 ? {} : _state$orderedModifie2,
            name = _state$orderedModifie.name;
          if (typeof fn === 'function') {
            state = fn({
              state: state,
              options: _options,
              name: name,
              instance: instance
            }) || state;
          }
        }
      },
      // Async and optimistically optimized update – it will not be executed if
      // not necessary (debounced to run at most once-per-tick)
      update: debounce$1(function () {
        return new Promise(function (resolve) {
          instance.forceUpdate();
          resolve(state);
        });
      }),
      destroy: function destroy() {
        cleanupModifierEffects();
        isDestroyed = true;
      }
    };
    if (!areValidElements(reference, popper)) {
      return instance;
    }
    instance.setOptions(options).then(function (state) {
      if (!isDestroyed && options.onFirstUpdate) {
        options.onFirstUpdate(state);
      }
    }); // Modifiers have the ability to execute arbitrary code before the first
    // update cycle runs. They will be executed in the same order as the update
    // cycle. This is useful when a modifier adds some persistent data that
    // other modifiers need to use, but the modifier is run after the dependent
    // one.

    function runModifierEffects() {
      state.orderedModifiers.forEach(function (_ref) {
        var name = _ref.name,
          _ref$options = _ref.options,
          options = _ref$options === void 0 ? {} : _ref$options,
          effect = _ref.effect;
        if (typeof effect === 'function') {
          var cleanupFn = effect({
            state: state,
            name: name,
            instance: instance,
            options: options
          });
          var noopFn = function noopFn() {};
          effectCleanupFns.push(cleanupFn || noopFn);
        }
      });
    }
    function cleanupModifierEffects() {
      effectCleanupFns.forEach(function (fn) {
        return fn();
      });
      effectCleanupFns = [];
    }
    return instance;
  };
}

var defaultModifiers = [eventListeners, popperOffsets$1, computeStyles$1, applyStyles$1, offset$1, flip$1, preventOverflow$1, arrow$1, hide$1];
var createPopper = /*#__PURE__*/popperGenerator({
  defaultModifiers: defaultModifiers
}); // eslint-disable-next-line import/no-unused-modules

/**!
* tippy.js v6.3.7
* (c) 2017-2021 atomiks
* MIT License
*/
var BOX_CLASS = "tippy-box";
var CONTENT_CLASS = "tippy-content";
var BACKDROP_CLASS = "tippy-backdrop";
var ARROW_CLASS = "tippy-arrow";
var SVG_ARROW_CLASS = "tippy-svg-arrow";
var TOUCH_OPTIONS = {
  passive: true,
  capture: true
};
var TIPPY_DEFAULT_APPEND_TO = function TIPPY_DEFAULT_APPEND_TO() {
  return document.body;
};
function hasOwnProperty(obj, key) {
  return {}.hasOwnProperty.call(obj, key);
}
function getValueAtIndexOrReturn(value, index, defaultValue) {
  if (Array.isArray(value)) {
    var v = value[index];
    return v == null ? Array.isArray(defaultValue) ? defaultValue[index] : defaultValue : v;
  }
  return value;
}
function isType(value, type) {
  var str = {}.toString.call(value);
  return str.indexOf('[object') === 0 && str.indexOf(type + "]") > -1;
}
function invokeWithArgsOrReturn(value, args) {
  return typeof value === 'function' ? value.apply(void 0, args) : value;
}
function debounce(fn, ms) {
  // Avoid wrapping in `setTimeout` if ms is 0 anyway
  if (ms === 0) {
    return fn;
  }
  var timeout;
  return function (arg) {
    clearTimeout(timeout);
    timeout = setTimeout(function () {
      fn(arg);
    }, ms);
  };
}
function removeProperties(obj, keys) {
  var clone = Object.assign({}, obj);
  keys.forEach(function (key) {
    delete clone[key];
  });
  return clone;
}
function splitBySpaces(value) {
  return value.split(/\s+/).filter(Boolean);
}
function normalizeToArray(value) {
  return [].concat(value);
}
function pushIfUnique(arr, value) {
  if (arr.indexOf(value) === -1) {
    arr.push(value);
  }
}
function unique(arr) {
  return arr.filter(function (item, index) {
    return arr.indexOf(item) === index;
  });
}
function getBasePlacement(placement) {
  return placement.split('-')[0];
}
function arrayFrom(value) {
  return [].slice.call(value);
}
function removeUndefinedProps(obj) {
  return Object.keys(obj).reduce(function (acc, key) {
    if (obj[key] !== undefined) {
      acc[key] = obj[key];
    }
    return acc;
  }, {});
}
function div() {
  return document.createElement('div');
}
function isElement(value) {
  return ['Element', 'Fragment'].some(function (type) {
    return isType(value, type);
  });
}
function isNodeList(value) {
  return isType(value, 'NodeList');
}
function isMouseEvent(value) {
  return isType(value, 'MouseEvent');
}
function isReferenceElement(value) {
  return !!(value && value._tippy && value._tippy.reference === value);
}
function getArrayOfElements(value) {
  if (isElement(value)) {
    return [value];
  }
  if (isNodeList(value)) {
    return arrayFrom(value);
  }
  if (Array.isArray(value)) {
    return value;
  }
  return arrayFrom(document.querySelectorAll(value));
}
function setTransitionDuration(els, value) {
  els.forEach(function (el) {
    if (el) {
      el.style.transitionDuration = value + "ms";
    }
  });
}
function setVisibilityState(els, state) {
  els.forEach(function (el) {
    if (el) {
      el.setAttribute('data-state', state);
    }
  });
}
function getOwnerDocument(elementOrElements) {
  var _element$ownerDocumen;
  var _normalizeToArray = normalizeToArray(elementOrElements),
    element = _normalizeToArray[0]; // Elements created via a <template> have an ownerDocument with no reference to the body

  return element != null && (_element$ownerDocumen = element.ownerDocument) != null && _element$ownerDocumen.body ? element.ownerDocument : document;
}
function isCursorOutsideInteractiveBorder(popperTreeData, event) {
  var clientX = event.clientX,
    clientY = event.clientY;
  return popperTreeData.every(function (_ref) {
    var popperRect = _ref.popperRect,
      popperState = _ref.popperState,
      props = _ref.props;
    var interactiveBorder = props.interactiveBorder;
    var basePlacement = getBasePlacement(popperState.placement);
    var offsetData = popperState.modifiersData.offset;
    if (!offsetData) {
      return true;
    }
    var topDistance = basePlacement === 'bottom' ? offsetData.top.y : 0;
    var bottomDistance = basePlacement === 'top' ? offsetData.bottom.y : 0;
    var leftDistance = basePlacement === 'right' ? offsetData.left.x : 0;
    var rightDistance = basePlacement === 'left' ? offsetData.right.x : 0;
    var exceedsTop = popperRect.top - clientY + topDistance > interactiveBorder;
    var exceedsBottom = clientY - popperRect.bottom - bottomDistance > interactiveBorder;
    var exceedsLeft = popperRect.left - clientX + leftDistance > interactiveBorder;
    var exceedsRight = clientX - popperRect.right - rightDistance > interactiveBorder;
    return exceedsTop || exceedsBottom || exceedsLeft || exceedsRight;
  });
}
function updateTransitionEndListener(box, action, listener) {
  var method = action + "EventListener"; // some browsers apparently support `transition` (unprefixed) but only fire
  // `webkitTransitionEnd`...

  ['transitionend', 'webkitTransitionEnd'].forEach(function (event) {
    box[method](event, listener);
  });
}
/**
 * Compared to xxx.contains, this function works for dom structures with shadow
 * dom
 */

function actualContains(parent, child) {
  var target = child;
  while (target) {
    var _target$getRootNode;
    if (parent.contains(target)) {
      return true;
    }
    target = target.getRootNode == null ? void 0 : (_target$getRootNode = target.getRootNode()) == null ? void 0 : _target$getRootNode.host;
  }
  return false;
}
var currentInput = {
  isTouch: false
};
var lastMouseMoveTime = 0;
/**
 * When a `touchstart` event is fired, it's assumed the user is using touch
 * input. We'll bind a `mousemove` event listener to listen for mouse input in
 * the future. This way, the `isTouch` property is fully dynamic and will handle
 * hybrid devices that use a mix of touch + mouse input.
 */

function onDocumentTouchStart() {
  if (currentInput.isTouch) {
    return;
  }
  currentInput.isTouch = true;
  if (window.performance) {
    document.addEventListener('mousemove', onDocumentMouseMove);
  }
}
/**
 * When two `mousemove` event are fired consecutively within 20ms, it's assumed
 * the user is using mouse input again. `mousemove` can fire on touch devices as
 * well, but very rarely that quickly.
 */

function onDocumentMouseMove() {
  var now = performance.now();
  if (now - lastMouseMoveTime < 20) {
    currentInput.isTouch = false;
    document.removeEventListener('mousemove', onDocumentMouseMove);
  }
  lastMouseMoveTime = now;
}
/**
 * When an element is in focus and has a tippy, leaving the tab/window and
 * returning causes it to show again. For mouse users this is unexpected, but
 * for keyboard use it makes sense.
 * TODO: find a better technique to solve this problem
 */

function onWindowBlur() {
  var activeElement = document.activeElement;
  if (isReferenceElement(activeElement)) {
    var instance = activeElement._tippy;
    if (activeElement.blur && !instance.state.isVisible) {
      activeElement.blur();
    }
  }
}
function bindGlobalEventListeners() {
  document.addEventListener('touchstart', onDocumentTouchStart, TOUCH_OPTIONS);
  window.addEventListener('blur', onWindowBlur);
}
var isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined';
var isIE11 = isBrowser ?
// @ts-ignore
!!window.msCrypto : false;
function createMemoryLeakWarning(method) {
  var txt = method === 'destroy' ? 'n already-' : ' ';
  return [method + "() was called on a" + txt + "destroyed instance. This is a no-op but", 'indicates a potential memory leak.'].join(' ');
}
function clean(value) {
  var spacesAndTabs = /[ \t]{2,}/g;
  var lineStartWithSpaces = /^[ \t]*/gm;
  return value.replace(spacesAndTabs, ' ').replace(lineStartWithSpaces, '').trim();
}
function getDevMessage(message) {
  return clean("\n  %ctippy.js\n\n  %c" + clean(message) + "\n\n  %c\uD83D\uDC77\u200D This is a development-only message. It will be removed in production.\n  ");
}
function getFormattedMessage(message) {
  return [getDevMessage(message),
  // title
  'color: #00C584; font-size: 1.3em; font-weight: bold;',
  // message
  'line-height: 1.5',
  // footer
  'color: #a6a095;'];
} // Assume warnings and errors never have the same message

var visitedMessages;
{
  resetVisitedMessages();
}
function resetVisitedMessages() {
  visitedMessages = new Set();
}
function warnWhen(condition, message) {
  if (condition && !visitedMessages.has(message)) {
    var _console;
    visitedMessages.add(message);
    (_console = console).warn.apply(_console, getFormattedMessage(message));
  }
}
function errorWhen(condition, message) {
  if (condition && !visitedMessages.has(message)) {
    var _console2;
    visitedMessages.add(message);
    (_console2 = console).error.apply(_console2, getFormattedMessage(message));
  }
}
function validateTargets(targets) {
  var didPassFalsyValue = !targets;
  var didPassPlainObject = Object.prototype.toString.call(targets) === '[object Object]' && !targets.addEventListener;
  errorWhen(didPassFalsyValue, ['tippy() was passed', '`' + String(targets) + '`', 'as its targets (first) argument. Valid types are: String, Element,', 'Element[], or NodeList.'].join(' '));
  errorWhen(didPassPlainObject, ['tippy() was passed a plain object which is not supported as an argument', 'for virtual positioning. Use props.getReferenceClientRect instead.'].join(' '));
}
var pluginProps = {
  animateFill: false,
  followCursor: false,
  inlinePositioning: false,
  sticky: false
};
var renderProps = {
  allowHTML: false,
  animation: 'fade',
  arrow: true,
  content: '',
  inertia: false,
  maxWidth: 350,
  role: 'tooltip',
  theme: '',
  zIndex: 9999
};
var defaultProps = Object.assign({
  appendTo: TIPPY_DEFAULT_APPEND_TO,
  aria: {
    content: 'auto',
    expanded: 'auto'
  },
  delay: 0,
  duration: [300, 250],
  getReferenceClientRect: null,
  hideOnClick: true,
  ignoreAttributes: false,
  interactive: false,
  interactiveBorder: 2,
  interactiveDebounce: 0,
  moveTransition: '',
  offset: [0, 10],
  onAfterUpdate: function onAfterUpdate() {},
  onBeforeUpdate: function onBeforeUpdate() {},
  onCreate: function onCreate() {},
  onDestroy: function onDestroy() {},
  onHidden: function onHidden() {},
  onHide: function onHide() {},
  onMount: function onMount() {},
  onShow: function onShow() {},
  onShown: function onShown() {},
  onTrigger: function onTrigger() {},
  onUntrigger: function onUntrigger() {},
  onClickOutside: function onClickOutside() {},
  placement: 'top',
  plugins: [],
  popperOptions: {},
  render: null,
  showOnCreate: false,
  touch: true,
  trigger: 'mouseenter focus',
  triggerTarget: null
}, pluginProps, renderProps);
var defaultKeys = Object.keys(defaultProps);
var setDefaultProps = function setDefaultProps(partialProps) {
  /* istanbul ignore else */
  {
    validateProps(partialProps, []);
  }
  var keys = Object.keys(partialProps);
  keys.forEach(function (key) {
    defaultProps[key] = partialProps[key];
  });
};
function getExtendedPassedProps(passedProps) {
  var plugins = passedProps.plugins || [];
  var pluginProps = plugins.reduce(function (acc, plugin) {
    var name = plugin.name,
      defaultValue = plugin.defaultValue;
    if (name) {
      var _name;
      acc[name] = passedProps[name] !== undefined ? passedProps[name] : (_name = defaultProps[name]) != null ? _name : defaultValue;
    }
    return acc;
  }, {});
  return Object.assign({}, passedProps, pluginProps);
}
function getDataAttributeProps(reference, plugins) {
  var propKeys = plugins ? Object.keys(getExtendedPassedProps(Object.assign({}, defaultProps, {
    plugins: plugins
  }))) : defaultKeys;
  var props = propKeys.reduce(function (acc, key) {
    var valueAsString = (reference.getAttribute("data-tippy-" + key) || '').trim();
    if (!valueAsString) {
      return acc;
    }
    if (key === 'content') {
      acc[key] = valueAsString;
    } else {
      try {
        acc[key] = JSON.parse(valueAsString);
      } catch (e) {
        acc[key] = valueAsString;
      }
    }
    return acc;
  }, {});
  return props;
}
function evaluateProps(reference, props) {
  var out = Object.assign({}, props, {
    content: invokeWithArgsOrReturn(props.content, [reference])
  }, props.ignoreAttributes ? {} : getDataAttributeProps(reference, props.plugins));
  out.aria = Object.assign({}, defaultProps.aria, out.aria);
  out.aria = {
    expanded: out.aria.expanded === 'auto' ? props.interactive : out.aria.expanded,
    content: out.aria.content === 'auto' ? props.interactive ? null : 'describedby' : out.aria.content
  };
  return out;
}
function validateProps(partialProps, plugins) {
  if (partialProps === void 0) {
    partialProps = {};
  }
  if (plugins === void 0) {
    plugins = [];
  }
  var keys = Object.keys(partialProps);
  keys.forEach(function (prop) {
    var nonPluginProps = removeProperties(defaultProps, Object.keys(pluginProps));
    var didPassUnknownProp = !hasOwnProperty(nonPluginProps, prop); // Check if the prop exists in `plugins`

    if (didPassUnknownProp) {
      didPassUnknownProp = plugins.filter(function (plugin) {
        return plugin.name === prop;
      }).length === 0;
    }
    warnWhen(didPassUnknownProp, ["`" + prop + "`", "is not a valid prop. You may have spelled it incorrectly, or if it's", 'a plugin, forgot to pass it in an array as props.plugins.', '\n\n', 'All props: https://atomiks.github.io/tippyjs/v6/all-props/\n', 'Plugins: https://atomiks.github.io/tippyjs/v6/plugins/'].join(' '));
  });
}
var innerHTML = function innerHTML() {
  return 'innerHTML';
};
function dangerouslySetInnerHTML(element, html) {
  element[innerHTML()] = html;
}
function createArrowElement(value) {
  var arrow = div();
  if (value === true) {
    arrow.className = ARROW_CLASS;
  } else {
    arrow.className = SVG_ARROW_CLASS;
    if (isElement(value)) {
      arrow.appendChild(value);
    } else {
      dangerouslySetInnerHTML(arrow, value);
    }
  }
  return arrow;
}
function setContent(content, props) {
  if (isElement(props.content)) {
    dangerouslySetInnerHTML(content, '');
    content.appendChild(props.content);
  } else if (typeof props.content !== 'function') {
    if (props.allowHTML) {
      dangerouslySetInnerHTML(content, props.content);
    } else {
      content.textContent = props.content;
    }
  }
}
function getChildren(popper) {
  var box = popper.firstElementChild;
  var boxChildren = arrayFrom(box.children);
  return {
    box: box,
    content: boxChildren.find(function (node) {
      return node.classList.contains(CONTENT_CLASS);
    }),
    arrow: boxChildren.find(function (node) {
      return node.classList.contains(ARROW_CLASS) || node.classList.contains(SVG_ARROW_CLASS);
    }),
    backdrop: boxChildren.find(function (node) {
      return node.classList.contains(BACKDROP_CLASS);
    })
  };
}
function render(instance) {
  var popper = div();
  var box = div();
  box.className = BOX_CLASS;
  box.setAttribute('data-state', 'hidden');
  box.setAttribute('tabindex', '-1');
  var content = div();
  content.className = CONTENT_CLASS;
  content.setAttribute('data-state', 'hidden');
  setContent(content, instance.props);
  popper.appendChild(box);
  box.appendChild(content);
  onUpdate(instance.props, instance.props);
  function onUpdate(prevProps, nextProps) {
    var _getChildren = getChildren(popper),
      box = _getChildren.box,
      content = _getChildren.content,
      arrow = _getChildren.arrow;
    if (nextProps.theme) {
      box.setAttribute('data-theme', nextProps.theme);
    } else {
      box.removeAttribute('data-theme');
    }
    if (typeof nextProps.animation === 'string') {
      box.setAttribute('data-animation', nextProps.animation);
    } else {
      box.removeAttribute('data-animation');
    }
    if (nextProps.inertia) {
      box.setAttribute('data-inertia', '');
    } else {
      box.removeAttribute('data-inertia');
    }
    box.style.maxWidth = typeof nextProps.maxWidth === 'number' ? nextProps.maxWidth + "px" : nextProps.maxWidth;
    if (nextProps.role) {
      box.setAttribute('role', nextProps.role);
    } else {
      box.removeAttribute('role');
    }
    if (prevProps.content !== nextProps.content || prevProps.allowHTML !== nextProps.allowHTML) {
      setContent(content, instance.props);
    }
    if (nextProps.arrow) {
      if (!arrow) {
        box.appendChild(createArrowElement(nextProps.arrow));
      } else if (prevProps.arrow !== nextProps.arrow) {
        box.removeChild(arrow);
        box.appendChild(createArrowElement(nextProps.arrow));
      }
    } else if (arrow) {
      box.removeChild(arrow);
    }
  }
  return {
    popper: popper,
    onUpdate: onUpdate
  };
} // Runtime check to identify if the render function is the default one; this
// way we can apply default CSS transitions logic and it can be tree-shaken away

render.$$tippy = true;
var idCounter = 1;
var mouseMoveListeners = []; // Used by `hideAll()`

var mountedInstances = [];
function createTippy(reference, passedProps) {
  var props = evaluateProps(reference, Object.assign({}, defaultProps, getExtendedPassedProps(removeUndefinedProps(passedProps)))); // ===========================================================================
  // 🔒 Private members
  // ===========================================================================

  var showTimeout;
  var hideTimeout;
  var scheduleHideAnimationFrame;
  var isVisibleFromClick = false;
  var didHideDueToDocumentMouseDown = false;
  var didTouchMove = false;
  var ignoreOnFirstUpdate = false;
  var lastTriggerEvent;
  var currentTransitionEndListener;
  var onFirstUpdate;
  var listeners = [];
  var debouncedOnMouseMove = debounce(onMouseMove, props.interactiveDebounce);
  var currentTarget; // ===========================================================================
  // 🔑 Public members
  // ===========================================================================

  var id = idCounter++;
  var popperInstance = null;
  var plugins = unique(props.plugins);
  var state = {
    // Is the instance currently enabled?
    isEnabled: true,
    // Is the tippy currently showing and not transitioning out?
    isVisible: false,
    // Has the instance been destroyed?
    isDestroyed: false,
    // Is the tippy currently mounted to the DOM?
    isMounted: false,
    // Has the tippy finished transitioning in?
    isShown: false
  };
  var instance = {
    // properties
    id: id,
    reference: reference,
    popper: div(),
    popperInstance: popperInstance,
    props: props,
    state: state,
    plugins: plugins,
    // methods
    clearDelayTimeouts: clearDelayTimeouts,
    setProps: setProps,
    setContent: setContent,
    show: show,
    hide: hide,
    hideWithInteractivity: hideWithInteractivity,
    enable: enable,
    disable: disable,
    unmount: unmount,
    destroy: destroy
  }; // TODO: Investigate why this early return causes a TDZ error in the tests —
  // it doesn't seem to happen in the browser

  /* istanbul ignore if */

  if (!props.render) {
    {
      errorWhen(true, 'render() function has not been supplied.');
    }
    return instance;
  } // ===========================================================================
  // Initial mutations
  // ===========================================================================

  var _props$render = props.render(instance),
    popper = _props$render.popper,
    onUpdate = _props$render.onUpdate;
  popper.setAttribute('data-tippy-root', '');
  popper.id = "tippy-" + instance.id;
  instance.popper = popper;
  reference._tippy = instance;
  popper._tippy = instance;
  var pluginsHooks = plugins.map(function (plugin) {
    return plugin.fn(instance);
  });
  var hasAriaExpanded = reference.hasAttribute('aria-expanded');
  addListeners();
  handleAriaExpandedAttribute();
  handleStyles();
  invokeHook('onCreate', [instance]);
  if (props.showOnCreate) {
    scheduleShow();
  } // Prevent a tippy with a delay from hiding if the cursor left then returned
  // before it started hiding

  popper.addEventListener('mouseenter', function () {
    if (instance.props.interactive && instance.state.isVisible) {
      instance.clearDelayTimeouts();
    }
  });
  popper.addEventListener('mouseleave', function () {
    if (instance.props.interactive && instance.props.trigger.indexOf('mouseenter') >= 0) {
      getDocument().addEventListener('mousemove', debouncedOnMouseMove);
    }
  });
  return instance; // ===========================================================================
  // 🔒 Private methods
  // ===========================================================================

  function getNormalizedTouchSettings() {
    var touch = instance.props.touch;
    return Array.isArray(touch) ? touch : [touch, 0];
  }
  function getIsCustomTouchBehavior() {
    return getNormalizedTouchSettings()[0] === 'hold';
  }
  function getIsDefaultRenderFn() {
    var _instance$props$rende;

    // @ts-ignore
    return !!((_instance$props$rende = instance.props.render) != null && _instance$props$rende.$$tippy);
  }
  function getCurrentTarget() {
    return currentTarget || reference;
  }
  function getDocument() {
    var parent = getCurrentTarget().parentNode;
    return parent ? getOwnerDocument(parent) : document;
  }
  function getDefaultTemplateChildren() {
    return getChildren(popper);
  }
  function getDelay(isShow) {
    // For touch or keyboard input, force `0` delay for UX reasons
    // Also if the instance is mounted but not visible (transitioning out),
    // ignore delay
    if (instance.state.isMounted && !instance.state.isVisible || currentInput.isTouch || lastTriggerEvent && lastTriggerEvent.type === 'focus') {
      return 0;
    }
    return getValueAtIndexOrReturn(instance.props.delay, isShow ? 0 : 1, defaultProps.delay);
  }
  function handleStyles(fromHide) {
    if (fromHide === void 0) {
      fromHide = false;
    }
    popper.style.pointerEvents = instance.props.interactive && !fromHide ? '' : 'none';
    popper.style.zIndex = "" + instance.props.zIndex;
  }
  function invokeHook(hook, args, shouldInvokePropsHook) {
    if (shouldInvokePropsHook === void 0) {
      shouldInvokePropsHook = true;
    }
    pluginsHooks.forEach(function (pluginHooks) {
      if (pluginHooks[hook]) {
        pluginHooks[hook].apply(pluginHooks, args);
      }
    });
    if (shouldInvokePropsHook) {
      var _instance$props;
      (_instance$props = instance.props)[hook].apply(_instance$props, args);
    }
  }
  function handleAriaContentAttribute() {
    var aria = instance.props.aria;
    if (!aria.content) {
      return;
    }
    var attr = "aria-" + aria.content;
    var id = popper.id;
    var nodes = normalizeToArray(instance.props.triggerTarget || reference);
    nodes.forEach(function (node) {
      var currentValue = node.getAttribute(attr);
      if (instance.state.isVisible) {
        node.setAttribute(attr, currentValue ? currentValue + " " + id : id);
      } else {
        var nextValue = currentValue && currentValue.replace(id, '').trim();
        if (nextValue) {
          node.setAttribute(attr, nextValue);
        } else {
          node.removeAttribute(attr);
        }
      }
    });
  }
  function handleAriaExpandedAttribute() {
    if (hasAriaExpanded || !instance.props.aria.expanded) {
      return;
    }
    var nodes = normalizeToArray(instance.props.triggerTarget || reference);
    nodes.forEach(function (node) {
      if (instance.props.interactive) {
        node.setAttribute('aria-expanded', instance.state.isVisible && node === getCurrentTarget() ? 'true' : 'false');
      } else {
        node.removeAttribute('aria-expanded');
      }
    });
  }
  function cleanupInteractiveMouseListeners() {
    getDocument().removeEventListener('mousemove', debouncedOnMouseMove);
    mouseMoveListeners = mouseMoveListeners.filter(function (listener) {
      return listener !== debouncedOnMouseMove;
    });
  }
  function onDocumentPress(event) {
    // Moved finger to scroll instead of an intentional tap outside
    if (currentInput.isTouch) {
      if (didTouchMove || event.type === 'mousedown') {
        return;
      }
    }
    var actualTarget = event.composedPath && event.composedPath()[0] || event.target; // Clicked on interactive popper

    if (instance.props.interactive && actualContains(popper, actualTarget)) {
      return;
    } // Clicked on the event listeners target

    if (normalizeToArray(instance.props.triggerTarget || reference).some(function (el) {
      return actualContains(el, actualTarget);
    })) {
      if (currentInput.isTouch) {
        return;
      }
      if (instance.state.isVisible && instance.props.trigger.indexOf('click') >= 0) {
        return;
      }
    } else {
      invokeHook('onClickOutside', [instance, event]);
    }
    if (instance.props.hideOnClick === true) {
      instance.clearDelayTimeouts();
      instance.hide(); // `mousedown` event is fired right before `focus` if pressing the
      // currentTarget. This lets a tippy with `focus` trigger know that it
      // should not show

      didHideDueToDocumentMouseDown = true;
      setTimeout(function () {
        didHideDueToDocumentMouseDown = false;
      }); // The listener gets added in `scheduleShow()`, but this may be hiding it
      // before it shows, and hide()'s early bail-out behavior can prevent it
      // from being cleaned up

      if (!instance.state.isMounted) {
        removeDocumentPress();
      }
    }
  }
  function onTouchMove() {
    didTouchMove = true;
  }
  function onTouchStart() {
    didTouchMove = false;
  }
  function addDocumentPress() {
    var doc = getDocument();
    doc.addEventListener('mousedown', onDocumentPress, true);
    doc.addEventListener('touchend', onDocumentPress, TOUCH_OPTIONS);
    doc.addEventListener('touchstart', onTouchStart, TOUCH_OPTIONS);
    doc.addEventListener('touchmove', onTouchMove, TOUCH_OPTIONS);
  }
  function removeDocumentPress() {
    var doc = getDocument();
    doc.removeEventListener('mousedown', onDocumentPress, true);
    doc.removeEventListener('touchend', onDocumentPress, TOUCH_OPTIONS);
    doc.removeEventListener('touchstart', onTouchStart, TOUCH_OPTIONS);
    doc.removeEventListener('touchmove', onTouchMove, TOUCH_OPTIONS);
  }
  function onTransitionedOut(duration, callback) {
    onTransitionEnd(duration, function () {
      if (!instance.state.isVisible && popper.parentNode && popper.parentNode.contains(popper)) {
        callback();
      }
    });
  }
  function onTransitionedIn(duration, callback) {
    onTransitionEnd(duration, callback);
  }
  function onTransitionEnd(duration, callback) {
    var box = getDefaultTemplateChildren().box;
    function listener(event) {
      if (event.target === box) {
        updateTransitionEndListener(box, 'remove', listener);
        callback();
      }
    } // Make callback synchronous if duration is 0
    // `transitionend` won't fire otherwise

    if (duration === 0) {
      return callback();
    }
    updateTransitionEndListener(box, 'remove', currentTransitionEndListener);
    updateTransitionEndListener(box, 'add', listener);
    currentTransitionEndListener = listener;
  }
  function on(eventType, handler, options) {
    if (options === void 0) {
      options = false;
    }
    var nodes = normalizeToArray(instance.props.triggerTarget || reference);
    nodes.forEach(function (node) {
      node.addEventListener(eventType, handler, options);
      listeners.push({
        node: node,
        eventType: eventType,
        handler: handler,
        options: options
      });
    });
  }
  function addListeners() {
    if (getIsCustomTouchBehavior()) {
      on('touchstart', onTrigger, {
        passive: true
      });
      on('touchend', onMouseLeave, {
        passive: true
      });
    }
    splitBySpaces(instance.props.trigger).forEach(function (eventType) {
      if (eventType === 'manual') {
        return;
      }
      on(eventType, onTrigger);
      switch (eventType) {
        case 'mouseenter':
          on('mouseleave', onMouseLeave);
          break;
        case 'focus':
          on(isIE11 ? 'focusout' : 'blur', onBlurOrFocusOut);
          break;
        case 'focusin':
          on('focusout', onBlurOrFocusOut);
          break;
      }
    });
  }
  function removeListeners() {
    listeners.forEach(function (_ref) {
      var node = _ref.node,
        eventType = _ref.eventType,
        handler = _ref.handler,
        options = _ref.options;
      node.removeEventListener(eventType, handler, options);
    });
    listeners = [];
  }
  function onTrigger(event) {
    var _lastTriggerEvent;
    var shouldScheduleClickHide = false;
    if (!instance.state.isEnabled || isEventListenerStopped(event) || didHideDueToDocumentMouseDown) {
      return;
    }
    var wasFocused = ((_lastTriggerEvent = lastTriggerEvent) == null ? void 0 : _lastTriggerEvent.type) === 'focus';
    lastTriggerEvent = event;
    currentTarget = event.currentTarget;
    handleAriaExpandedAttribute();
    if (!instance.state.isVisible && isMouseEvent(event)) {
      // If scrolling, `mouseenter` events can be fired if the cursor lands
      // over a new target, but `mousemove` events don't get fired. This
      // causes interactive tooltips to get stuck open until the cursor is
      // moved
      mouseMoveListeners.forEach(function (listener) {
        return listener(event);
      });
    } // Toggle show/hide when clicking click-triggered tooltips

    if (event.type === 'click' && (instance.props.trigger.indexOf('mouseenter') < 0 || isVisibleFromClick) && instance.props.hideOnClick !== false && instance.state.isVisible) {
      shouldScheduleClickHide = true;
    } else {
      scheduleShow(event);
    }
    if (event.type === 'click') {
      isVisibleFromClick = !shouldScheduleClickHide;
    }
    if (shouldScheduleClickHide && !wasFocused) {
      scheduleHide(event);
    }
  }
  function onMouseMove(event) {
    var target = event.target;
    var isCursorOverReferenceOrPopper = getCurrentTarget().contains(target) || popper.contains(target);
    if (event.type === 'mousemove' && isCursorOverReferenceOrPopper) {
      return;
    }
    var popperTreeData = getNestedPopperTree().concat(popper).map(function (popper) {
      var _instance$popperInsta;
      var instance = popper._tippy;
      var state = (_instance$popperInsta = instance.popperInstance) == null ? void 0 : _instance$popperInsta.state;
      if (state) {
        return {
          popperRect: popper.getBoundingClientRect(),
          popperState: state,
          props: props
        };
      }
      return null;
    }).filter(Boolean);
    if (isCursorOutsideInteractiveBorder(popperTreeData, event)) {
      cleanupInteractiveMouseListeners();
      scheduleHide(event);
    }
  }
  function onMouseLeave(event) {
    var shouldBail = isEventListenerStopped(event) || instance.props.trigger.indexOf('click') >= 0 && isVisibleFromClick;
    if (shouldBail) {
      return;
    }
    if (instance.props.interactive) {
      instance.hideWithInteractivity(event);
      return;
    }
    scheduleHide(event);
  }
  function onBlurOrFocusOut(event) {
    if (instance.props.trigger.indexOf('focusin') < 0 && event.target !== getCurrentTarget()) {
      return;
    } // If focus was moved to within the popper

    if (instance.props.interactive && event.relatedTarget && popper.contains(event.relatedTarget)) {
      return;
    }
    scheduleHide(event);
  }
  function isEventListenerStopped(event) {
    return currentInput.isTouch ? getIsCustomTouchBehavior() !== event.type.indexOf('touch') >= 0 : false;
  }
  function createPopperInstance() {
    destroyPopperInstance();
    var _instance$props2 = instance.props,
      popperOptions = _instance$props2.popperOptions,
      placement = _instance$props2.placement,
      offset = _instance$props2.offset,
      getReferenceClientRect = _instance$props2.getReferenceClientRect,
      moveTransition = _instance$props2.moveTransition;
    var arrow = getIsDefaultRenderFn() ? getChildren(popper).arrow : null;
    var computedReference = getReferenceClientRect ? {
      getBoundingClientRect: getReferenceClientRect,
      contextElement: getReferenceClientRect.contextElement || getCurrentTarget()
    } : reference;
    var tippyModifier = {
      name: '$$tippy',
      enabled: true,
      phase: 'beforeWrite',
      requires: ['computeStyles'],
      fn: function fn(_ref2) {
        var state = _ref2.state;
        if (getIsDefaultRenderFn()) {
          var _getDefaultTemplateCh = getDefaultTemplateChildren(),
            box = _getDefaultTemplateCh.box;
          ['placement', 'reference-hidden', 'escaped'].forEach(function (attr) {
            if (attr === 'placement') {
              box.setAttribute('data-placement', state.placement);
            } else {
              if (state.attributes.popper["data-popper-" + attr]) {
                box.setAttribute("data-" + attr, '');
              } else {
                box.removeAttribute("data-" + attr);
              }
            }
          });
          state.attributes.popper = {};
        }
      }
    };
    var modifiers = [{
      name: 'offset',
      options: {
        offset: offset
      }
    }, {
      name: 'preventOverflow',
      options: {
        padding: {
          top: 2,
          bottom: 2,
          left: 5,
          right: 5
        }
      }
    }, {
      name: 'flip',
      options: {
        padding: 5
      }
    }, {
      name: 'computeStyles',
      options: {
        adaptive: !moveTransition
      }
    }, tippyModifier];
    if (getIsDefaultRenderFn() && arrow) {
      modifiers.push({
        name: 'arrow',
        options: {
          element: arrow,
          padding: 3
        }
      });
    }
    modifiers.push.apply(modifiers, (popperOptions == null ? void 0 : popperOptions.modifiers) || []);
    instance.popperInstance = createPopper(computedReference, popper, Object.assign({}, popperOptions, {
      placement: placement,
      onFirstUpdate: onFirstUpdate,
      modifiers: modifiers
    }));
  }
  function destroyPopperInstance() {
    if (instance.popperInstance) {
      instance.popperInstance.destroy();
      instance.popperInstance = null;
    }
  }
  function mount() {
    var appendTo = instance.props.appendTo;
    var parentNode; // By default, we'll append the popper to the triggerTargets's parentNode so
    // it's directly after the reference element so the elements inside the
    // tippy can be tabbed to
    // If there are clipping issues, the user can specify a different appendTo
    // and ensure focus management is handled correctly manually

    var node = getCurrentTarget();
    if (instance.props.interactive && appendTo === TIPPY_DEFAULT_APPEND_TO || appendTo === 'parent') {
      parentNode = node.parentNode;
    } else {
      parentNode = invokeWithArgsOrReturn(appendTo, [node]);
    } // The popper element needs to exist on the DOM before its position can be
    // updated as Popper needs to read its dimensions

    if (!parentNode.contains(popper)) {
      parentNode.appendChild(popper);
    }
    instance.state.isMounted = true;
    createPopperInstance();
    /* istanbul ignore else */

    {
      // Accessibility check
      warnWhen(instance.props.interactive && appendTo === defaultProps.appendTo && node.nextElementSibling !== popper, ['Interactive tippy element may not be accessible via keyboard', 'navigation because it is not directly after the reference element', 'in the DOM source order.', '\n\n', 'Using a wrapper <div> or <span> tag around the reference element', 'solves this by creating a new parentNode context.', '\n\n', 'Specifying `appendTo: document.body` silences this warning, but it', 'assumes you are using a focus management solution to handle', 'keyboard navigation.', '\n\n', 'See: https://atomiks.github.io/tippyjs/v6/accessibility/#interactivity'].join(' '));
    }
  }
  function getNestedPopperTree() {
    return arrayFrom(popper.querySelectorAll('[data-tippy-root]'));
  }
  function scheduleShow(event) {
    instance.clearDelayTimeouts();
    if (event) {
      invokeHook('onTrigger', [instance, event]);
    }
    addDocumentPress();
    var delay = getDelay(true);
    var _getNormalizedTouchSe = getNormalizedTouchSettings(),
      touchValue = _getNormalizedTouchSe[0],
      touchDelay = _getNormalizedTouchSe[1];
    if (currentInput.isTouch && touchValue === 'hold' && touchDelay) {
      delay = touchDelay;
    }
    if (delay) {
      showTimeout = setTimeout(function () {
        instance.show();
      }, delay);
    } else {
      instance.show();
    }
  }
  function scheduleHide(event) {
    instance.clearDelayTimeouts();
    invokeHook('onUntrigger', [instance, event]);
    if (!instance.state.isVisible) {
      removeDocumentPress();
      return;
    } // For interactive tippies, scheduleHide is added to a document.body handler
    // from onMouseLeave so must intercept scheduled hides from mousemove/leave
    // events when trigger contains mouseenter and click, and the tip is
    // currently shown as a result of a click.

    if (instance.props.trigger.indexOf('mouseenter') >= 0 && instance.props.trigger.indexOf('click') >= 0 && ['mouseleave', 'mousemove'].indexOf(event.type) >= 0 && isVisibleFromClick) {
      return;
    }
    var delay = getDelay(false);
    if (delay) {
      hideTimeout = setTimeout(function () {
        if (instance.state.isVisible) {
          instance.hide();
        }
      }, delay);
    } else {
      // Fixes a `transitionend` problem when it fires 1 frame too
      // late sometimes, we don't want hide() to be called.
      scheduleHideAnimationFrame = requestAnimationFrame(function () {
        instance.hide();
      });
    }
  } // ===========================================================================
  // 🔑 Public methods
  // ===========================================================================

  function enable() {
    instance.state.isEnabled = true;
  }
  function disable() {
    // Disabling the instance should also hide it
    // https://github.com/atomiks/tippy.js-react/issues/106
    instance.hide();
    instance.state.isEnabled = false;
  }
  function clearDelayTimeouts() {
    clearTimeout(showTimeout);
    clearTimeout(hideTimeout);
    cancelAnimationFrame(scheduleHideAnimationFrame);
  }
  function setProps(partialProps) {
    /* istanbul ignore else */
    {
      warnWhen(instance.state.isDestroyed, createMemoryLeakWarning('setProps'));
    }
    if (instance.state.isDestroyed) {
      return;
    }
    invokeHook('onBeforeUpdate', [instance, partialProps]);
    removeListeners();
    var prevProps = instance.props;
    var nextProps = evaluateProps(reference, Object.assign({}, prevProps, removeUndefinedProps(partialProps), {
      ignoreAttributes: true
    }));
    instance.props = nextProps;
    addListeners();
    if (prevProps.interactiveDebounce !== nextProps.interactiveDebounce) {
      cleanupInteractiveMouseListeners();
      debouncedOnMouseMove = debounce(onMouseMove, nextProps.interactiveDebounce);
    } // Ensure stale aria-expanded attributes are removed

    if (prevProps.triggerTarget && !nextProps.triggerTarget) {
      normalizeToArray(prevProps.triggerTarget).forEach(function (node) {
        node.removeAttribute('aria-expanded');
      });
    } else if (nextProps.triggerTarget) {
      reference.removeAttribute('aria-expanded');
    }
    handleAriaExpandedAttribute();
    handleStyles();
    if (onUpdate) {
      onUpdate(prevProps, nextProps);
    }
    if (instance.popperInstance) {
      createPopperInstance(); // Fixes an issue with nested tippies if they are all getting re-rendered,
      // and the nested ones get re-rendered first.
      // https://github.com/atomiks/tippyjs-react/issues/177
      // TODO: find a cleaner / more efficient solution(!)

      getNestedPopperTree().forEach(function (nestedPopper) {
        // React (and other UI libs likely) requires a rAF wrapper as it flushes
        // its work in one
        requestAnimationFrame(nestedPopper._tippy.popperInstance.forceUpdate);
      });
    }
    invokeHook('onAfterUpdate', [instance, partialProps]);
  }
  function setContent(content) {
    instance.setProps({
      content: content
    });
  }
  function show() {
    /* istanbul ignore else */
    {
      warnWhen(instance.state.isDestroyed, createMemoryLeakWarning('show'));
    } // Early bail-out

    var isAlreadyVisible = instance.state.isVisible;
    var isDestroyed = instance.state.isDestroyed;
    var isDisabled = !instance.state.isEnabled;
    var isTouchAndTouchDisabled = currentInput.isTouch && !instance.props.touch;
    var duration = getValueAtIndexOrReturn(instance.props.duration, 0, defaultProps.duration);
    if (isAlreadyVisible || isDestroyed || isDisabled || isTouchAndTouchDisabled) {
      return;
    } // Normalize `disabled` behavior across browsers.
    // Firefox allows events on disabled elements, but Chrome doesn't.
    // Using a wrapper element (i.e. <span>) is recommended.

    if (getCurrentTarget().hasAttribute('disabled')) {
      return;
    }
    invokeHook('onShow', [instance], false);
    if (instance.props.onShow(instance) === false) {
      return;
    }
    instance.state.isVisible = true;
    if (getIsDefaultRenderFn()) {
      popper.style.visibility = 'visible';
    }
    handleStyles();
    addDocumentPress();
    if (!instance.state.isMounted) {
      popper.style.transition = 'none';
    } // If flipping to the opposite side after hiding at least once, the
    // animation will use the wrong placement without resetting the duration

    if (getIsDefaultRenderFn()) {
      var _getDefaultTemplateCh2 = getDefaultTemplateChildren(),
        box = _getDefaultTemplateCh2.box,
        content = _getDefaultTemplateCh2.content;
      setTransitionDuration([box, content], 0);
    }
    onFirstUpdate = function onFirstUpdate() {
      var _instance$popperInsta2;
      if (!instance.state.isVisible || ignoreOnFirstUpdate) {
        return;
      }
      ignoreOnFirstUpdate = true; // reflow

      void popper.offsetHeight;
      popper.style.transition = instance.props.moveTransition;
      if (getIsDefaultRenderFn() && instance.props.animation) {
        var _getDefaultTemplateCh3 = getDefaultTemplateChildren(),
          _box = _getDefaultTemplateCh3.box,
          _content = _getDefaultTemplateCh3.content;
        setTransitionDuration([_box, _content], duration);
        setVisibilityState([_box, _content], 'visible');
      }
      handleAriaContentAttribute();
      handleAriaExpandedAttribute();
      pushIfUnique(mountedInstances, instance); // certain modifiers (e.g. `maxSize`) require a second update after the
      // popper has been positioned for the first time

      (_instance$popperInsta2 = instance.popperInstance) == null ? void 0 : _instance$popperInsta2.forceUpdate();
      invokeHook('onMount', [instance]);
      if (instance.props.animation && getIsDefaultRenderFn()) {
        onTransitionedIn(duration, function () {
          instance.state.isShown = true;
          invokeHook('onShown', [instance]);
        });
      }
    };
    mount();
  }
  function hide() {
    /* istanbul ignore else */
    {
      warnWhen(instance.state.isDestroyed, createMemoryLeakWarning('hide'));
    } // Early bail-out

    var isAlreadyHidden = !instance.state.isVisible;
    var isDestroyed = instance.state.isDestroyed;
    var isDisabled = !instance.state.isEnabled;
    var duration = getValueAtIndexOrReturn(instance.props.duration, 1, defaultProps.duration);
    if (isAlreadyHidden || isDestroyed || isDisabled) {
      return;
    }
    invokeHook('onHide', [instance], false);
    if (instance.props.onHide(instance) === false) {
      return;
    }
    instance.state.isVisible = false;
    instance.state.isShown = false;
    ignoreOnFirstUpdate = false;
    isVisibleFromClick = false;
    if (getIsDefaultRenderFn()) {
      popper.style.visibility = 'hidden';
    }
    cleanupInteractiveMouseListeners();
    removeDocumentPress();
    handleStyles(true);
    if (getIsDefaultRenderFn()) {
      var _getDefaultTemplateCh4 = getDefaultTemplateChildren(),
        box = _getDefaultTemplateCh4.box,
        content = _getDefaultTemplateCh4.content;
      if (instance.props.animation) {
        setTransitionDuration([box, content], duration);
        setVisibilityState([box, content], 'hidden');
      }
    }
    handleAriaContentAttribute();
    handleAriaExpandedAttribute();
    if (instance.props.animation) {
      if (getIsDefaultRenderFn()) {
        onTransitionedOut(duration, instance.unmount);
      }
    } else {
      instance.unmount();
    }
  }
  function hideWithInteractivity(event) {
    /* istanbul ignore else */
    {
      warnWhen(instance.state.isDestroyed, createMemoryLeakWarning('hideWithInteractivity'));
    }
    getDocument().addEventListener('mousemove', debouncedOnMouseMove);
    pushIfUnique(mouseMoveListeners, debouncedOnMouseMove);
    debouncedOnMouseMove(event);
  }
  function unmount() {
    /* istanbul ignore else */
    {
      warnWhen(instance.state.isDestroyed, createMemoryLeakWarning('unmount'));
    }
    if (instance.state.isVisible) {
      instance.hide();
    }
    if (!instance.state.isMounted) {
      return;
    }
    destroyPopperInstance(); // If a popper is not interactive, it will be appended outside the popper
    // tree by default. This seems mainly for interactive tippies, but we should
    // find a workaround if possible

    getNestedPopperTree().forEach(function (nestedPopper) {
      nestedPopper._tippy.unmount();
    });
    if (popper.parentNode) {
      popper.parentNode.removeChild(popper);
    }
    mountedInstances = mountedInstances.filter(function (i) {
      return i !== instance;
    });
    instance.state.isMounted = false;
    invokeHook('onHidden', [instance]);
  }
  function destroy() {
    /* istanbul ignore else */
    {
      warnWhen(instance.state.isDestroyed, createMemoryLeakWarning('destroy'));
    }
    if (instance.state.isDestroyed) {
      return;
    }
    instance.clearDelayTimeouts();
    instance.unmount();
    removeListeners();
    delete reference._tippy;
    instance.state.isDestroyed = true;
    invokeHook('onDestroy', [instance]);
  }
}
function tippy(targets, optionalProps) {
  if (optionalProps === void 0) {
    optionalProps = {};
  }
  var plugins = defaultProps.plugins.concat(optionalProps.plugins || []);
  /* istanbul ignore else */

  {
    validateTargets(targets);
    validateProps(optionalProps, plugins);
  }
  bindGlobalEventListeners();
  var passedProps = Object.assign({}, optionalProps, {
    plugins: plugins
  });
  var elements = getArrayOfElements(targets);
  /* istanbul ignore else */

  {
    var isSingleContentElement = isElement(passedProps.content);
    var isMoreThanOneReferenceElement = elements.length > 1;
    warnWhen(isSingleContentElement && isMoreThanOneReferenceElement, ['tippy() was passed an Element as the `content` prop, but more than', 'one tippy instance was created by this invocation. This means the', 'content element will only be appended to the last tippy instance.', '\n\n', 'Instead, pass the .innerHTML of the element, or use a function that', 'returns a cloned version of the element instead.', '\n\n', '1) content: element.innerHTML\n', '2) content: () => element.cloneNode(true)'].join(' '));
  }
  var instances = elements.reduce(function (acc, reference) {
    var instance = reference && createTippy(reference, passedProps);
    if (instance) {
      acc.push(instance);
    }
    return acc;
  }, []);
  return isElement(targets) ? instances[0] : instances;
}
tippy.defaultProps = defaultProps;
tippy.setDefaultProps = setDefaultProps;
tippy.currentInput = currentInput;

// every time the popper is destroyed (i.e. a new target), removing the styles
// and causing transitions to break for singletons when the console is open, but
// most notably for non-transform styles being used, `gpuAcceleration: false`.

Object.assign({}, applyStyles$1, {
  effect: function effect(_ref) {
    var state = _ref.state;
    var initialStyles = {
      popper: {
        position: state.options.strategy,
        left: '0',
        top: '0',
        margin: '0'
      },
      arrow: {
        position: 'absolute'
      },
      reference: {}
    };
    Object.assign(state.elements.popper.style, initialStyles.popper);
    state.styles = initialStyles;
    if (state.elements.arrow) {
      Object.assign(state.elements.arrow.style, initialStyles.arrow);
    } // intentionally return no cleanup function
    // return () => { ... }
  }
});
var mouseCoords = {
  clientX: 0,
  clientY: 0
};
var activeInstances = [];
function storeMouseCoords(_ref) {
  var clientX = _ref.clientX,
    clientY = _ref.clientY;
  mouseCoords = {
    clientX: clientX,
    clientY: clientY
  };
}
function addMouseCoordsListener(doc) {
  doc.addEventListener('mousemove', storeMouseCoords);
}
function removeMouseCoordsListener(doc) {
  doc.removeEventListener('mousemove', storeMouseCoords);
}
var followCursor = {
  name: 'followCursor',
  defaultValue: false,
  fn: function fn(instance) {
    var reference = instance.reference;
    var doc = getOwnerDocument(instance.props.triggerTarget || reference);
    var isInternalUpdate = false;
    var wasFocusEvent = false;
    var isUnmounted = true;
    var prevProps = instance.props;
    function getIsInitialBehavior() {
      return instance.props.followCursor === 'initial' && instance.state.isVisible;
    }
    function addListener() {
      doc.addEventListener('mousemove', onMouseMove);
    }
    function removeListener() {
      doc.removeEventListener('mousemove', onMouseMove);
    }
    function unsetGetReferenceClientRect() {
      isInternalUpdate = true;
      instance.setProps({
        getReferenceClientRect: null
      });
      isInternalUpdate = false;
    }
    function onMouseMove(event) {
      // If the instance is interactive, avoid updating the position unless it's
      // over the reference element
      var isCursorOverReference = event.target ? reference.contains(event.target) : true;
      var followCursor = instance.props.followCursor;
      var clientX = event.clientX,
        clientY = event.clientY;
      var rect = reference.getBoundingClientRect();
      var relativeX = clientX - rect.left;
      var relativeY = clientY - rect.top;
      if (isCursorOverReference || !instance.props.interactive) {
        instance.setProps({
          // @ts-ignore - unneeded DOMRect properties
          getReferenceClientRect: function getReferenceClientRect() {
            var rect = reference.getBoundingClientRect();
            var x = clientX;
            var y = clientY;
            if (followCursor === 'initial') {
              x = rect.left + relativeX;
              y = rect.top + relativeY;
            }
            var top = followCursor === 'horizontal' ? rect.top : y;
            var right = followCursor === 'vertical' ? rect.right : x;
            var bottom = followCursor === 'horizontal' ? rect.bottom : y;
            var left = followCursor === 'vertical' ? rect.left : x;
            return {
              width: right - left,
              height: bottom - top,
              top: top,
              right: right,
              bottom: bottom,
              left: left
            };
          }
        });
      }
    }
    function create() {
      if (instance.props.followCursor) {
        activeInstances.push({
          instance: instance,
          doc: doc
        });
        addMouseCoordsListener(doc);
      }
    }
    function destroy() {
      activeInstances = activeInstances.filter(function (data) {
        return data.instance !== instance;
      });
      if (activeInstances.filter(function (data) {
        return data.doc === doc;
      }).length === 0) {
        removeMouseCoordsListener(doc);
      }
    }
    return {
      onCreate: create,
      onDestroy: destroy,
      onBeforeUpdate: function onBeforeUpdate() {
        prevProps = instance.props;
      },
      onAfterUpdate: function onAfterUpdate(_, _ref2) {
        var followCursor = _ref2.followCursor;
        if (isInternalUpdate) {
          return;
        }
        if (followCursor !== undefined && prevProps.followCursor !== followCursor) {
          destroy();
          if (followCursor) {
            create();
            if (instance.state.isMounted && !wasFocusEvent && !getIsInitialBehavior()) {
              addListener();
            }
          } else {
            removeListener();
            unsetGetReferenceClientRect();
          }
        }
      },
      onMount: function onMount() {
        if (instance.props.followCursor && !wasFocusEvent) {
          if (isUnmounted) {
            onMouseMove(mouseCoords);
            isUnmounted = false;
          }
          if (!getIsInitialBehavior()) {
            addListener();
          }
        }
      },
      onTrigger: function onTrigger(_, event) {
        if (isMouseEvent(event)) {
          mouseCoords = {
            clientX: event.clientX,
            clientY: event.clientY
          };
        }
        wasFocusEvent = event.type === 'focus';
      },
      onHidden: function onHidden() {
        if (instance.props.followCursor) {
          unsetGetReferenceClientRect();
          removeListener();
          isUnmounted = true;
        }
      }
    };
  }
};
tippy.setDefaultProps({
  render: render
});

var t = function () {
  return t = Object.assign || function (t) {
    for (var e, n = 1, i = arguments.length; n < i; n++) for (var r in e = arguments[n]) Object.prototype.hasOwnProperty.call(e, r) && (t[r] = e[r]);
    return t;
  }, t.apply(this, arguments);
};
"function" == typeof SuppressedError && SuppressedError;
var e;
!function (t) {
  t[t.render = 0] = "render", t[t.selected = 1] = "selected";
}(e || (e = {}));
var n = function () {
  function e(e, n) {
    void 0 === n && (n = {}), this._initStatus = !1, this.onArr = [], this.prefix = "mark", this._selectionchangeTimeOut = 0, this.markRange = [], this.sectionChangeDelay = 100, this.lineColor = "#F17F53", this.lineWidth = 2, this.eventController = new AbortController(), this.options = {
      idPrefix: "mark-svg"
    };
    var i = null;
    if ("string" == typeof e ? i = document.getElementById(e) : e.nodeType == Node.ELEMENT_NODE && (i = e), !i) throw new Error("target错误 或 未找到对应元素");
    this.targetElement = i, this.onArr = [], this.options = t(t({}, this.options), n);
    var r = n.sectionChangeDelay,
      o = n.lineColor,
      a = n.lineWidth;
    r && (this.sectionChangeDelay = r), o && (this.lineColor = o), a && (this.lineWidth = a);
  }
  return e.prototype.render = function () {
    var t = this;
    if (!this._initStatus) {
      var e = this.targetElement.parentNode,
        n = document.createElement("div");
      n.className = "mark-view", n.style.position = "relative", n.style.width = "fit-content", n.style.height = "fit-content", n.style.minWidth = "100%";
      var i = document.createElement("style");
      i.innerHTML = "\n              @keyframes blink {\n                0%, 100% { opacity: 0; }\n                50% { opacity: 1; }\n              }\n              .blink {\n                animation: blink 1s linear 0;\n                animation-iteration-count: 3;\n              }\n            ", n.appendChild(i);
      var r = this.targetElement.cloneNode(!0);
      this.targetNode = r, n.appendChild(r);
      var o = document.createElementNS("http://www.w3.org/2000/svg", "svg");
      this.svgDom = o, o.id = "".concat(this.options.idPrefix || "mark-svg").concat(this.options.id ? "_#_" + this.options.id : ""), o.style.position = "absolute", o.style.left = "0px", o.style.top = "0px", o.style.width = "100%", o.style.height = "100%", o.style.mixBlendMode = "multiply", o.setAttribute("width", "100%"), o.setAttribute("height", "100%"), o.setAttribute("pointer-events", "none"), n.appendChild(o), null == e || e.replaceChild(n, this.targetElement), this.rootElement = n, this.targetNodeRect = this.rootElement.getBoundingClientRect(), this.targetNode.addEventListener("click", function (e) {
        if (t.rootElement) {
          var n = t.rootElement.getBoundingClientRect(),
            i = e,
            r = i.pageX - n.x,
            o = i.pageY - n.y,
            a = t.markRange.filter(function (t) {
              return t.position.filter(function (t) {
                return r > t.x1 && r < t.x2 && o > t.y1 && o < t.y2;
              }).length > 0;
            });
          a.length > 0 && a.forEach(function (t) {
            var e = new Event("click");
            t.node.dispatchEvent(e);
          });
        }
      }, {
        signal: this.eventController.signal
      }), this._handletListener(), this._update(), this._handleOn("render", this.rootElement);
    }
    this._initStatus = !0;
  }, e.prototype.update = function () {
    var t = this;
    this.markRange.forEach(function (e) {
      var n = t.svgDom.querySelector("[data-id='".concat(e.markStr, "']"));
      if (n && (n.innerHTML = "", !t._handleEfiToRange(e.markStr).collapsed)) {
        var i = e.range.getClientRects(),
          r = [],
          o = document.createDocumentFragment(),
          a = t._detachRangeRects(i),
          l = a.textRunRects;
        a.rowRects;
        for (var s = 0; s < l.length; s++) {
          var h = l[s],
            c = {
              line: "underline" === e.type ? e.styleScheme : "",
              rect: "highlight" === e.type ? e.styleScheme : ""
            },
            d = t._handleCreateSvgG(h, o, e.type, c);
          d.group;
          var u = d.position;
          r.push(u);
        }
        n.appendChild(o), e.position = r;
      }
    });
  }, e.prototype.add = function (t) {
    var e,
      n,
      i = t.type,
      r = null !== (e = t.click) && void 0 !== e ? e : null,
      o = this._handleEfiToRange(t.markStr);
    if (!o.collapsed) {
      var a = o.getClientRects(),
        l = document.createElementNS("http://www.w3.org/2000/svg", "g"),
        s = "";
      t.className && (s = t.className.split("__")[1], l.classList.add(t.className)), this.options.id && l.setAttribute("id", "".concat(this.options.id, "_#_").concat(t.markStr)), l.setAttribute("data-id", t.markStr), l.setAttribute("data-styleScheme", s), l.setAttribute("data-type", t.type), l.setAttribute("opacity", "0.5");
      var h = [],
        c = document.createDocumentFragment(),
        d = this._detachRangeRects(a),
        u = d.textRunRects;
      d.rowRects;
      for (var p = 0; p < u.length; p++) {
        var g = u[p],
          f = {
            line: "underline" === t.type ? s : "",
            rect: "highlight" === t.type ? s : ""
          },
          m = this._handleCreateSvgG(g, c, i, f);
        m.group;
        var v = m.position;
        h.push(v);
      }
      l.appendChild(c), this.markRange.push({
        markStr: t.markStr,
        range: o,
        type: i,
        styleScheme: s,
        position: h,
        node: l,
        data: null !== (n = t.data) && void 0 !== n ? n : {}
      }), r && "function" == typeof r && l.addEventListener("click", function (t) {
        var e = this.getAttribute("data-id");
        r.apply(this, [t, e]);
      }, {
        signal: this.eventController.signal
      }), this.svgDom.appendChild(l);
    }
  }, e.prototype.remove = function (t, e) {
    var n;
    if (!t) throw new Error("未传入MarkEfiCode");
    for (var i = this.markRange.map(function (t, e) {
        return {
          item: t,
          index: e
        };
      }).filter(function (n) {
        return n.item.markStr == t && (!e || n.item.type == e);
      }), r = 0, o = this.svgDom, a = 0; a < i.length; a++) {
      var l = i[a].index - r,
        s = i[a].item;
      null === (n = o.querySelector("[data-id='".concat(s.markStr, "']"))) || void 0 === n || n.remove(), this.markRange.splice(l, 1), r++;
    }
  }, e.prototype.animate = function (t, e) {
    if (void 0 === e && (e = {
      type: "blink"
    }), !t) throw new Error("未传入动画目标target");
    var n = this.svgDom.querySelectorAll('g[data-id="'.concat(t, '"] > rect'));
    Array.from(n).forEach(function (t, n) {
      t.classList.add(e.type), t.addEventListener("animationend", function () {
        t.classList.contains("blink") && t.classList.remove("blink");
      });
    });
  }, e.prototype.highlight = function (t, e, n, i) {
    if (void 0 === i && (i = {}), !t) throw new Error("未传入MarkEfiCode");
    this.add({
      type: "highlight",
      markStr: t,
      className: e,
      click: n,
      data: i
    });
  }, e.prototype.underline = function (t, e, n, i) {
    if (void 0 === i && (i = {}), !t) throw new Error("未传入MarkEfiCode");
    this.add({
      type: "underline",
      markStr: t,
      className: e,
      click: n,
      data: i
    });
  }, e.prototype.show = function (t) {
    var e, n;
    t ? null === (e = this.svgDom) || void 0 === e || e.querySelectorAll('g[data-type="'.concat(t, '"]')).forEach(function (t) {
      t.setAttribute("display", "auto");
    }) : null === (n = this.svgDom) || void 0 === n || n.querySelectorAll("g").forEach(function (t) {
      t.setAttribute("display", "auto");
    });
  }, e.prototype.hide = function (t) {
    var e, n;
    t ? null === (e = this.svgDom) || void 0 === e || e.querySelectorAll('g[data-type="'.concat(t, '"]')).forEach(function (t) {
      t.setAttribute("display", "none");
    }) : null === (n = this.svgDom) || void 0 === n || n.querySelectorAll("g").forEach(function (t) {
      t.setAttribute("display", "none");
    });
  }, e.prototype.clear = function (t) {
    for (var e, n = this.markRange.map(function (t, e) {
        return {
          item: t,
          index: e
        };
      }).filter(function (e) {
        return !t || e.item.type == t;
      }), i = 0, r = this.svgDom, o = 0; o < n.length; o++) {
      var a = n[o].index - i,
        l = n[o].item;
      null === (e = r.querySelector("[data-id='".concat(l.markStr, "']"))) || void 0 === e || e.remove(), this.markRange.splice(a, 1), i++;
    }
  }, e.prototype.on = function (t, e) {
    this.onArr.push({
      key: t,
      func: e
    });
  }, e.prototype.destroy = function () {
    this.eventController.abort(), this.rootElement = void 0, this.targetNode = void 0, this.svgDom = void 0, this.markRange = [], this.onArr = [], this._initStatus = !1;
  }, e.prototype.getMarks = function () {
    return this.markRange.map(function (t) {
      return {
        markStr: t.markStr,
        type: t.type,
        data: t.data
      };
    });
  }, e.prototype._update = function () {
    var t = this;
    window.addEventListener("resize", function () {
      requestAnimationFrame(function () {
        t.rootElement && (t.targetNodeRect = t.rootElement.getBoundingClientRect(), t.update());
      });
    }, {
      signal: this.eventController.signal
    });
  }, e.prototype._handletListener = function () {
    var t = this,
      e = this;
    document.addEventListener("selectionchange", function () {
      for (var n = [], i = 0; i < arguments.length; i++) n[i] = arguments[i];
      clearTimeout(t._selectionchangeTimeOut), t._selectionchangeTimeOut = setTimeout(function () {
        t._handleSelected.apply(t, n);
      }, e.sectionChangeDelay || 250);
    }, {
      signal: e.eventController.signal
    });
  }, e.prototype._handleSelected = function () {
    var t,
      e,
      n,
      i = window.getSelection();
    if (i && !i.isCollapsed) {
      var r = i.getRangeAt(0),
        o = this._handleSelectRangePostion(r),
        a = r.getClientRects(),
        l = a[0],
        s = a[a.length - 1],
        h = (null === (t = this.rootElement) || void 0 === t ? void 0 : t.getBoundingClientRect()) || this.targetNodeRect || {},
        c = null !== (e = null == h ? void 0 : h.top) && void 0 !== e ? e : 0,
        d = null !== (n = null == h ? void 0 : h.left) && void 0 !== n ? n : 0,
        u = {
          top_left: [l.left - d, l.top - c],
          top_center: [l.left + l.width / 2 - d, l.top - c],
          top_right: [l.right - d, l.top - c],
          center_left: [s.left - d, l.top + (s.bottom - l.top) / 2 - c],
          center: [s.left + (l.right - s.left) / 2 - d, l.top + (s.bottom - l.top) / 2 - c],
          center_right: [l.right - d, l.top + (s.bottom - l.top) / 2 - c],
          bottom_left: [s.left - d, s.bottom - c],
          bottom_center: [s.left + s.width / 2 - d, s.top + s.height - c],
          bottom_right: [s.right - d, s.bottom - c]
        };
      this._handleOn("selected", {
        markStr: o,
        range: r,
        position: u
      });
    }
  }, e.prototype._handleSelectRangePostion = function (t) {
    var e = this._handleSelectNodePostion(t.startContainer),
      n = t.startOffset,
      i = this._handleSelectNodePostion(t.endContainer),
      r = t.endOffset;
    return "".concat(this.prefix, "(").concat(e, ":").concat(n, ",").concat(i, ":").concat(r, ")");
  }, e.prototype._handleSelectNodePostion = function (t) {
    for (var e = [], n = t; n != this.targetNode;) {
      for (var i = 0; n.previousSibling;) i++, n = n.previousSibling;
      if (e.push(i), null == n.parentNode) break;
      n = n.parentNode;
    }
    return e.reverse().join("/");
  }, e.prototype._handleEfiToRange = function (t) {
    var e = document.createRange(),
      n = this._handleCheckEfi(t);
    if (!n) return e;
    for (var i = this.targetNode, r = null, o = 0; o < n.start_arr.length; o++) {
      var a = n.start_arr[o];
      i = r = i.childNodes[a];
    }
    n.start_node = r, i = this.targetNode;
    for (o = 0; o < n.end_arr.length; o++) {
      a = n.end_arr[o];
      i = r = i.childNodes[a];
    }
    return n.end_node = r, e.setStart(n.start_node, n.start_offset), e.setEnd(n.end_node, n.end_offset), e;
  }, e.prototype._handleOn = function (t, e) {
    void 0 === e && (e = {}), this.onArr.filter(function (e) {
      return e.key == t;
    }).forEach(function (t) {
      null == t || t.func(e);
    });
  }, e.prototype._handleCheckEfi = function (t) {
    var e = new RegExp("".concat(this.prefix, "(.*,.*)")),
      n = t.match(e);
    if (!n || n.length < 2) return null;
    var i = n[1],
      r = (i = i.replace("(", "").replace(")", "")).split(",");
    return {
      start_arr: r[0].split(":")[0].split("/").map(function (t) {
        return Number(t);
      }),
      start_offset: Number(r[0].split(":")[1]),
      end_arr: r[1].split(":")[0].split("/").map(function (t) {
        return Number(t);
      }),
      end_offset: Number(r[1].split(":")[1]),
      start_node: null,
      end_node: null
    };
  }, e.prototype._detachRangeRects = function (t) {
    for (var e = [], n = [], i = [], r = 0, o = t.length; r < o; r++) {
      var a = !0,
        l = t[r],
        s = r ? t[r - 1] : null;
      s && s.x === l.x && l.y < s.y + s.height && (a = !1), a || (i[r - 1] = !1), i.push(!0);
    }
    return i.forEach(function (i, r) {
      i ? e.push(t[r]) : n.push(t[r]);
    }), {
      textRunRects: e,
      rowRects: n
    };
  }, e.prototype._handleCreateRect = function (t, e) {
    var n;
    void 0 === e && (e = {
      opcity: !1
    });
    var i = document.createElementNS("http://www.w3.org/2000/svg", "rect"),
      r = (null === (n = this.rootElement) || void 0 === n ? void 0 : n.getBoundingClientRect()) || this.targetNodeRect || {},
      o = t.x - r.x,
      a = t.y - r.y;
    return i.setAttribute("x", o.toString()), i.setAttribute("y", a.toString()), i.setAttribute("width", t.width.toString()), i.setAttribute("height", t.height.toString()), i.setAttribute("fill", e.isPlaceholder ? this.options.animationColor || "#D6D6D6" : "#FFFF00"), i.setAttribute("mix-blend-mode", "multiply"), e.opcity && i.setAttribute("opacity", "0"), i;
  }, e.prototype._handleCreateLine = function (t, e) {
    var n,
      i = document.createElementNS("http://www.w3.org/2000/svg", "line"),
      r = (null === (n = this.rootElement) || void 0 === n ? void 0 : n.getBoundingClientRect()) || this.targetNodeRect || {},
      o = this.lineColor,
      a = t.x - r.x,
      l = t.y - r.y + t.height;
    "dashed" === (null == e ? void 0 : e.styleScheme) && (l += 3, o = "#25B774");
    var s = a + t.width,
      h = l;
    return i.setAttribute("x1", a.toString()), i.setAttribute("y1", l.toString()), i.setAttribute("x2", s.toString()), i.setAttribute("y2", h.toString()), i.setAttribute("stroke-width", "".concat(this.lineWidth) || "2"), i.setAttribute("stroke", o || "#03a9f4"), i.setAttribute("mix-blend-mode", "multiply"), "dashed" === (null == e ? void 0 : e.styleScheme) && i.setAttribute("stroke-dasharray", "6,3"), i;
  }, e.prototype._handleCreateSvgG = function (t, e, n, i) {
    var r,
      o = (null === (r = this.rootElement) || void 0 === r ? void 0 : r.getBoundingClientRect()) || this.targetNodeRect || {},
      a = document.createDocumentFragment();
    if ("highlight" == n) {
      var l = this._handleCreateRect(t, {
        styleScheme: i.rect
      });
      e.appendChild(l);
    }
    if ("underline" == n) {
      l = this._handleCreateRect(t, {
        opcity: !0,
        isPlaceholder: !0
      });
      var s = this._handleCreateLine(t, {
        styleScheme: i.line
      });
      e.appendChild(l), e.appendChild(s);
    }
    var h = t.x - o.x,
      c = t.y - o.y;
    return {
      group: a,
      position: {
        x1: h,
        y1: c,
        x2: h + t.width,
        y2: c + t.height
      }
    };
  }, e;
}();

//

// @pos 导入
/***
 * 文本块
 */

let prevOverflow = '';
var script = {
  name: 'XmlTextRender',
  components: {
    addFile: __vue_component__$1,
    XmlTextDialogRender: __vue_component__$3,
    [ImagePreview$1.Component.name]: ImagePreview$1.Component
  },
  props: {
    //模式：preview 预览 (默认)，editor 编辑
    mode: {
      type: String,
      default: function () {
        return 'editor';
      }
    },
    pBlockData: {
      type: Object,
      default: function () {
        return {};
      }
    },
    //块儿数据名
    blockDataName: String,
    //页面类型，取值h5、pc、pad
    pageType: {
      type: String,
      default: 'h5'
    },
    resourceBasisPath: {
      type: String,
      default: ''
    },
    //当前所处组的规则
    currentRule: {
      type: Object,
      default: function () {
        return {};
      }
    },
    ruleIndex: Number,
    dataIndex: Number,
    //数据下标
    containerClass: String,
    extendParams: {
      type: Object,
      default: function () {
        return {
          //默认开启编辑器
          defaultOpenEditor: false
        };
      }
    },
    headers: {
      // 上传文件头部
      type: Object,
      default: () => {}
    },
    action: {
      // 上传文件地址
      type: String,
      default: ''
    },
    data: {
      // 上传文件附带的额外参数
      type: Object,
      default: () => {}
    },
    textBookData: Object //数字教材信息
  },
  data() {
    return {
      blockId: `blockId${v4()}`,
      propertyComponentsName: 'XmlTextProperty',
      editorId: `editor-container${`${Math.random()}`.replaceAll('0.', '')}`,
      blockData: {
        html: ''
      },
      showViewer: false,
      imageViewerTitles: [],
      imageViewerSrcs: [],
      inlineWordsModal: {
        visible: false,
        title: '',
        content: '',
        stylemode: ''
      },
      markRootId: `mark-view__${v4()}`,
      markEfiStr: '',
      markInstance: null,
      activeTippy: null,
      tippyTplBarId: `tipbar-tpl__${v4()}`,
      tippyTplNoteId: `tipnote-tpl__${v4()}`,
      actionCopyId: `act-copy__${v4()}`,
      actionNoteId: `act-note__${v4()}`,
      actionHighlightId: `act-light__${v4()}`,
      addTeacherResourcesId: `add-teacher-resources__${v4()}`,
      noteInputId: `note_input__${v4()}`,
      actNoteCancelId: `act-cancel__${v4()}`,
      actNoteConfirmId: `act-confirm__${v4()}`,
      editNoteTplId: `editnote-tpl__${v4()}`,
      actNoteDeleteId: `act-delete__${v4()}`,
      actNoteEditId: `act-edit__${v4()}`,
      noteOperateMode: '',
      tempMarkModel: {},
      noteData: {
        selectionText: '',
        content: ''
      },
      noteEditData: {
        selectionText: '',
        content: ''
      },
      tempMarkEfiStr: '',
      isMobile: false,
      notePopupVisible: false
    };
  },
  inject: {
    getProviderUserType: {
      from: 'getProviderUserType',
      default: () => () => ''
    },
    getProviderInsideIndex: {
      from: 'getProviderInsideIndex',
      default: () => () => -1
    },
    getSingleGroupLocation: {
      from: 'getSingleGroupLocation',
      default: () => () => ''
    },
    getToolbarVisible: {
      from: 'getToolbarVisible',
      default: () => () => false
    },
    getReaderBoxId: {
      from: 'getReaderBoxId',
      default: () => () => ''
    },
    getTeacherNoteList: {
      from: 'getTeacherNoteList',
      default: () => () => []
    },
    getStudentNoteList: {
      from: 'getStudentNoteList',
      default: () => () => []
    },
    getHighlightList: {
      from: 'getHighlightList',
      default: () => () => []
    },
    getKeyboardShow: {
      from: 'getKeyboardShow',
      default: () => () => false
    },
    getInitialLoad: {
      from: 'getInitialLoad',
      default: () => () => false
    }
  },
  computed: {
    feedback() {
      return {
        ruleIndex: this.ruleIndex,
        dataName: this.blockDataName,
        data: this.pBlockData,
        dataIndex: this.dataIndex,
        blockId: this.blockId
      };
    },
    userType() {
      return this.getProviderUserType();
    },
    insideIndex() {
      return this.getProviderInsideIndex();
    },
    groupLocation() {
      return this.getSingleGroupLocation();
    },
    toolbarVisible() {
      return this.getToolbarVisible();
    },
    readerBoxId() {
      return this.getReaderBoxId();
    },
    keyboardShow() {
      return this.getKeyboardShow();
    },
    mergeMarkList() {
      let teacherNoteList = this.getTeacherNoteList() || [],
        studentNoteList = this.getStudentNoteList() || [],
        highlightList = this.getHighlightList() || [];
      return [...teacherNoteList.filter(item => item.location === this.groupLocation && item.blockIndex === this.ruleIndex), ...studentNoteList.filter(item => item.location === this.groupLocation && item.blockIndex === this.ruleIndex), ...highlightList.filter(item => item.location === this.groupLocation && item.blockIndex === this.ruleIndex)];
    }
  },
  watch: {
    mergeMarkList: {
      handler(newValue) {
        // console.log("%c%s","font-size:2em;background: #00965E;color: #FFF",'教师笔记回显0',newValue,this.markInstance)
        // this.$nextTick(() => {
        //   if (newValue?.length && this.markInstance) {
        //     this.updateMarkView()
        //   }
        // })
      },
      immediate: true,
      deep: true
    }
  },
  created() {},
  mounted() {
    // 兼容一期文本弹窗=====
    this.$nextTick(() => {
      setTimeout(() => {
        jquery('a').attr('target', '_self');
      }, 2000);
      window.inlineWordsShow = uuid => {
        const ele = document.getElementById(`words__${uuid}`);
        const {
          title = '',
          content = ''
        } = ele.dataset || {};
        this.inlineWordsModal = {
          title,
          content,
          visible: true
        };
      };
    });
    // ==================
    let _this = this;
    this.blockData = this.pBlockData;
    if (!this.blockData.html) {
      this.blockData.html = '<span>暂无内容</span>';
    }
    const wrapSelector = `#${this.blockId} .richtext-reset-wrapper--view`;
    let mceMagicLinkRegistered = window.customElements?.get('magic-link');
    if (!mceMagicLinkRegistered) {
      window.customElements.whenDefined('magic-link').then(res => {
        console.log('%c%s', 'font-size:2em;background: #00965E;color: #FFF', '富文本组件MCE注册完成', res);
      });
      window.customElements.define('magic-link', MagicLink);
    }
    let containerSelector = `#${this.blockId}.richtext-reset-container`;
    this.$nextTick(() => {
      jquery(wrapSelector).on('click', 'img', function (e) {
        let target = jquery(e.target);
        console.log('%c%s', 'font-size:2em;background: #00965E;color: #FFF', '事件对象', e, target, target.index('img[preview]'));
        let title = target.attr('alt');
        let src = target.attr('src');
        let notallowgallery = target.attr('notallowgallery');
        if (notallowgallery) {
          return;
        }
        _this.imageViewerTitles = [title];
        _this.imageViewerSrcs = [src];
        prevOverflow = document.body.style.overflow;
        document.body.style.overflow = 'hidden';
        if (_this.pageType == 'pc') {
          _this.showViewer = true;
        } else {
          ImagePreview$1({
            images: [src],
            startPosition: 0,
            closeable: true
          });
        }
      });
      jquery(containerSelector).on('click', 'magic-link', function (e) {
        let {
          plaintext,
          title,
          content,
          type,
          isPlaying,
          stylemode
        } = e.target.dataset;
        console.log('%c%s', 'font-size:2em;background: #00965E;color: #FFF', 'magic-link点击', e, e.target.dataset);
        if (_this.mode === 'editor') {
          _this.$message.info('当前内容仅支持在预览模式下查看');
          return;
        }
        if (type === 'image') {
          // 魔链图片
          _this.imageViewerTitles = [plaintext];
          _this.imageViewerSrcs = [content];
          prevOverflow = document.body.style.overflow;
          document.body.style.overflow = 'hidden';
          _this.showViewer = true;
        }
        if (type === 'audio') {
          // 魔链音频
          _this.$EventBus.$emit('handleMagicLinkAudioPlay', {
            plaintext,
            title,
            content,
            type,
            isPlaying,
            targetId: e.target.id,
            callback: audio => {
              e.target.setAttribute('data-isplaying', audio.paused ? 'false' : 'true');
            }
          });
        }
        if (type === 'richtext') {
          content = content.replace(/text\-align:\s?justify/g, 'text-align:left');
          // 魔链富文本
          _this.inlineWordsModal = {
            title,
            content,
            stylemode,
            visible: true
          };
        }
        if (type === 'sheet') {
          // 插入活页
          window.open(process.env.VUE_APP_TEXTBOOK_WEB + 'previewLooseLeaf?pageType=' + _this.pageType + '&businessType=looseLeaf' + '&looseLeafId=' + content + '&isTrial=' + true + '&uuid=' + v4());
        }
      });
      jquery(containerSelector).on('openTarget', 'magic-link', function (e) {
        // let {plaintext,title,content,type,isPlaying,stylemode} = e.target.dataset
        console.log('%c%s', 'font-size:2em;background: #00965E;color: #FFF', 'leaflet target点击', e, e.detail);
      });
      jquery(`#${this.blockId} .inline-link-wrap`).each(function (i) {
        let parent = jquery(this).parent();
        // let indent = parent ? parent.css("text-indent") : '' // 此处使用css()方法获取属性值有内部bug
        let elem = parent.length ? parent[0] : null;
        if (elem) {
          let indent = getComputedStyle(elem, null)['textIndent'];
          let hackStyle = jquery(this).attr('style') + `max-width:calc(100% - ${indent})`;
          jquery(this).attr('style', hackStyle);
        }
      });
      jquery(`#${this.blockId} :not(.inline-link-wrap) img`).each(function (i) {
        let parent = jquery(this).parent();
        let elem = parent.length ? parent[0] : null;
        if (elem) {
          let indent = getComputedStyle(elem, null)['textIndent'];
          let hackStyle = jquery(this).attr('style') + `max-width:calc(100% - ${indent}) !important`;
          jquery(this).attr('style', hackStyle);
        }
      });
      if ('ontouchstart' in window || 'onmsgesturechange' in window) {
        this.isMobile = true;
        console.log('%c%s', 'font-size:2em;background: #00965E;color: #FFF', '当前环境:移动端');
      } else {
        this.isMobile = false;
        console.log('%c%s', 'font-size:2em;background: #00965E;color: #FFF', '当前环境:PC端');
      }

      // @pos 初始化tippy
      tippy.setDefaultProps({
        plugins: [followCursor]
      });
      _this.activeTippy = tippy(`#${_this.blockId}`, {
        content: '',
        placement: 'top',
        trigger: 'manual',
        theme: 'light',
        animation: 'shift-away',
        interactive: true,
        allowHTML: true,
        // followCursor: this.isMobile ? true : 'initial',
        followCursor: 'initial'
      });
      function findParentByClassName(node, className) {
        if (node && !(node.nodeType == 1 && node.tagName.toLowerCase() === 'body')) {
          while (node) {
            let isBody = node && node.nodeType == 1 && node.tagName.toLowerCase() == 'body';
            let hasClass = node && node.nodeType == 1 && node.classList.contains(className);
            if (hasClass || isBody) {
              return !hasClass ? null : node;
            }
            node = node.parentNode;
          }
        }
        return null;
      }
      if (this.userType) {
        this.markInstance = new n(this.markRootId, {
          id: this.currentRule.xmlCompRef
        });
        let timer = null;
        this.markInstance.on('selected', data => {
          if (this.insideIndex === this.ruleIndex) {
            console.log('%c%s', 'font-size:2em;background: #00965E;color: #FFF', 'SelectionChange', data);
            let {
              startContainer,
              endContainer
            } = data.range;
            let startParent = startContainer && findParentByClassName(startContainer, 'richtext-reset-wrapper--view');
            let endParent = endContainer && findParentByClassName(endContainer, 'richtext-reset-wrapper--view');
            if (startParent && endParent && startParent !== endParent) {
              _this.activeTippy[0].setContent('暂不支持跨组件标注');
              _this.activeTippy[0].show();
              setTimeout(handler => {
                _this.hideTippy();
              }, 1500);
              return;
            }
            _this.markEfiStr = data.markStr;
            if (_this.tempMarkEfiStr) {
              this.markInstance.remove(_this.tempMarkEfiStr, 'underline');
            }
            if (timer) {
              clearTimeout(timer);
            }
            if (this.isMobile) {
              _this.activeTippy[0] && _this.hideTippy();
              timer = setTimeout(() => {
                _this.handleMouseUp();
              }, 200);
            }
          }
        });
        this.markInstance.render();
        this.$nextTick(() => {
          this.$EventBus.$on('previewRepaint', () => {
            setTimeout(() => {
              _this.markInstance.update();
            }, 10);
          });
          this.$EventBus.$on('markJumpIn', target => {
            setTimeout(() => {
              if (target.location === _this.groupLocation && target.blockIndex === _this.ruleIndex) {
                _this.markInstance.animate(target.markEfiCode);
              }
            }, 10);
          });
          this.$once('hook:beforeDestroy', () => {
            _this.$EventBus.$off('previewRepaint');
            _this.$EventBus.$off('markJumpIn');
          });
          this.updateCodeBlock();
          setTimeout(() => {
            this.updateMarkView();
          }, this.getInitialLoad() ? 1000 : 0);
        });
      } else {
        this.updateCodeBlock();
      }
    });
    this.$EventBus.$on('clickToolbarTip', function (data) {
      if (data.type == 'copy' && data.tippyTplBarId == _this.tippyTplBarId) {
        _this.actionCopy();
      } else if (data.type == 'note' && data.tippyTplBarId == _this.tippyTplBarId) {
        _this.actionAddNote();
      } else if (data.type == 'highlight' && data.tippyTplBarId == _this.tippyTplBarId) {
        _this.actionAddHighlight();
      }
      _this.$EventBus.$emit('selectionTextChange', {
        state: false,
        tippyTplBarId: _this.tippyTplBarId
      });
    });
    this.$once('hook:beforeDestroy', () => {
      _this.$EventBus.$off('clickToolbarTip');
    });
    this.$EventBus.$on('underlineSign', function (data) {
      // this.noteOperateMode = 'add'
      // let defaultUnderlineStyle = 'mk-underline__default'
      if (data.operationType == 'add' && _this.groupLocation == data.location) {
        _this.markInstance.underline(data.markEfiCode, 'mk-underline__default', e => {
        });
        _this.tempMarkEfiStr = '';
      } else if (data.operationType == 'remove' && _this.groupLocation == data.location) {
        _this.markInstance.remove(data.markEfiCode, data.signType);
      }
    });
    this.$once('hook:beforeDestroy', () => {
      _this.$EventBus.$off('underlineSign');
    });
  },
  beforeDestroy() {
    if (this.markInstance) {
      this.markInstance.destroy();
    }
    if (this.activeTippy && this.activeTippy[0]) {
      this.activeTippy[0].destroy();
    }
  },
  methods: {
    // // 添加教师资源
    // addTeacherResources() {
    //   let markId = `mark__${uuidv4()}`
    //   // let styleType = 'mk-addTeacherResources__default'
    //   let model = {
    //     selectionText: this.noteData.selectionText,
    //     markEfiCode: this.markEfiStr,
    //     type: `note__${this.userType}`,
    //     // styleType,
    //     blockIndex: this.ruleIndex,
    //     markId
    //   }
    //   this.emitRollbackHandler('addTeacherResources', model)
    //     .then((id) => {
    //       id === markId && _this.markInstance.remove(rollbackMark, 'addTeacherResources')
    //       console.log(222)
    //     })
    //     .catch((err) => {
    //       console.log(err)
    //     })
    // },
    // 打开添加教师资源弹窗
    addTeacherResources(e) {
      let markId = `mark__${v4()}`;
      // let styleType = 'mk-addTeacherResources__default'
      let model = {
        selectionText: this.noteData.selectionText,
        markEfiCode: this.markEfiStr,
        type: `note__${this.userType}`,
        // styleType,
        blockIndex: this.ruleIndex,
        markId
      };
      let _this = this;
      // this.noteOperateMode = 'add'
      // let defaultUnderlineStyle = 'mk-underline__default'
      _this.tempMarkEfiStr = _this.markEfiStr;
      _this.noteData.content = '';
      // _this.markInstance.underline(_this.markEfiStr, defaultUnderlineStyle, (e) => {
      //   try {
      //     // 下划线点击事件, 比如打开编辑框
      //     // let markEfiStr = e.target.getAttribute('data-id')
      //     // _this.noteClick(e, markEfiStr)
      //   } catch (error) {
      //     console.log('%c%s', 'font-size:2em;background: #DD5644;color: #FFF', 'underline error', error)
      //   }
      // })
      this.emitRollbackHandler('addTeacherResources', model).then(id => {
        id === markId && _this.markInstance.remove(rollbackMark, 'underline');
      }).catch(err => {
        console.log(err);
      });
      this.hideTippy();
    },
    // 添加数据
    addData(type, item) {
      this.data[type].list.push(item);
      let list = JSON.stringify(this.data);
      localStorage.setItem('simulated-data_' + this.textBookData.id, list);
      this.getData(type, item);
    },
    // 确认添加教师资源
    addResources(e) {
      this.$emit('addResources', e);
    },
    // 编辑教师资源
    editTeachingResource(e) {
      this.$refs.addTeacherResources.open({
        isEdit: true,
        ...e
      });
    },
    // 确认编辑教师资源
    editResources(e) {
      this.$emit('editResources', e);
    },
    updateMarkView() {
      // @pos 硬刷新Mark视图
      let _this = this;
      this.markInstance.clear();
      this.mergeMarkList.forEach(item => {
        if (item.type === 'note__teacher') {
          this.markInstance.underline(item.markEfiCode, item.styleType, e => {
            try {
              // 下划线点击事件, 比如打开编辑框
              let markEfiStr = e.target.getAttribute('data-id');
              console.log('%c%s', 'font-size:2em;background: #00965E;color: #FFF', 'Mark Click', e, markEfiStr);
              console.log('下划线点击事件, 比如打开编辑框', markEfiStr);
              this.emitRollbackHandler('openTeacherResources', {
                ...e,
                markEfiStr
              });
              // _this.noteClick(e, markEfiStr)
            } catch (error) {
              console.log('%c%s', 'font-size:2em;background: #DD5644;color: #FFF', 'MarkClick Error', error);
            }
          });
        }
        if (item.type === 'note__student') {
          this.markInstance.underline(item.markEfiCode, item.styleType, e => {
            try {
              // 下划线点击事件, 比如打开编辑框
              // if (!_this.markEfiStr) {
              let markEfiStr = e.target.getAttribute('data-id');
              _this.noteClick(e, markEfiStr);
              // }
            } catch (error) {
              console.log('%c%s', 'font-size:2em;background: #DD5644;color: #FFF', 'MarkClick Error', error);
            }
          });
        }
        if (item.type === 'highlight__student') {
          this.markInstance.highlight(item.markEfiCode, item.styleType, e => {
            try {
              // 下划线点击事件, 比如打开编辑框
              let markEfiStr = e.target.getAttribute('data-id');
              _this.highlightClick(e, markEfiStr);
            } catch (error) {
              console.log('%c%s', 'font-size:2em;background: #DD5644;color: #FFF', 'HighlightClick Error', error);
            }
          });
        }
      });
    },
    handleMouseUp() {
      // @pos MouseUp
      let _this = this;
      if (this.userType && this.insideIndex === this.ruleIndex) {
        setTimeout(() => {
          console.log('%c%s', 'font-size:2em;background: #00965E;color: #FFF', 'MouseUp', _this.markEfiStr);
          this.$EventBus.$emit('selectionTextChange', {
            state: false,
            tippyTplBarId: _this.tippyTplBarId
          });
          const text = window?.getSelection()?.toString() || '';
          if (text.length && text.length <= 200 && _this.markEfiStr) {
            let checkHasSaved = _this.mergeMarkList.find(item => item.markEfiCode === _this.markEfiStr);
            if (checkHasSaved) {
              let msg = '当前位置已存在标记',
                resourceType = checkHasSaved.resourcesType || checkHasSaved.type?.split('__')[0];
              if (checkHasSaved.resourcesName) {
                resourceType = 'resource';
              }
              switch (resourceType) {
                case 'notes':
                  msg = '当前位置已存在笔记';
                  break;
                case 'recorded':
                  msg = '当前位置已存在录音';
                  break;
                case 'underline':
                  msg = '当前位置已存在笔记';
                  break;
                case 'highlight':
                  msg = '当前位置已存在高亮';
                  break;
                case 'resource':
                  msg = '当前位置已存在资源';
                  break;
              }
              _this.activeTippy[0].setContent(msg);
              _this.activeTippy[0].show();
              _this.markEfiStr = '';
              setTimeout(handler => {
                _this.hideTippy();
              }, 1500);
              return;
            }
            _this.noteData.selectionText = text;
            const templateBar = document.getElementById(_this.tippyTplBarId);
            // let HTMLContentClone = $J(`#${_this.tippyTplBarId}`)?.clone(true,true)?.get(0)
            let content = templateBar?.innerHTML || '<span style="color:"#EE3751;"">选区解析错误</span>';
            let u = navigator.userAgent;
            if (_this.pageType == 'pc' || !u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
              _this.activeTippy[0].setProps({
                content,
                onShown: instance => {
                  // @pos 显示tippybar
                  let actCopy = instance.popper.children[0]?.querySelector(`#${_this.actionCopyId}`),
                    actNote = instance.popper.children[0]?.querySelector(`#${_this.actionNoteId}`),
                    actHighlight = instance.popper.children[0]?.querySelector(`#${_this.actionHighlightId}`),
                    addTeacherResources = instance.popper.children[0]?.querySelector(`#${_this.addTeacherResourcesId}`);
                  if (actCopy) {
                    actCopy.addEventListener('click', _this.actionCopy, {
                      once: true
                    });
                  }
                  if (actNote) {
                    actNote.addEventListener('click', _this.actionAddNote, {
                      once: true
                    });
                  }
                  if (actHighlight) {
                    actHighlight.addEventListener('click', _this.actionAddHighlight, {
                      once: true
                    });
                  }
                  if (addTeacherResources) {
                    addTeacherResources.addEventListener('click', _this.addTeacherResources, {
                      once: true
                    });
                  }
                }
              });
              // _this.activeTippy = tippy(e.target, {
              //   content: templateBar,
              //   placement: 'top',
              //   trigger: 'manual',
              //   theme: 'light',
              //   animation: 'shift-away',
              //   interactive: true,
              //   onClickOutside(instance, event) {
              //     instance.hide()
              //   },
              // })
              _this.activeTippy[0].show();
            } else {
              this.$EventBus.$emit('selectionTextChange', {
                state: true,
                tippyTplBarId: _this.tippyTplBarId
              });
            }
          } else if (text.length > 200) {
            _this.activeTippy[0].setContent(`<div style="color:#666;">可选文本最多为200字</div>`);
            _this.activeTippy[0].show();
            setTimeout(handler => {
              _this.activeTippy[0].hide();
            }, 2000);
          }
        }, 110);
      }
    },
    resetTempNote() {
      if (this.tempMarkEfiStr) {
        this.noteData.selectionText = '';
        this.markInstance.remove(this.tempMarkEfiStr, 'underline');
      }
    },
    actionCopy() {
      if (!this.noteData.selectionText) {
        this.$message.error('未选中任何内容');
        return;
      }
      document.execCommand('copy');
      this.$message.success('复制成功');
      this.hideTippy();
      this.markEfiStr = '';
      this.noteData = {
        selectionText: '',
        content: ''
      };
      window.getSelection()?.removeAllRanges();
    },
    cancelEditNote(instance) {
      this.noteEditData = {
        selectionText: '',
        content: ''
      };
      this.noteOperateMode = '';
      this.tempMarkModel = {};
      instance.hide();
      instance.destroy();
    },
    deleteNote(instance) {
      let _this = this;
      let noteModel = {
        ...this.tempMarkModel
      };
      let markId = noteModel.markId;
      if (this.userType && this.insideIndex === this.ruleIndex) {
        let rollbackMark = noteModel.markEfiCode;
        this.emitRollbackHandler('deleteNote', noteModel).then(id => {
          id === markId && _this.markInstance.remove(rollbackMark, 'underline');
        });
      }
      this.cancelEditNote(instance);
    },
    confirmEditNote(noteInput, instance) {
      let value = noteInput?.value || '';
      if (!value) {
        this.$message.error('笔记内容不能为空');
        return;
      }
      let noteModel = {
        ...this.tempMarkModel,
        noteContent: value
      };
      if (this.userType && this.insideIndex === this.ruleIndex) {
        this.$EventBus.$emit('editNote', noteModel);
      }
      this.cancelEditNote(instance);
    },
    showEditNoteTippy() {
      let _this = this;
      try {
        const templateNote = document.getElementById(_this.editNoteTplId);
        let content = templateNote?.innerHTML || '笔记面板加载错误';
        // @pos 解决tippy不弹出问题
        let newTippy = tippy(`#${_this.blockId}`, {
          content,
          placement: 'top',
          trigger: 'manual',
          theme: 'light',
          animation: 'shift-away',
          interactive: true,
          allowHTML: true,
          followCursor: 'initial',
          onShown: instance => {
            // @pos 弹出编辑笔记tippy
            let actNoteCancel = instance.popper.children[0]?.querySelector(`#${_this.actNoteCancelId}`),
              actNoteDelete = instance.popper.children[0]?.querySelector(`#${_this.actNoteDeleteId}`),
              actNoteEditSave = instance.popper.children[0]?.querySelector(`#${_this.actNoteEditId}`),
              noteInput = instance.popper.children[0]?.querySelector(`#${_this.noteInputId}`);
            console.log('%c%s', 'font-size:2em;background: #00965E;color: #FFF', '获取不到事件?', {
              actNoteCancel,
              actNoteDelete,
              actNoteEditSave,
              noteInput
            });
            if (noteInput) {
              noteInput.value = _this.noteEditData.content;
              noteInput.addEventListener('input', e => {
                let value = e.target.value;
                if (value === _this.noteEditData.content) {
                  actNoteEditSave && actNoteEditSave.parentElement.classList.add('disabled');
                } else {
                  actNoteEditSave && actNoteEditSave.parentElement.classList.remove('disabled');
                }
              });
            }
            if (actNoteCancel) {
              actNoteCancel.addEventListener('click', () => _this.cancelEditNote(instance), {
                once: true
              });
            }
            if (actNoteDelete) {
              actNoteDelete.addEventListener('click', () => _this.deleteNote(instance), {
                once: true
              });
            }
            if (actNoteEditSave && noteInput) {
              actNoteEditSave.addEventListener('click', () => _this.confirmEditNote(noteInput, instance), {
                once: true
              });
            }
          }
        });
        newTippy[0].show();
      } catch (error) {
        console.log('%c%s', 'font-size:2em;background: #DD5644;color: #FFF', 'error', error);
      }
    },
    // @pos 学生笔记编辑
    noteClick(e, markEfi) {
      let _this = this;
      let styleScheme = e.target.getAttribute('data-styleScheme');
      console.log('%c%s', 'font-size:2em;background: #DD5644;color: #FFF', '下划线样式', styleScheme);
      if (this.userType === 'student' && styleScheme === 'default' || this.userType === 'teacher' && styleScheme === 'dashed') {
        // 学生和教师分别仅可触发各自对应的笔记下划线点击事件
        return;
      }
      let model = this.mergeMarkList.find(item => item.markEfiCode === markEfi);
      if (!model) {
        _this.activeTippy[0].setContent('查找笔记出错');
        _this.activeTippy[0].show();
        setTimeout(handler => {
          _this.hideTippy();
        }, 1500);
        return;
      }
      this.noteOperateMode = 'edit';
      this.tempMarkModel = model;
      if (this.userType === 'student' && this.isMobile) {
        this.notePopupVisible = true;
        this.noteData = {
          selectionText: model.selectionText,
          content: model.noteContent
        };
      } else {
        this.noteEditData = {
          selectionText: model.selectionText,
          content: model.noteContent
        };
        this.$nextTick(() => {
          this.showEditNoteTippy(e);
        });
      }
    },
    actionAddNote(e) {
      // @pos 添加笔记
      // e?.stopPropagation && e.stopPropagation()
      let _this = this;
      this.noteOperateMode = 'add';
      let defaultUnderlineStyle = this.userType === 'teacher' ? 'mk-underline__default' : 'mk-underline__dashed';
      _this.markInstance.underline(_this.markEfiStr, defaultUnderlineStyle, e => {
        try {
          // 下划线点击事件, 比如打开编辑框
          let markEfiStr = e.target.getAttribute('data-id');
          console.log('%c%s', 'font-size:2em;background: #00965E;color: #FFF', 'UnderlineClick', e, markEfiStr);
          _this.noteClick(e, markEfiStr);
        } catch (error) {
          console.log('%c%s', 'font-size:2em;background: #DD5644;color: #FFF', 'underline error', error);
        }
      });
      _this.tempMarkEfiStr = _this.markEfiStr;
      _this.noteData.content = '';
      console.log('this.isMobile', this.isMobile);
      if (!this.isMobile) {
        const templateNote = document.getElementById(_this.tippyTplNoteId);
        let content = templateNote?.innerHTML || '笔记面板加载错误';
        _this.activeTippy[0].setProps({
          content,
          onAfterUpdate: instance => {
            // @pos 更新tippy
            _this.noteEventController = new AbortController();
            let actNoteCancel = instance.popper.children[0]?.querySelector(`#${_this.actNoteCancelId}`),
              actNoteConfirm = instance.popper.children[0]?.querySelector(`#${_this.actNoteConfirmId}`),
              noteInput = instance.popper.children[0]?.querySelector(`#${_this.noteInputId}`);
            if (actNoteCancel && noteInput) {
              actNoteCancel.addEventListener('click', _this.cancelAddNote, {
                once: true
              });
            }
            if (actNoteConfirm) {
              actNoteConfirm.addEventListener('click', () => _this.confirmAddNote(noteInput), {
                signal: _this.noteEventController.signal
              });
            }
          },
          onUntrigger: instance => {
            console.log('%c%s', 'font-size:2em;background: #DD5644;color: #FFF', 'Untrigger');
          }
        });
      } else {
        this.hideTippy();
        this.notePopupVisible = true;
      }
      window.getSelection()?.removeAllRanges();
    },
    confirmAddStudentNote() {
      let noteContent = this.noteData.content;
      console.log('%c%s', 'font-size:2em;background: #DD5644;color: #FFF', '内容', noteContent);
      if (!noteContent) {
        this.$message.error('请输入笔记内容');
        return;
      }
      if (this.noteOperateMode === 'edit') {
        this.confirmEditStudentNote(noteContent);
        return;
      }
      let markId = `mark__${v4()}`;
      let noteModel = {
        selectionText: this.noteData.selectionText,
        noteContent,
        markEfiCode: this.markEfiStr,
        type: `note__${this.userType}`,
        styleType: 'mk-underline__dashed',
        blockIndex: this.ruleIndex,
        markId
      };
      this.tempMarkEfiStr = '';
      this.noteData = {
        selectionText: '',
        content: ''
      };
      if (this.userType && this.insideIndex === this.ruleIndex) {
        let rollbackMark = this.markEfiStr;
        this.emitRollbackHandler('createNote', noteModel).then(id => {
          id === markId && _this.markInstance.remove(rollbackMark, 'underline');
        });
      }
      this.notePopupVisible = false;
    },
    confirmEditStudentNote(noteContent) {
      let noteModel = {
        ...this.tempMarkModel,
        noteContent
      };
      this.tempMarkEfiStr = '';
      this.noteData = {
        selectionText: '',
        content: ''
      };
      if (this.userType && this.insideIndex === this.ruleIndex) {
        this.$EventBus.$emit('editNote', noteModel);
      }
      this.notePopupVisible = false;
      this.noteOperateMode = '';
      this.tempMarkModel = {};
    },
    deleteStudentNote() {
      let _this = this;
      let noteModel = {
        ...this.tempMarkModel
      };
      let markId = noteModel.markId;
      if (this.userType && this.insideIndex === this.ruleIndex) {
        let rollbackMark = noteModel.markEfiCode;
        this.emitRollbackHandler('deleteNote', noteModel).then(id => {
          id === markId && _this.markInstance.remove(rollbackMark, 'underline');
        });
      }
      this.notePopupVisible = false;
      this.noteOperateMode = '';
      this.tempMarkModel = {};
    },
    actionAddHighlight() {
      let _this = this;
      let styleType = 'mk-hightlight__default';
      _this.markInstance.highlight(_this.markEfiStr, styleType, e => {
        try {
          let markEfiStr = e.target.getAttribute('data-id');
          _this.highlightClick(e, markEfiStr);
        } catch (error) {
          console.log('%c%s', 'font-size:2em;background: #DD5644;color: #FFF', 'underline error', error);
        }
      });
      this.hideTippy();
      let markId = `mark__${v4()}`;
      let model = {
        selectionText: this.noteData.selectionText,
        markEfiCode: this.markEfiStr,
        type: `highlight__${this.userType}`,
        styleType,
        blockIndex: this.ruleIndex,
        markId
      };
      this.noteData.selectionText = '';
      if (this.userType && this.insideIndex === this.ruleIndex) {
        // this.$EventBus.$emit('createHighlight', model)
        let rollbackMark = this.markEfiStr;
        this.emitRollbackHandler('createHighlight', model).then(id => {
          id === markId && _this.markInstance.remove(rollbackMark, 'highlight');
        });
      }
      window.getSelection()?.removeAllRanges();
    },
    highlightClick(e, efi) {
      console.log('%c%s', 'font-size:2em;background: #00965E;color: #FFF', 'HighLight Click', e, _this.markEfiStr);
    },
    emitRollbackHandler(eventName, eventData) {
      console.log('emitRollbackHandler', eventName, eventData);
      return new Promise((resolve, reject) => {
        this.$EventBus.$emit(eventName, eventData, resolve);
      });
    },
    confirmAddNote(noteInput) {
      let value = noteInput?.value || '';
      if (!value) {
        this.$message.error('请输入笔记内容');
        return;
      }
      if (!value.trim()) {
        this.$message.error('笔记内容不能为空！');
        return;
      }
      this.hideTippy();
      let markId = `mark__${v4()}`;
      let noteModel = {
        selectionText: this.noteData.selectionText,
        noteContent: value,
        markEfiCode: this.markEfiStr,
        type: `note__${this.userType}`,
        styleType: 'mk-underline__dashed',
        blockIndex: this.ruleIndex,
        markId
      };
      this.tempMarkEfiStr = '';
      this.noteData = {
        selectionText: '',
        content: ''
      };
      if (this.userType && this.insideIndex === this.ruleIndex) {
        let rollbackMark = this.markEfiStr;
        this.emitRollbackHandler('createNote', noteModel).then(id => {
          id === markId && _this.markInstance.remove(rollbackMark, 'underline');
        });
      }
      this.noteEventController.abort();
    },
    cancelAddNote() {
      this.hideTippy();
      this.markEfiStr && this.markInstance.remove(this.markEfiStr, 'underline');
      this.markEfiStr = '';
      this.noteData = {
        selectionText: '',
        content: ''
      };
    },
    hideTippy() {
      this.activeTippy[0].hide();
      this.activeTippy[0].setContent('');
    },
    closeViewer() {
      document.body.style.overflow = prevOverflow;
      this.showViewer = false;
      this.imageViewTitles = [];
      this.imageViewSrcs = [];
    },
    formatImg(str) {
      if (str) {
        let data = str.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/gi, (match, p1) => {
          if (match.indexOf('style') !== -1) {
            // if (match.indexOf('http') !== -1) {
            //   return match
            // } else {
            //   let src = this.resourceBasisPath + p1.split('./')[1]
            //   let image = match.replace(p1, src)
            //   return image.split('style="')[0] + 'style="max-width:100% !important;' + image.split('style="')[1]
            // }
            let src = this.resourceBasisPath + p1.split('./')[1];
            let image = match.indexOf('http') !== -1 ? match : match.replace(p1, src);
            return image.split('style="')[0] + 'style="max-width:100% !important;' + image.split('style="')[1];
          } else {
            return `<img src='${p1.indexOf('http') > -1 ? p1 : this.resourceBasisPath + p1.split('./')[1]}' style="max-width:100%;" />`;
          }
        });
        return data;
      }
    },
    updateCodeBlock() {
      jquery(`#${this.blockId} .richtext-reset-wrapper--view pre`).each(function (i) {
        let classStrs = jquery(this).attr('class');
        let classArr = classStrs.split(';');
        classArr = classArr[0].split(':');
        let lang = 'language-' + classArr[1];
        let codeElemStr = '<code class="line-numbers ' + lang + '" data-prismjs-copy="复制代码" data-prismjs-copy-success="复制完成">' + jquery(this).html() + '</code>';
        jquery(this).html(codeElemStr);
        jquery(this).attr('class', 'line-numbers');
        let codeElem = jquery(this).children('code').get(0);
        // Prism.highlightAll();
        prism.highlightElement(codeElem);
      });
    },
    groupDataChange() {
      this.$emit('groupDataChange', {
        ruleIndex: this.ruleIndex,
        dataName: this.blockDataName,
        data: this.blockData,
        dataIndex: this.dataIndex
      });
    },
    //编辑器是否存在
    getIsEditorContainerExist() {
      const container = document.getElementById(this.editorId);
      if (!container) return false;
      const isWeExist = container.getAttribute('data-w-e-textarea');
      return isWeExist;
    },
    // 此方法必须要，用户注册块儿点击事件
    blockClick() {
      // this.markEfiStr = ''
      this.hideTippy();
      this.$emit('blockclick', {
        blockData: this.blockData,
        dataName: this.blockDataName,
        propertyComponentsName: this.propertyComponentsName,
        blockId: this.blockId,
        ruleIndex: this.ruleIndex,
        dataIndex: this.dataIndex
      });
    }
  }
};

/* script */
const __vue_script__ = script;
/* template */
var __vue_render__ = function () {
  var _vm = this;
  var _h = _vm.$createElement;
  var _c = _vm._self._c || _h;
  return _c(
    "div",
    {
      class: [
        "xml-text-" + _vm.pageType,
        "" + _vm.containerClass,
        "richtext-reset-container",
      ],
      attrs: { id: _vm.blockId },
      on: { mousedown: _vm.blockClick, mouseup: _vm.handleMouseUp },
    },
    [
      _vm.mode === "editor"
        ? _vm._t("editor", null, { feedback: _vm.feedback })
        : _c("div", {
            staticClass: "richtext-reset-wrapper--view",
            attrs: { id: _vm.markRootId },
            domProps: { innerHTML: _vm._s(_vm.formatImg(_vm.pBlockData.html)) },
          }),
      _vm._v(" "),
      _vm._t("mater-lib-dialog"),
      _vm._v(" "),
      _vm._t("mater-lib-dialog2"),
      _vm._v(" "),
      _c(
        "el-dialog",
        {
          staticClass: "xml-text-preview-box-dialog",
          attrs: {
            visible: _vm.inlineWordsModal.visible,
            "append-to-body": true,
            width: _vm.pageType == "pc" ? "40%" : "80%",
            center: "",
            "show-close": false,
          },
          on: {
            "update:visible": function ($event) {
              return _vm.$set(_vm.inlineWordsModal, "visible", $event)
            },
          },
        },
        [
          _c("xml-text-dialog-render", {
            attrs: {
              content: _vm.inlineWordsModal.content,
              textstyle: _vm.inlineWordsModal.stylemode
                ? _vm.inlineWordsModal.stylemode
                : "D",
              "page-type": _vm.pageType,
              resourceBasisPath: _vm.resourceBasisPath,
            },
          }),
        ],
        1
      ),
      _vm._v(" "),
      _vm.showViewer
        ? _c("xml-image-viewer", {
            attrs: {
              title: _vm.imageViewerTitles,
              "z-index": 2000,
              "on-close": _vm.closeViewer,
              "url-list": _vm.imageViewerSrcs,
            },
          })
        : _vm._e(),
      _vm._v(" "),
      _c(
        "div",
        { staticStyle: { display: "none" }, attrs: { id: _vm.tippyTplBarId } },
        [
          _c(
            "div",
            {
              staticClass: "tipbar tipbar-tpl",
              on: {
                click: function ($event) {
                  $event.stopPropagation();
                },
              },
            },
            [
              _c(
                "div",
                {
                  directives: [
                    {
                      name: "show",
                      rawName: "v-show",
                      value: _vm.isMobile,
                      expression: "isMobile",
                    },
                  ],
                  staticClass: "tipbar-remark--mobile",
                },
                [
                  _c("span", { staticClass: "tipbar-remark" }, [
                    _vm._v("均<=200字"),
                  ]),
                ]
              ),
              _vm._v(" "),
              _c(
                "div",
                {
                  staticClass: "tipbar-action",
                  attrs: { id: _vm.actionCopyId },
                  on: {
                    click: function ($event) {
                      $event.stopPropagation();
                      return _vm.actionCopy.apply(null, arguments)
                    },
                  },
                },
                [
                  _c("i", { staticClass: "tipbar-icon copy" }),
                  _vm._v(" "),
                  _c("span", [_vm._v("复制")]),
                ]
              ),
              _vm._v(" "),
              _c(
                "span",
                {
                  directives: [
                    {
                      name: "show",
                      rawName: "v-show",
                      value: !_vm.isMobile,
                      expression: "!isMobile",
                    },
                  ],
                  staticClass: "tipbar-separator",
                },
                [_vm._v("|")]
              ),
              _vm._v(" "),
              _c("span", {
                directives: [
                  {
                    name: "show",
                    rawName: "v-show",
                    value: _vm.isMobile,
                    expression: "isMobile",
                  },
                ],
                staticClass: "tipbar-separator--mobile",
              }),
              _vm._v(" "),
              _vm.userType !== "teacher"
                ? [
                    _c(
                      "div",
                      {
                        staticClass: "tipbar-action",
                        attrs: { id: _vm.actionNoteId },
                        on: {
                          click: function ($event) {
                            $event.stopPropagation();
                            return _vm.actionAddNote.apply(null, arguments)
                          },
                        },
                      },
                      [
                        _c("i", { staticClass: "tipbar-icon note" }),
                        _vm._v(" "),
                        _c("span", [_vm._v("笔记")]),
                      ]
                    ),
                    _vm._v(" "),
                    _c(
                      "span",
                      {
                        directives: [
                          {
                            name: "show",
                            rawName: "v-show",
                            value: !_vm.isMobile,
                            expression: "!isMobile",
                          },
                        ],
                        staticClass: "tipbar-separator",
                      },
                      [_vm._v("|")]
                    ),
                  ]
                : _vm._e(),
              _vm._v(" "),
              _c("span", {
                directives: [
                  {
                    name: "show",
                    rawName: "v-show",
                    value: _vm.isMobile,
                    expression: "isMobile",
                  },
                ],
                staticClass: "tipbar-separator--mobile",
              }),
              _vm._v(" "),
              _vm.userType == "teacher"
                ? _c(
                    "div",
                    {
                      staticClass: "tipbar-action",
                      attrs: { id: _vm.addTeacherResourcesId },
                      on: {
                        click: function ($event) {
                          return _vm.addTeacherResources()
                        },
                      },
                    },
                    [
                      _c("i", {
                        staticClass: "tipbar-icon addTeacherResources",
                      }),
                      _vm._v(" "),
                      _c("span", [_vm._v("资源")]),
                    ]
                  )
                : _vm._e(),
              _vm._v(" "),
              _vm.userType === "student"
                ? _c(
                    "div",
                    {
                      staticClass: "tipbar-action",
                      attrs: { id: _vm.actionHighlightId },
                    },
                    [
                      _c("i", { staticClass: "tipbar-icon highlight" }),
                      _vm._v(" "),
                      _c("span", [_vm._v("高亮")]),
                    ]
                  )
                : _vm._e(),
              _vm._v(" "),
              _c(
                "span",
                {
                  directives: [
                    {
                      name: "show",
                      rawName: "v-show",
                      value: !_vm.isMobile,
                      expression: "!isMobile",
                    },
                  ],
                  staticClass: "tipbar-remark",
                },
                [_vm._v("均<=200字")]
              ),
            ],
            2
          ),
        ]
      ),
      _vm._v(" "),
      _c(
        "div",
        { staticStyle: { display: "none" }, attrs: { id: _vm.tippyTplNoteId } },
        [
          _c("div", { staticClass: "tipnote tipnote-tpl" }, [
            _c("div", { staticClass: "tipnote-title" }, [
              _vm._v(_vm._s(_vm.noteData.selectionText)),
            ]),
            _vm._v(" "),
            _c("textarea", {
              directives: [
                {
                  name: "model",
                  rawName: "v-model.trim",
                  value: _vm.noteData.content,
                  expression: "noteData.content",
                  modifiers: { trim: true },
                },
              ],
              ref: "tippyTextarea",
              staticClass: "tipnote-textarea",
              attrs: {
                id: _vm.noteInputId,
                placeholder: "请输入笔记内容",
                maxlength: "200",
                rows: "5",
              },
              domProps: { value: _vm.noteData.content },
              on: {
                input: function ($event) {
                  if ($event.target.composing) {
                    return
                  }
                  _vm.$set(_vm.noteData, "content", $event.target.value.trim());
                },
                blur: function ($event) {
                  return _vm.$forceUpdate()
                },
              },
            }),
            _vm._v(" "),
            _c("div", { staticClass: "tipnote-footer" }, [
              _c(
                "div",
                {
                  staticClass: "tipnote-btn cancel",
                  attrs: { id: _vm.actNoteCancelId },
                  on: { click: _vm.cancelAddNote },
                },
                [_c("span", [_vm._v("取消")])]
              ),
              _vm._v(" "),
              _c(
                "div",
                {
                  staticClass: "tipnote-btn confirm",
                  attrs: { id: _vm.actNoteConfirmId },
                  on: { click: _vm.confirmAddNote },
                },
                [_c("span", [_vm._v("确认")])]
              ),
            ]),
          ]),
        ]
      ),
      _vm._v(" "),
      _c(
        "div",
        { staticStyle: { display: "none" }, attrs: { id: _vm.editNoteTplId } },
        [
          _c("div", { staticClass: "tipnote tipnote-tpl" }, [
            _c("div", { staticClass: "tipnote-title" }, [
              _vm._v(_vm._s(_vm.noteEditData.selectionText)),
            ]),
            _vm._v(" "),
            _c("textarea", {
              ref: "tippyTextarea",
              staticClass: "tipnote-textarea",
              attrs: {
                id: _vm.noteInputId,
                placeholder: "请输入笔记内容",
                maxlength: "200",
                rows: "5",
              },
              domProps: { value: _vm.noteEditData.content },
            }),
            _vm._v(" "),
            _c("div", { staticClass: "tipnote-footer" }, [
              _c(
                "div",
                {
                  staticClass: "tipnote-btn cancel",
                  attrs: { id: _vm.actNoteCancelId },
                },
                [_c("span", [_vm._v("取消")])]
              ),
              _vm._v(" "),
              _c(
                "div",
                {
                  staticClass: "tipnote-btn delete",
                  attrs: { id: _vm.actNoteDeleteId },
                },
                [_c("span", [_vm._v("删除")])]
              ),
              _vm._v(" "),
              _c("div", { staticClass: "tipnote-btn btn-wrap disabled" }, [
                _c(
                  "div",
                  { staticClass: "btn-edit", attrs: { id: _vm.actNoteEditId } },
                  [_c("span", [_vm._v("保存修改")])]
                ),
              ]),
            ]),
          ]),
        ]
      ),
      _vm._v(" "),
      _vm.isMobile
        ? _c(
            "van-popup",
            {
              style: { backgroundColor: "transparent" },
              attrs: { "get-container": "body", position: "bottom" },
              on: { "click-overlay": _vm.resetTempNote },
              model: {
                value: _vm.notePopupVisible,
                callback: function ($$v) {
                  _vm.notePopupVisible = $$v;
                },
                expression: "notePopupVisible",
              },
            },
            [
              _c(
                "div",
                {
                  staticClass: "xml-reader-phone-mark-note-popup",
                  class: [
                    _vm.toolbarVisible &&
                      !_vm.keyboardShow &&
                      "is-toolbar-shown",
                    _vm.keyboardShow && "keyboard-show",
                    _vm.toolbarVisible && "toolbar-show",
                  ],
                  on: {
                    click: function ($event) {
                      $event.stopPropagation();
                    },
                  },
                },
                [
                  _c("div", { staticClass: "mark-note__selection" }, [
                    _c("div", [_vm._v(_vm._s(_vm.noteData.selectionText))]),
                  ]),
                  _vm._v(" "),
                  _c("section", { staticClass: "mark-note__wrap" }, [
                    _c("textarea", {
                      directives: [
                        {
                          name: "model",
                          rawName: "v-model.trim",
                          value: _vm.noteData.content,
                          expression: "noteData.content",
                          modifiers: { trim: true },
                        },
                      ],
                      ref: "popupTextarea",
                      staticClass: "mark-note__textarea",
                      attrs: {
                        placeholder: "添加笔记...",
                        maxlength: "200",
                        rows: "5",
                      },
                      domProps: { value: _vm.noteData.content },
                      on: {
                        input: function ($event) {
                          if ($event.target.composing) {
                            return
                          }
                          _vm.$set(
                            _vm.noteData,
                            "content",
                            $event.target.value.trim()
                          );
                        },
                        blur: function ($event) {
                          return _vm.$forceUpdate()
                        },
                      },
                    }),
                    _vm._v(" "),
                    _c("div", { staticClass: "mark-note__footer" }, [
                      _c("div", { staticClass: "mark-note__count" }, [
                        _vm._v(_vm._s(_vm.noteData.content.length) + "/200"),
                      ]),
                      _vm._v(" "),
                      _vm.noteOperateMode === "edit"
                        ? _c(
                            "div",
                            {
                              staticClass: "mark-note__delete",
                              on: {
                                click: function ($event) {
                                  if ($event.target !== $event.currentTarget) {
                                    return null
                                  }
                                  return _vm.deleteStudentNote.apply(
                                    null,
                                    arguments
                                  )
                                },
                              },
                            },
                            [_vm._v("删除")]
                          )
                        : _vm._e(),
                      _vm._v(" "),
                      _c(
                        "div",
                        {
                          staticClass: "mark-note__confirm",
                          class: _vm.noteData.content.length && "enable",
                          on: {
                            click: function ($event) {
                              if ($event.target !== $event.currentTarget) {
                                return null
                              }
                              return _vm.confirmAddStudentNote.apply(
                                null,
                                arguments
                              )
                            },
                          },
                        },
                        [_vm._v("\n            保存\n          ")]
                      ),
                    ]),
                  ]),
                ]
              ),
            ]
          )
        : _vm._e(),
    ],
    2
  )
};
var __vue_staticRenderFns__ = [];
__vue_render__._withStripped = true;

  /* style */
  const __vue_inject_styles__ = undefined;
  /* scoped */
  const __vue_scope_id__ = "data-v-640283d5";
  /* module identifier */
  const __vue_module_identifier__ = undefined;
  /* functional template */
  const __vue_is_functional_template__ = false;
  /* style inject */
  
  /* style inject SSR */
  
  /* style inject shadow dom */
  

  
  const __vue_component__ = /*#__PURE__*/normalizeComponent(
    { render: __vue_render__, staticRenderFns: __vue_staticRenderFns__ },
    __vue_inject_styles__,
    __vue_script__,
    __vue_scope_id__,
    __vue_is_functional_template__,
    __vue_module_identifier__,
    false,
    undefined,
    undefined,
    undefined
  );

const TextComponents = [__vue_component__, __vue_component__$3];
var index = {
  ...TextComponents
};

export { index as default };
